added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T22:37:19.757461+00:00 | 2012-06-04T11:28:53 | 73ba958171a27e843f4ab9d128598375507ffefc | {
"blob_id": "73ba958171a27e843f4ab9d128598375507ffefc",
"branch_name": "refs/heads/master",
"committer_date": "2012-06-04T11:28:53",
"content_id": "0a0b69972e9f452ed5d96b145614f9581c5f82d6",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "cf6e057d64053f5101a8d883ff7599705a3f9618",
"extension": "c",
"filename": "cc2500.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 4546153,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5122,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/platform/stm32test/driver/cc2500.c",
"provenance": "stackv2-0107.json.gz:99249",
"repo_name": "srjklssj/contiki-port103z",
"revision_date": "2012-06-04T11:28:53",
"revision_id": "6a3e52fe3697edb2c45571322feb677fc3188884",
"snapshot_id": "227740f6db0d50fe21ea61493447bb75dc93aa2f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/srjklssj/contiki-port103z/6a3e52fe3697edb2c45571322feb677fc3188884/platform/stm32test/driver/cc2500.c",
"visit_date": "2021-01-13T01:36:34.382454"
} | stackv2 | #include <stdio.h>
#include "cc2500.h"
#include "spi-arch.h"
#include "system-basis.h"
void cc2500_cmd(unsigned char cmd) {
CC2500_SELECT();
SPI2_RW(cmd);
CC2500_UNSELECT();
}
void cc2500_wreg(unsigned char addr, unsigned char val) {
CC2500_SELECT();
addr &= 0x7F;
SPI2_RW(addr);
SPI2_RW(val);
CC2500_UNSELECT();
}
unsigned char cc2500_rreg(unsigned char addr) {
unsigned char val;
CC2500_SELECT();
SPI2_RW(addr | 0x80);
val = SPI2_RW(0xFF);
CC2500_UNSELECT();
return val;
}
void cc2500_init(void) {
int i;
// GDO0
GPIO_CONF_INPUT_PORT(B, 1, PU_PD);
// reset cc2500
cc2500_cmd(CCxxx0_SIDLE);
DELAY_MS(20);
CC2500_SELECT();
DELAY_MS(20);
CC2500_UNSELECT();
DELAY_MS(40);
cc2500_cmd(CCxxx0_SRES);
// write regs
cc2500_wreg(CCxxx0_FSCAL1, 0x09);
cc2500_wreg(CCxxx0_FSCTRL0, 0x00);
cc2500_wreg(CCxxx0_FREQ2, 0x5D);
cc2500_wreg(CCxxx0_FREQ1, 0x93);
cc2500_wreg(CCxxx0_FREQ0, 0xB1);
cc2500_wreg(CCxxx0_MDMCFG4, 0x2D);
cc2500_wreg(CCxxx0_MDMCFG3, 0x3B);
cc2500_wreg(CCxxx0_MDMCFG2, 0x73);
cc2500_wreg(CCxxx0_MDMCFG1, 0xA2);
cc2500_wreg(CCxxx0_MDMCFG0, 0xF8);
cc2500_wreg(CCxxx0_CHANNR, 0x00);
cc2500_wreg(CCxxx0_DEVIATN, 0x01);
cc2500_wreg(CCxxx0_FREND1, 0x56);
cc2500_wreg(CCxxx0_FREND0, 0x10);
cc2500_wreg(CCxxx0_MCSM1, 0x00);
cc2500_wreg(CCxxx0_MCSM0, 0x18);
cc2500_wreg(CCxxx0_FOCCFG, 0x15);
cc2500_wreg(CCxxx0_BSCFG, 0x6C);
cc2500_wreg(CCxxx0_AGCCTRL2, 0x07);
cc2500_wreg(CCxxx0_AGCCTRL1, 0x00);
cc2500_wreg(CCxxx0_AGCCTRL0, 0x91);
cc2500_wreg(CCxxx0_FSCAL3, 0xEA);
cc2500_wreg(CCxxx0_FSCAL2, 0x0A);
cc2500_wreg(CCxxx0_FSCAL1, 0x00);
cc2500_wreg(CCxxx0_FSCAL0, 0x11);
cc2500_wreg(CCxxx0_FSTEST, 0x59);
cc2500_wreg(CCxxx0_TEST2, 0x8F);
cc2500_wreg(CCxxx0_TEST1, 0x21);
cc2500_wreg(CCxxx0_TEST0, 0x0B);
cc2500_wreg(CCxxx0_IOCFG2, 0x24);
cc2500_wreg(CCxxx0_IOCFG0, 0x06);
cc2500_wreg(CCxxx0_PKTCTRL1, 0x00);
cc2500_wreg(CCxxx0_PKTCTRL0, 0x05);
cc2500_wreg(CCxxx0_ADDR, 0x00);
cc2500_wreg(CCxxx0_PKTLEN, 0xFF);
CC2500_SELECT();
SPI2_RW(CCxxx0_PATABLE | WRITE_BURST);
for (i = 0; i < 8; ++i)
SPI2_RW(0xFF);
CC2500_UNSELECT();
// set cc2500 in rx mode
CC2500_RX_MODE();
}
unsigned char cc2500_read_status(unsigned char addr) {
unsigned char value;
CC2500_SELECT();
SPI2_RW(addr | READ_BURST);
value = SPI2_RW(0xFF);
CC2500_UNSELECT();
return value;
}
int cc2500_receive_packet(unsigned char *buffer) {
unsigned char status, bytes_in_fifo;
unsigned char total_bytes, need_to_receive;
unsigned char i = 0;
unsigned short timer_counter = 1;
// make sure cc2500 is working on rx mode
//status = 0x01 | (cc2500_read_status(CCxxx0_RXBYTES));
status = cc2500_read_status(CCxxx0_RXBYTES);
if((status & 0x7F) == 0x00) {
status = cc2500_read_status(CCxxx0_MARCSTATE);
if((status != 0x0D) && (status != 0x08))
CC2500_RX_MODE();
return 0;
}
// rx fifo overflow, flush it
if (0x80 == (status & 0x80)) {
CC2500_RX_MODE();
printf("CC2500:rx fifo overflow\r\n");
return -1;
}
CC2500_SELECT();
status = SPI2_RW(CCxxx0_RXFIFO_Muti);
bytes_in_fifo = (status & CC2500_FIFO_BYTES_AVAILABLE_BM);
if (bytes_in_fifo) {
total_bytes = need_to_receive = SPI2_RW(0xFF);
--bytes_in_fifo;
i = 0;
} else { // no need to check, but the warning ...
CC2500_UNSELECT();
return 0;
}
while (need_to_receive) {
need_to_receive -= bytes_in_fifo;
while (bytes_in_fifo--)
buffer[i++] = SPI2_RW(0xFF);
CC2500_UNSELECT();
if (need_to_receive) {
CC2500_SELECT();
status = SPI2_RW(CCxxx0_RXFIFO_Muti);
bytes_in_fifo = (status & CC2500_FIFO_BYTES_AVAILABLE_BM);
}
if (!(timer_counter++)) {
printf("CC2500:receive time out!\r\n");
CC2500_UNSELECT();
return -1;
}
}
CC2500_UNSELECT();
return (int)((unsigned int)total_bytes);
/*
for(i = 0; i < len; ++i)
buffer[i] = SPI2_RW(0xFF);
CC2500_UNSELECT();
CC2500_RX_MODE();
return len;
*/
}
int cc2500_send_packet(unsigned char len, unsigned char *buffer) {
unsigned char i;
unsigned char sendp, freespace_in_fifo;
if (len > MAX_PACKET_SIZE) {
printf("cc2500:packet size too large!\r\n");
return -1;
}
cc2500_cmd(CCxxx0_SIDLE);
cc2500_cmd(CCxxx0_SFTX); // flash tx fifo
sendp = (len < RFTXDBUFFSIZE) ? len : RFTXDBUFFSIZE;
CC2500_SELECT();
SPI2_RW(CCxxx0_TXFIFO_Muti);
SPI2_RW(len);
for(i = 0; i < sendp; ++i) {
SPI2_RW(buffer[i]);
}
CC2500_UNSELECT();
cc2500_cmd(CCxxx0_STX);
while (sendp < len) {
DELAY_US(20);
freespace_in_fifo = RFTXDBUFFSIZE - (cc2500_read_status(CCxxx0_TXBYTES) & 0x7F);
freespace_in_fifo = (len - sendp < freespace_in_fifo) ? (len - sendp) : freespace_in_fifo;
//printf("freespace in fifo %d\r\n", freespace_in_fifo);
CC2500_SELECT();
SPI2_RW(CCxxx0_TXFIFO_Muti);
for (i = 0; i < freespace_in_fifo; ++i)
SPI2_RW(buffer[sendp++]);
CC2500_UNSELECT();
}
while(!GDO0_IN()); //wait high
while(GDO0_IN()); //wait low, end send
//DELAY_MS(10); // no need
return 0;
}
| 2.078125 | 2 |
2024-11-18T22:37:19.838782+00:00 | 2021-09-02T08:52:31 | af905e3c14d407fea68c3bc1c17e256a6a87742f | {
"blob_id": "af905e3c14d407fea68c3bc1c17e256a6a87742f",
"branch_name": "refs/heads/work",
"committer_date": "2021-09-02T08:52:31",
"content_id": "18603d058eae7ac8037cd2d81304afde7846d28f",
"detected_licenses": [
"MIT"
],
"directory_id": "9888a5ad26e1f91dba099416294b5d322b728617",
"extension": "h",
"filename": "udp.h",
"fork_events_count": 0,
"gha_created_at": "2021-08-14T13:50:46",
"gha_event_created_at": "2021-09-04T08:51:56",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 396023081,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 891,
"license": "MIT",
"license_type": "permissive",
"path": "/udp.h",
"provenance": "stackv2-0107.json.gz:99377",
"repo_name": "atrn0/microps",
"revision_date": "2021-09-02T08:52:31",
"revision_id": "1ba8ce6e0229e7e505932df5c309fff9a5490d22",
"snapshot_id": "b8b1e42e8410b14675ed56ba110e384259ecf244",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/atrn0/microps/1ba8ce6e0229e7e505932df5c309fff9a5490d22/udp.h",
"visit_date": "2023-07-25T02:02:55.607829"
} | stackv2 | #ifndef UDP_H
#define UDP_H
#include <stddef.h>
#include <stdint.h>
#include "ip.h"
#define UDP_ENDPOINT_STR_LEN (IP_ADDR_STR_LEN + 6)
/* xxx.xxx.xxx.xxx:yyyyy\n */
struct udp_endpoint {
ip_addr_t addr;
uint16_t port;
};
extern int udp_endpoint_pton(const char *p, struct udp_endpoint *n);
extern char *udp_endpoint_ntop(const struct udp_endpoint *n, char *p,
size_t size);
extern ssize_t udp_output(struct udp_endpoint *src, struct udp_endpoint *dst,
const uint8_t *buf, size_t len);
extern int udp_open(void);
extern int udp_bind(int index, struct udp_endpoint *local);
extern ssize_t udp_sendto(int id, uint8_t *buf, size_t len, struct udp_endpoint *foreign);
extern ssize_t udp_recvfrom(int id, uint8_t *buf, size_t size, struct udp_endpoint *foreign);
extern int udp_close(int id);
extern int udp_init(void);
#endif
| 2.140625 | 2 |
2024-11-18T22:37:20.073955+00:00 | 2019-06-30T20:38:34 | 8704ed900651aaf554a0cacd82b4496653fc2598 | {
"blob_id": "8704ed900651aaf554a0cacd82b4496653fc2598",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-30T20:38:34",
"content_id": "7044e09ffff9bd8e02b7f1c4b65df1a8d71b6bb6",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "1485aeffa4957c4b8f72d976ece06a6da9454328",
"extension": "h",
"filename": "curlutil.h",
"fork_events_count": 0,
"gha_created_at": "2019-06-30T20:36:54",
"gha_event_created_at": "2019-06-30T20:36:54",
"gha_language": null,
"gha_license_id": null,
"github_id": 194559099,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 923,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/net_libcurl/src/curlutil.h",
"provenance": "stackv2-0107.json.gz:99635",
"repo_name": "alisiikh/samples",
"revision_date": "2019-06-30T20:38:34",
"revision_id": "3dc6b44937e1ab490340238b422413ba46ac01df",
"snapshot_id": "06902f9604e9b49db0b0c9018979d225860ac9e2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alisiikh/samples/3dc6b44937e1ab490340238b422413ba46ac01df/net_libcurl/src/curlutil.h",
"visit_date": "2020-06-13T05:47:22.075371"
} | stackv2 | #ifndef _CURLUTIL_H
#define _CURLUTIL_H
#include <stdio.h>
#include <malloc.h>
#include <curl/curl.h>
struct stringcurl
{
char *ptr;
size_t len;
};
void init_stringcurl(struct stringcurl *s) {
s->len = 0;
s->ptr = (char*)malloc(s->len+1);
if (s->ptr == NULL) {
fprintf(stderr, "malloc() failed\n");
return;
//exit(EXIT_FAILURE);
}
s->ptr[0] = '\0';
}
size_t curl_write_headers(void *ptr, size_t size, size_t nmemb, struct stringcurl *s) {
size_t new_len = s->len + size * nmemb;
s->ptr = (char *)realloc(s->ptr, new_len + 1);
if (s->ptr == NULL)
{
fprintf(stderr, "realloc() failed\n");
return 0;
}
memcpy(s->ptr + s->len, ptr, size * nmemb);
s->ptr[new_len] = '\0';
s->len = new_len;
return size * nmemb;
}
size_t curl_write_to_file(void *ptr, size_t size, size_t nmemb, void *stream) {
size_t written = sceIoWrite(*(int *)stream, ptr, size * nmemb);
return written;
}
#endif | 2.390625 | 2 |
2024-11-18T22:37:20.215321+00:00 | 2021-04-23T18:40:53 | fcc4522092d5cb6b0d4344340ac8eed8a533c8c9 | {
"blob_id": "fcc4522092d5cb6b0d4344340ac8eed8a533c8c9",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-23T18:40:53",
"content_id": "e914342fb0e89658a6eb635ace9a2582cd80584b",
"detected_licenses": [
"MIT"
],
"directory_id": "a37d6a5d606298f41eae3f70f82fd9b001f5bfc9",
"extension": "h",
"filename": "bl_section.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6792,
"license": "MIT",
"license_type": "permissive",
"path": "/core/bl_section.h",
"provenance": "stackv2-0107.json.gz:99767",
"repo_name": "hemi454/specter-bootloader",
"revision_date": "2021-04-23T18:40:53",
"revision_id": "6fa6157906dcb0018781432daac4a22e1bba86d7",
"snapshot_id": "927bfb304a6820714f6ceba1067fba39fa0d8aa9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hemi454/specter-bootloader/6fa6157906dcb0018781432daac4a22e1bba86d7/core/bl_section.h",
"visit_date": "2023-04-08T23:34:01.855843"
} | stackv2 | /**
* @file bl_section.h
* @brief Bootloader sections and operations on them
* @author Mike Tolkachev <contact@miketolkachev.dev>
* @copyright Copyright 2020 Crypto Advance GmbH. All rights reserved.
*/
#ifndef BL_SECTION_H_INCLUDED
/// Avoids multiple inclusion of the same file
#define BL_SECTION_H_INCLUDED
#include "bl_util.h"
#include "bl_syscalls.h"
/// Magic word, "SECT" in LE
#define BL_SECT_MAGIC 0x54434553UL
/// Structure revision
#define BL_SECT_STRUCT_REV 1U
/// Maximum allowed size of payload (16 megabytes)
#define BL_PAYLOAD_SIZE_MAX (16U * 1024U * 1024U)
/// Size of SHA-256 output
#define BL_HASH_SIZE 32U
/// Maximum size of string attribute including null character
#define BL_ATTR_STR_MAX (32U + 1U)
/// Maximum size of a signature message including terminating null character
#define BL_SIG_MSG_MAX (90U + 1U)
/// Type of unsigned integer attribute
typedef uint64_t bl_uint_t;
/// Attribute identifiers
typedef enum bl_attr_t {
bl_attr_algorithm = 1, ///< Digital signature algorithm, string
bl_attr_base_addr = 2, ///< Base address of firmware
bl_attr_entry_point = 3, ///< Entry point of firmware
bl_attr_platform = 4 ///< Platform identifier, string
} bl_attr_t;
/**
* Section header
*
* This structure has a fixed size of 256 bytes. All 32-bit words are stored in
* little-endian format. CRC is calculated over first 252 bytes of this
* structure.
* @return typedef struct
*/
typedef struct BL_ATTRS((packed)) bl_section_t {
uint32_t magic; ///< Magic word, BL_SECT_MAGIC (“SECT” in LE)
uint32_t struct_rev; ///< Revision of structure format
char name[16]; ///< Name, zero terminated, unused bytes are 0x00
uint32_t pl_ver; ///< Payload version, 0 if not available
uint32_t pl_size; ///< Payload size
uint32_t pl_crc; ///< Payload CRC
uint8_t attr_list[216]; ///< Attributes, list of: { key, size [, value] }
uint32_t struct_crc; ///< CRC of this structure using LE representation
} bl_section_t;
/// Hash of a payload section with additional information from section's header
typedef struct BL_ATTRS((packed)) bl_hash_t {
/// Digest calculated over the header and the payload
uint8_t digest[BL_HASH_SIZE];
/// Section name, zero terminated, unused bytes are 0x00
char sect_name[16];
/// Version of section's payload
uint32_t pl_ver;
} bl_hash_t;
#ifdef __cplusplus
extern "C" {
#endif
/**
* Validates header of the section
*
* @param p_hdr pointer to header
* @return true if successful
*/
bool blsect_validate_header(const bl_section_t* p_hdr);
/**
* Validates payload from memory
*
* @param p_hdr pointer to header, assumed to be valid
* @param pl_buf buffer containing payload
* @return true if paylad is valid
*/
bool blsect_validate_payload(const bl_section_t* p_hdr, const uint8_t* pl_buf);
/**
* Validates payload reading it from file
*
* This function expects that given file is open and its position indicator
* points to the beginning of payload. After successful execution, position
* indicator will be moved to the end of payload. If the function fails,
* resulting file position is undefined.
*
* @param p_hdr pointer to header, assumed to be valid
* @param file file with position set to beginning of the payload
* @param progr_arg argument passed to progress callback function
* @return true if paylad is valid
*/
bool blsect_validate_payload_from_file(const bl_section_t* p_hdr,
bl_file_t file, bl_cbarg_t progr_arg);
/**
* Validates payload reading it from flash memory
*
* @param p_hdr pointer to header, assumed to be valid
* @param addr starting address of payload in flash memory
* @param progr_arg argument passed to progress callback function
* @return true if paylad is valid
*/
bool blsect_validate_payload_from_flash(const bl_section_t* p_hdr,
bl_addr_t addr, bl_cbarg_t progr_arg);
/**
* Checks if the given section is a Payload section (contains firmware)
*
* @param p_hdr pointer to header, assumed to be valid
* @return true if the section contains firmware
*/
bool blsect_is_payload(const bl_section_t* p_hdr);
/**
* Checks if the given section is a Signature section
*
* @param p_hdr pointer to header, assumed to be valid
* @return true if the section contains signatures
*/
bool blsect_is_signature(const bl_section_t* p_hdr);
/**
* Gets attribute from header of "unsigned integer" type
*
* @param p_hdr pointer to header, assumed to be valid
* @param attr_id attribute identifier
* @param p_value pointer to variable, receiving attribute value
* @return true if successful
*/
bool blsect_get_attr_uint(const bl_section_t* p_hdr, bl_attr_t attr_id,
bl_uint_t* p_value);
/**
* Gets attribute from header of "string" type
*
* @param p_hdr pointer to header, assumed to be valid
* @param attr_id attribute identifier
* @param buf buffer where decoded null-terminated string will be placed
* @param buf_size size of provided buffer in bytes
* @return true if successful
*/
bool blsect_get_attr_str(const bl_section_t* p_hdr, bl_attr_t attr_id,
char* buf, size_t buf_size);
/**
* Calculates hash of a Payload section reading payload from flash memory
*
* @param p_hdr pointer to header, assumed to be valid
* @param pl_addr address of payload in flash memory
* @param p_result pointer to variable receiving produced hash
* @param progr_arg argument passed to progress callback function
* @return true if successful
*/
bool blsect_hash_over_flash(const bl_section_t* p_hdr, bl_addr_t pl_addr,
bl_hash_t* p_result, bl_cbarg_t progr_arg);
/**
* Creates a message to be used with signature algorithm from a set of section
* hashes
*
* The message is produced in Bech32 format having version information in
* its human readable part and a combined hash of all Payload sections in its
* data part.
*
* @param msg_buf buffer where produced message is placed
* @param p_msg_size pointer to variable holding capacity of the message
* buffer, filled with actual message size on return
* @param p_hashes input hash structures
* @param hash_items number of hash structures to process
* @return true if successful
*/
bool blsect_make_signature_message(uint8_t* msg_buf, size_t* p_msg_size,
const bl_hash_t* p_hashes,
size_t hash_items);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // BL_SECTION_H_INCLUDED
| 2.40625 | 2 |
2024-11-18T22:37:21.056424+00:00 | 2021-01-16T21:38:27 | 032888c2091d0234d35a416fcc4c657823b8e117 | {
"blob_id": "032888c2091d0234d35a416fcc4c657823b8e117",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-16T21:38:27",
"content_id": "676fddf5bd0b201e04d843db3d4bb7d98921773d",
"detected_licenses": [
"MIT"
],
"directory_id": "7f3b840df69fcb5fd6bda7d1a454ea193adc250b",
"extension": "c",
"filename": "user_data.c",
"fork_events_count": 7,
"gha_created_at": "2020-05-23T21:13:16",
"gha_event_created_at": "2021-01-16T21:38:28",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 266420480,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1021,
"license": "MIT",
"license_type": "permissive",
"path": "/external/wren/test/api/user_data.c",
"provenance": "stackv2-0107.json.gz:100026",
"repo_name": "canoi12/tinycoffee",
"revision_date": "2021-01-16T21:38:27",
"revision_id": "1711dac26586af4f873cc5fb45f213bfc1463ef5",
"snapshot_id": "a94c81b03b1132ed242b81da550fbaf1ae7bc23c",
"src_encoding": "UTF-8",
"star_events_count": 70,
"url": "https://raw.githubusercontent.com/canoi12/tinycoffee/1711dac26586af4f873cc5fb45f213bfc1463ef5/external/wren/test/api/user_data.c",
"visit_date": "2023-02-21T03:47:36.365293"
} | stackv2 | #include <string.h>
#include "user_data.h"
static const char* data = "my user data";
static const char* otherData = "other user data";
static void test(WrenVM* vm)
{
WrenConfiguration configuration;
wrenInitConfiguration(&configuration);
// Should default to NULL.
if (configuration.userData != NULL)
{
wrenSetSlotBool(vm, 0, false);
return;
}
configuration.userData = (void*)data;
WrenVM* otherVM = wrenNewVM(&configuration);
// Should be able to get it.
if (wrenGetUserData(otherVM) != data)
{
wrenSetSlotBool(vm, 0, false);
wrenFreeVM(otherVM);
return;
}
// Should be able to set it.
wrenSetUserData(otherVM, (void*)otherData);
if (wrenGetUserData(otherVM) != otherData)
{
wrenSetSlotBool(vm, 0, false);
wrenFreeVM(otherVM);
return;
}
wrenSetSlotBool(vm, 0, true);
wrenFreeVM(otherVM);
}
WrenForeignMethodFn userDataBindMethod(const char* signature)
{
if (strcmp(signature, "static UserData.test") == 0) return test;
return NULL;
}
| 2.421875 | 2 |
2024-11-18T22:37:21.119922+00:00 | 2020-05-20T12:25:52 | d2982f8f197572a4532ed872e43c2b9166854512 | {
"blob_id": "d2982f8f197572a4532ed872e43c2b9166854512",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-20T12:25:52",
"content_id": "3aaf22a8d34d5c5bb87d16f71c3c4d89d81d003c",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "4b385d948ae71eea5adf895dab17cc3249212401",
"extension": "h",
"filename": "rfc5444.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 260793132,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2237,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/crfc5444/rfc5444.h",
"provenance": "stackv2-0107.json.gz:100156",
"repo_name": "jeandudey/rust-rfc5444",
"revision_date": "2020-05-20T12:25:52",
"revision_id": "6c221378752441d3476e6b21bc05f77f2966e091",
"snapshot_id": "581460b3b24500b99a97735c397bb3080bf50e90",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jeandudey/rust-rfc5444/6c221378752441d3476e6b21bc05f77f2966e091/crfc5444/rfc5444.h",
"visit_date": "2022-07-26T19:37:55.523052"
} | stackv2 | /*
* Copyright 2020 Jean Pierre Dudey. See the LICENSE-MIT and
* LICENSE-APACHE files at the top-level directory of this
* distribution.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/
#ifndef RUST_RFC5444_H
#define RUST_RFC5444_H
/* Generated with cbindgen:0.14.2 */
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
/**
* @brief Supported RFC 5444 version.
*/
#define RFC5444_VERSION 0
/**
* @brief Packet header
*/
typedef struct {
/**
* Version
*/
uint8_t version;
/**
* Has a seq_num?
*/
bool has_seq_num;
/**
* Sequence number
*/
uint16_t seq_num;
/**
* Has a TLV block?
*/
bool has_tlv_block;
} rfc5444_pkt_header_t;
/**
* @brief Represents an slice of a buffer
*/
typedef struct {
/**
* Pointer to buffer
*/
const uint8_t *buf;
/**
* Buffer size
*/
uintptr_t buf_len;
} rfc5444_buf_t;
/**
* @brief Packet messages
*/
typedef struct {
/**
* Buffer containing the packet messages
*/
rfc5444_buf_t buf;
} rfc5444_messages_t;
/**
* @brief Representation of an RFC 5444 packet.
*/
typedef struct {
/**
* Packet header
*/
rfc5444_pkt_header_t hdr;
/**
* Packet messages
*/
rfc5444_messages_t messages;
} rfc5444_packet_t;
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
* @brief Read a single RFC 5444 packet.
*
* @pre `(buf != NULL) && (pkt != NULL)`
*
* @param[in] buf The buffer with the packet data to parse/read.
* @param[in] buf_len `buf` length in bytes.
* @param[out] pkt The parsed packet.
*
* @return 0 on successful parse.
* @return -EOF on unexpected end of file.
* @return -EINVAL on invalid packet.
*/
int rfc5444_read_packet(const uint8_t *buf,
size_t buf_len,
rfc5444_packet_t *pkt);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif /* RUST_RFC5444_H */
| 2.03125 | 2 |
2024-11-18T22:37:21.523485+00:00 | 2023-08-16T08:49:18 | d20fe921ec73f5853cfac63fd19f7f2432093980 | {
"blob_id": "d20fe921ec73f5853cfac63fd19f7f2432093980",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-16T08:49:18",
"content_id": "7398c7682e0f92e942063d050878be3e5ccafdc0",
"detected_licenses": [
"MIT"
],
"directory_id": "e3acfc4f06840e23ef1185dcf367f40d3e3f59b4",
"extension": "c",
"filename": "76-realloc.c",
"fork_events_count": 62,
"gha_created_at": "2011-07-18T15:10:56",
"gha_event_created_at": "2023-09-14T18:48:34",
"gha_language": "OCaml",
"gha_license_id": "MIT",
"github_id": 2066905,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 887,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/regression/02-base/76-realloc.c",
"provenance": "stackv2-0107.json.gz:100412",
"repo_name": "goblint/analyzer",
"revision_date": "2023-08-16T08:49:18",
"revision_id": "69ee7163eef0bfbfd6a4f3b9fda7cea5ce9ab79f",
"snapshot_id": "d62d3c610b86ed288849371b41c330c30678abc7",
"src_encoding": "UTF-8",
"star_events_count": 141,
"url": "https://raw.githubusercontent.com/goblint/analyzer/69ee7163eef0bfbfd6a4f3b9fda7cea5ce9ab79f/tests/regression/02-base/76-realloc.c",
"visit_date": "2023-08-16T21:58:53.013737"
} | stackv2 | // PARAM: --enable ana.race.free
#include <stdlib.h>
#include <goblint.h>
#include <pthread.h>
void test1_f() {
__goblint_check(1); // reachable
}
void test1() {
void (**fpp)(void) = malloc(sizeof(void(**)(void)));
*fpp = &test1_f;
fpp = realloc(fpp, sizeof(void(**)(void))); // same size
// (*fpp)();
void (*fp)(void) = *fpp;
fp(); // should call test1_f
}
void* test2_f(void *arg) {
int *p = arg;
*p = 1; // RACE!
return NULL;
}
void test2() {
int *p = malloc(sizeof(int));
pthread_t id;
pthread_create(&id, NULL, test2_f, p);
realloc(p, sizeof(int)); // RACE!
}
void* test3_f(void *arg) {
int *p = arg;
int x = *p; // RACE!
return NULL;
}
void test3() {
int *p = malloc(sizeof(int));
pthread_t id;
pthread_create(&id, NULL, test3_f, p);
realloc(p, sizeof(int)); // RACE!
}
int main() {
test1();
test2();
test3();
return 0;
}
| 2.75 | 3 |
2024-11-18T22:48:43.941878+00:00 | 2019-09-15T16:53:24 | cb4b52206bbba52ba0e06176580f2b0c9769d8ba | {
"blob_id": "cb4b52206bbba52ba0e06176580f2b0c9769d8ba",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-15T16:53:24",
"content_id": "4bbadc41609a013570b6bd4a00a2728871311c1d",
"detected_licenses": [
"MIT"
],
"directory_id": "d2a39f6cb758b7972b40c2ac9fef5e8922392c4f",
"extension": "h",
"filename": "parser_suite.h",
"fork_events_count": 0,
"gha_created_at": "2019-09-15T16:57:14",
"gha_event_created_at": "2019-09-15T16:57:15",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 208626454,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5633,
"license": "MIT",
"license_type": "permissive",
"path": "/test/parser_suite.h",
"provenance": "stackv2-0108.json.gz:75816",
"repo_name": "Minichota/nothing",
"revision_date": "2019-09-15T16:53:24",
"revision_id": "6d0f1d4843fd0f87f3495fcf89783c631e384a71",
"snapshot_id": "083f7e464de20f732642fdc4798fcb7e9219ede3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Minichota/nothing/6d0f1d4843fd0f87f3495fcf89783c631e384a71/test/parser_suite.h",
"visit_date": "2020-07-26T11:15:22.802017"
} | stackv2 | #ifndef PARSER_SUITE_H_
#define PARSER_SUITE_H_
#include "test.h"
#include "ebisp/parser.h"
#include "ebisp/gc.h"
#include "ebisp/builtins.h"
TEST(read_expr_from_file_test)
{
Gc *gc = create_gc();
struct ParseResult result = read_expr_from_file(gc, "test-data/simple-sum.ebi");
ASSERT_TRUE(!result.is_error, {
fprintf(stderr,
"Parsing failed: %s",
result.error_message);
});
struct Expr head = result.expr;
struct Expr expr = head;
ASSERT_INTEQ(EXPR_CONS, expr.type);
ASSERT_INTEQ(EXPR_ATOM, expr.cons->car.type);
ASSERT_INTEQ(ATOM_SYMBOL, expr.cons->car.atom->type);
ASSERT_STREQ("+", expr.cons->car.atom->sym);
expr = expr.cons->cdr;
ASSERT_INTEQ(EXPR_CONS, expr.type);
ASSERT_INTEQ(EXPR_ATOM, expr.cons->car.type);
ASSERT_INTEQ(ATOM_NUMBER, expr.cons->car.atom->type);
ASSERT_LONGINTEQ(1L, expr.cons->car.atom->num);
expr = expr.cons->cdr;
ASSERT_INTEQ(EXPR_CONS, expr.type);
ASSERT_INTEQ(EXPR_ATOM, expr.cons->car.type);
ASSERT_INTEQ(ATOM_NUMBER, expr.cons->car.atom->type);
ASSERT_LONGINTEQ(2L, expr.cons->car.atom->num);
expr = expr.cons->cdr;
ASSERT_INTEQ(EXPR_CONS, expr.type);
ASSERT_INTEQ(EXPR_ATOM, expr.cons->car.type);
ASSERT_INTEQ(ATOM_NUMBER, expr.cons->car.atom->type);
ASSERT_LONGINTEQ(3L, expr.cons->car.atom->num);
expr = expr.cons->cdr;
ASSERT_INTEQ(EXPR_ATOM, expr.type);
ASSERT_INTEQ(ATOM_SYMBOL, expr.atom->type);
ASSERT_STREQ("nil", expr.atom->sym);
destroy_gc(gc);
return 0;
}
TEST(parse_negative_numbers_test)
{
Gc *gc = create_gc();
struct ParseResult result = read_expr_from_string(gc, "-12345");
ASSERT_FALSE(result.is_error, {
fprintf(stderr, "Parsing failed: %s", result.error_message);
});
ASSERT_EQ(enum ExprType, EXPR_ATOM, result.expr.type, {
fprintf(stderr, "Expected: %s\n", expr_type_as_string(_expected));
fprintf(stderr, "Actual: %s\n", expr_type_as_string(_actual));
});
ASSERT_EQ(enum AtomType, ATOM_NUMBER, result.expr.atom->type, {
fprintf(stderr, "Expected: %s\n", atom_type_as_string(_expected));
fprintf(stderr, "Actual: %s\n", atom_type_as_string(_actual));
});
ASSERT_LONGINTEQ(-12345L, result.expr.atom->num);
destroy_gc(gc);
return 0;
}
TEST(read_all_exprs_from_string_empty_test)
{
Gc *gc = create_gc();
struct ParseResult result = read_all_exprs_from_string(gc, "");
ASSERT_FALSE(result.is_error, {
fprintf(stderr,
"Parsing was unsuccessful: %s\n",
result.error_message);
});
ASSERT_EQ(long int, 0, length_of_list(result.expr), {
fprintf(stderr, "Expected: %ld\n", _expected);
fprintf(stderr, "Actual: %ld\n", _actual);
fprintf(stderr, "Expression: ");
print_expr_as_sexpr(stderr, result.expr);
fprintf(stderr, "\n");
});
destroy_gc(gc);
return 0;
}
TEST(read_all_exprs_from_string_one_test)
{
Gc *gc = create_gc();
struct ParseResult result = read_all_exprs_from_string(gc, "(+ 1 2)");
ASSERT_FALSE(result.is_error, {
fprintf(stderr,
"Parsing was unsuccessful: %s\n",
result.error_message);
});
ASSERT_EQ(long int, 1, length_of_list(result.expr), {
fprintf(stderr, "Expected: %ld\n", _expected);
fprintf(stderr, "Actual: %ld\n", _actual);
fprintf(stderr, "Expression: ");
print_expr_as_sexpr(stderr, result.expr);
fprintf(stderr, "\n");
});
destroy_gc(gc);
return 0;
}
TEST(read_all_exprs_from_string_two_test)
{
Gc *gc = create_gc();
struct ParseResult result = read_all_exprs_from_string(
gc,
"(+ 1 2) (+ 3 4)");
ASSERT_FALSE(result.is_error, {
fprintf(stderr,
"Parsing was unsuccessful: %s\n",
result.error_message);
});
ASSERT_EQ(long int, 2, length_of_list(result.expr), {
fprintf(stderr, "Expected: %ld\n", _expected);
fprintf(stderr, "Actual: %ld\n", _actual);
fprintf(stderr, "Expression: ");
print_expr_as_sexpr(stderr, result.expr);
fprintf(stderr, "\n");
});
destroy_gc(gc);
return 0;
}
TEST(read_all_exprs_from_string_bad_test)
{
Gc *gc = create_gc();
struct ParseResult result = read_all_exprs_from_string(
gc,
"(+ 1 2) + 3 4)");
ASSERT_TRUE(result.is_error, {
fprintf(stderr, "Parsing didn't fail as expected\n");
});
destroy_gc(gc);
return 0;
}
TEST(read_all_exprs_from_string_trailing_spaces_test)
{
Gc *gc = create_gc();
const char *source_code = "5 ";
struct ParseResult result = read_all_exprs_from_string(gc, source_code);
ASSERT_FALSE(result.is_error, {
fprintf(stderr, "Parsing failed: %s\n", result.error_message);
fprintf(stderr, "Position: %zd\n", result.end - source_code);
});
return 0;
}
TEST_SUITE(parser_suite)
{
TEST_RUN(read_expr_from_file_test);
TEST_RUN(parse_negative_numbers_test);
TEST_RUN(read_all_exprs_from_string_empty_test);
TEST_RUN(read_all_exprs_from_string_one_test);
TEST_RUN(read_all_exprs_from_string_two_test);
// TODO(#467): read_all_exprs_from_string_bad_test is failing
TEST_IGNORE(read_all_exprs_from_string_bad_test);
TEST_RUN(read_all_exprs_from_string_trailing_spaces_test);
return 0;
}
#endif // PARSER_SUITE_H_
| 2.515625 | 3 |
2024-11-18T22:48:44.167972+00:00 | 2023-06-28T23:23:07 | 7e12ece9f06e4adb5524789ce47386fd6ba44454 | {
"blob_id": "7e12ece9f06e4adb5524789ce47386fd6ba44454",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-28T23:23:07",
"content_id": "276379c8114d4c591701307aa9478b3e59aa6501",
"detected_licenses": [
"MIT"
],
"directory_id": "7ca15701b9543f778930907d63fcd5ca344354e5",
"extension": "h",
"filename": "gestures.h",
"fork_events_count": 35,
"gha_created_at": "2019-09-14T20:43:57",
"gha_event_created_at": "2023-06-28T23:23:08",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 208501458,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4870,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gestures.h",
"provenance": "stackv2-0108.json.gz:76075",
"repo_name": "janet-lang/jaylib",
"revision_date": "2023-06-28T23:23:07",
"revision_id": "f62fb0d9bc780c1095a9d5ac7e4c380eebacc0a1",
"snapshot_id": "e43f6819d68a3528c4f96f2e69be03f6d4e58b33",
"src_encoding": "UTF-8",
"star_events_count": 103,
"url": "https://raw.githubusercontent.com/janet-lang/jaylib/f62fb0d9bc780c1095a9d5ac7e4c380eebacc0a1/src/gestures.h",
"visit_date": "2023-07-07T00:59:11.507171"
} | stackv2 | static int jaylib_getgesture(const Janet *argv, int32_t n) {
const uint8_t *kw = janet_getkeyword(argv, n);
if (!janet_cstrcmp(kw, "tap")) {
return GESTURE_TAP;
} else if (!janet_cstrcmp(kw, "double-tap")) {
return GESTURE_DOUBLETAP;
} else if (!janet_cstrcmp(kw, "hold")) {
return GESTURE_HOLD;
} else if (!janet_cstrcmp(kw, "drag")) {
return GESTURE_DRAG;
} else if (!janet_cstrcmp(kw, "swipe-right")) {
return GESTURE_SWIPE_RIGHT;
} else if (!janet_cstrcmp(kw, "swipe-left")) {
return GESTURE_SWIPE_LEFT;
} else if (!janet_cstrcmp(kw, "swipe-up")) {
return GESTURE_SWIPE_UP;
} else if (!janet_cstrcmp(kw, "swipe-down")) {
return GESTURE_SWIPE_DOWN;
} else if (!janet_cstrcmp(kw, "pinch-in")) {
return GESTURE_PINCH_IN;
} else if (!janet_cstrcmp(kw, "pinch-out")) {
return GESTURE_PINCH_OUT;
} else {
janet_panicf("unknown gesture %v", argv[n]);
}
}
static Janet cfun_SetGesturesEnabled(int32_t argc, Janet *argv) {
unsigned int flags = 0;
for (int32_t i = 0; i < argc; i++)
flags |= jaylib_getgesture(argv, i);
SetGesturesEnabled(flags);
return janet_wrap_nil();
}
static Janet cfun_IsGestureDetected(int32_t argc, Janet *argv) {
janet_fixarity(argc, 1);
int gesture = jaylib_getgesture(argv, 0);
return janet_wrap_boolean(IsGestureDetected(gesture));
}
static Janet cfun_GetGestureDetected(int32_t argc, Janet *argv) {
(void) argv;
janet_fixarity(argc, 0);
switch (GetGestureDetected()) {
default:
case GESTURE_NONE:
return janet_wrap_nil();
case GESTURE_TAP:
return janet_ckeywordv("tap");
case GESTURE_DOUBLETAP:
return janet_ckeywordv("double-tap");
case GESTURE_HOLD:
return janet_ckeywordv("hold");
case GESTURE_DRAG:
return janet_ckeywordv("drag");
case GESTURE_SWIPE_RIGHT:
return janet_ckeywordv("swipe-right");
case GESTURE_SWIPE_LEFT:
return janet_ckeywordv("swipe-left");
case GESTURE_SWIPE_UP:
return janet_ckeywordv("swipe-up");
case GESTURE_SWIPE_DOWN:
return janet_ckeywordv("swipe-down");
case GESTURE_PINCH_IN:
return janet_ckeywordv("pinch-in");
case GESTURE_PINCH_OUT:
return janet_ckeywordv("pinch-out");
}
}
static Janet cfun_GetTouchPointCount(int32_t argc, Janet *argv) {
(void) argv;
janet_fixarity(argc, 0);
return janet_wrap_integer(GetTouchPointCount());
}
static Janet cfun_GetGestureHoldDuration(int32_t argc, Janet *argv) {
(void) argv;
janet_fixarity(argc, 0);
return janet_wrap_number((double) GetGestureHoldDuration());
}
static Janet cfun_GetGestureDragVector(int32_t argc, Janet *argv) {
(void) argv;
janet_fixarity(argc, 0);
return jaylib_wrap_vec2(GetGestureDragVector());
}
static Janet cfun_GetGestureDragAngle(int32_t argc, Janet *argv) {
(void) argv;
janet_fixarity(argc, 0);
return janet_wrap_number((double) GetGestureDragAngle());
}
static Janet cfun_GetGesturePinchVector(int32_t argc, Janet *argv) {
(void) argv;
janet_fixarity(argc, 0);
return jaylib_wrap_vec2(GetGesturePinchVector());
}
static Janet cfun_GetGesturePinchAngle(int32_t argc, Janet *argv) {
(void) argv;
janet_fixarity(argc, 0);
return janet_wrap_number((double) GetGesturePinchAngle());
}
static JanetReg gesture_cfuns[] = {
{"set-gestures-enabled", cfun_SetGesturesEnabled,
"(set-gestures-enabled flags)\n\n"
"Enable a set of gestures using flags"
},
{"gesture-detected?", cfun_IsGestureDetected,
"(gesture-detected? gesture)\n\n"
"Check if a gesture have been detected"
},
{"get-gesture-detected", cfun_GetGestureDetected,
"(get-gesture-detected)\n\n"
"Get latest detected gesture"
},
{"get-touch-point-count", cfun_GetTouchPointCount,
"(get-touch-point-count)\n\n"
"Get number of touch points"
},
{"get-gesture-hold-duration", cfun_GetGestureHoldDuration,
"(get-gesture-hold-duration)\n\n"
"Get gesture hold time in milliseconds"
},
{"get-gesture-drag-vector", cfun_GetGestureDragVector,
"(get-gesture-drag-vector)\n\n"
"Get gesture drag vector"
},
{"get-gesture-drag-angle", cfun_GetGestureDragAngle,
"(get-gesture-drag-angle)\n\n"
"Get gesture drag angle"
},
{"get-gesture-pinch-vector", cfun_GetGesturePinchVector,
"(get-gesture-pinch-vector)\n\n"
"Get gesture pinch delta"
},
{"get-gesture-pinch-angle", cfun_GetGesturePinchAngle,
"(get-gesture-pinch-angle)\n\n"
"Get gesture pinch angle"
},
{NULL, NULL, NULL}
};
| 2 | 2 |
2024-11-18T22:48:44.529475+00:00 | 2021-10-03T21:42:43 | 5b5dbb4d8b24d07e1ffc5eb432df4a004e27a95f | {
"blob_id": "5b5dbb4d8b24d07e1ffc5eb432df4a004e27a95f",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-03T21:42:43",
"content_id": "0fc19f02f4a6b2c76368e26804cd4ca7a86d194d",
"detected_licenses": [
"Unlicense"
],
"directory_id": "1cbfacf883eae11cc1b33bd1301e74e22f4d99a4",
"extension": "h",
"filename": "philo.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 343532271,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2992,
"license": "Unlicense",
"license_type": "permissive",
"path": "/philo/include/philo.h",
"provenance": "stackv2-0108.json.gz:76333",
"repo_name": "Victor-Akio/Philosofers-42",
"revision_date": "2021-10-03T21:42:43",
"revision_id": "9da39b1fcdc74d9c07b6822b4f2fc83666101c04",
"snapshot_id": "1259c30e4385c7c395cdca3ec32d3890ac1a6307",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Victor-Akio/Philosofers-42/9da39b1fcdc74d9c07b6822b4f2fc83666101c04/philo/include/philo.h",
"visit_date": "2023-08-02T22:04:49.230068"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vminomiy <vminomiy@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/08 23:10:38 by vminomiy #+# #+# */
/* Updated: 2021/09/15 02:11:38 by vminomiy ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef PHILO_H
# define PHILO_H
# include <string.h>
# include <stdio.h>
# include <unistd.h>
# include <fcntl.h>
# include <stdlib.h>
# include <stddef.h>
# include <errno.h>
# include <sys/types.h>
# include <sys/time.h>
# include <stdbool.h>
# include <pthread.h>
/*
** As requested by the subject, the following options should be set as:
**
** p_num == number_of_philosophers;
** t_die == time_to_die;
** t_eat == time_to_eat;
** t_slp == time_to_sleep;
** t_meal == number_of_times_each_philosopher_must_eat;
*/
typedef struct timeval t_timeval;
typedef struct s_table
{
int n;
t_timeval start;
t_timeval t_die;
t_timeval t_eat;
t_timeval t_slp;
int t_meal;
} t_table;
typedef struct s_philo
{
int alive;
pthread_t thread;
pthread_mutex_t *r_fork;
pthread_mutex_t *l_fork;
pthread_mutex_t take_fork;
pthread_mutex_t drop_fork;
pthread_mutex_t death;
pthread_mutex_t *init;
pthread_mutex_t *timestamp;
int idx;
int fed;
unsigned int locks;
t_table *table;
t_timeval last_feed;
} t_philo;
typedef struct s_monitor
{
t_table *table;
t_philo *philo;
int idx;
pthread_mutex_t *forks;
int *queue;
int work;
pthread_mutex_t init;
pthread_mutex_t food;
pthread_mutex_t timestamp;
} t_monitor;
typedef struct s_status
{
int state;
pthread_mutex_t mutex;
} t_status;
int ft_atoi(const char *str);
int ft_aredigit(char *str);
void *ft_memset(void *b, int c, size_t len);
int init_table(t_table *table, int ac, char **av);
int memalloc_struct(t_table **table, t_monitor **monitor, int n);
int validate_args(char **av);
void init_queue(t_monitor *monitor);
void init_monitor(t_monitor *monitor);
void help(void);
void init_phi(t_monitor *monitor);
void *routine(void *philosofer);
unsigned long current_time(struct timeval *t1, struct timeval *t2);
unsigned long timeval_to_usec(struct timeval timeval);
void take_forks(t_philo *phi);
void *end_dinner(t_monitor *monitor);
void *food_manager(void *monitor);
void *monitor_manager(void *monitor);
void display(t_philo *phi, char flag);
#endif
| 2.25 | 2 |
2024-11-18T22:48:44.681632+00:00 | 2023-03-22T03:05:00 | 72356ff0cb95215dce2c837af6aa01fdaed51cc9 | {
"blob_id": "72356ff0cb95215dce2c837af6aa01fdaed51cc9",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-22T03:05:00",
"content_id": "2dcb7f177959b5d941f584e97095c0258a40547f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c434f0466868b5d7b38ae344dca0abf620045faf",
"extension": "c",
"filename": "main.c",
"fork_events_count": 11,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 122421022,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8857,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/SampleCode/RegBased/CLK_ClockDetector/main.c",
"provenance": "stackv2-0108.json.gz:76595",
"repo_name": "OpenNuvoton/M451BSP",
"revision_date": "2023-03-22T03:05:00",
"revision_id": "835ded99dec3776db16015b7c0ae155d7877e2fd",
"snapshot_id": "bf950163a1c4ba87e64b7d6d4a50c1e5c7956471",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/OpenNuvoton/M451BSP/835ded99dec3776db16015b7c0ae155d7877e2fd/SampleCode/RegBased/CLK_ClockDetector/main.c",
"visit_date": "2023-04-15T22:25:26.377643"
} | stackv2 | /**************************************************************************//**
* @file main.c
* @version V3.00
* $Revision: 11 $
* $Date: 15/09/02 10:03a $
* @brief Show the usage of clock fail detector and clock frequency monitor function.
* @note
* Copyright (C) 2013~2015 Nuvoton Technology Corp. All rights reserved.
*
******************************************************************************/
#include "stdio.h"
#include "M451Series.h"
#define PLLCTL_SETTING CLK_PLLCTL_72MHz_HXT
#define PLL_CLOCK 72000000
extern char GetChar(void);
/*---------------------------------------------------------------------------------------------------------*/
/* Clock Fail Detector IRQ Handler */
/*---------------------------------------------------------------------------------------------------------*/
void CLKFAIL_IRQHandler(void)
{
uint32_t u32Reg, u32TimeOutCnt;
/* Unlock protected registers */
SYS_UnlockReg();
u32Reg = CLK->CLKDSTS;
if(u32Reg & CLK_CLKDSTS_HXTFIF_Msk)
{
/* HCLK is switched to HIRC automatically if HXT clock fail interrupt is happened */
printf("HXT Clock is stopped! HCLK is switched to HIRC.\n");
/* Disable HXT clock fail interrupt */
CLK->CLKDCTL &= ~(CLK_CLKDCTL_HXTFDEN_Msk | CLK_CLKDCTL_HXTFIEN_Msk);
/* Write 1 to clear HXT Clock fail interrupt flag */
CLK->CLKDSTS = CLK_CLKDSTS_HXTFIF_Msk;
}
if(u32Reg & CLK_CLKDSTS_LXTFIF_Msk)
{
/* LXT clock fail interrupt is happened */
printf("LXT Clock is stopped!\n");
/* Disable LXT clock fail interrupt */
CLK->CLKDCTL &= ~(CLK_CLKDCTL_LXTFIEN_Msk | CLK_CLKDCTL_LXTFDEN_Msk);
/* Write 1 to clear LXT Clock fail interrupt flag */
CLK->CLKDSTS = CLK_CLKDSTS_LXTFIF_Msk;
}
if(u32Reg & CLK_CLKDSTS_HXTFQIF_Msk)
{
/* HCLK should be switched to HIRC if HXT clock frequency monitor interrupt is happened */
CLK->PWRCTL |= CLK_PWRCTL_HIRCEN_Msk;
u32TimeOutCnt = SystemCoreClock; /* 1 second time-out */
while(!(CLK->STATUS & CLK_STATUS_HIRCSTB_Msk))
if(--u32TimeOutCnt == 0) break;
CLK->CLKSEL0 = (CLK->CLKSEL0 & (~CLK_CLKSEL0_HCLKSEL_Msk)) | CLK_CLKSEL0_HCLKSEL_HIRC;
printf("HXT Frequency is abnormal! HCLK is switched to HIRC.\n");
/* Disable HXT clock frequency monitor interrupt */
CLK->CLKDCTL &= ~(CLK_CLKDCTL_HXTFQDEN_Msk | CLK_CLKDCTL_HXTFQIEN_Msk);
/* Write 1 to clear HXT Clock frequency monitor interrupt */
CLK->CLKDSTS = CLK_CLKDSTS_HXTFQIF_Msk;
}
/* Lock protected registers */
SYS_LockReg();
}
void SYS_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init System Clock */
/*---------------------------------------------------------------------------------------------------------*/
/* Enable HIRC, HXT and LXT clock */
CLK->PWRCTL |= CLK_PWRCTL_HIRCEN_Msk;
CLK->PWRCTL |= CLK_PWRCTL_HXTEN_Msk;
CLK->PWRCTL |= CLK_PWRCTL_LXTEN_Msk;
/* Wait for HIRC, HXT and LXT clock ready */
while(!(CLK->STATUS & CLK_STATUS_HIRCSTB_Msk));
while(!(CLK->STATUS & CLK_STATUS_HXTSTB_Msk));
while(!(CLK->STATUS & CLK_STATUS_LXTSTB_Msk));
/* Select HCLK clock source as HIRC and HCLK clock divider as 1 */
CLK->CLKSEL0 = (CLK->CLKSEL0 & (~CLK_CLKSEL0_HCLKSEL_Msk)) | CLK_CLKSEL0_HCLKSEL_HIRC;
CLK->CLKDIV0 = (CLK->CLKDIV0 & (~CLK_CLKDIV0_HCLKDIV_Msk)) | CLK_CLKDIV0_HCLK(1);
/* Set PLL to Power-down mode */
CLK->PLLCTL |= CLK_PLLCTL_PD_Msk;
/* Set core clock as PLL_CLOCK from PLL */
CLK->PLLCTL = PLLCTL_SETTING;
while(!(CLK->STATUS & CLK_STATUS_PLLSTB_Msk));
CLK->CLKSEL0 = (CLK->CLKSEL0 & (~CLK_CLKSEL0_HCLKSEL_Msk)) | CLK_CLKSEL0_HCLKSEL_PLL;
/* Update System Core Clock */
PllClock = PLL_CLOCK; // PLL
SystemCoreClock = PLL_CLOCK / 1; // HCLK
CyclesPerUs = PLL_CLOCK / 1000000; // For CLK_SysTickDelay()
/* Enable UART module clock */
CLK->APBCLK0 |= CLK_APBCLK0_UART0CKEN_Msk;
/* Select UART module clock source as HIRC and UART module clock divider as 1 */
CLK->CLKSEL1 = (CLK->CLKSEL1 & (~CLK_CLKSEL1_UARTSEL_Msk)) | CLK_CLKSEL1_UARTSEL_HIRC;
CLK->CLKDIV0 = (CLK->CLKDIV0 & (~CLK_CLKDIV0_UARTDIV_Msk)) | CLK_CLKDIV0_UART(1);
/*---------------------------------------------------------------------------------------------------------*/
/* Init I/O Multi-function */
/*---------------------------------------------------------------------------------------------------------*/
/* Set PD multi-function pins for UART0 RXD(PD.0) and TXD(PD.1) */
SYS->GPD_MFPL &= ~(SYS_GPD_MFPL_PD0MFP_Msk | SYS_GPD_MFPL_PD1MFP_Msk);
SYS->GPD_MFPL |= (SYS_GPD_MFPL_PD0MFP_UART0_RXD | SYS_GPD_MFPL_PD1MFP_UART0_TXD);
/* Set PC multi-function pins for CLKO(PC.1) */
SYS->GPC_MFPL &= ~SYS_GPC_MFPL_PC1MFP_Msk;
SYS->GPC_MFPL |= SYS_GPC_MFPL_PC1MFP_CLKO;
/* Set PF multi-function pins for X32_OUT(PF.0) and X32_IN(PF.1) */
SYS->GPF_MFPL &= ~(SYS_GPF_MFPL_PF0MFP_Msk | SYS_GPF_MFPL_PF1MFP_Msk);
SYS->GPF_MFPL |= SYS_GPF_MFPL_PF0MFP_X32_OUT | SYS_GPF_MFPL_PF1MFP_X32_IN;
}
void UART0_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init UART */
/*---------------------------------------------------------------------------------------------------------*/
/* Reset UART0 */
SYS->IPRST1 |= SYS_IPRST1_UART0RST_Msk;
SYS->IPRST1 &= ~SYS_IPRST1_UART0RST_Msk;
/* Configure UART0 and set UART0 baud rate */
UART0->BAUD = UART_BAUD_MODE2 | UART_BAUD_MODE2_DIVIDER(__HIRC, 115200);
UART0->LINE = UART_WORD_LEN_8 | UART_PARITY_NONE | UART_STOP_BIT_1;
}
/*---------------------------------------------------------------------------------------------------------*/
/* Main Function */
/*---------------------------------------------------------------------------------------------------------*/
int32_t main(void)
{
/* Unlock protected registers */
SYS_UnlockReg();
/* Init System, peripheral clock and multi-function I/O */
SYS_Init();
/* Lock protected registers */
SYS_LockReg();
/* Init UART0 for printf */
UART0_Init();
printf("\n\nCPU @ %d Hz\n", SystemCoreClock);
printf("+-------------------------------------------------------------+\n");
printf("| M451 Clock Detector Sample Code |\n");
printf("+-------------------------------------------------------------+\n");
printf("| 1. HXT clock fail interrupt will happen if HXT is stopped. |\n");
printf("| HCLK clock source will be switched from HXT to HIRC. |\n");
printf("| 2. LXT clock fail interrupt will happen if LXT is stopped. |\n");
printf("+-------------------------------------------------------------+\n");
printf("\nStop HXT or LXT to test.\n\n");
/* Enable clock output, select CLKO clock source as HCLK and set clock output frequency is HCLK/4.
HCLK clock source will be switched to HIRC if HXT stop and HCLK clock source is from HXT.
You can check if HCLK clock source is switched to HIRC by clock output pin output frequency.
*/
/* Enable CKO clock source */
CLK->APBCLK0 |= CLK_APBCLK0_CLKOCKEN_Msk;
/* CKO = clock source / 2^(1 + 1) */
CLK->CLKOCTL = CLK_CLKOCTL_CLKOEN_Msk | (1);
/* Select CLKO clock source as HCLK */
CLK->CLKSEL1 = (CLK->CLKSEL1 & (~CLK_CLKSEL1_CLKOSEL_Msk)) | CLK_CLKSEL1_CLKOSEL_HCLK;
/* Set the HXT clock frequency monitor upper and lower boundary value.
The upper boundary value should be more than 512*(HXT/HIRC).
The low boundary value should be less than 512*(HXT/HIRC).
*/
CLK->CDUPB = 278;
CLK->CDLOWB = 277;
/* Set clock fail detector function enabled and interrupt enabled */
CLK->CLKDCTL = CLK_CLKDCTL_HXTFDEN_Msk |
CLK_CLKDCTL_HXTFIEN_Msk |
CLK_CLKDCTL_LXTFDEN_Msk |
CLK_CLKDCTL_LXTFIEN_Msk |
CLK_CLKDCTL_HXTFQDEN_Msk |
CLK_CLKDCTL_HXTFQIEN_Msk;
/* Enable clock fail detector interrupt */
NVIC_EnableIRQ(CKFAIL_IRQn);
/* Wait for clock fail detector interrupt happened */
while(1);
}
| 2.34375 | 2 |
2024-11-18T22:48:45.159739+00:00 | 2019-10-20T23:12:12 | c0f5253a56ead12ef503d020e575c7e4b6b69ffd | {
"blob_id": "c0f5253a56ead12ef503d020e575c7e4b6b69ffd",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-20T23:12:12",
"content_id": "06755c9d962ee5e55104b26ea6b008ad3f46196a",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "0c08cf8b7b9827b91e0cbf91356b7381905c9963",
"extension": "c",
"filename": "iaslverchk.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3004,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/MinnowTools/iaslverchk.c",
"provenance": "stackv2-0108.json.gz:76984",
"repo_name": "listenli1213/edk2-vUDK2018",
"revision_date": "2019-10-20T23:12:12",
"revision_id": "66f72685c07e42dc1caf7473e81d9655a7365033",
"snapshot_id": "12283cda873a610a2651aa65a6f4c874dc498f68",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/listenli1213/edk2-vUDK2018/66f72685c07e42dc1caf7473e81d9655a7365033/MinnowTools/iaslverchk.c",
"visit_date": "2023-03-20T14:23:45.333293"
} | stackv2 | /*!
@copyright
Copyright (c) 2019, MinnowWare. All rights reserved.
This program and the accompanying materials are licensed and made
available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license
may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@file IaslVerChk.c
@brief check build system, if c:\asl\IASL.EXE version 20160527-32 is installed and available
@details check build system, if c:\asl\IASL.EXE version 20160527-32 is installed and available
@todo
@mainpage
IaslVerChk support tool
@section intro_sec Introduction
IaslVerChk checks the installed IASL version to support "submodule"
@subsection Parm_sec Command line parameters
1. unarchive file1 file2 dir1 dir2
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int nRet = 0;
int nMajor, t;
int iVerbose = 0, iHelp = 0, i,c;
char buffer[256];
do {
for (i = 1; i < argc; i++) {
if (0 == strcmp(argv[i], "-h") ||
0 == strcmp(argv[i], "/h") ||
0 == strcmp(argv[i], "--h") ||
0 == strcmp(argv[i], "--help")
)iHelp = i;
if (0 == strcmp(argv[i], "-verbose"))
iVerbose = i;
}
if (argc > 1){
if (iHelp) {
printf("IaslVerChk - Iasl version check\nusage: iaslverchk (w/o parameter) -- version check\n iaslverchk -h -- help screen\n iaslverchk -verbose -- verbose mode, print version match message\n");
break;
}
}
if (argc > 1 && 0 == strcmp(argv[1], "2831DEBC-DB3B-43D2-9635-E6464933C898")) {
char* versionstrings[]={ {"Intel"},{"ACPI"},{"Component"},{"Architecture"},{"ASL+"},{"Optimizing"},{"Compiler"},{"version"},{"20160527-32"} };
for (i = 0; i < sizeof(versionstrings) / sizeof(versionstrings[0]); i++) {
scanf("%s", buffer);
if (0 != strcmp(versionstrings[i], buffer)) {
//printf("DIFF\n");
nRet = 1000;
break;
}
}
if (1000 == nRet) {
fprintf(stderr, "WARNING: IASL v20160527 shall be used.\n https://acpica.org/sites/acpica/files/iasl-win-20160527.zip\n");
nRet = 1;
}
} else {
nRet = system("c:\\asl\\iasl.exe -v | iaslverchk.exe 2831DEBC-DB3B-43D2-9635-E6464933C898");
}
} while (0);
if (nRet != 0/*keep the messages on screen for a moment in case of error*/) {
system("ping 127.0.0.0 > nul");
}
else if (0 != iVerbose)
printf("IASL version accepted.\n");
return nRet;
} | 2.375 | 2 |
2024-11-18T22:48:45.355818+00:00 | 2020-10-06T06:40:27 | 8368b0215d222a209ea4cf24991c17fe622608b4 | {
"blob_id": "8368b0215d222a209ea4cf24991c17fe622608b4",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-06T06:40:27",
"content_id": "2926c828efb92c3e7e5eb15b2d3af1279beb83d8",
"detected_licenses": [
"MIT"
],
"directory_id": "9ae7bd9c5892aa1d313fb1685dc0d79b1c4a66d1",
"extension": "c",
"filename": "search.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 288870208,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2902,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/search.c",
"provenance": "stackv2-0108.json.gz:77112",
"repo_name": "levonhart/binpack",
"revision_date": "2020-10-06T06:40:27",
"revision_id": "1065a449924f8c9dfb1ede05d45bbc93e6f3d868",
"snapshot_id": "0f5eaaea0dcd229bfef337e39ddedc01d8f2008f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/levonhart/binpack/1065a449924f8c9dfb1ede05d45bbc93e6f3d868/tests/search.c",
"visit_date": "2022-12-26T23:17:45.600193"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "binpack.h"
int main(int argc, char *argv[]){
int c = 1000;
int n = 60;
int items[] = { 495, 474, 473, 472, 466, 450, 445, 444, 439, 430, 419, 414,
410, 395, 372, 370, 366, 366, 366, 363, 361, 357, 355, 351,
350, 350, 347, 320, 315, 307, 303, 299, 298, 298, 292, 288,
287, 283, 275, 275, 274, 273, 273, 272, 272, 271, 269, 269,
268, 263, 262, 261, 259, 258, 255, 254, 252, 252, 252, 251 };
double std2 = 0, avg = 0;
size_t order[n];
for (size_t i = 0; i < n; ++i) {
order[i] = (n-1) - i;
avg += items[i];
std2 += items[i]*items[i];
}
std2 /= 1.0*n;
avg /= 1.0*n;
std2 -= avg*avg;
binpack_t * bp = binpack_create(c,n,items);
bp->method = HC;
int niter = binpack_solve(bp);
assert(binpack_is_feasible(bp->best));
binpack_solution_t * s = binpack_get_best(bp);
if (s == NULL) {
perror("Hillclimb failed");
return 1;
}
assert(binpack_is_feasible(s));
char * str = binpack_solution_str(s);
printf("HC[%d] solution:\n%s", niter, str);
double eval = binpack_solution_eval(s);
printf("Evaluation: %.2lf (err:%.2lf)\n\n", eval, eval-std2);
binpack_solution_t * trivial = binpack_trivial(bp);
binpack_reset(bp);
binpack_set_start(bp, trivial);
binpack_solution_destroy(trivial);
niter = binpack_solve(bp);
assert(binpack_is_feasible(bp->best));
binpack_solution_destroy(s);
s = binpack_get_best(bp);
if (s == NULL) {
perror("set_start failed");
return 1;
}
assert(binpack_is_feasible(s));
free(str); str = binpack_solution_str(s);
printf("HC[%d] solution starting from trivial solution:\n%s", niter, str);
eval = binpack_solution_eval(s);
printf("Evaluation: %.2lf (err:%.2lf)\n\n", eval, eval-std2);
if (binpack_search(NULL,ILS) > 0) {
perror("Wrong Value for BP_INVAL");
}
binpack_solution_t * ff = binpack_firstfit(bp);
binpack_reset(bp);
binpack_set_start(bp, ff);
binpack_solution_destroy(ff);
niter = binpack_search(bp, VND);
assert(binpack_is_feasible(bp->best));
binpack_solution_destroy(s);
s = binpack_get_best(bp);
assert(binpack_is_feasible(s));
free(str); str = binpack_solution_str(s);
printf("VND[%d] solution starting from trivial solution:\n%s", niter, str);
eval = binpack_solution_eval(s);
printf("Evaluation: %.2lf (err:%.2lf)\n\n", eval, eval-std2);
if (binpack_search(NULL,ILS) > 0) {
perror("Wrong Value for BP_INVAL");
return -1;
}
binpack_reset(bp);
niter = binpack_search(bp, VNS);
assert(binpack_is_feasible(bp->best));
binpack_solution_destroy(s);
s = binpack_get_best(bp);
if(binpack_is_feasible(s) == 0){
perror("VNS failed");
return 5;
}
free(str); str = binpack_solution_str(s);
printf("VNS[%d] solution:\n%s", niter, str);
eval = binpack_solution_eval(s);
printf("Evaluation: %.2lf (err:%.2lf)\n\n", eval, eval-std2);
binpack_solution_destroy(s);
binpack_destroy(bp);
return 0;
}
| 2.171875 | 2 |
2024-11-18T22:48:45.549260+00:00 | 2016-04-16T14:01:33 | 7cc9f682bed2f257a5aa2e9b6f093555f7c09af8 | {
"blob_id": "7cc9f682bed2f257a5aa2e9b6f093555f7c09af8",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-16T14:01:33",
"content_id": "652c25cf30f6d0441db7f06f189ba78c80fd2818",
"detected_licenses": [
"MIT"
],
"directory_id": "2aefe6b3a68c62d3e2b4349989ca891426b31527",
"extension": "c",
"filename": "skipfile.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1303,
"license": "MIT",
"license_type": "permissive",
"path": "/src/skipfile.c",
"provenance": "stackv2-0108.json.gz:77240",
"repo_name": "charliexp/akasn1lib",
"revision_date": "2016-04-16T14:01:33",
"revision_id": "b0eff9a74b15cbf73d2cd661b3ebaf9b196e54dc",
"snapshot_id": "5fb33b8f69ae5bc3e8c9055c69db83815ddb5ec9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/charliexp/akasn1lib/b0eff9a74b15cbf73d2cd661b3ebaf9b196e54dc/src/skipfile.c",
"visit_date": "2021-01-19T13:49:22.729469"
} | stackv2 | /*
* skipfile.c
*
* written 1993 by Andreas Kraft
*/
# if defined(__TURBOC__) | defined(__WATCOMC__) | defined(_MSC_VER)
# include <io.h>
# elif solaris
# include <sys/types.h>
# include <unistd.h>
# elif linux
# include <sys/types.h>
# include <unistd.h>
# elif __svr4__
# include <sys/types.h>
# include <unistd.h>
# else
# include <sys/file.h>
# include <unistd.h>
# endif /* __TURBOC__ */
# include "akasn1.h"
/**
* \brief Skip a portion of the opened ASN.1 file
*
* \details This function skips `length` bytes of the data in the opened
* ASN.1 file.
*
* \return If an error occures, the function returns -1, or 0 otherwise.
*
* \see asnFtell, asnFSeek, asnOpenReadFile, asnOpenWriteFile
*/
int asnSkipFile (long length) {
if (asnfd == -1)
return -1; /* error */
if (!length)
return 0;
# if defined(__TURBOC__) | defined(__WATCOMC__) | defined(_MSC_VER)
return (lseek (asnfd, length, SEEK_CUR) == 1l) ? -1 : 0;
# elif solaris
return (lseek (asnfd, length, SEEK_CUR) == 1l) ? -1 : 0;
# elif linux
return (lseek (asnfd, length, SEEK_CUR) == 1l) ? -1 : 0;
# elif __svr4__
return (lseek (asnfd, length, SEEK_CUR) == 1l) ? -1 : 0;
# else
return (lseek (asnfd, length, L_INCR) == -1l) ? -1 : 0;
# endif
}
| 2.390625 | 2 |
2024-11-18T22:48:45.954757+00:00 | 2021-08-26T11:18:55 | 78bbe1e06abe1a269eed295c6c3dbfdd75d4dac0 | {
"blob_id": "78bbe1e06abe1a269eed295c6c3dbfdd75d4dac0",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-26T11:18:55",
"content_id": "cc3b279b861b04829e79cedc80c927a3c7adace0",
"detected_licenses": [
"MIT"
],
"directory_id": "ae8047ad8a872854fd2299351b97aef959a5031b",
"extension": "h",
"filename": "ringbuf.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 973,
"license": "MIT",
"license_type": "permissive",
"path": "/kernel/include/snx/ringbuf.h",
"provenance": "stackv2-0108.json.gz:77369",
"repo_name": "reymontero/SynnixOS",
"revision_date": "2021-08-26T11:18:55",
"revision_id": "c26993479d78eae3881bdbad147b5bb4b5704844",
"snapshot_id": "241ac3d92cfa678b5a807da382b526208cd76622",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/reymontero/SynnixOS/c26993479d78eae3881bdbad147b5bb4b5704844/kernel/include/snx/ringbuf.h",
"visit_date": "2023-07-14T01:10:18.895693"
} | stackv2 | #pragma once
#ifndef SNX_RINGBUF_H
#define SNX_RINGBUF_H
#include <basic.h>
#include <stddef.h>
#include <stdint.h>
/** @file
* @brief Ring Buffers
*
*/
/**
* @brief Ring Buffer structure
*
*/
struct ringbuf {
char *data;
size_t size;
size_t len;
size_t head;
};
/**
* @brief Create new Ring Buffer
*
* @param size
* @return struct ringbuf*
*/
struct ringbuf *new_ring(size_t size);
void emplace_ring(struct ringbuf *ring, size_t size);
/**
* @brief Free a Ring Buffer
*
*/
void free_ring(struct ringbuf *);
/**
* @brief Write data to Ring Buffer
*
* @param data
* @param len
* @return size_t
*/
size_t ring_write(struct ringbuf *, const void *data, size_t len);
/**
* @brief Read data from Ring Buffer
*
* @param data
* @param len
* @return size_t
*/
size_t ring_read(struct ringbuf *, void *data, size_t len);
/**
* @brief Alias emplace_ring to ring_emplace
*
*/
#define ring_emplace emplace_ring
#endif
| 2.125 | 2 |
2024-11-18T22:48:46.024073+00:00 | 2023-07-17T21:01:17 | 36409d60f036df7b7962d9a80a010c22523ec419 | {
"blob_id": "36409d60f036df7b7962d9a80a010c22523ec419",
"branch_name": "refs/heads/main",
"committer_date": "2023-07-21T00:07:03",
"content_id": "98cb670e74d71debd9198e32c4b91dadc364a1e4",
"detected_licenses": [
"MIT",
"BSD-2-Clause"
],
"directory_id": "9f33f09e5398d9b6104e09d54264c89e0a1e0e86",
"extension": "c",
"filename": "daemon.c",
"fork_events_count": 24,
"gha_created_at": "2018-09-04T21:50:32",
"gha_event_created_at": "2023-06-30T18:14:03",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 147424126,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2004,
"license": "MIT,BSD-2-Clause",
"license_type": "permissive",
"path": "/src/daemon.c",
"provenance": "stackv2-0108.json.gz:77499",
"repo_name": "NICMx/FORT-validator",
"revision_date": "2023-07-17T21:01:17",
"revision_id": "d195700bbac43128e1f74fa0bef4c406450a374d",
"snapshot_id": "4c5c52b2a40135868b898dd1f8def40239368d9d",
"src_encoding": "UTF-8",
"star_events_count": 43,
"url": "https://raw.githubusercontent.com/NICMx/FORT-validator/d195700bbac43128e1f74fa0bef4c406450a374d/src/daemon.c",
"visit_date": "2023-08-28T11:53:53.650125"
} | stackv2 | #include "daemon.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include "log.h"
/*
* Daemonize fort execution. The function "daemon()" from unistd header isn't
* utilized since isn't standardized (too bad).
*
* The logs must be sent to syslog before this call, the @log_cb is called to
* initialize logging after the first fork() call.
*
* This function exits on any error once the first fork is successfully done.
*/
int
daemonize(daemon_log_cb log_cb)
{
char *pwd;
pid_t pid;
long int fds;
int error;
/* Already a daemon, just return */
if (getppid() == 1)
return 0;
/* Get the working dir, the daemon will use (and free) it later */
pwd = getcwd(NULL, 0);
if (pwd == NULL)
enomem_panic();
pid = fork();
if (pid < 0) {
error = errno;
pr_op_err("Couldn't fork to daemonize: %s", strerror(error));
return error;
}
/* Terminate parent */
if (pid > 0)
exit(0);
/* Activate logs */
log_cb();
/* Child goes on from here */
if (setsid() < 0) {
error = errno;
pr_op_err("Couldn't create new session, ending execution: %s",
strerror(error));
exit(error);
}
/*
* Ignore SIGHUP. SIGCHLD isn't ignored since we still do a fork to
* execute rsync; when that's not the case then:
* signal(SIGCHLD, SIG_IGN);
*/
signal(SIGHUP, SIG_IGN);
/* Assure this is not a session leader */
pid = fork();
if (pid < 0) {
error = errno;
pr_op_err("Couldn't fork again to daemonize, ending execution: %s",
strerror(error));
exit(error);
}
/* Terminate parent */
if (pid > 0)
exit(0);
/* Close all descriptors, getdtablesize() isn't portable */
fds = sysconf(_SC_OPEN_MAX);
while (fds >= 0) {
close(fds);
fds--;
}
/* No privileges revoked to create files/dirs */
umask(0);
if (chdir(pwd) < 0) {
error = errno;
pr_op_err("Couldn't chdir() of daemon, ending execution: %s",
strerror(error));
exit(error);
}
free(pwd);
return 0;
}
| 2.734375 | 3 |
2024-11-18T22:48:46.633892+00:00 | 2017-07-06T13:51:54 | dac1ec92c539228349861747f7d5497d9824303b | {
"blob_id": "dac1ec92c539228349861747f7d5497d9824303b",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-06T13:51:54",
"content_id": "8f7bb1a2bc1518928f02e7b9e2f79dc44ef4d18c",
"detected_licenses": [
"Unlicense"
],
"directory_id": "dd6ce43ddff7acc03a8e4fcbc8305273bca69c21",
"extension": "c",
"filename": "print.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 96435143,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 152,
"license": "Unlicense",
"license_type": "permissive",
"path": "/print.c",
"provenance": "stackv2-0108.json.gz:77757",
"repo_name": "jijo733/MyTests",
"revision_date": "2017-07-06T13:51:54",
"revision_id": "4cb1715b69728158d893b3f6e5912970e8ac3f40",
"snapshot_id": "6714da303dbb187513204d05f0b91df722f6af96",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jijo733/MyTests/4cb1715b69728158d893b3f6e5912970e8ac3f40/print.c",
"visit_date": "2020-12-02T17:49:45.652181"
} | stackv2 | #include <stdio.h>
int main(int argc, char* argv[])
{
int age;
int height;
age=150;
printf("age is %d , height is :%d \n",age,height);
return 0;
}
| 2.265625 | 2 |
2024-11-18T22:48:47.670847+00:00 | 2021-11-04T23:45:34 | 286e5f1af20fa7dc86c15b4582e8ebe8c97b034e | {
"blob_id": "286e5f1af20fa7dc86c15b4582e8ebe8c97b034e",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-04T23:45:34",
"content_id": "bcd2efc271a955d12dd453963babf54c1a1b7097",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "1cc48fee60e05513a562d73a88426c4f2ef6e75e",
"extension": "c",
"filename": "ex89.c",
"fork_events_count": 0,
"gha_created_at": "2021-08-24T01:41:50",
"gha_event_created_at": "2021-08-24T01:41:51",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 399300030,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5978,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/mat/tests/ex89.c",
"provenance": "stackv2-0108.json.gz:78660",
"repo_name": "reelandry/petsc",
"revision_date": "2021-11-04T23:45:34",
"revision_id": "e9b07ec78073c524aae74396c6f5cf0a28b9102a",
"snapshot_id": "a66ce8a10bdd2d1ae0e05ccd675413260b9b8f26",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/reelandry/petsc/e9b07ec78073c524aae74396c6f5cf0a28b9102a/src/mat/tests/ex89.c",
"visit_date": "2023-08-27T04:57:32.226474"
} | stackv2 | static char help[] ="Tests MatPtAP() for MPIMAIJ and MPIAIJ \n ";
#include <petscdmda.h>
int main(int argc,char **argv)
{
PetscErrorCode ierr;
DM coarsedm,finedm;
PetscMPIInt size,rank;
PetscInt M,N,Z,i,nrows;
PetscScalar one = 1.0;
PetscReal fill=2.0;
Mat A,P,C;
PetscScalar *array,alpha;
PetscBool Test_3D=PETSC_FALSE,flg;
const PetscInt *ia,*ja;
PetscInt dof;
MPI_Comm comm;
ierr = PetscInitialize(&argc,&argv,NULL,help);if (ierr) return ierr;
comm = PETSC_COMM_WORLD;
ierr = MPI_Comm_rank(comm,&rank);CHKERRMPI(ierr);
ierr = MPI_Comm_size(comm,&size);CHKERRMPI(ierr);
M = 10; N = 10; Z = 10;
dof = 10;
ierr = PetscOptionsGetBool(NULL,NULL,"-test_3D",&Test_3D,NULL);CHKERRQ(ierr);
ierr = PetscOptionsGetInt(NULL,NULL,"-M",&M,NULL);CHKERRQ(ierr);
ierr = PetscOptionsGetInt(NULL,NULL,"-N",&N,NULL);CHKERRQ(ierr);
ierr = PetscOptionsGetInt(NULL,NULL,"-Z",&Z,NULL);CHKERRQ(ierr);
/* Set up distributed array for fine grid */
if (!Test_3D) {
ierr = DMDACreate2d(comm,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_STAR,M,N,PETSC_DECIDE,PETSC_DECIDE,dof,1,NULL,NULL,&coarsedm);CHKERRQ(ierr);
} else {
ierr = DMDACreate3d(comm,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_STAR,M,N,Z,PETSC_DECIDE,PETSC_DECIDE,PETSC_DECIDE,dof,1,NULL,NULL,NULL,&coarsedm);CHKERRQ(ierr);
}
ierr = DMSetFromOptions(coarsedm);CHKERRQ(ierr);
ierr = DMSetUp(coarsedm);CHKERRQ(ierr);
/* This makes sure the coarse DMDA has the same partition as the fine DMDA */
ierr = DMRefine(coarsedm,PetscObjectComm((PetscObject)coarsedm),&finedm);CHKERRQ(ierr);
/*------------------------------------------------------------*/
ierr = DMSetMatType(finedm,MATAIJ);CHKERRQ(ierr);
ierr = DMCreateMatrix(finedm,&A);CHKERRQ(ierr);
/* set val=one to A */
if (size == 1) {
ierr = MatGetRowIJ(A,0,PETSC_FALSE,PETSC_FALSE,&nrows,&ia,&ja,&flg);CHKERRQ(ierr);
if (flg) {
ierr = MatSeqAIJGetArray(A,&array);CHKERRQ(ierr);
for (i=0; i<ia[nrows]; i++) array[i] = one;
ierr = MatSeqAIJRestoreArray(A,&array);CHKERRQ(ierr);
}
ierr = MatRestoreRowIJ(A,0,PETSC_FALSE,PETSC_FALSE,&nrows,&ia,&ja,&flg);CHKERRQ(ierr);
} else {
Mat AA,AB;
ierr = MatMPIAIJGetSeqAIJ(A,&AA,&AB,NULL);CHKERRQ(ierr);
ierr = MatGetRowIJ(AA,0,PETSC_FALSE,PETSC_FALSE,&nrows,&ia,&ja,&flg);CHKERRQ(ierr);
if (flg) {
ierr = MatSeqAIJGetArray(AA,&array);CHKERRQ(ierr);
for (i=0; i<ia[nrows]; i++) array[i] = one;
ierr = MatSeqAIJRestoreArray(AA,&array);CHKERRQ(ierr);
}
ierr = MatRestoreRowIJ(AA,0,PETSC_FALSE,PETSC_FALSE,&nrows,&ia,&ja,&flg);CHKERRQ(ierr);
ierr = MatGetRowIJ(AB,0,PETSC_FALSE,PETSC_FALSE,&nrows,&ia,&ja,&flg);CHKERRQ(ierr);
if (flg) {
ierr = MatSeqAIJGetArray(AB,&array);CHKERRQ(ierr);
for (i=0; i<ia[nrows]; i++) array[i] = one;
ierr = MatSeqAIJRestoreArray(AB,&array);CHKERRQ(ierr);
}
ierr = MatRestoreRowIJ(AB,0,PETSC_FALSE,PETSC_FALSE,&nrows,&ia,&ja,&flg);CHKERRQ(ierr);
}
/* Create interpolation between the fine and coarse grids */
ierr = DMCreateInterpolation(coarsedm,finedm,&P,NULL);CHKERRQ(ierr);
/* Test P^T * A * P - MatPtAP() */
/*------------------------------*/
/* (1) Developer API */
ierr = MatProductCreate(A,P,NULL,&C);CHKERRQ(ierr);
ierr = MatProductSetType(C,MATPRODUCT_PtAP);CHKERRQ(ierr);
ierr = MatProductSetAlgorithm(C,"allatonce");CHKERRQ(ierr);
ierr = MatProductSetFill(C,PETSC_DEFAULT);CHKERRQ(ierr);
ierr = MatProductSetFromOptions(C);CHKERRQ(ierr);
ierr = MatProductSymbolic(C);CHKERRQ(ierr);
ierr = MatProductNumeric(C);CHKERRQ(ierr);
ierr = MatProductNumeric(C);CHKERRQ(ierr); /* Test reuse of symbolic C */
{ /* Test MatProductView() */
PetscViewer viewer;
ierr = PetscViewerASCIIOpen(comm,NULL, &viewer);CHKERRQ(ierr);
ierr = PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_INFO);CHKERRQ(ierr);
ierr = MatProductView(C,viewer);CHKERRQ(ierr);
ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
}
ierr = MatPtAPMultEqual(A,P,C,10,&flg);CHKERRQ(ierr);
if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_PLIB,"Error in MatProduct_PtAP");
ierr = MatDestroy(&C);CHKERRQ(ierr);
/* (2) User API */
ierr = MatPtAP(A,P,MAT_INITIAL_MATRIX,fill,&C);CHKERRQ(ierr);
/* Test MAT_REUSE_MATRIX - reuse symbolic C */
alpha=1.0;
for (i=0; i<1; i++) {
alpha -= 0.1;
ierr = MatScale(A,alpha);CHKERRQ(ierr);
ierr = MatPtAP(A,P,MAT_REUSE_MATRIX,fill,&C);CHKERRQ(ierr);
}
/* Free intermediate data structures created for reuse of C=Pt*A*P */
ierr = MatProductClear(C);CHKERRQ(ierr);
ierr = MatPtAPMultEqual(A,P,C,10,&flg);CHKERRQ(ierr);
if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_PLIB,"Error in MatPtAP");
ierr = MatDestroy(&C);CHKERRQ(ierr);
ierr = MatDestroy(&A);CHKERRQ(ierr);
ierr = MatDestroy(&P);CHKERRQ(ierr);
ierr = DMDestroy(&finedm);CHKERRQ(ierr);
ierr = DMDestroy(&coarsedm);CHKERRQ(ierr);
ierr = PetscFinalize();
return ierr;
}
/*TEST
test:
args: -M 10 -N 10 -Z 10
output_file: output/ex89_1.out
test:
suffix: allatonce
nsize: 4
args: -M 10 -N 10 -Z 10
output_file: output/ex89_2.out
test:
suffix: allatonce_merged
nsize: 4
args: -M 10 -M 5 -M 10 -matproduct_ptap_via allatonce_merged
output_file: output/ex89_3.out
test:
suffix: nonscalable_3D
nsize: 4
args: -M 10 -M 5 -M 10 -test_3D 1 -matproduct_ptap_via nonscalable
output_file: output/ex89_4.out
test:
suffix: allatonce_merged_3D
nsize: 4
args: -M 10 -M 5 -M 10 -test_3D 1 -matproduct_ptap_via allatonce_merged
output_file: output/ex89_3.out
test:
suffix: nonscalable
nsize: 4
args: -M 10 -N 10 -Z 10 -matproduct_ptap_via nonscalable
output_file: output/ex89_5.out
TEST*/
| 2.109375 | 2 |
2024-11-18T22:48:47.752374+00:00 | 2023-04-02T14:03:47 | bc44d25adfb55315ac71f9c8c12ec1e95c16e6ce | {
"blob_id": "bc44d25adfb55315ac71f9c8c12ec1e95c16e6ce",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-02T14:03:47",
"content_id": "fd3a426afba9fb6f1077a7b684fb218ab62b10f3",
"detected_licenses": [
"MIT"
],
"directory_id": "b6f6ad22a1fb82dba50071b35586006066c649f4",
"extension": "c",
"filename": "common.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 249990040,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3084,
"license": "MIT",
"license_type": "permissive",
"path": "/src/common.c",
"provenance": "stackv2-0108.json.gz:78788",
"repo_name": "kobayasy/pSync",
"revision_date": "2023-04-02T14:03:47",
"revision_id": "8a01db116dab3a7bdc2a3a711e19437297b83437",
"snapshot_id": "a95bd641a05e517d5cf723c0eacd60f73712c68a",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/kobayasy/pSync/8a01db116dab3a7bdc2a3a711e19437297b83437/src/common.c",
"visit_date": "2023-04-14T12:37:47.829489"
} | stackv2 | /* common.c - Last modified: 29-Mar-2023 (kobayasy)
*
* Copyright (C) 2018-2023 by Yuichi Kobayashi <kobayasy@kobayasy.com>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* #ifdef HAVE_CONFIG_H */
#include <limits.h>
#include <string.h>
#include <unistd.h>
#ifdef POLL_TIMEOUT
#include <poll.h>
#endif /* #ifdef POLL_TIMEOUT */
#include "common.h"
ssize_t write_size(int fd, const void *buf, size_t count) {
ssize_t status = -1;
#ifdef POLL_TIMEOUT
struct pollfd fds = {
.fd = fd,
.events = POLLOUT
};
#endif /* #ifdef POLL_TIMEOUT */
size_t size;
ssize_t n;
size = count;
while (size > 0) {
#ifdef POLL_TIMEOUT
if (poll(&fds, 1, POLL_TIMEOUT) != 1)
goto error;
if (!(fds.revents & POLLOUT))
goto error;
#endif /* #ifdef POLL_TIMEOUT */
n = write(fd, buf, size);
switch (n) {
case -1:
case 0: /* end of file */
goto error;
}
size -= n;
buf += n;
}
status = count;
error:
return status;
}
ssize_t read_size(int fd, void *buf, size_t count) {
ssize_t status = -1;
#ifdef POLL_TIMEOUT
struct pollfd fds = {
.fd = fd,
.events = POLLIN
};
#endif /* #ifdef POLL_TIMEOUT */
size_t size;
ssize_t n;
size = count;
while (size > 0) {
#ifdef POLL_TIMEOUT
if (poll(&fds, 1, POLL_TIMEOUT) != 1)
goto error;
if (!(fds.revents & POLLIN))
goto error;
#endif /* #ifdef POLL_TIMEOUT */
n = read(fd, buf, size);
switch (n) {
case -1:
case 0: /* end of file */
goto error;
}
size -= n;
buf += n;
}
status = count;
error:
return status;
}
int strcmp_next(const char *s1, const char *s2) {
int n = strcmp(s1, s2);
if (n < 0) {
if (!*s1)
n = INT_MAX;
}
else if (n > 0) {
if (!*s2)
n = INT_MIN;
}
return n;
}
| 2.109375 | 2 |
2024-11-18T22:48:48.121296+00:00 | 2019-02-24T21:21:02 | 5a39714ae4ddfc531f3e4345d0f0b69cfd921a99 | {
"blob_id": "5a39714ae4ddfc531f3e4345d0f0b69cfd921a99",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-24T21:21:02",
"content_id": "b59c66a9afb9dca0d39a5aa889de04c9d5d0a04e",
"detected_licenses": [
"MIT",
"SunPro"
],
"directory_id": "95e491ad81771f5959d738c5cebe3a3007efe215",
"extension": "c",
"filename": "tmpfile.c",
"fork_events_count": 0,
"gha_created_at": "2019-03-16T21:58:39",
"gha_event_created_at": "2019-03-16T21:58:39",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 176029341,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1913,
"license": "MIT,SunPro",
"license_type": "permissive",
"path": "/src/stdio/tmpfile.c",
"provenance": "stackv2-0108.json.gz:79045",
"repo_name": "vendu/hlibc",
"revision_date": "2019-02-24T21:21:02",
"revision_id": "597b96a83b0f84be152e53e55b30e60d705cfca1",
"snapshot_id": "c75f79d027779b4103d682e9dcda26974e60ffad",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/vendu/hlibc/597b96a83b0f84be152e53e55b30e60d705cfca1/src/stdio/tmpfile.c",
"visit_date": "2020-04-29T09:33:18.289299"
} | stackv2 | /*
Copyright 2019 CM Graff
Copyright 2019 zhiayang
Thanks to ryuo and alphamule for providing feedback during
the design stage of the temp file functions
todo:
*) add the L_tmpnam variable
*/
#include <time.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
/* 128 passes should be sufficient to reject */
#define MAX_TRIES 128
/*
this is a bad hack!! internal.h and stdio.h are mutually exclusive due
to how FILE is declared and defined ):
so we don't include internal.h and we fwd-declare these guys.
we want stdio instead for the L_tmpnam and P_tmpdir constants,
so we don't have them in two places.
*/
char *__fill_string_randomly(char *s, int cnt);
FILE *__internal_fopen(const char *, const char *, int);
static char *__generate_tmp_filename(char *buf)
{
static char storage[4096];
char *output = (buf ? buf : storage);
char *name = strcpy(output, "/tmp/") + 5;
srand(time(NULL));
/* NULL terminate the string. __fill_blabla returns one-past-the-end */
__fill_string_randomly(name, L_tmpnam - strlen(P_tmpdir))[0] = 0;
return output;
}
char *tmpnam(char *s)
{
char *name = NULL;
int counter = MAX_TRIES;
do {
name = __generate_tmp_filename(NULL);
if (access(name, X_OK) == 0)
break;
} while (counter--);
if (counter == 0)
return NULL;
return name;
}
FILE *tmpfile(void)
{
FILE *fd = NULL;
char *name = NULL;
int counter = MAX_TRIES;
do {
name = __generate_tmp_filename(NULL);
if ((fd = __internal_fopen(name, "w+", 2)))
break;
} while (counter--);
if (fd)
{
/*
unlink the file, which removes it from the disk. since we already fopen-ed it, the file
will continue to exist until the last user gets closes it. since nobody else know about
the file (in theory), this process will be the last user, and the file will be freed when
the process exits.
*/
unlink(name);
}
return fd;
}
| 2.984375 | 3 |
2024-11-18T22:48:49.957598+00:00 | 2021-02-24T21:12:19 | e4731394e4dec8013c4d4464dfae98c490cc7c24 | {
"blob_id": "e4731394e4dec8013c4d4464dfae98c490cc7c24",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-24T21:12:19",
"content_id": "ffc820f2be1e29a214b94fb9f72b8a52052bdca2",
"detected_licenses": [
"MIT"
],
"directory_id": "4b4b267537a8437a897301a7bbc881a8644f4c2e",
"extension": "c",
"filename": "poti.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 339771867,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1118,
"license": "MIT",
"license_type": "permissive",
"path": "/source/libs/poti.c",
"provenance": "stackv2-0108.json.gz:79690",
"repo_name": "step-sequencer/step-sequencer",
"revision_date": "2021-02-24T21:12:19",
"revision_id": "e68ae0a63b685b1b705c72cf10cbe203859addce",
"snapshot_id": "ddf0f3102f113baa672eddb7cc12b1943c9b9454",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/step-sequencer/step-sequencer/e68ae0a63b685b1b705c72cf10cbe203859addce/source/libs/poti.c",
"visit_date": "2023-03-10T23:21:04.152172"
} | stackv2 | #include "poti.h"
// Method initilaizes the analog digital conversion
void init_poti_adc()
{
// Set the AREF input pin as a reference pin for ADC calculation
ADMUX = (1 << REFS0);
// ADC Enable and prescaler of 128 -> high prescaler -> low accuracy
// F_CPU/128 = 125000
ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
}
// Method reads analog input pin and returns value between 0 and 1023
uint16_t adc_read_poti(uint8_t pin)
{
// Activate PC0 / ADC0 pin as analog input pin
ADMUX = (ADMUX & 0xF8) | pin; // clears the bottom 3 bits before ORing
// Setting ADSC bit will start conversion
ADCSRA |= (1 << ADSC);
// wait for conversion to complete
// ADSC becomes ’0′ again
while (ADCSRA & (1 << ADSC))
{
};
// returning the result stored in the ADC register
return (ADC);
}
// Method used to read poti values. It takes the average out of 64 reads
uint16_t get_poti_average(uint8_t pin)
{
uint16_t potiSum = 0;
for (int i = 0; i < 64; i++)
{
potiSum += adc_read_poti(pin);
}
return potiSum >> 6;
} | 2.953125 | 3 |
2024-11-18T22:48:50.019910+00:00 | 2017-07-16T15:11:13 | 6d8dac092f155ed7c9f20d904bcb70f55597c213 | {
"blob_id": "6d8dac092f155ed7c9f20d904bcb70f55597c213",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-16T15:11:13",
"content_id": "dd03dd177a0dbb90626f5294cd74139abbafde30",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b1a91c74f1ce796cf039e561404b01d2a1495505",
"extension": "h",
"filename": "geom.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 93006020,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2332,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/geom.h",
"provenance": "stackv2-0108.json.gz:79820",
"repo_name": "ryanisaacg/au-engine",
"revision_date": "2017-07-16T15:11:13",
"revision_id": "604d92be6ad59f1ebfdec6af0bed3ce31e5262e5",
"snapshot_id": "0ad460ff398f986730f324930cb4087a664353cd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ryanisaacg/au-engine/604d92be6ad59f1ebfdec6af0bed3ce31e5262e5/geom.h",
"visit_date": "2021-01-23T05:56:57.391283"
} | stackv2 | #pragma once
#include <stdbool.h>
//A 2D vector
typedef struct {
float x, y;
} AU_Vector;
//Add two vectors
AU_Vector au_geom_vec_add(AU_Vector, AU_Vector);
//Subtract two vectors
AU_Vector au_geom_vec_sub(AU_Vector, AU_Vector);
//Clamp a vector by component
AU_Vector au_geom_vec_cmp_clamp(AU_Vector, float lower, float higher);
//Clamp a veector by length
AU_Vector au_geom_vec_len_clamp(AU_Vector, float lower, float higher);
//Scale a vector by a scalar
AU_Vector au_geom_vec_scl(AU_Vector, float);
//Normalize a vector to a length of one
AU_Vector au_geom_vec_nor(AU_Vector);
//Set the length of a vector
AU_Vector au_geom_vec_set_len(AU_Vector, float);
//Get the squared length of a vector
float au_geom_vec_len2(AU_Vector);
//Get the length of a vector
float au_geom_vec_len(AU_Vector);
//Check if two vectors are equal
bool au_geom_vec_eq(AU_Vector, AU_Vector);
//Generate a random vector bounded by two vectors
AU_Vector au_geom_vec_rand(AU_Vector min, AU_Vector max);
//Do a dot product of two vectors
float au_geom_vec_dot(AU_Vector, AU_Vector);
//Rotate a vector around another by a given angle
AU_Vector au_geom_vec_rot_abt(AU_Vector, AU_Vector origin, float);
//A 3x3 matrix indexed by [row][col]
typedef struct {
float data[3][3];
} AU_Transform;
//Return an identity transformation matrix
AU_Transform au_geom_identity();
//Apply a transform matrix to a vector
AU_Vector au_geom_transform(AU_Transform, AU_Vector);
//Concatenate two transformations together
AU_Transform au_geom_transform_concat(AU_Transform, AU_Transform);
//Get a translation matrix
AU_Transform au_geom_transform_translate(float x, float y);
//Get a rotation matrix (in degrees)
AU_Transform au_geom_transform_rotate(float angle);
//Get a scale matrix
AU_Transform au_geom_transform_scale(float x_scale, float y_scale);
//An axis aligned rectangle
typedef struct {
float x, y, width, height;
} AU_Rectangle;
//A circle
typedef struct {
float x, y, radius;
} AU_Circle;
bool au_geom_rect_overlaps_rect(AU_Rectangle, AU_Rectangle);
bool au_geom_rect_overlaps_circ(AU_Rectangle, AU_Circle);
bool au_geom_circ_overlaps_circ(AU_Circle, AU_Circle);
#define au_geom_circ_overlaps_rect(circ, rect) (au_geom_rect_overlaps_circ(rect, circ))
bool au_geom_rect_contains(AU_Rectangle, AU_Vector);
bool au_geom_circ_contains(AU_Circle, AU_Vector);
| 2.359375 | 2 |
2024-11-18T22:48:50.282501+00:00 | 2022-06-11T10:43:35 | 651c4ac54db81f3aff844f9b762edf28dc1fbaba | {
"blob_id": "651c4ac54db81f3aff844f9b762edf28dc1fbaba",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-11T10:48:44",
"content_id": "ad0308bf1b5acc752bb7c5f9a11af692bff71bd0",
"detected_licenses": [
"MIT"
],
"directory_id": "ebff7c39d1746127e502d201c0ed5b79e619e0a6",
"extension": "h",
"filename": "print_ip.h",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 193844325,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1283,
"license": "MIT",
"license_type": "permissive",
"path": "/src/util/print_ip.h",
"provenance": "stackv2-0108.json.gz:80080",
"repo_name": "dywisor/ip-dedup",
"revision_date": "2022-06-11T10:43:35",
"revision_id": "6ecacda0c660e2b19e2df8840ac73a7ec7c8ea94",
"snapshot_id": "80742e12c78b79dbdf0d0a675d05ee2b1234d96b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dywisor/ip-dedup/6ecacda0c660e2b19e2df8840ac73a7ec7c8ea94/src/util/print_ip.h",
"visit_date": "2022-06-14T14:50:22.189611"
} | stackv2 | #ifndef _HAVE_UTIL_PRINT_IP_H_
#define _HAVE_UTIL_PRINT_IP_H_
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include "../ip.h"
/* print func typedef */
typedef int (*ip4_print_func) (
FILE* const restrict stream,
const struct ip4_addr_t* const addr
);
typedef int (*ip6_print_func) (
FILE* const restrict stream,
const struct ip6_addr_t* const addr
);
/* IPv4 */
int fprint_ip4_addr_data (
FILE* const restrict stream,
const ip4_addr_data_t addr_data
);
int fprint_ip4_addr (
FILE* const restrict stream,
const struct ip4_addr_t* const addr
);
int fprint_ip4_net (
FILE* const restrict stream,
const struct ip4_addr_t* const addr
);
int fprint_ip4_addr_or_net (
FILE* const restrict stream,
const struct ip4_addr_t* const addr
);
/* IPv6 */
int fprint_ip6_addr_data (
FILE* const restrict stream,
const ip6_addr_data_t addr_data
);
int fprint_ip6_addr (
FILE* const restrict stream,
const struct ip6_addr_t* const addr
);
int fprint_ip6_net (
FILE* const restrict stream,
const struct ip6_addr_t* const addr
);
int fprint_ip6_addr_or_net (
FILE* const restrict stream,
const struct ip6_addr_t* const addr
);
#endif /* _HAVE_UTIL_PRINT_IP_H_ */
| 2.046875 | 2 |
2024-11-18T22:48:50.630204+00:00 | 2016-04-24T08:44:59 | 244bfb98b46582e46158f224764bbff9c24c6643 | {
"blob_id": "244bfb98b46582e46158f224764bbff9c24c6643",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-24T08:44:59",
"content_id": "61f931e935d372cf6dc725d0110520624605e7bf",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "8d5bb2c9b90fbe8bebcda5413b85dd7017dd9d8e",
"extension": "h",
"filename": "Singleton.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 56962266,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 985,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/brCommon/src/libs/data/brType/Singleton.h",
"provenance": "stackv2-0108.json.gz:80338",
"repo_name": "eirTony/BelaRust",
"revision_date": "2016-04-24T08:44:59",
"revision_id": "e26c020ad3b8fa5c38325caf907e9ab18cc95603",
"snapshot_id": "d1afedb7d2fdce377ffd10511a62e8b4f0349316",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/eirTony/BelaRust/e26c020ad3b8fa5c38325caf907e9ab18cc95603/brCommon/src/libs/data/brType/Singleton.h",
"visit_date": "2016-09-13T15:13:54.676141"
} | stackv2 | #ifndef SINGLETON_H
#define SINGLETON_H
/*! @file Singleton.h Macros for Singleton classes
*
* Usage:
*
* .h File
*
* @code
* class Log
* {
* DECLARE_SINGLETON(Log)
* // do NOT declare Log(void);
* ...
* };
* @endcode
*
* .cpp File
* @code
* DEFINE_SINGLETON(Log)
*
* Log::Log(void)
* {
* ...
* }
* @endcode
*
*/
// TODO: Non-void c'tor()
#define DECLARE_SINGLETON(CLASS) \
protected: \
CLASS(void); \
public: \
static CLASS * pointer(void); \
static CLASS & reference(void); \
private: \
static CLASS * instance(void); \
static CLASS * smpClass; \
#define DEFINE_SINGLETON(CLASS) \
CLASS * CLASS::smpClass = 0; \
CLASS * CLASS::instance(void) \
{ if ( ! smpClass) smpClass = new CLASS; return smpClass; } \
CLASS * CLASS::pointer(void) { return instance(); } \
CLASS & CLASS::reference(void) { return *instance(); } \
#endif // SINGLETON_H
| 2.078125 | 2 |
2024-11-18T22:48:50.822803+00:00 | 2022-05-09T12:02:14 | 02c4e2d31b809c28440113da3f27bf2e5852b0cf | {
"blob_id": "02c4e2d31b809c28440113da3f27bf2e5852b0cf",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-09T12:02:14",
"content_id": "742222ad6d749947b7329ca5e2c7c41eedc926ea",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "16ab123894d3bbbe25adac0380366b3dfc31444b",
"extension": "c",
"filename": "mmap_write.c",
"fork_events_count": 22,
"gha_created_at": "2020-04-04T13:11:26",
"gha_event_created_at": "2022-01-05T01:27:29",
"gha_language": "Makefile",
"gha_license_id": "Apache-2.0",
"github_id": 253000308,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 439,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/mm/map_driver/mmap_write.c",
"provenance": "stackv2-0108.json.gz:80597",
"repo_name": "linuxkerneltravel/LearningLinuxKernel",
"revision_date": "2022-05-09T12:02:14",
"revision_id": "5c868fc7f62d4da19e2229d4fb5055394ddf3c8e",
"snapshot_id": "3ffb4f3ef0a7183765ea94533ee1cd9448dd0acf",
"src_encoding": "UTF-8",
"star_events_count": 56,
"url": "https://raw.githubusercontent.com/linuxkerneltravel/LearningLinuxKernel/5c868fc7f62d4da19e2229d4fb5055394ddf3c8e/mm/map_driver/mmap_write.c",
"visit_date": "2022-05-13T13:50:20.398757"
} | stackv2 | # include <stdio.h>
# include <unistd.h>
# include <sys/mman.h>
# include <sys/types.h>
# include <fcntl.h>
# include <stdlib.h>
#define LEN (10*4096)
int main(void)
{
int fd;
char *vadr;
if((fd = open("/dev/mapnopage", O_RDWR)) < 0) {
return 0;
}
vadr = (char *)mmap(0, LEN, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, fd, 0);
sprintf( vadr, "write from userspace");
while(1){
sleep(1);
}
return 0;
}
| 2.546875 | 3 |
2024-11-18T22:48:50.871158+00:00 | 2023-01-11T13:16:27 | b9159d93ec7a5228a9f5126c5d976979e4942e7f | {
"blob_id": "b9159d93ec7a5228a9f5126c5d976979e4942e7f",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-11T13:16:27",
"content_id": "3bc8c4ac20abf66745c51ef024928a0225c6863e",
"detected_licenses": [
"MIT"
],
"directory_id": "f874d5539e16ced98a23d8bd85829e0174461e10",
"extension": "c",
"filename": "SRF05.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 191346074,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1241,
"license": "MIT",
"license_type": "permissive",
"path": "/SRF05/SRF05/SRF05.c",
"provenance": "stackv2-0108.json.gz:80727",
"repo_name": "phonght32/msp430g2553",
"revision_date": "2023-01-11T13:16:27",
"revision_id": "31e195ce1472f83187d979b84a5c7f0e12c44b87",
"snapshot_id": "6b1cf54584894e71a1d432db30228d5fde206cb7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/phonght32/msp430g2553/31e195ce1472f83187d979b84a5c7f0e12c44b87/SRF05/SRF05/SRF05.c",
"visit_date": "2023-01-25T04:19:55.512651"
} | stackv2 | /*
* SRF05.c
*
* Created on: Aug 15, 2018
* Author: Phong
*/
#include "SRF05.h"
extern float SRF05_Get_Range(void)
{
Data_Ready=0;
Falling_Rising_Edge =1;
PORT_SRF05_OUT |= PIN_SRF05_TRIG;
_delay_cycles(20*Freq_MHz);
PORT_SRF05_OUT &=~ PIN_SRF05_TRIG;
while(!Data_Ready)
{
}
Data_Ready=0;
Range = Time_Echo/58;
return Range;
}
extern void SRF05_Init(void)
{
PORT_SRF05_SEL &=~ PIN_SRF05_TRIG;
PORT_SRF05_SEL2 &=~ PIN_SRF05_TRIG;
PORT_SRF05_DIR |= PIN_SRF05_TRIG;
PORT_SRF05_OUT &=~ PIN_SRF05_TRIG;
PORT_SRF05_SEL |= PIN_SRF05_ECHO;
PORT_SRF05_SEL2 &=~ PIN_SRF05_ECHO;
PORT_SRF05_DIR &=~ PIN_SRF05_ECHO;
TA0CTL = TASSEL_2 + MC_2 + TAIE;
TA0CCTL1 |= CM_3 +CCIS_0+CAP+CCIE;
_BIS_SR(GIE);
}
extern void SRF05_Process(void)
{
if(Falling_Rising_Edge) //rising edge
{
TA0R = 0;
Falling_Rising_Edge = 0;
}
else
{
Time_Echo = TA0CCR1 ;
Falling_Rising_Edge = 1;
Data_Ready=1;
}
}
#pragma vector=TIMER0_A1_VECTOR
__interrupt void SRF05_Echo_Int(void)
{
switch(TA0IV)
{
case TA0IV_TACCR1 :
{
SRF05_Process();
break;
}
}
}
| 2.015625 | 2 |
2024-11-18T22:48:51.886656+00:00 | 2018-08-17T03:52:32 | 2eb0d5589d7f45fa868332d4fd50d237ae3319b8 | {
"blob_id": "2eb0d5589d7f45fa868332d4fd50d237ae3319b8",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-17T03:52:32",
"content_id": "53d83a046a59b45ca8440abc954afb73f278fc92",
"detected_licenses": [
"MIT"
],
"directory_id": "08d850aaa8677a79184b55a25de8500117398a56",
"extension": "c",
"filename": "fetch_info.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 143265561,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10906,
"license": "MIT",
"license_type": "permissive",
"path": "/fetch_info.c",
"provenance": "stackv2-0108.json.gz:81507",
"repo_name": "samarxie/fetch-sys-info",
"revision_date": "2018-08-17T03:52:32",
"revision_id": "b2cbf4b6c6f49e506bfa2c7d292c8eefc43b7e15",
"snapshot_id": "ef5b6a11340aa69fe580556a70d9220198981999",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/samarxie/fetch-sys-info/b2cbf4b6c6f49e506bfa2c7d292c8eefc43b7e15/fetch_info.c",
"visit_date": "2020-03-25T01:56:20.628166"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#define CPU_NUM_PATH "/sys/devices/system/cpu/present"
#define SYSTEM_FPS_PATH "/proc/fps_tm/fps_count"
#define SYSTEM_GPU_FREQ_PATH "/sys/kernel/debug/ged/hal/current_freqency"
#define SYSTEM_GPU_LOADING_PATH "/sys/kernel/debug/ged/hal/gpu_utilization"
#define SYSTEM_GPU_AND_POWER_LIMIT_PATH "/proc/thermlmt"
#define SYSTEM_CPU_FREQ_PATH "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq"
#define SYSTEM_CPU_STAT "/proc/stat"
#define SYSTEM_INFO 10
#define CPU_TIME_NUM 7
typedef int int32;
static char outfile[10];
enum eCsvWriteMode
{
ECWM_ONELINE=1,
ECWM_OTHERLINE,
};
static int cpu_tz_id = 0;
static int bat_tz_id = 0;
static int pcb_tz_id = 0;
static int sensor_temp;
static int cpu_num = 0;
static int thermal_zone_num(void);
static int fps_num = 0;
static int curr_gpu_freq = 0;
static int curr_gpu_loading = 0;
static int cpu_power_limit = 0;
static int gpu_power_limit = 0;
static unsigned long curr_cpu_freq[SYSTEM_INFO];
static unsigned long new_cpu_time[SYSTEM_INFO][CPU_TIME_NUM];
static unsigned long old_cpu_time[SYSTEM_INFO][CPU_TIME_NUM];
static unsigned long total_cpu_time[SYSTEM_INFO];
static unsigned long user_system_cpu_time[SYSTEM_INFO];
static unsigned long cpu_loading[SYSTEM_INFO];
#define ERR_RETURN(STR) printf(STR)
int32 putString2Csv(char str[],char filename[],int mode)
{
FILE *_fp;
//try to open filename
if ((_fp=fopen(filename,"a"))==NULL) {
ERR_RETURN("fopen called error");
}
int _mode=mode;
switch(_mode) {
case ECWM_ONELINE:
{
fputs(str,_fp);
fputs("\t",_fp);
}break;
case ECWM_OTHERLINE:
{
fputs("\n",_fp);
}break;
default:
break;
}
if (fclose(_fp) !=0){
ERR_RETURN("fclose called error");
}
return 1;
}
/*
* save file name:time
* */
static char logfile[39];
static void create_collect_log_timestamp(void)
{
struct tm *newtime;
int len = 0;
time_t t1;
t1 = time(NULL);
newtime=localtime(&t1);
strftime( outfile, 10,"%H:%M:%S", newtime);
outfile[10]=0;
}
static void create_save_log_file(void)
{
struct tm *newtime;
int len = 0;
time_t t1;
t1 = time(NULL);
newtime = localtime(&t1);
strftime(logfile,39,"fetch-log-%Y-%m-%d-%H:%M:%S.csv",newtime);
logfile[38] = 0;
}
/*
* get cpu battery and pcb temp
* */
static int get_sensor_temp(int sensor_id)
{
char temp[50];
FILE *fp;
char buf[5];
sprintf(temp,"/sys/class/thermal/thermal_zone%d/temp",sensor_id);
if((fp = fopen(temp,"r")) != NULL) {
fscanf(fp,"%d",&sensor_temp);
fclose(fp);
}
// strcpy(sensor_temp,buf);
return sensor_temp;
}
static int get_cpu_num(void)
{
char temp[100];
FILE *fp;
char buf[4];
if((fp = fopen(CPU_NUM_PATH,"r")) != NULL) {
fread(buf,1,4,fp);
buf[4]=0;
}
cpu_num = atoi(buf + 2);
return cpu_num;
}
/*
*
* get cpu freq
*
* */
static unsigned long get_cpu_freq()
{
unsigned long a[10];
int i = 0;
FILE *fp;
for(; i < cpu_num + 1; i++) {
char temp[100];
sprintf(temp,SYSTEM_CPU_FREQ_PATH,i);
if((fp = fopen(temp,"r")) !=NULL) {
fscanf(fp,"%lu",&curr_cpu_freq[i]);
fclose(fp);
} else {
curr_cpu_freq[i] = 0;
}
}
return 0 ;
}
/*
* the function can optimization
* */
static int get_cpu_loading()
{
FILE *fp = fopen(SYSTEM_CPU_STAT, "r");
char *delim = " ";
char szTest[1000] = {0};
char *p;
char cpu[5];
int i = 0;
int cpu_id = 0;
if(NULL == fp) {
printf("failed to open %s file node\n",SYSTEM_CPU_STAT);
return 1;
}
while(!feof(fp)) {
memset(szTest, 0, sizeof(szTest));
fgets(szTest, sizeof(szTest) - 1, fp);//include<\n>
if(szTest[3] == ' ')
continue;
if(szTest[0] != 'c')
break;
cpu_id = szTest[3] - '0';
sscanf(szTest,"%s %lu %lu %lu %lu %lu %lu %lu",
cpu,&new_cpu_time[cpu_id][0],&new_cpu_time[cpu_id][1],
&new_cpu_time[cpu_id][2],&new_cpu_time[cpu_id][3],
&new_cpu_time[cpu_id][4],&new_cpu_time[cpu_id][5],
&new_cpu_time[cpu_id][6]);
}
fclose(fp);
return 0;
}
/*
* get thermal_zone ID
*/
static int all_thermal_zone_num = 0;
static int thermal_zone_num(void)
{
int i = 0;
char temp[50];
char buf[15];
FILE *fp;
while(1) {
sprintf(temp,"/sys/class/thermal/thermal_zone%d/type",i);
if((fp = fopen(temp,"r")) !=NULL) {
all_thermal_zone_num++;
fread(buf,1,15,fp);
buf[14]=0;
if(strncmp(buf,"mtktsAP",6/*"mtktsbattery",12*/) == 0)
pcb_tz_id = i;
else if(strncmp(buf,"mtktscpu",8/*"mtktscpu",8*/) == 0)
cpu_tz_id = i;
else if(strncmp(buf,"mtktsbattery",12) == 0)
bat_tz_id = i;
fclose(fp);
} else {
break;
}
i++;
}
return all_thermal_zone_num;
}
/*
* get fps
* */
static int get_system_fps(void)
{
FILE *fp;
if((fp = fopen(SYSTEM_FPS_PATH,"r")) != NULL) {
fscanf(fp,"%d",&fps_num);
fclose(fp);
}
return fps_num;
}
static int get_system_gpu_and_power_limit(void)
{
FILE *fp;
if((fp = fopen(SYSTEM_GPU_AND_POWER_LIMIT_PATH,"r")) != NULL) {
fscanf(fp,"%d,%d,%d,%d",&cpu_power_limit,&gpu_power_limit,&curr_gpu_loading,&curr_gpu_freq);
fclose(fp);
}
return 0 ;
}
static void cacl_cpu_loading()
{
int i = 0,j = 0;
for(i = 0; i < SYSTEM_INFO; i++) {
if(new_cpu_time[i][0] == old_cpu_time[i][0]) {
cpu_loading[i] = 0;
continue;
}
for( j = 0; j < CPU_TIME_NUM; j++ ) {
total_cpu_time[i] += (new_cpu_time[i][j] - old_cpu_time[i][j]);
}
user_system_cpu_time[i] = (new_cpu_time[i][0] + new_cpu_time[i][2]) - (old_cpu_time[i][0] + old_cpu_time[i][2]);
cpu_loading[i] = user_system_cpu_time[i] * 100 / total_cpu_time[i];
}
}
static const char *title_name[29]={"time","cpu_temp","bat_temp","pcb_temp","cpu0_freq",
"cpu0_load","cpu1_freq","cpu1_load","cpu2_freq","cpu2_load",
"cpu3_freq","cpu3_load","cpu4_freq","cpu4_load","cpu5_freq",
"cpu5_load","cpu6_freq","cpu6_load","cpu7_freq","cpu7_load",
"cpu8_freq","cpu8_load","cpu9_freq","cpu9_load","gpu_freq",
"gpu_load","fps","cpu_limit","gpu_limit"};
static void usage(char *cmd)
{
fprintf(stderr, "Usage: %s [ -d delay_time ] [ -r running_time ] [ -h ]\n"
" -d num sleep num collect a thermal data, unit is seconds.\n"
" -r num Collect num thermal data.\n"
" -h Display this help screen.\n"
" default running a hour time per a second to collect thermal data.\n",
cmd);
}
int fetch_info_main(int argc, char *argv[])
{
int i = 0,j = 0;
unsigned long time = 0;
int delay_time = 1;
unsigned long running_time = 3600;
create_save_log_file();
char save_log_path[55] = "/data/";
strcat(save_log_path,logfile);
printf("save log path is: %s\n",save_log_path);
for(i = 1; i < argc; i++) {
if(!strcmp(argv[i],"-d")) {
if(i + 1 >= argc) {
fprintf(stderr,"Option -d expects an argument\n");
usage(argv[0]);
return 0;
}
delay_time = atoi(argv[++i]);
if(delay_time > 3)
delay_time = 3;
}
if(!strcmp(argv[i],"-r")) {
if(i + 1 >= argc) {
fprintf(stderr,"Option -r expects an argument\n");
usage(argv[0]);
}
running_time = atol(argv[++i]);
continue;
}
if(!strcmp(argv[i],"-h")) {
usage(argv[0]);
return 0;
}
fprintf(stderr, "Invalid argument \"%s\".\n",argv[i]);
usage(argv[0]);
return 0;
}
for (i = 0;i < 29; ++i) {
char strtemp[256];
sprintf(strtemp,"%s",title_name[i]);
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
}
putString2Csv("",save_log_path,ECWM_OTHERLINE);//must
get_cpu_num();
get_cpu_loading();
while (time++ < running_time) {
/*save old cpu idle and busy time*/
for( i = 0;i < SYSTEM_INFO; i++ ) {
for( j = 0;j < CPU_TIME_NUM;j++) {
old_cpu_time[i][j] = new_cpu_time[i][j];
}
}
sleep(delay_time);
for( i = 0; i< SYSTEM_INFO;i++ ) {
total_cpu_time[i] = 0;
user_system_cpu_time[i] = 0;
}
get_cpu_loading();
cacl_cpu_loading();
/*
* collect data and format data.
* */
thermal_zone_num();
get_system_fps();
get_cpu_freq();
get_system_gpu_and_power_limit();
char strtemp[256];
create_collect_log_timestamp();
sprintf(strtemp,"%s",outfile);
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
sprintf(strtemp,"%d",get_sensor_temp(cpu_tz_id));
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
sprintf(strtemp,"%d",get_sensor_temp(bat_tz_id));
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
sprintf(strtemp,"%d",get_sensor_temp(pcb_tz_id));
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
for(i = 0;i < SYSTEM_INFO;i++) {
sprintf(strtemp,"%lu",curr_cpu_freq[i]);
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
sprintf(strtemp,"%lu",cpu_loading[i]);
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
}
sprintf(strtemp,"%d",curr_gpu_freq);
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
sprintf(strtemp,"%d",curr_gpu_loading);
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
sprintf(strtemp,"%d",fps_num);
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
sprintf(strtemp,"%d",cpu_power_limit);
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
sprintf(strtemp,"%d",gpu_power_limit);
putString2Csv(strtemp,save_log_path,ECWM_ONELINE);
putString2Csv("",save_log_path,ECWM_OTHERLINE);//must
#if 1
for( i = 0;i < SYSTEM_INFO;i++ ) {
for(j = 0;j < CPU_TIME_NUM;j++) {
old_cpu_time[i][j] = 0;
}
cpu_loading[i] = 0;
}
#endif
}
return 0;
}
| 2.109375 | 2 |
2024-11-18T22:48:53.913714+00:00 | 2018-01-22T03:21:42 | 0ec0dcc9429b26ce98cacdc5d1dfc2049b8b8f25 | {
"blob_id": "0ec0dcc9429b26ce98cacdc5d1dfc2049b8b8f25",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-22T03:21:42",
"content_id": "ce6b696612d6465043c7f18c40dcb43fdd749049",
"detected_licenses": [
"BSD-2-Clause-Views"
],
"directory_id": "e8f49eed91153114275420d8a085c552b56497b6",
"extension": "h",
"filename": "elf64.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 120602094,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3825,
"license": "BSD-2-Clause-Views",
"license_type": "permissive",
"path": "/include/sys/elf64.h",
"provenance": "stackv2-0108.json.gz:81636",
"repo_name": "dbaddam/OperatingSystems",
"revision_date": "2018-01-22T03:21:42",
"revision_id": "7fd7c73919f25e7282d47b37660e4afd6bc656cc",
"snapshot_id": "58a5b7b2dc1463ea89398d64356dec772725cf70",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dbaddam/OperatingSystems/7fd7c73919f25e7282d47b37660e4afd6bc656cc/include/sys/elf64.h",
"visit_date": "2021-05-03T07:06:07.334875"
} | stackv2 | #ifndef _ELF64_H
#define _ELF64_H
#define EI_NIDENT 16
#define ELF_RELOC_ERROR -1
typedef uint64_t Elf64_Addr;
typedef uint16_t Elf64_Half;
typedef uint64_t Elf64_Lword;
typedef uint64_t Elf64_Off;
typedef uint32_t Elf64_Sword;
typedef uint64_t Elf64_Sxword;
typedef uint32_t Elf64_Word;
typedef uint64_t Elf64_Xword;
typedef struct
{
unsigned char e_ident[EI_NIDENT];
Elf64_Half e_type;
Elf64_Half e_machine;
Elf64_Word e_version;
Elf64_Addr e_entry;
Elf64_Off e_phoff;
Elf64_Off e_shoff;
Elf64_Word e_flags;
Elf64_Half e_ehsize;
Elf64_Half e_phentsize;
Elf64_Half e_phnum;
Elf64_Half e_shentsize;
Elf64_Half e_shnum;
Elf64_Half e_shstrndx;
} Elf64_Ehdr;
typedef struct
{
Elf64_Word p_type;
Elf64_Word p_flags;
Elf64_Off p_offset;
Elf64_Addr p_vaddr;
Elf64_Addr p_paddr;
Elf64_Xword p_filesz;
Elf64_Xword p_memsz;
Elf64_Xword p_align;
} Elf64_Phdr;
enum Elf_Ident
{
EI_MAG0 = 0, // 0x7F
EI_MAG1 = 1, // 'E'
EI_MAG2 = 2, // 'L'
EI_MAG3 = 3, // 'F'
EI_CLASS = 4, // Architecture (32/64)
EI_DATA = 5, // Byte Order
EI_VERSION = 6, // ELF Version
EI_OSABI = 7, // OS Specific
EI_ABIVERSION = 8, // OS Specific
EI_PAD = 9 // Padding
};
# define ELFMAG0 0x7F // e_ident[EI_MAG0]
# define ELFMAG1 'E' // e_ident[EI_MAG1]
# define ELFMAG2 'L' // e_ident[EI_MAG2]
# define ELFMAG3 'F' // e_ident[EI_MAG3]
# define ELFCLASS32 1 // 32-bit objects
# define ELFCLASS64 2 // 64-bit objects
# define ELFDATA2LSB 1 // obj file data structers are little-endian
# define ELFDATA2MSB 2 // obj file data structers are big-endian
enum Elf_Type
{
ET_NONE = 0, // unknown type
ET_REL = 1, // Recolatable type
ET_EXEC = 2, // Executable type
};
# define EM_X86 0x3E // x86 machine type, from elf wiki page
# define EV_CURRENT 1 // ELF current version
typedef struct
{
Elf64_Word sh_name; /* Section name */
Elf64_Word sh_type; /* Section type */
Elf64_Xword sh_flags; /* Section attributes */
Elf64_Addr sh_addr; /* Virtual address in memory */
Elf64_Off sh_offset; /* Offset in file */
Elf64_Xword sh_size; /* Size of section */
Elf64_Word sh_link; /* Link to other section */
Elf64_Word sh_info; /* Miscellaneous information */
Elf64_Xword sh_addralign; /* Address alignment boundary */
Elf64_Xword sh_entsize; /* Size of entries, if section has table */
} Elf64_Shdr;
# define SHN_UNDEF (0x00) // Undefined/Not present
enum ShT_Types
{
SHT_NULL = 0, // Null section
SHT_PROGBITS = 1, // Program information
SHT_SYMTAB = 2, // Symbol table
SHT_STRTAB = 3, // String table
SHT_RELA = 4, // Relocation (w/ addend)
SHT_NOBITS = 8, // Not present in file
SHT_REL = 9 // Relocation (no addend)
};
enum ShT_Attributes
{
SHF_WRITE = 0x01, // Writable section
SHF_ALLOC = 0x02 // Exists in memory
};
typedef struct
{
Elf64_Word st_name; /* Symbol name */
unsigned char st_info; /* Type and Binding attributes */
unsigned char st_other; /* Reserved */
Elf64_Half st_shndx; /* Section table index */
Elf64_Addr st_value; /* Symbol value */
Elf64_Xword st_size; /* Size of object (e.g., common) */
} Elf64_Sym;
# define ELF32_ST_BIND(INFO) ((INFO) >> 4)
# define ELF32_ST_TYPE(INFO) ((INFO) & 0x0F)
enum StT_Bindings
{
STB_LOCAL = 0, // Local scope
STB_GLOBAL = 1, // Global scope
STB_WEAK = 2 // Weak, (ie. __attribute__((weak)))
};
enum StT_Types
{
STT_NOTYPE = 0, // No type
STT_OBJECT = 1, // Variables, arrays, etc.
STT_FUNC = 2 // Methods or functions
};
void *elf_load_file(void *file, uint64_t cr3);
void elf_copy_contents(uint64_t vaddr, uint64_t contents, uint64_t fsize,
uint64_t msize, uint64_t cr3);
int32_t is_elf(void *file);
#endif
| 2.234375 | 2 |
2024-11-18T22:48:54.605425+00:00 | 2023-05-15T14:43:56 | dd975287210e5b5f28a7c66cf76e962dca285285 | {
"blob_id": "dd975287210e5b5f28a7c66cf76e962dca285285",
"branch_name": "refs/heads/main",
"committer_date": "2023-05-15T14:43:56",
"content_id": "7aefabcf16ebdb18d4ae5d00c43bb0722ad9d17d",
"detected_licenses": [
"MIT"
],
"directory_id": "04429b2469e556c36a5d8c46d60a00ff986797c3",
"extension": "c",
"filename": "typedef1.c",
"fork_events_count": 11,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 236056100,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 229,
"license": "MIT",
"license_type": "permissive",
"path": "/eloadasok/07_stilus_mutatok_struct_typedef/sources/typedef1.c",
"provenance": "stackv2-0108.json.gz:81764",
"repo_name": "jabbalaci/Programozas_1",
"revision_date": "2023-05-15T14:43:56",
"revision_id": "c1fa3179ae52b77b8662600d4a061bf2f48fd9a3",
"snapshot_id": "63feb9efd272f55c31efee33bff35af32d2bfd78",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/jabbalaci/Programozas_1/c1fa3179ae52b77b8662600d4a061bf2f48fd9a3/eloadasok/07_stilus_mutatok_struct_typedef/sources/typedef1.c",
"visit_date": "2023-05-25T06:28:16.571136"
} | stackv2 | #include <stdio.h>
/*
A C nyelvet ne magyarosítsuk! Ez csak egy példa.
*/
typedef int egesz;
int main()
{
int a = 5;
egesz b = 9;
printf("%d\n", a); // 5
printf("%d\n", b); // 9
return 0;
}
| 2.9375 | 3 |
2024-11-18T22:48:54.989260+00:00 | 2018-03-23T14:46:49 | 78bb9e9d8ca931e0425b38e079797041088f0063 | {
"blob_id": "78bb9e9d8ca931e0425b38e079797041088f0063",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-23T14:46:49",
"content_id": "2d06e80e245802dc167504ae4b37232259f59c7b",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "a3f1426721628f25d75fa6387af45fb53d7f8c35",
"extension": "c",
"filename": "grow.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 235,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/libs/appengine/geom/box/grow.c",
"provenance": "stackv2-0108.json.gz:82285",
"repo_name": "sahwar/PrivateEye",
"revision_date": "2018-03-23T14:46:49",
"revision_id": "ec404d5d866729ac1877bb67b0b34897f2b7c65d",
"snapshot_id": "444372f264be1c25d074f85fb458f2f344f95c5f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sahwar/PrivateEye/ec404d5d866729ac1877bb67b0b34897f2b7c65d/libs/appengine/geom/box/grow.c",
"visit_date": "2020-09-06T18:28:55.990159"
} | stackv2 |
#include "oslib/os.h"
#include "appengine/geom/box.h"
/* increases the size of box "box" by "change" */
void box_grow(os_box *box, int change)
{
box->x0 -= change;
box->y0 -= change;
box->x1 += change;
box->y1 += change;
}
| 2.109375 | 2 |
2024-11-18T22:48:55.048207+00:00 | 2021-09-14T01:06:12 | c2ad54896d2a23fb9f85067f0287f3f076dae693 | {
"blob_id": "c2ad54896d2a23fb9f85067f0287f3f076dae693",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-14T01:06:12",
"content_id": "4a5ec645ce8ead0729a4ab9f2bceec361abea594",
"detected_licenses": [
"MIT"
],
"directory_id": "a68ba3fc0eb86b0ea1fa21152ba253eeee06b63e",
"extension": "c",
"filename": "Ex3Lista1ESExtra.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 406155520,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1189,
"license": "MIT",
"license_type": "permissive",
"path": "/Sequencial Structures/Entregar Lista 1/Ex3Lista1ESExtra.c",
"provenance": "stackv2-0108.json.gz:82414",
"repo_name": "whoiswelliton/Programming_Fundamentals",
"revision_date": "2021-09-14T01:06:12",
"revision_id": "63d41e0d14b67cc64d38b0188b583dd8f8ac2905",
"snapshot_id": "68e458ce5b1c36f24e82a09085445763be8aa322",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/whoiswelliton/Programming_Fundamentals/63d41e0d14b67cc64d38b0188b583dd8f8ac2905/Sequencial Structures/Entregar Lista 1/Ex3Lista1ESExtra.c",
"visit_date": "2023-09-05T00:55:52.418712"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <Pause.h>
/*
Ler a quantidade de kilowatts de energia elétrica consumidos por uma residência.
Calcular e mostrar o valor em reais de cada kilowatts, o valor total a ser pago e o novo valor a ser pago
por essa residência quando há desconto de 10%. Considere que 100 kilowatts custam 1/7 do salário mínimo.
Ler o valor do salário mínimo.
*/
int main (void)
{
char Continuar;
float K,S,T;
do
{
system("cls");
printf("\n________________________________________________________________________________\n");
printf("Informe a quantidade de kilowatts consumidos no mes: ");
scanf("%f",&K);
printf("Informe o salaraio minimo da casa: ");
scanf("%f",&S);
printf("__________________________________________________________________________________\n");
printf("_________________________________________________________________________________\n\n");
printf("\n Executar Novamente (S/s para Sim): ");
fflush(stdin);
scanf("%c",&Continuar);
}while(Continuar == 's' || Continuar == 'S');
Pause();
}
| 2.9375 | 3 |
2024-11-18T22:48:55.310023+00:00 | 2016-09-15T20:55:13 | 843f1058ee611177a28f49fef17a8ceaaa287993 | {
"blob_id": "843f1058ee611177a28f49fef17a8ceaaa287993",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-15T20:55:13",
"content_id": "d283a86de420e4b6f9ec0b3f1cc33d47fa9922e8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0519f296839596e6704ed1c074f0b2dc940b9b5c",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12728,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/source/main.c",
"provenance": "stackv2-0108.json.gz:82543",
"repo_name": "jessehamner/ukub-sensor-node",
"revision_date": "2016-09-15T20:55:13",
"revision_id": "ee19741c91a1466971a7433b6add3818386ba64a",
"snapshot_id": "f146ccc046ce7dd85d3f5023b4f5639aff9b2a02",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jessehamner/ukub-sensor-node/ee19741c91a1466971a7433b6add3818386ba64a/source/main.c",
"visit_date": "2021-01-14T11:58:14.145521"
} | stackv2 | /*
* KubOS RT
* Copyright (C) 2016 Kubos Corporation
*
* 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 <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include "queue.h"
#include "kubos-hal/gpio.h"
#include "kubos-hal/uart.h"
#include "kubos-hal/i2c.h"
#include "kubos-core/modules/klog.h"
#include "kubos-core/modules/sensors/htu21d.h"
#include "kubos-core/modules/sensors/bno055.h"
#include "kubos-core/modules/fs/fs.h"
#include "kubos-core/modules/fatfs/ff.h"
#include "kubos-core/modules/fatfs/diskio.h"
#include <csp/csp.h>
static bno055_offsets_t offsets;
static bool offsets_set;
static inline void blink(int pin) {
#define BLINK_MS 100
k_gpio_write(pin, 1);
vTaskDelay(1);
k_gpio_write(pin, 0);
}
/**
* This code specifically interacts with the Bosch BNO055
* "Intelligent 9-axis absolute orientation sensor"
* (inertial movement unit / magnetometer / gyroscope)
* and is written against the November 2014 (version 1.2) documentation.
*
*
* Throughout this code, comments that are not meant to be machine-
* readable data are made with leading double-splats (asterisks)
* for ease of extraction.
*
*
* This code assumes that the BNO055 is mounted in the standard
* orientation as specified in the Bosch datasheet. That is,
* AXIS_REMAP_CONFIG is set to P1 (0x24), and
* AXIS_REMAP_SIGN is st to 0x00. Other mounting configurations are
* supported. See
* kubos-core/source/modules/sensors/bno055.c
* and
* kubos-core/modules/sensors/bno055.h
*/
/* ------------ */
/* Functions */
/* ------------ */
/**
* The displayCalStatus function checks calibration status and either
* prints an error statement to UART or else prints the current calibration
* values to UART in a bar- and tab-separated text format.
*/
void displayCalStatus(void)
{
/* Get the four calibration values (0..3) */
/**
* When retrieving the four calibration values (2 bit, 0..3),
* Any sensor data reporting 0 should be ignored, and
* 3 means 'fully calibrated".
*
* KSensorStatus is described in kubos-core/modules/sensors/sensors.h
*/
bno055_calibration_data_t calib;
KSensorStatus status;
status = bno055_get_calibration(&calib);
if( status != SENSOR_OK)
{
printf("** Couldn't get calibration values! Status=%d\r\n", status);
}
/* Display the individual values */
printf("S:\t%d\tG:\t%d\tA:\t%d\tM:\t%d\r\n",
calib.sys,
calib.gyro,
calib.accel,
calib.mag
);
}
/**
* The open_file function ( from the FatFS library) opens the calibration
* profile file, if one exists.
* @param Fil a pointer to the file object structure
* @param settings a string of mode flags, a list of which can be found at
* http://elm-chan.org/fsw/ff/en/open.html
* @return result a table of values which (0 being 'okay') is found at
* http://elm-chan.org/fsw/ff/en/rc.html
*
*/
uint16_t open_file(FIL * Fil, char settings)
{
uint16_t result;
char * path = "CALIB.txt";
result = f_open(Fil, path, settings);
printf("** Opened file: %d\r\n", result);
return result;
}
/**
* The close_file function closes a file and releases the handle.
* @param Fil a pointer to the file object structure
* @return ret a table of values which (0 being 'okay') is found at
* http://elm-chan.org/fsw/ff/en/rc.html
*/
uint16_t close_file(FIL * Fil)
{
uint16_t ret;
ret = f_close(Fil);
return ret;
}
/**
* The read_value function checks for an available string to read
* from the calibration profile file and, if it is available, reads the
* string.
*
* @param Fil, pointer to the file object structure
* @return ret, 0 being 'FR_OK')
* and -1 being either 'at the end of tile' or 'this thing is not a digit'.
*/
uint16_t read_value(FIL * Fil, uint16_t * value)
{
uint16_t ret = FR_OK;
uint16_t temp = 0;
int c;
char buffer[128];
/* Make sure there's something to read */
if(f_eof(Fil))
{
return -1;
}
f_gets(buffer, sizeof buffer, Fil);
if(!isdigit(buffer[0]))
{
return -1;
}
/* convert read string to uint */
for (c = 0; isdigit(buffer[c]); c++)
{
temp = temp * 10 + buffer[c] - '0';
}
*value = temp;
return ret;
}
/**
* write_value: a function to write a calibration profile value to the file.
* If successful, the green LED blinks.
* @param Fil, pointer to the file object structure
* @param value, the thing you want to write to the file
* @return ret, a table of values which (0 being 'okay') is found at
* http://elm-chan.org/fsw/ff/en/rc.html
*/
uint16_t write_value(FIL * Fil, uint16_t value)
{
uint16_t ret;
uint16_t bw;
if ((ret = f_printf(Fil, "%d\n", value)) != -1)
{
blink(K_LED_GREEN);
ret = 0;
}
return ret;
}
/**
* load_calibration: a function to load the calibration profile.
* If it's the first time loading a value, mount the file system too.
* @return ret,
*/
KSensorStatus load_calibration(void)
{
KSensorStatus ret = SENSOR_ERROR;
static FATFS FatFs;
static FIL Fil;
uint16_t sd_stat = FR_OK;
/* Mount the file system if needed. */
if(!offsets_set)
{
sd_stat = f_mount(&FatFs, "", 1);
}
offsets_set = false;
if(sd_stat == FR_OK)
{
/* Open the calibration file */
if((sd_stat = open_file(&Fil, FA_READ | FA_OPEN_EXISTING)) == FR_OK)
{
sd_stat = read_value(&Fil, &offsets.accel_offset_x);
sd_stat |= read_value(&Fil, &offsets.accel_offset_y);
sd_stat |= read_value(&Fil, &offsets.accel_offset_z);
sd_stat |= read_value(&Fil, &offsets.accel_radius);
sd_stat |= read_value(&Fil, &offsets.gyro_offset_x);
sd_stat |= read_value(&Fil, &offsets.gyro_offset_y);
sd_stat |= read_value(&Fil, &offsets.gyro_offset_z);
sd_stat |= read_value(&Fil, &offsets.mag_offset_x);
sd_stat |= read_value(&Fil, &offsets.mag_offset_y);
sd_stat |= read_value(&Fil, &offsets.mag_offset_z);
sd_stat |= read_value(&Fil, &offsets.mag_radius);
if(sd_stat == FR_OK)
{
printf("** Loaded calibration from SD card\r\n");
offsets_set = true;
}
sd_stat = close_file(&Fil);
}
}
/**
* The code is set to provide default calibration values three primary
* sensors (three axes each for the accelerometer, gyroscope, and
* magnetometer, plus a radius value for the accelerometer and magnetometer).
*/
if(!offsets_set)
{
printf("** Loading default calibration values\r\n");
/* Load values into offset structure */
offsets.accel_offset_x = 65530;
offsets.accel_offset_y = 81;
offsets.accel_offset_z = 27;
offsets.accel_radius = 1000;
offsets.gyro_offset_x = 0;
offsets.gyro_offset_y = 0;
offsets.gyro_offset_z = 0;
offsets.mag_offset_x = 65483;
offsets.mag_offset_y = 5;
offsets.mag_offset_z = 76;
offsets.mag_radius = 661;
offsets_set= true;
}
/* Set the values */
ret = bno055_set_sensor_offset_struct(offsets);
return ret;
}
/**
* save_calibration: push the calibration values to a file on the uSD card.
* @param calib the bno055_offsets_t struct that stores calibration values
*/
void save_calibration(bno055_offsets_t calib)
{
static FATFS FatFs;
static FIL Fil;
uint16_t sd_stat = FR_OK;
/* Open calibration file */
if((sd_stat = open_file(&Fil, FA_WRITE | FA_OPEN_ALWAYS)) == FR_OK)
{
sd_stat = write_value(&Fil, calib.accel_offset_x);
sd_stat |= write_value(&Fil, calib.accel_offset_y);
sd_stat |= write_value(&Fil, calib.accel_offset_z);
sd_stat |= write_value(&Fil, calib.accel_radius);
sd_stat |= write_value(&Fil, calib.gyro_offset_x);
sd_stat |= write_value(&Fil, calib.gyro_offset_y);
sd_stat |= write_value(&Fil, calib.gyro_offset_z);
sd_stat |= write_value(&Fil, calib.mag_offset_x);
sd_stat |= write_value(&Fil, calib.mag_offset_y);
sd_stat |= write_value(&Fil, calib.mag_offset_z);
sd_stat |= write_value(&Fil, calib.mag_radius);
if(sd_stat == FR_OK)
{
printf("** Saved calibration to SD card\r\n");
}
close_file(&Fil);
}
}
/**
* task_sensors: the primary task for sensor operation.
*
*/
void task_sensors(void *p)
{
float temp = 0;
float hum = 0;
bno055_quat_data_t quat_data;
bno055_vector_data_t eul_vector;
bno055_vector_data_t grav_vector;
bno055_vector_data_t lin_vector;
bno055_vector_data_t acc_vector;
uint32_t time_ms;
static char msg[255];
uint8_t count = 1;
uint8_t calibCount = 0;
uint8_t oldCount = 0;
static KI2CStatus bno_stat;
htu21d_setup();
htu21d_reset();
bno_stat = bno055_setup(OPERATION_MODE_NDOF);
load_calibration(); //Load bno055 calibration profile
// get_position(&pos_vector);
blink(K_LED_ORANGE);
htu21d_read_temperature(&temp);
blink(K_LED_ORANGE);
htu21d_read_humidity(&hum);
/**
* the Orange LED (on the MicroPython board) blinks orange when reading the
* temperature value.
*/
while(1)
{
blink(K_LED_ORANGE);
time_ms = csp_get_ms();
if ((++count % 30) == 0)
{
blink(K_LED_ORANGE);
htu21d_read_temperature(&temp);
blink(K_LED_ORANGE);
htu21d_read_temperature(&temp);
blink(K_LED_ORANGE);
displayCalStatus();
/* Check status of calibration */
oldCount = calibCount;
if(bno055_check_calibration(&calibCount, 5, &offsets) != SENSOR_OK)
{
/* Reload the calibration profile */
if(calibCount == 0)
{
printf("** Reloading calibration profile\r\n");
load_calibration();
}
/**
* While the calibration profile is being loaded, the red LED will blink
* in three-blink groups.
*/
blink(K_LED_RED);
vTaskDelay(100);
blink(K_LED_RED);
vTaskDelay(100);
blink(K_LED_RED);
}
else if(oldCount != 0)
{
save_calibration(offsets);
}
count = 1;
}
/**
* If the I2C setup is okay and the sensor is calibrated, the system will
* blink the orange LED as it gets the quaternions data and the
* Euler angles (here again, note the sensor is expected to be in
* "fusion mode" and not gathering raw inputs).
*
* Next, display the calibration status.
*
* Then print out the resulting data separated by bars.
* Upon writing the string to the UART, the green LED will blink.
*/
if (bno_stat != I2C_OK && bno_stat != SENSOR_NOT_CALIBRATED)
{
printf("** bno_stat = %d\r\n", bno_stat);
blink(K_LED_RED);
blink(K_LED_RED);
bno_stat = bno055_setup(OPERATION_MODE_NDOF);
load_calibration();
}
else
{
blink(K_LED_ORANGE);
bno055_get_position(&quat_data);
blink(K_LED_ORANGE);
bno055_get_data_vector(VECTOR_EULER, &eul_vector);
blink(K_LED_ORANGE);
bno055_get_data_vector(VECTOR_GRAVITY, &grav_vector);
blink(K_LED_ORANGE);
bno055_get_data_vector(VECTOR_LINEARACCEL, &lin_vector);
blink(K_LED_ORANGE);
bno055_get_data_vector(VECTOR_ACCELEROMETER, &acc_vector);
}
sprintf(msg, "%d|%3.2f|%3.2f|%f|%f|%f|%f|%f|%f|%f|%f|%f|%f|%f|%f|%f|%f|%f|%f\r\n",
time_ms, temp, hum,
quat_data.w, quat_data.x, quat_data.y, quat_data.z,
eul_vector.x, eul_vector.y, eul_vector.z,
grav_vector.x, grav_vector.y, grav_vector.z,
lin_vector.x, lin_vector.y, lin_vector.z,
acc_vector.x, acc_vector.y, acc_vector.z
);
k_uart_write(K_UART_CONSOLE, msg, strlen(msg));
blink(K_LED_GREEN);
}
}
/* ------------ */
/* Main */
/* ------------ */
int main(void)
{
k_uart_console_init();
k_gpio_init(K_LED_GREEN, K_GPIO_OUTPUT, K_GPIO_PULL_NONE);
k_gpio_init(K_LED_ORANGE, K_GPIO_OUTPUT, K_GPIO_PULL_NONE);
k_gpio_init(K_LED_RED, K_GPIO_OUTPUT, K_GPIO_PULL_NONE);
k_gpio_init(K_LED_BLUE, K_GPIO_OUTPUT, K_GPIO_PULL_NONE);
xTaskCreate(task_sensors, "sensors", configMINIMAL_STACK_SIZE * 4, NULL, 2, NULL);
vTaskStartScheduler();
return 0;
}
| 2.140625 | 2 |
2024-11-18T22:48:55.581077+00:00 | 2018-11-15T19:10:18 | 7f74a2e977da8b96fd5a43ad55ba6e8babfdeabd | {
"blob_id": "7f74a2e977da8b96fd5a43ad55ba6e8babfdeabd",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-15T19:10:18",
"content_id": "473c7c2d2b1d60cd96347232122b63d221c0e1e2",
"detected_licenses": [
"MIT"
],
"directory_id": "ca84f482c3290b34471b5f48abfdc5927f1a05dc",
"extension": "c",
"filename": "ETHERDFS.C",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 157753595,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 72980,
"license": "MIT",
"license_type": "permissive",
"path": "/src/ETHERDFS.C",
"provenance": "stackv2-0108.json.gz:82929",
"repo_name": "BrianHoldsworth/etherdfs-client",
"revision_date": "2018-11-15T19:10:18",
"revision_id": "36eb9e4320dfc50eb6779899cdccb39920db17c9",
"snapshot_id": "dddcd9e9e1df770169cf8a996204df537138abcd",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/BrianHoldsworth/etherdfs-client/36eb9e4320dfc50eb6779899cdccb39920db17c9/src/ETHERDFS.C",
"visit_date": "2020-04-06T19:53:49.999082"
} | stackv2 | /*
* EtherDFS - a network drive for DOS running over raw ethernet
* http://etherdfs.sourceforge.net
*
* Copyright (C) 2017, 2018 Mateusz Viste
*
* 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 <i86.h> /* union INTPACK */
#include "chint.h" /* _mvchain_intr() */
#include "version.h" /* program & protocol version */
/* set DEBUGLEVEL to 0, 1 or 2 to turn on debug mode with desired verbosity */
#define DEBUGLEVEL 0
/* define the maximum size of a frame, as sent or received by etherdfs.
* example: value 1084 accomodates payloads up to 1024 bytes +all headers */
#define FRAMESIZE 1090
#include "dosstruc.h" /* definitions of structures used by DOS */
#include "globals.h" /* global variables used by etherdfs */
/* define NULL, for readability of the code */
#ifndef NULL
#define NULL (void *)0
#endif
/* all the resident code goes to segment 'BEGTEXT' */
#pragma code_seg(BEGTEXT, CODE)
/* copies l bytes from *s to *d */
static void copybytes(void far *d, void far *s, unsigned int l) {
while (l != 0) {
l--;
*(unsigned char far *)d = *(unsigned char far *)s;
d = (unsigned char far *)d + 1;
s = (unsigned char far *)s + 1;
}
}
static unsigned short mystrlen(void far *s) {
unsigned short res = 0;
while (*(unsigned char far *)s != 0) {
res++;
s = ((unsigned char far *)s) + 1;
}
return(res);
}
/* returns -1 if the NULL-terminated s string contains any wildcard (?, *)
* character. otherwise returns the length of the string. */
static int len_if_no_wildcards(char far *s) {
int r = 0;
for (;;) {
switch (*s) {
case 0: return(r);
case '?':
case '*': return(-1);
}
r++;
s++;
}
}
/* computes a BSD checksum of l bytes at dataptr location */
static unsigned short bsdsum(unsigned char *dataptr, unsigned short l) {
unsigned short cksum = 0;
_asm {
cld /* clear direction flag */
xor bx, bx /* bx will hold the result */
xor ax, ax
mov cx, l
mov si, dataptr
iterate:
lodsb /* load a byte from DS:SI into AL and INC SI */
ror bx, 1
add bx, ax
dec cx /* DEC CX + JNZ could be replaced by a single LOOP */
jnz iterate /* instruction, but DEC+JNZ is 3x faster (on 8086) */
mov cksum, bx
}
return(cksum);
}
/* this function is called two times by the packet driver. One time for
* telling that a packet is incoming, and how big it is, so the application
* can prepare a buffer for it and hand it back to the packet driver. the
* second call is just to let know that the frame has been copied into the
* buffer. This is a naked function - I don't need the compiler to get into
* the way when dealing with packet driver callbacks.
* IMPORTANT: this function must take care to modify ONLY the registers
* ES and DI - packet drivers can be easily confused should anything else
* be modified. */
void __declspec(naked) far pktdrv_recv(void) {
_asm {
jmp skip
SIG db 'p','k','t','r'
skip:
/* save DS and flags to stack */
push ds /* save old ds (I will change it) */
push bx /* save bx (I use it as a temporary register) */
pushf /* save flags */
/* set my custom DS (not 0, it has been patched at runtime already) */
mov bx, 0
mov ds, bx
/* handle the call */
cmp ax, 0
jne secondcall /* if ax != 0, then packet driver just filled my buffer */
/* first call: the packet driver needs a buffer of CX bytes */
cmp cx, FRAMESIZE /* is cx > FRAMESIZE ? (unsigned) */
ja nobufferavail /* it is too small (that's what she said!) */
/* see if buffer not filled already... */
cmp glob_pktdrv_recvbufflen, 0 /* is bufflen > 0 ? (signed) */
jg nobufferavail /* if signed > 0, then we are busy already */
/* buffer is available, set its seg:off in es:di */
push ds /* set es:di to recvbuff */
pop es
mov di, offset glob_pktdrv_recvbuff
/* set bufferlen to expected len and switch it to neg until data comes */
mov glob_pktdrv_recvbufflen, cx
neg glob_pktdrv_recvbufflen
/* restore flags, bx and ds, then return */
jmp restoreandret
nobufferavail: /* no buffer available, or it's too small -> fail */
xor bx,bx /* set bx to zero... */
push bx /* and push it to the stack... */
push bx /* twice */
pop es /* zero out es and di - this tells the */
pop di /* packet driver 'sorry no can do' */
/* restore flags, bx and ds, then return */
jmp restoreandret
secondcall: /* second call: I've just got data in buff */
/* I switch back bufflen to positive so the app can see that something is there now */
neg glob_pktdrv_recvbufflen
/* restore flags, bx and ds, then return */
restoreandret:
popf /* restore flags */
pop bx /* restore bx */
pop ds /* restore ds */
retf
}
}
/* translates a drive letter (either upper- or lower-case) into a number (A=0,
* B=1, C=2, etc) */
#define DRIVETONUM(x) (((x) >= 'a') && ((x) <= 'z')?x-'a':x-'A')
/* all the calls I support are in the range AL=0..2Eh - the list below serves
* as a convenience to compare AL (subfunction) values */
enum AL_SUBFUNCTIONS {
AL_INSTALLCHK = 0x00,
AL_RMDIR = 0x01,
AL_MKDIR = 0x03,
AL_CHDIR = 0x05,
AL_CLSFIL = 0x06,
AL_CMMTFIL = 0x07,
AL_READFIL = 0x08,
AL_WRITEFIL = 0x09,
AL_LOCKFIL = 0x0A,
AL_UNLOCKFIL = 0x0B,
AL_DISKSPACE = 0x0C,
AL_SETATTR = 0x0E,
AL_GETATTR = 0x0F,
AL_RENAME = 0x11,
AL_DELETE = 0x13,
AL_OPEN = 0x16,
AL_CREATE = 0x17,
AL_FINDFIRST = 0x1B,
AL_FINDNEXT = 0x1C,
AL_SKFMEND = 0x21,
AL_UNKNOWN_2D = 0x2D,
AL_SPOPNFIL = 0x2E,
AL_UNKNOWN = 0xFF
};
/* this table makes it easy to figure out if I want a subfunction or not */
static unsigned char supportedfunctions[0x2F] = {
AL_INSTALLCHK, /* 0x00 */
AL_RMDIR, /* 0x01 */
AL_UNKNOWN, /* 0x02 */
AL_MKDIR, /* 0x03 */
AL_UNKNOWN, /* 0x04 */
AL_CHDIR, /* 0x05 */
AL_CLSFIL, /* 0x06 */
AL_CMMTFIL, /* 0x07 */
AL_READFIL, /* 0x08 */
AL_WRITEFIL, /* 0x09 */
AL_LOCKFIL, /* 0x0A */
AL_UNLOCKFIL, /* 0x0B */
AL_DISKSPACE, /* 0x0C */
AL_UNKNOWN, /* 0x0D */
AL_SETATTR, /* 0x0E */
AL_GETATTR, /* 0x0F */
AL_UNKNOWN, /* 0x10 */
AL_RENAME, /* 0x11 */
AL_UNKNOWN, /* 0x12 */
AL_DELETE, /* 0x13 */
AL_UNKNOWN, /* 0x14 */
AL_UNKNOWN, /* 0x15 */
AL_OPEN, /* 0x16 */
AL_CREATE, /* 0x17 */
AL_UNKNOWN, /* 0x18 */
AL_UNKNOWN, /* 0x19 */
AL_UNKNOWN, /* 0x1A */
AL_FINDFIRST, /* 0x1B */
AL_FINDNEXT, /* 0x1C */
AL_UNKNOWN, /* 0x1D */
AL_UNKNOWN, /* 0x1E */
AL_UNKNOWN, /* 0x1F */
AL_UNKNOWN, /* 0x20 */
AL_SKFMEND, /* 0x21 */
AL_UNKNOWN, /* 0x22 */
AL_UNKNOWN, /* 0x23 */
AL_UNKNOWN, /* 0x24 */
AL_UNKNOWN, /* 0x25 */
AL_UNKNOWN, /* 0x26 */
AL_UNKNOWN, /* 0x27 */
AL_UNKNOWN, /* 0x28 */
AL_UNKNOWN, /* 0x29 */
AL_UNKNOWN, /* 0x2A */
AL_UNKNOWN, /* 0x2B */
AL_UNKNOWN, /* 0x2C */
AL_UNKNOWN_2D, /* 0x2D */
AL_SPOPNFIL /* 0x2E */
};
/*
an INTPACK struct contains following items:
regs.w.gs
regs.w.fs
regs.w.es
regs.w.ds
regs.w.di
regs.w.si
regs.w.bp
regs.w.sp
regs.w.bx
regs.w.dx
regs.w.cx
regs.w.ax
regs.w.ip
regs.w.cs
regs.w.flags (AND with INTR_CF to fetch the CF flag - INTR_CF is defined as 0x0001)
regs.h.bl
regs.h.bh
regs.h.dl
regs.h.dh
regs.h.cl
regs.h.ch
regs.h.al
regs.h.ah
*/
/* sends query out, as found in glob_pktdrv_sndbuff, and awaits for an answer.
* this function returns the length of replyptr, or 0xFFFF on error. */
static unsigned short sendquery(unsigned char query, unsigned char drive, unsigned short bufflen, unsigned char **replyptr, unsigned short **replyax, unsigned int updatermac) {
static unsigned char seq;
unsigned short count;
unsigned char t;
unsigned char volatile far *rtc = (unsigned char far *)0x46C; /* this points to a char, while the rtc timer is a word - but I care only about the lowest 8 bits. Be warned that this location won't increment while interrupts are disabled! */
/* resolve remote drive - no need to validate it, it has been validated
* already by inthandler() */
drive = glob_data.ldrv[drive];
/* bufflen provides payload's lenght, but I prefer knowing the frame's len */
bufflen += 60;
/* if query too long then quit */
if (bufflen > sizeof(glob_pktdrv_sndbuff)) return(0);
/* inc seq */
seq++;
/* I do not fill in ethernet headers (src mac, dst mac, ethertype), nor
* PROTOVER, since all these have been inited already at transient time */
/* padding (38 bytes) */
((unsigned short *)glob_pktdrv_sndbuff)[26] = bufflen; /* total frame len */
glob_pktdrv_sndbuff[57] = seq; /* seq number */
glob_pktdrv_sndbuff[58] = drive;
glob_pktdrv_sndbuff[59] = query; /* AL value (query) */
if (glob_pktdrv_sndbuff[56] & 128) { /* if CKSUM enabled, compute it */
/* fill in the BSD checksum at offset 54 */
((unsigned short *)glob_pktdrv_sndbuff)[27] = bsdsum(glob_pktdrv_sndbuff + 56, bufflen - 56);
}
/* I do not copy anything more into glob_pktdrv_sndbuff - the caller is
* expected to have already copied all relevant data into glob_pktdrv_sndbuff+60
* copybytes((unsigned char far *)glob_pktdrv_sndbuff + 60, (unsigned char far *)buff, bufflen);
*/
/* send the query frame and wait for an answer for about 100ms. then, resend
* the query again and again, up to 5 times. the RTC clock at 0x46C is used
* as a timing reference. */
glob_pktdrv_recvbufflen = 0; /* mark the receiving buffer empty */
for (count = 5; count != 0; count--) { /* faster than count=0; count<5; count++ */
/* send the query frame out */
_asm {
/* save registers */
push ax
push cx
push dx /* may be changed by the packet driver (set to errno) */
push si
pushf /* must be last register pushed (expected by 'call') */
/* */
mov ah, 4h /* SendPkt */
mov cx, bufflen
mov si, offset glob_pktdrv_sndbuff /* DS:SI points to buff, I do not
modify DS because the buffer should already
be in my data segment (small memory model) */
/* int to variable vector is a mess, so I have fetched its vector myself
* and pushf + cli + call far it now to simulate a regular int */
/* pushf -- already on the stack */
cli
call dword ptr glob_pktdrv_pktcall
/* restore registers (but not pushf, already restored by call) */
pop si
pop dx
pop cx
pop ax
}
/* wait for (and validate) the answer frame */
t = *rtc;
for (;;) {
int i;
if ((t != *rtc) && (t+1 != *rtc) && (*rtc != 0)) break; /* timeout, retry */
if (glob_pktdrv_recvbufflen < 1) continue;
/* I've got something! */
/* is the frame long enough for me to care? */
if (glob_pktdrv_recvbufflen < 60) goto ignoreframe;
/* is it for me? (correct src mac & dst mac) */
for (i = 0; i < 6; i++) {
if (glob_pktdrv_recvbuff[i] != GLOB_LMAC[i]) goto ignoreframe;
if ((updatermac == 0) && (glob_pktdrv_recvbuff[i+6] != GLOB_RMAC[i])) goto ignoreframe;
}
/* is the ethertype and seq what I expect? */
if ((((unsigned short *)glob_pktdrv_recvbuff)[6] != 0xF5EDu) || (glob_pktdrv_recvbuff[57] != seq)) goto ignoreframe;
/* validate frame length (if provided) */
if (((unsigned short *)glob_pktdrv_recvbuff)[26] > glob_pktdrv_recvbufflen) {
/* frame appears to be truncated */
goto ignoreframe;
}
if (((unsigned short *)glob_pktdrv_recvbuff)[26] < 60) {
/* malformed frame */
goto ignoreframe;
}
glob_pktdrv_recvbufflen = ((unsigned short *)glob_pktdrv_recvbuff)[26];
/* if CKSUM enabled, check it on received frame */
if (glob_pktdrv_sndbuff[56] & 128) {
/* is the cksum ok? */
if (bsdsum(glob_pktdrv_recvbuff + 56, glob_pktdrv_recvbufflen - 56) != (((unsigned short *)glob_pktdrv_recvbuff)[27])) {
/* DEBUG - prints a '!' on screen on cksum error */ /*{
unsigned short far *v = (unsigned short far *)0xB8000000l;
v[0] = 0x4000 | '!';
}*/
goto ignoreframe;
}
}
/* return buffer (without headers and seq) */
*replyptr = glob_pktdrv_recvbuff + 60;
*replyax = (unsigned short *)(glob_pktdrv_recvbuff + 58);
/* update glob_rmac if needed, then return */
if (updatermac != 0) copybytes(GLOB_RMAC, glob_pktdrv_recvbuff + 6, 6);
return(glob_pktdrv_recvbufflen - 60);
ignoreframe: /* ignore this frame and wait for the next one */
glob_pktdrv_recvbufflen = 0; /* mark the buffer empty */
}
}
return(0xFFFFu); /* return error */
}
/* reset CF (set on error only) and AX (expected to contain the error code,
* I might set it later) - I assume a success */
#define SUCCESSFLAG glob_intregs.w.ax = 0; glob_intregs.w.flags &= ~(INTR_CF);
#define FAILFLAG(x) {glob_intregs.w.ax = x; glob_intregs.w.flags |= INTR_CF;}
/* this function contains the logic behind INT 2F processing */
void process2f(void) {
#if DEBUGLEVEL > 0
char far *dbg_msg = NULL;
#endif
short i;
unsigned char *answer;
unsigned char *buff; /* pointer to the "query arguments" part of glob_pktdrv_sndbuff */
unsigned char subfunction;
unsigned short *ax; /* used to collect the resulting value of AX */
buff = glob_pktdrv_sndbuff + 60;
/* DEBUG output (RED) */
#if DEBUGLEVEL > 0
dbg_xpos &= 511;
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x4e00 | ' ';
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x4e00 | (dbg_hexc[(glob_intregs.h.al >> 4) & 0xf]);
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x4e00 | (dbg_hexc[glob_intregs.h.al & 0xf]);
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x4e00 | ' ';
#endif
/* remember the AL register (0x2F subfunction id) */
subfunction = glob_intregs.h.al;
/* if we got here, then the call is definitely for us. set AX and CF to */
/* 'success' (being a natural optimist I assume success) */
SUCCESSFLAG;
/* look what function is called exactly and process it */
switch (subfunction) {
case AL_RMDIR: /*** 01h: RMDIR ******************************************/
/* RMDIR is like MKDIR, but I need to check if dir is not current first */
for (i = 0; glob_sdaptr->fn1[i] != 0; i++) {
if (glob_sdaptr->fn1[i] != glob_sdaptr->drive_cdsptr[i]) goto proceedasmkdir;
}
FAILFLAG(16); /* err 16 = "attempted to remove current directory" */
break;
proceedasmkdir:
case AL_MKDIR: /*** 03h: MKDIR ******************************************/
i = mystrlen(glob_sdaptr->fn1);
/* fn1 must be at least 2 bytes long */
if (i < 2) {
FAILFLAG(3); /* "path not found" */
break;
}
/* copy fn1 to buff (but skip drive part) */
i -= 2;
copybytes(buff, glob_sdaptr->fn1 + 2, i);
/* send query providing fn1 */
if (sendquery(subfunction, glob_reqdrv, i, &answer, &ax, 0) == 0) {
glob_intregs.w.ax = *ax;
if (*ax != 0) glob_intregs.w.flags |= INTR_CF;
} else {
FAILFLAG(2);
}
break;
case AL_CHDIR: /*** 05h: CHDIR ******************************************/
/* The INT 2Fh/1105h redirector callback is executed by DOS when
* changing directories. The Phantom authors (and RBIL contributors)
* clearly thought that it was the redirector's job to update the CDS,
* but in fact the callback is only meant to validate that the target
* directory exists; DOS subsequently updates the CDS. */
/* fn1 must be at least 2 bytes long */
i = mystrlen(glob_sdaptr->fn1);
if (i < 2) {
FAILFLAG(3); /* "path not found" */
break;
}
/* copy fn1 to buff (but skip the drive: part) */
i -= 2;
copybytes(buff, glob_sdaptr->fn1 + 2, i);
/* send query providing fn1 */
if (sendquery(AL_CHDIR, glob_reqdrv, i, &answer, &ax, 0) == 0) {
glob_intregs.w.ax = *ax;
if (*ax != 0) glob_intregs.w.flags |= INTR_CF;
} else {
FAILFLAG(3); /* "path not found" */
}
break;
case AL_CLSFIL: /*** 06h: CLSFIL ****************************************/
/* my only job is to decrement the SFT's handle count (which I didn't
* have to increment during OPENFILE since DOS does it... talk about
* consistency. I also inform the server about this, just so it knows */
/* ES:DI points to the SFT */
{
struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di);
if (sftptr->handle_count > 0) sftptr->handle_count--;
((unsigned short *)buff)[0] = sftptr->start_sector;
if (sendquery(AL_CLSFIL, glob_reqdrv, 2, &answer, &ax, 0) == 0) {
if (*ax != 0) FAILFLAG(*ax);
}
}
break;
case AL_CMMTFIL: /*** 07h: CMMTFIL **************************************/
/* I have nothing to do here */
break;
case AL_READFIL: /*** 08h: READFIL **************************************/
{ /* ES:DI points to the SFT (whose file_pos needs to be updated) */
/* CX = number of bytes to read (to be updated with number of bytes actually read) */
/* SDA DTA = read buffer */
struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di);
unsigned short totreadlen;
/* is the file open for write-only? */
if (sftptr->open_mode & 1) {
FAILFLAG(5); /* "access denied" */
break;
}
/* return immediately if the caller wants to read 0 bytes */
if (glob_intregs.x.cx == 0) break;
/* do multiple read operations so chunks can fit in my eth frames */
totreadlen = 0;
for (;;) {
int chunklen, len;
if ((glob_intregs.x.cx - totreadlen) < (FRAMESIZE - 60)) {
chunklen = glob_intregs.x.cx - totreadlen;
} else {
chunklen = FRAMESIZE - 60;
}
/* query is OOOOSSLL (offset, start sector, lenght to read) */
((unsigned long *)buff)[0] = sftptr->file_pos + totreadlen;
((unsigned short *)buff)[2] = sftptr->start_sector;
((unsigned short *)buff)[3] = chunklen;
len = sendquery(AL_READFIL, glob_reqdrv, 8, &answer, &ax, 0);
if (len == 0xFFFFu) { /* network error */
FAILFLAG(2);
break;
} else if (*ax != 0) { /* backend error */
FAILFLAG(*ax);
break;
} else { /* success */
copybytes(glob_sdaptr->curr_dta + totreadlen, answer, len);
totreadlen += len;
if ((len < chunklen) || (totreadlen == glob_intregs.x.cx)) { /* EOF - update SFT and break out */
sftptr->file_pos += totreadlen;
glob_intregs.x.cx = totreadlen;
break;
}
}
}
}
break;
case AL_WRITEFIL: /*** 09h: WRITEFIL ************************************/
{ /* ES:DI points to the SFT (whose file_pos needs to be updated) */
/* CX = number of bytes to write (to be updated with number of bytes actually written) */
/* SDA DTA = read buffer */
struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di);
unsigned short bytesleft, chunklen, written = 0;
/* is the file open for read-only? */
if ((sftptr->open_mode & 3) == 0) {
FAILFLAG(5); /* "access denied" */
break;
}
/* TODO FIXME I should update the file's time in the SFT here */
/* do multiple write operations so chunks can fit in my eth frames */
bytesleft = glob_intregs.x.cx;
while (bytesleft > 0) {
unsigned short len;
chunklen = bytesleft;
if (chunklen > FRAMESIZE - 66) chunklen = FRAMESIZE - 66;
/* query is OOOOSS (file offset, start sector/fileid) */
((unsigned long *)buff)[0] = sftptr->file_pos;
((unsigned short *)buff)[2] = sftptr->start_sector;
copybytes(buff + 6, glob_sdaptr->curr_dta + written, chunklen);
len = sendquery(AL_WRITEFIL, glob_reqdrv, chunklen + 6, &answer, &ax, 0);
if (len == 0xFFFFu) { /* network error */
FAILFLAG(2);
break;
} else if ((*ax != 0) || (len != 2)) { /* backend error */
FAILFLAG(*ax);
break;
} else { /* success - write amount of bytes written into CX and update SFT */
len = ((unsigned short *)answer)[0];
written += len;
bytesleft -= len;
glob_intregs.x.cx = written;
sftptr->file_pos += len;
if (sftptr->file_pos > sftptr->file_size) sftptr->file_size = sftptr->file_pos;
if (len != chunklen) break; /* something bad happened on the other side */
}
}
}
break;
case AL_LOCKFIL: /*** 0Ah: LOCKFIL **************************************/
{
struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di);
((unsigned short *)buff)[0] = glob_intregs.x.cx;
((unsigned short *)buff)[1] = sftptr->start_sector;
if (glob_intregs.h.bl > 1) FAILFLAG(2); /* BL should be either 0 (lock) or 1 (unlock) */
/* copy 8*CX bytes from DS:DX to buff+4 (parameters block) */
copybytes(buff + 4, MK_FP(glob_intregs.x.ds, glob_intregs.x.dx), glob_intregs.x.cx << 3);
if (sendquery(AL_LOCKFIL + glob_intregs.h.bl, glob_reqdrv, (glob_intregs.x.cx << 3) + 4, &answer, &ax, 0) != 0) {
FAILFLAG(2);
}
}
break;
case AL_UNLOCKFIL: /*** 0Bh: UNLOCKFIL **********************************/
/* Nothing here - this isn't supposed to be used by DOS 4+ */
FAILFLAG(2);
break;
case AL_DISKSPACE: /*** 0Ch: get disk information ***********************/
if (sendquery(AL_DISKSPACE, glob_reqdrv, 0, &answer, &ax, 0) == 6) {
glob_intregs.w.ax = *ax; /* sectors per cluster */
glob_intregs.w.bx = ((unsigned short *)answer)[0]; /* total clusters */
glob_intregs.w.cx = ((unsigned short *)answer)[1]; /* bytes per sector */
glob_intregs.w.dx = ((unsigned short *)answer)[2]; /* num of available clusters */
} else {
FAILFLAG(2);
}
break;
case AL_SETATTR: /*** 0Eh: SETATTR **************************************/
/* sdaptr->fn1 -> file to set attributes for
stack word -> new attributes (stack must not be changed!) */
/* fn1 must be at least 2 characters long */
i = mystrlen(glob_sdaptr->fn1);
if (i < 2) {
FAILFLAG(2);
break;
}
/* */
buff[0] = glob_reqstkword;
/* copy fn1 to buff (but without the drive part) */
copybytes(buff + 1, glob_sdaptr->fn1 + 2, i - 2);
#if DEBUGLEVEL > 0
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1000 | dbg_hexc[(glob_reqstkword >> 4) & 15];
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1000 | dbg_hexc[glob_reqstkword & 15];
#endif
i = sendquery(AL_SETATTR, glob_reqdrv, i - 1, &answer, &ax, 0);
if (i != 0) {
FAILFLAG(2);
} else if (*ax != 0) {
FAILFLAG(*ax);
}
break;
case AL_GETATTR: /*** 0Fh: GETATTR **************************************/
i = mystrlen(glob_sdaptr->fn1);
if (i < 2) {
FAILFLAG(2);
break;
}
i -= 2;
copybytes(buff, glob_sdaptr->fn1 + 2, i);
i = sendquery(AL_GETATTR, glob_reqdrv, i, &answer, &ax, 0);
if ((unsigned short)i == 0xffffu) {
FAILFLAG(2);
} else if ((i != 9) || (*ax != 0)) {
FAILFLAG(*ax);
} else { /* all good */
/* CX = timestamp
* DX = datestamp
* BX:DI = fsize
* AX = attr
* NOTE: Undocumented DOS talks only about setting AX, no fsize, time
* and date, these are documented in RBIL and used by SHSUCDX */
glob_intregs.w.cx = ((unsigned short *)answer)[0]; /* time */
glob_intregs.w.dx = ((unsigned short *)answer)[1]; /* date */
glob_intregs.w.bx = ((unsigned short *)answer)[3]; /* fsize hi word */
glob_intregs.w.di = ((unsigned short *)answer)[2]; /* fsize lo word */
glob_intregs.w.ax = answer[8]; /* file attribs */
}
break;
case AL_RENAME: /*** 11h: RENAME ****************************************/
/* sdaptr->fn1 = old name
* sdaptr->fn2 = new name */
/* is the operation for the SAME drive? */
if (glob_sdaptr->fn1[0] != glob_sdaptr->fn2[0]) {
FAILFLAG(2);
break;
}
/* prepare the query (LSSS...DDD...) */
i = mystrlen(glob_sdaptr->fn1);
if (i < 2) {
FAILFLAG(2);
break;
}
i -= 2; /* trim out the drive: part (C:\FILE --> \FILE) */
buff[0] = i;
copybytes(buff + 1, glob_sdaptr->fn1 + 2, i);
i = len_if_no_wildcards(glob_sdaptr->fn2);
if (i < 2) {
FAILFLAG(3);
break;
}
i -= 2; /* trim out the drive: part (C:\FILE --> \FILE) */
copybytes(buff + 1 + buff[0], glob_sdaptr->fn2 + 2, i);
/* send the query out */
i = sendquery(AL_RENAME, glob_reqdrv, 1 + buff[0] + i, &answer, &ax, 0);
if (i != 0) {
FAILFLAG(2);
} else if (*ax != 0) {
FAILFLAG(*ax);
}
break;
case AL_DELETE: /*** 13h: DELETE ****************************************/
#if DEBUGLEVEL > 0
dbg_msg = glob_sdaptr->fn1;
#endif
/* compute length of fn1 and copy it to buff (w/o the 'drive:' part) */
i = mystrlen(glob_sdaptr->fn1);
if (i < 2) {
FAILFLAG(2);
break;
}
i -= 2;
copybytes(buff, glob_sdaptr->fn1 + 2, i);
/* send query */
i = sendquery(AL_DELETE, glob_reqdrv, i, &answer, &ax, 0);
if ((unsigned short)i == 0xffffu) {
FAILFLAG(2);
} else if ((i != 0) || (*ax != 0)) {
FAILFLAG(*ax);
}
break;
case AL_OPEN: /*** 16h: OPEN ********************************************/
case AL_CREATE: /*** 17h: CREATE ****************************************/
case AL_SPOPNFIL: /*** 2Eh: SPOPNFIL ************************************/
#if DEBUGLEVEL > 0
dbg_msg = glob_sdaptr->fn1;
#endif
/* fail if fn1 contains any wildcard, otherwise get len of fn1 */
i = len_if_no_wildcards(glob_sdaptr->fn1);
if (i < 2) {
FAILFLAG(3);
break;
}
i -= 2;
/* prepare and send query (SSCCMMfff...) */
((unsigned short *)buff)[0] = glob_reqstkword; /* WORD from the stack */
((unsigned short *)buff)[1] = glob_sdaptr->spop_act; /* action code (SPOP only) */
((unsigned short *)buff)[2] = glob_sdaptr->spop_mode; /* open mode (SPOP only) */
copybytes(buff + 6, glob_sdaptr->fn1 + 2, i);
i = sendquery(subfunction, glob_reqdrv, i + 6, &answer, &ax, 0);
if ((unsigned short)i == 0xffffu) {
FAILFLAG(2);
} else if ((i != 25) || (*ax != 0)) {
FAILFLAG(*ax);
} else {
/* ES:DI contains an uninitialized SFT */
struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di);
/* special treatment for SPOP, (set open_mode and return CX, too) */
if (subfunction == AL_SPOPNFIL) {
glob_intregs.w.cx = ((unsigned short *)answer)[11];
}
if (sftptr->open_mode & 0x8000) { /* if bit 15 is set, then it's a "FCB open", and requires the internal DOS "Set FCB Owner" function to be called */
/* TODO FIXME set_sft_owner() */
#if DEBUGLEVEL > 0
dbg_VGA[25*80] = 0x1700 | '$';
#endif
}
sftptr->file_attr = answer[0];
sftptr->dev_info_word = 0x8040 | glob_reqdrv; /* mark device as network & unwritten drive */
sftptr->dev_drvr_ptr = NULL;
sftptr->start_sector = ((unsigned short *)answer)[10];
sftptr->file_time = ((unsigned long *)answer)[3];
sftptr->file_size = ((unsigned long *)answer)[4];
sftptr->file_pos = 0;
sftptr->open_mode &= 0xff00u;
sftptr->open_mode |= answer[24];
sftptr->rel_sector = 0xffff;
sftptr->abs_sector = 0xffff;
sftptr->dir_sector = 0;
sftptr->dir_entry_no = 0xff; /* why such value? no idea, PHANTOM.C uses that, too */
copybytes(sftptr->file_name, answer + 1, 11);
}
break;
case AL_FINDFIRST: /*** 1Bh: FINDFIRST **********************************/
case AL_FINDNEXT: /*** 1Ch: FINDNEXT ***********************************/
{
/* AX = 111Bh
SS = DS = DOS DS
[DTA] = uninitialized 21-byte findfirst search data
(see #01626 at INT 21/AH=4Eh)
SDA first filename pointer (FN1, 9Eh) -> fully-qualified search template
SDA CDS pointer -> current directory structure for drive with file
SDA search attribute = attribute mask for search
Return:
CF set on error
AX = DOS error code (see #01680 at INT 21/AH=59h/BX=0000h)
-> http://www.ctyme.com/intr/rb-3012.htm
CF clear if successful
[DTA] = updated findfirst search data
(bit 7 of first byte must be set)
[DTA+15h] = standard directory entry for file (see #01352)
FindNext is the same, but only DTA should be used to fetch search params
*/
struct sdbstruct far *dta;
#if DEBUGLEVEL > 0
dbg_msg = glob_sdaptr->fn1;
#endif
/* prepare the query buffer (i must provide query's length) */
if (subfunction == AL_FINDFIRST) {
dta = (struct sdbstruct far *)(glob_sdaptr->curr_dta);
/* FindFirst needs to fetch search arguments from SDA */
buff[0] = glob_sdaptr->srch_attr; /* file attributes to look for */
/* copy fn1 (w/o drive) to buff */
for (i = 2; glob_sdaptr->fn1[i] != 0; i++) buff[i-1] = glob_sdaptr->fn1[i];
i--; /* adjust i because its one too much otherwise */
} else { /* FindNext needs to fetch search arguments from DTA (es:di) */
dta = MK_FP(glob_intregs.x.es, glob_intregs.x.di);
((unsigned short *)buff)[0] = dta->par_clstr;
((unsigned short *)buff)[1] = dta->dir_entry;
buff[4] = dta->srch_attr;
/* copy search template to buff */
for (i = 0; i < 11; i++) buff[i+5] = dta->srch_tmpl[i];
i += 5; /* i must provide the exact query's length */
}
/* send query to remote peer and wait for answer */
i = sendquery(subfunction, glob_reqdrv, i, &answer, &ax, 0);
if (i == 0xffffu) {
if (subfunction == AL_FINDFIRST) {
FAILFLAG(2); /* a failed findfirst returns error 2 (file not found) */
} else {
FAILFLAG(18); /* a failed findnext returns error 18 (no more files) */
}
break;
} else if ((*ax != 0) || (i != 24)) {
FAILFLAG(*ax);
break;
}
/* fill in the directory entry 'found_file' (32 bytes)
* 00h unsigned char fname[11]
* 0Bh unsigned char fattr (1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEV)
* 0Ch unsigned char f1[10]
* 16h unsigned short time_lstupd
* 18h unsigned short date_lstupd
* 1Ah unsigned short start_clstr *optional*
* 1Ch unsigned long fsize
*/
copybytes(glob_sdaptr->found_file.fname, answer+1, 11); /* found file name */
glob_sdaptr->found_file.fattr = answer[0]; /* found file attributes */
glob_sdaptr->found_file.time_lstupd = ((unsigned short *)answer)[6]; /* time (word) */
glob_sdaptr->found_file.date_lstupd = ((unsigned short *)answer)[7]; /* date (word) */
glob_sdaptr->found_file.start_clstr = 0; /* start cluster (I don't care) */
glob_sdaptr->found_file.fsize = ((unsigned long *)answer)[4]; /* fsize (word) */
/* put things into DTA so I can understand where I left should FindNext
* be called - this shall be a valid FindFirst structure (21 bytes):
* 00h unsigned char drive letter (7bits, MSB must be set for remote drives)
* 01h unsigned char search_tmpl[11]
* 0Ch unsigned char search_attr (1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEV)
* 0Dh unsigned short entry_count_within_directory
* 0Fh unsigned short cluster number of start of parent directory
* 11h unsigned char reserved[4]
* -- RBIL says: [DTA+15h] = standard directory entry for file
* 15h 11-bytes (FCB-style) filename+ext ("FILE0000TXT")
* 20h unsigned char attr. of file found (1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEV)
* 21h 10-bytes reserved
* 2Bh unsigned short file time
* 2Dh unsigned short file date
* 2Fh unsigned short cluster
* 31h unsigned long file size
*/
/* init some stuff only on FindFirst (FindNext contains valid values already) */
if (subfunction == AL_FINDFIRST) {
dta->drv_lett = glob_reqdrv | 128; /* bit 7 set means 'network drive' */
copybytes(dta->srch_tmpl, glob_sdaptr->fcb_fn1, 11);
dta->srch_attr = glob_sdaptr->srch_attr;
}
dta->par_clstr = ((unsigned short *)answer)[10];
dta->dir_entry = ((unsigned short *)answer)[11];
/* then 32 bytes as in the found_file record */
copybytes(dta + 0x15, &(glob_sdaptr->found_file), 32);
}
break;
case AL_SKFMEND: /*** 21h: SKFMEND **************************************/
{
struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di);
((unsigned short *)buff)[0] = glob_intregs.x.dx;
((unsigned short *)buff)[1] = glob_intregs.x.cx;
((unsigned short *)buff)[2] = sftptr->start_sector;
/* send query to remote peer and wait for answer */
i = sendquery(AL_SKFMEND, glob_reqdrv, 6, &answer, &ax, 0);
if (i == 0xffffu) {
FAILFLAG(2);
} else if ((*ax != 0) || (i != 4)) {
FAILFLAG(*ax);
} else { /* put new position into DX:AX */
glob_intregs.w.ax = ((unsigned short *)answer)[0];
glob_intregs.w.dx = ((unsigned short *)answer)[1];
}
break;
}
case AL_UNKNOWN_2D: /*** 2Dh: UNKNOWN_2D ********************************/
/* this is only called in MS-DOS v4.01, its purpose is unknown. MSCDEX
* returns AX=2 there, and so do I. */
glob_intregs.w.ax = 2;
break;
}
/* DEBUG */
#if DEBUGLEVEL > 0
while ((dbg_msg != NULL) && (*dbg_msg != 0)) dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x4f00 | *(dbg_msg++);
#endif
}
/* this function is hooked on INT 2Fh */
void __interrupt __far inthandler(union INTPACK r) {
/* insert a static code signature so I can reliably patch myself later,
* this will also contain the DS segment to use and actually set it */
_asm {
jmp SKIPTSRSIG
TSRSIG DB 'M','V','e','t'
SKIPTSRSIG:
/* save AX */
push ax
/* switch to new (patched) DS */
mov ax, 0
mov ds, ax
/* save one word from the stack (might be used by SETATTR later)
* The original stack should be at SS:BP+30 */
mov ax, ss:[BP+30]
mov glob_reqstkword, ax
/* uncomment the debug code below to insert a stack's dump into snd eth
* frame - debugging ONLY! */
/*
mov ax, ss:[BP+20]
mov word ptr [glob_pktdrv_sndbuff+16], ax
mov ax, ss:[BP+22]
mov word ptr [glob_pktdrv_sndbuff+18], ax
mov ax, ss:[BP+24]
mov word ptr [glob_pktdrv_sndbuff+20], ax
mov ax, ss:[BP+26]
mov word ptr [glob_pktdrv_sndbuff+22], ax
mov ax, ss:[BP+28]
mov word ptr [glob_pktdrv_sndbuff+24], ax
mov ax, ss:[BP+30]
mov word ptr [glob_pktdrv_sndbuff+26], ax
mov ax, ss:[BP+32]
mov word ptr [glob_pktdrv_sndbuff+28], ax
mov ax, ss:[BP+34]
mov word ptr [glob_pktdrv_sndbuff+30], ax
mov ax, ss:[BP+36]
mov word ptr [glob_pktdrv_sndbuff+32], ax
mov ax, ss:[BP+38]
mov word ptr [glob_pktdrv_sndbuff+34], ax
mov ax, ss:[BP+40]
mov word ptr [glob_pktdrv_sndbuff+36], ax
*/
/* restore AX */
pop ax
}
/* DEBUG output (BLUE) */
#if DEBUGLEVEL > 1
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1e00 | (dbg_hexc[(r.h.ah >> 4) & 0xf]);
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1e00 | (dbg_hexc[r.h.ah & 0xf]);
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1e00 | (dbg_hexc[(r.h.al >> 4) & 0xf]);
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1e00 | (dbg_hexc[r.h.al & 0xf]);
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0;
#endif
/* is it a multiplex call for me? */
if (r.h.ah == glob_multiplexid) {
if (r.h.al == 0) { /* install check */
r.h.al = 0xff; /* 'installed' */
r.w.bx = 0x4d86; /* MV */
r.w.cx = 0x7e1; /* 2017 */
return;
}
if ((r.h.al == 1) && (r.x.cx == 0x4d86)) { /* get shared data ptr (AX=0, ptr under BX:CX) */
_asm {
push ds
pop glob_reqstkword
}
r.w.ax = 0; /* zero out AX */
r.w.bx = glob_reqstkword; /* ptr returned at BX:CX */
r.w.cx = FP_OFF(&glob_data);
return;
}
}
/* if not related to a redirector function (AH=11h), or the function is
* an 'install check' (0), or the function is over our scope (2Eh), or it's
* an otherwise unsupported function (as pointed out by supportedfunctions),
* then call the previous INT 2F handler immediately */
if ((r.h.ah != 0x11) || (r.h.al == AL_INSTALLCHK) || (r.h.al > 0x2E) || (supportedfunctions[r.h.al] == AL_UNKNOWN)) goto CHAINTOPREVHANDLER;
/* DEBUG output (GREEN) */
#if DEBUGLEVEL > 0
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x2e00 | (dbg_hexc[(r.h.al >> 4) & 0xf]);
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x2e00 | (dbg_hexc[r.h.al & 0xf]);
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0;
#endif
/* determine whether or not the query is meant for a drive I control,
* and if not - chain to the previous INT 2F handler */
if (((r.h.al >= AL_CLSFIL) && (r.h.al <= AL_UNLOCKFIL)) || (r.h.al == AL_SKFMEND) || (r.h.al == AL_UNKNOWN_2D)) {
/* ES:DI points to the SFT: if the bottom 6 bits of the device information
* word in the SFT are > last drive, then it relates to files not associated
* with drives, such as LAN Manager named pipes. */
struct sftstruct far *sft = MK_FP(r.w.es, r.w.di);
glob_reqdrv = sft->dev_info_word & 0x3F;
} else {
switch (r.h.al) {
case AL_FINDNEXT:
glob_reqdrv = glob_sdaptr->sdb.drv_lett & 0x1F;
break;
case AL_SETATTR:
case AL_GETATTR:
case AL_DELETE:
case AL_OPEN:
case AL_CREATE:
case AL_SPOPNFIL:
case AL_MKDIR:
case AL_RMDIR:
case AL_CHDIR:
case AL_RENAME: /* check sda.fn1 for drive */
glob_reqdrv = DRIVETONUM(glob_sdaptr->fn1[0]);
break;
default: /* otherwise check out the CDS (at ES:DI) */
{
struct cdsstruct far *cds = MK_FP(r.w.es, r.w.di);
glob_reqdrv = DRIVETONUM(cds->current_path[0]);
#if DEBUGLEVEL > 0 /* DEBUG output (ORANGE) */
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x6e00 | ('A' + glob_reqdrv);
dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x6e00 | ':';
#endif
}
break;
}
}
/* validate drive */
if ((glob_reqdrv > 25) || (glob_data.ldrv[glob_reqdrv] == 0xff)) {
goto CHAINTOPREVHANDLER;
}
/* This should not be necessary. DOS usually generates an FCB-style name in
* the appropriate SDA area. However, in the case of user input such as
* 'CD ..' or 'DIR ..' it leaves the fcb area all spaces, hence the need to
* normalize the fcb area every time. */
if (r.h.al != AL_DISKSPACE) {
unsigned short i;
unsigned char far *path = glob_sdaptr->fn1;
/* fast forward 'path' to first character of the filename */
for (i = 0;; i++) {
if (glob_sdaptr->fn1[i] == '\\') path = glob_sdaptr->fn1 + i + 1;
if (glob_sdaptr->fn1[i] == 0) break;
}
/* clear out fcb_fn1 by filling it with spaces */
for (i = 0; i < 11; i++) glob_sdaptr->fcb_fn1[i] = ' ';
/* copy 'path' into fcb_name using the fcb syntax ("FILE TXT") */
for (i = 0; *path != 0; path++) {
if (*path == '.') {
i = 8;
} else {
glob_sdaptr->fcb_fn1[i++] = *path;
}
}
}
/* copy interrupt registers into glob_intregs so the int handler can access them without using any stack */
copybytes(&glob_intregs, &r, sizeof(union INTPACK));
/* set stack to my custom memory */
_asm {
cli /* make sure to disable interrupts, so nobody gets in the way while I'm fiddling with the stack */
mov glob_oldstack_seg, SS
mov glob_oldstack_off, SP
/* set SS to DS */
mov ax, ds
mov ss, ax
/* set SP to the end of my DATASEGSZ (-2) */
mov sp, DATASEGSZ-2
sti
}
/* call the actual INT 2F processing function */
process2f();
/* switch stack back */
_asm {
cli
mov SS, glob_oldstack_seg
mov SP, glob_oldstack_off
sti
}
/* copy all registers back so watcom will set them as required 'for real' */
copybytes(&r, &glob_intregs, sizeof(union INTPACK));
return;
/* hand control to the previous INT 2F handler */
CHAINTOPREVHANDLER:
_mvchain_intr(MK_FP(glob_data.prev_2f_handler_seg, glob_data.prev_2f_handler_off));
}
/*********************** HERE ENDS THE RESIDENT PART ***********************/
#pragma code_seg("_TEXT", "CODE");
/* this function obviously does nothing - but I need it because it is a
* 'low-water' mark for the end of my resident code (so I know how much memory
* exactly I can trim when going TSR) */
void begtextend(void) {
}
/* registers a packet driver handle to use on subsequent calls */
static int pktdrv_accesstype(void) {
unsigned char cflag = 0;
_asm {
mov ax, 201h /* AH=subfunction access_type(), AL=if_class=1(eth) */
mov bx, 0ffffh /* if_type = 0xffff means 'all' */
mov dl, 0 /* if_number: 0 (first interface) */
/* DS:SI should point to the ethertype value in network byte order */
mov si, offset glob_pktdrv_sndbuff + 12 /* I don't set DS, it's good already */
mov cx, 2 /* typelen (ethertype is 16 bits) */
/* ES:DI points to the receiving routine */
push cs /* write segment of pktdrv_recv into es */
pop es
mov di, offset pktdrv_recv
mov cflag, 1 /* pre-set the cflag variable to failure */
/* int to variable vector is a mess, so I have fetched its vector myself
* and pushf + cli + call far it now to simulate a regular int */
pushf
cli
call dword ptr glob_pktdrv_pktcall
/* get CF state - reset cflag if CF clear, and get pkthandle from AX */
jc badluck /* Jump if Carry */
mov word ptr [glob_data + GLOB_DATOFF_PKTHANDLE], ax /* Pkt handle should be in AX */
mov cflag, 0
badluck:
}
if (cflag != 0) return(-1);
return(0);
}
/* get my own MAC addr. target MUST point to a space of at least 6 chars */
static void pktdrv_getaddr(unsigned char *dst) {
_asm {
mov ah, 6 /* subfunction: get_addr() */
mov bx, word ptr [glob_data + GLOB_DATOFF_PKTHANDLE]; /* handle */
push ds /* write segment of dst into es */
pop es
mov di, dst /* offset of dst (in small mem model dst IS an offset) */
mov cx, 6 /* expected length (ethernet = 6 bytes) */
/* int to variable vector is a mess, so I have fetched its vector myself
* and pushf + cli + call far it now to simulate a regular int */
pushf
cli
call dword ptr glob_pktdrv_pktcall
}
}
static int pktdrv_init(unsigned short pktintparam, int nocksum) {
unsigned short far *intvect = (unsigned short far *)MK_FP(0, pktintparam << 2);
unsigned short pktdrvfuncoffs = *intvect;
unsigned short pktdrvfuncseg = *(intvect+1);
unsigned short rseg = 0, roff = 0;
char far *pktdrvfunc = (char far *)MK_FP(pktdrvfuncseg, pktdrvfuncoffs);
int i;
char sig[8];
/* preload sig with "PKT DRVR" -- I could it just as well with
* char sig[] = "PKT DRVR", but I want to avoid this landing in
* my DATA segment so it doesn't pollute the TSR memory space. */
sig[0] = 'P';
sig[1] = 'K';
sig[2] = 'T';
sig[3] = ' ';
sig[4] = 'D';
sig[5] = 'R';
sig[6] = 'V';
sig[7] = 'R';
/* set my ethertype to 0xF5ED (EDF5 in network byte order) */
glob_pktdrv_sndbuff[12] = 0xED;
glob_pktdrv_sndbuff[13] = 0xF5;
/* set protover and CKSUM flag in send buffer (I won't touch it again) */
if (nocksum == 0) {
glob_pktdrv_sndbuff[56] = PROTOVER | 128; /* protocol version */
} else {
glob_pktdrv_sndbuff[56] = PROTOVER; /* protocol version */
}
pktdrvfunc += 3; /* skip three bytes of executable code */
for (i = 0; i < 8; i++) if (sig[i] != pktdrvfunc[i]) return(-1);
glob_data.pktint = pktintparam;
/* fetch the vector of the pktdrv interrupt and save it for later */
_asm {
mov ah, 35h /* AH=GetVect */
mov al, byte ptr [glob_data] + GLOB_DATOFF_PKTINT; /* AL=int number */
push es /* save ES and BX (will be overwritten) */
push bx
int 21h
mov rseg, es
mov roff, bx
pop bx
pop es
}
glob_pktdrv_pktcall = rseg;
glob_pktdrv_pktcall <<= 16;
glob_pktdrv_pktcall |= roff;
return(pktdrv_accesstype());
}
static void pktdrv_free(unsigned long pktcall) {
_asm {
mov ah, 3
mov bx, word ptr [glob_data + GLOB_DATOFF_PKTHANDLE]
/* int to variable vector is a mess, so I have fetched its vector myself
* and pushf + cli + call far it now to simulate a regular int */
pushf
cli
call dword ptr glob_pktdrv_pktcall
}
/* if (regs.x.cflag != 0) return(-1);
return(0);*/
}
static struct sdastruct far *getsda(void) {
/* DOS 3.0+ - GET ADDRESS OF SDA (Swappable Data Area)
* AX = 5D06h
*
* CF set on error (AX=error code)
* DS:SI -> sda pointer
*/
unsigned short rds = 0, rsi = 0;
_asm {
mov ax, 5d06h
push ds
push si
int 21h
mov bx, ds
mov cx, si
pop si
pop ds
mov rds, bx
mov rsi, cx
}
return(MK_FP(rds, rsi));
}
/* returns the CDS struct for drive. requires DOS 4+ */
static struct cdsstruct far *getcds(unsigned int drive) {
/* static to preserve state: only do init once */
static unsigned char far *dir;
static int ok = -1;
static unsigned char lastdrv;
/* init of never inited yet */
if (ok == -1) {
/* DOS 3.x+ required - no CDS in earlier versions */
ok = 1;
/* offsets of CDS and lastdrv in the List of Lists depends on the DOS version:
* DOS < 3 no CDS at all
* DOS 3.0 lastdrv at 1Bh, CDS pointer at 17h
* DOS 3.1+ lastdrv at 21h, CDS pointer at 16h */
/* fetch lastdrv and CDS through a little bit of inline assembly */
_asm {
push si /* SI needs to be preserved */
/* get the List of Lists into ES:BX */
mov ah, 52h
int 21h
/* get the LASTDRIVE value */
mov si, 21h /* 21h for DOS 3.1+, 1Bh on DOS 3.0 */
mov ah, byte ptr es:[bx+si]
mov lastdrv, ah
/* get the CDS */
mov si, 16h /* 16h for DOS 3.1+, 17h on DOS 3.0 */
les bx, es:[bx+si]
mov word ptr dir+2, es
mov word ptr dir, bx
/* restore the original SI value*/
pop si
}
/* some OSes (at least OS/2) set the CDS pointer to FFFF:FFFF */
if (dir == (unsigned char far *) -1l) ok = 0;
} /* end of static initialization */
if (ok == 0) return(NULL);
if (drive > lastdrv) return(NULL);
/* return the CDS array entry for drive - note that currdir_size depends on
* DOS version: 0x51 on DOS 3.x, and 0x58 on DOS 4+ */
return((struct cdsstruct __far *)((unsigned char __far *)dir + (drive * 0x58 /*currdir_size*/)));
}
/******* end of CDS-related stuff *******/
/* primitive message output used instead of printf() to limit memory usage
* and binary size */
static void outmsg(char *s) {
_asm {
mov ah, 9h /* DOS 1+ - WRITE STRING TO STANDARD OUTPUT */
mov dx, s /* small memory model: no need to set DS, 's' is an offset */
int 21h
}
}
/* zero out an object of l bytes */
static void zerobytes(void *obj, unsigned short l) {
unsigned char *o = obj;
while (l-- != 0) {
*o = 0;
o++;
}
}
/* expects a hex string of exactly two chars "XX" and returns its value, or -1
* if invalid */
static int hexpair2int(char *hx) {
unsigned char h[2];
unsigned short i;
/* translate hx[] to numeric values and validate */
for (i = 0; i < 2; i++) {
if ((hx[i] >= 'A') && (hx[i] <= 'F')) {
h[i] = hx[i] - ('A' - 10);
} else if ((hx[i] >= 'a') && (hx[i] <= 'f')) {
h[i] = hx[i] - ('a' - 10);
} else if ((hx[i] >= '0') && (hx[i] <= '9')) {
h[i] = hx[i] - '0';
} else { /* invalid */
return(-1);
}
}
/* compute the end result and return it */
i = h[0];
i <<= 4;
i |= h[1];
return(i);
}
/* translates an ASCII MAC address into a 6-bytes binary string */
static int string2mac(unsigned char *d, char *mac) {
int i, v;
/* is it exactly 17 chars long? */
for (i = 0; mac[i] != 0; i++);
if (i != 17) return(-1);
/* are nibble pairs separated by colons? */
for (i = 2; i < 16; i += 3) if (mac[i] != ':') return(-1);
/* translate each byte to its numeric value */
for (i = 0; i < 16; i += 3) {
v = hexpair2int(mac + i);
if (v < 0) return(-1);
*d = v;
d++;
}
return(0);
}
#define ARGFL_QUIET 1
#define ARGFL_AUTO 2
#define ARGFL_UNLOAD 4
#define ARGFL_NOCKSUM 8
/* a structure used to pass and decode arguments between main() and parseargv() */
struct argstruct {
int argc; /* original argc */
char **argv; /* original argv */
unsigned short pktint; /* custom packet driver interrupt */
unsigned char flags; /* ARGFL_QUIET, ARGFL_AUTO, ARGFL_UNLOAD, ARGFL_CKSUM */
};
/* parses (and applies) command-line arguments. returns 0 on success,
* non-zero otherwise */
static int parseargv(struct argstruct *args) {
int i, drivemapflag = 0, gotmac = 0;
/* iterate through arguments, if any */
for (i = 1; i < args->argc; i++) {
char opt;
char *arg;
/* is it a drive mapping, like "c-x"? */
if ((args->argv[i][0] >= 'A') && (args->argv[i][1] == '-') && (args->argv[i][2] >= 'A') && (args->argv[i][3] == 0)) {
unsigned char ldrv, rdrv;
rdrv = DRIVETONUM(args->argv[i][0]);
ldrv = DRIVETONUM(args->argv[i][2]);
if ((ldrv > 25) || (rdrv > 25)) return(-2);
if (glob_data.ldrv[ldrv] != 0xff) return(-2);
glob_data.ldrv[ldrv] = rdrv;
drivemapflag = 1;
continue;
}
/* not a drive mapping -> is it an option? */
if (args->argv[i][0] == '/') {
if (args->argv[i][1] == 0) return(-3);
opt = args->argv[i][1];
/* fetch option's argument, if any */
if (args->argv[i][2] == 0) { /* single option */
arg = NULL;
} else if (args->argv[i][2] == '=') { /* trailing argument */
arg = args->argv[i] + 3;
} else {
return(-3);
}
/* normalize the option char to lower case */
if ((opt >= 'A') && (opt <= 'Z')) opt += ('a' - 'A');
/* what is the option about? */
switch (opt) {
case 'q':
if (arg != NULL) return(-4);
args->flags |= ARGFL_QUIET;
break;
case 'p':
if (arg == NULL) return(-4);
/* I expect an exactly 2-characters string */
if ((arg[0] == 0) || (arg[1] == 0) || (arg[2] != 0)) return(-1);
if ((args->pktint = hexpair2int(arg)) < 1) return(-4);
break;
case 'n': /* disable CKSUM */
if (arg != NULL) return(-4);
args->flags |= ARGFL_NOCKSUM;
break;
case 'u': /* unload EtherDFS */
if (arg != NULL) return(-4);
args->flags |= ARGFL_UNLOAD;
break;
default: /* invalid parameter */
return(-5);
}
continue;
}
/* not a drive mapping nor an option -> so it's a MAC addr perhaps? */
if (gotmac != 0) return(-1); /* fail if got a MAC already */
/* read the srv mac address, unless it's "::" (auto) */
if ((args->argv[i][0] == ':') && (args->argv[i][1] == ':') && (args->argv[i][2] == 0)) {
args->flags |= ARGFL_AUTO;
} else {
if (string2mac(GLOB_RMAC, args->argv[i]) != 0) return(-1);
}
gotmac = 1;
}
/* fail if MAC+unload or mapping+unload */
if (args->flags & ARGFL_UNLOAD) {
if ((gotmac != 0) || (drivemapflag != 0)) return(-1);
return(0);
}
/* did I get at least one drive mapping? and a MAC? */
if ((drivemapflag == 0) || (gotmac == 0)) return(-6);
return(0);
}
/* translates an unsigned byte into a 2-characters string containing its hex
* representation. s needs to be at least 3 bytes long. */
static void byte2hex(char *s, unsigned char b) {
char h[16];
unsigned short i;
/* pre-compute h[] with a string 0..F -- I could do the same thing easily
* with h[] = "0123456789ABCDEF", but then this would land inside the DATA
* segment, while I want to keep it in stack to avoid polluting the TSR's
* memory space */
for (i = 0; i < 10; i++) h[i] = '0' + i;
for (; i < 16; i++) h[i] = ('A' - 10) + i;
/* */
s[0] = h[b >> 4];
s[1] = h[b & 15];
s[2] = 0;
}
/* allocates sz bytes of memory and returns the segment to allocated memory or
* 0 on error. the allocation strategy is 'highest possible' (last fit) to
* avoid memory fragmentation */
static unsigned short allocseg(unsigned short sz) {
unsigned short volatile res = 0;
/* sz should contains number of 16-byte paragraphs instead of bytes */
sz += 15; /* make sure to allocate enough paragraphs */
sz >>= 4;
/* ask DOS for memory */
_asm {
push cx /* save cx */
/* set strategy to 'last fit' */
mov ah, 58h
xor al, al /* al = 0 means 'get strategy' */
int 21h /* now current strategy is in ax */
mov cx, ax /* copy current strategy to cx */
mov ah, 58h
mov al, 1 /* al = 1 means 'set strategy' */
mov bl, 2 /* 2 or greater means 'last fit' */
int 21h
/* do the allocation now */
mov ah, 48h /* alloc memory (DOS 2+) */
mov bx, sz /* number of paragraphs to allocate */
mov res, 0 /* pre-set res to failure (0) */
int 21h /* returns allocated segment in AX */
/* check CF */
jc failed
mov res, ax /* set res to actual result */
failed:
/* set strategy back to its initial setting */
mov ah, 58h
mov al, 1
mov bx, cx
int 21h
pop cx /* restore cx */
}
return(res);
}
/* free segment previously allocated through allocseg() */
static void freeseg(unsigned short segm) {
_asm {
mov ah, 49h /* free memory (DOS 2+) */
mov es, segm /* put segment to free into ES */
int 21h
}
}
/* patch the TSR routine and packet driver handler so they use my new DS.
* return 0 on success, non-zero otherwise */
static int updatetsrds(void) {
unsigned short newds;
unsigned char far *ptr;
unsigned short far *sptr;
newds = 0;
_asm {
push ds
pop newds
}
/* first patch the TSR routine */
ptr = (unsigned char far *)inthandler + 24; /* the interrupt handler's signature appears at offset 23 (this might change at each source code modification and/or optimization settings) */
/*{
int x;
unsigned short far *VGA = (unsigned short far *)(0xB8000000l);
for (x = 0; x < 128; x++) VGA[80*12 + ((x >> 6) * 80) + (x & 63)] = 0x1f00 | ptr[x];
}*/
sptr = (unsigned short far *)ptr;
/* check for the routine's signature first ("MVet") */
if ((ptr[0] != 'M') || (ptr[1] != 'V') || (ptr[2] != 'e') || (ptr[3] != 't')) return(-1);
sptr[3] = newds;
/* now patch the pktdrv_recv() routine */
ptr = (unsigned char far *)pktdrv_recv + 3;
sptr = (unsigned short far *)ptr;
/*{
int x;
unsigned short far *VGA = (unsigned short far *)(0xB8000000l);
for (x = 0; x < 128; x++) VGA[80*12 + ((x >> 6) * 80) + (x & 63)] = 0x1f00 | ptr[x];
}*/
/* check for the routine's signature first */
if ((ptr[0] != 'p') || (ptr[1] != 'k') || (ptr[2] != 't') || (ptr[3] != 'r')) return(-1);
sptr[4] = newds;
/*{
int x;
unsigned short far *VGA = (unsigned short far *)(0xB8000000l);
for (x = 0; x < 128; x++) VGA[80*20 + ((x >> 6) * 80) + (x & 63)] = 0x1f00 | ptr[x];
}*/
return(0);
}
/* scans the 2Fh interrupt for some available 'multiplex id' in the range
* C0..FF. also checks for EtherDFS presence at the same time. returns:
* - the available id if found
* - the id of the already-present etherdfs instance
* - 0 if no available id found
* presentflag set to 0 if no etherdfs found loaded, non-zero otherwise. */
static unsigned char findfreemultiplex(unsigned char *presentflag) {
unsigned char id = 0, freeid = 0, pflag = 0;
_asm {
mov id, 0C0h /* start scanning at C0h */
checkid:
xor al, al /* subfunction is 'installation check' (00h) */
mov ah, id
int 2Fh
/* is it free? (AL == 0) */
test al, al
jnz notfree /* not free - is it me perhaps? */
mov freeid, ah /* it's free - remember it, I may use it myself soon */
jmp checknextid
notfree:
/* is it me? (AL=FF + BX=4D86 CX=7E1 [MV 2017]) */
cmp al, 0ffh
jne checknextid
cmp bx, 4d86h
jne checknextid
cmp cx, 7e1h
jne checknextid
/* if here, then it's me... */
mov ah, id
mov freeid, ah
mov pflag, 1
jmp gameover
checknextid:
/* if not me, then check next id */
inc id
jnz checkid /* if id is zero, then all range has been covered (C0..FF) */
gameover:
}
*presentflag = pflag;
return(freeid);
}
int main(int argc, char **argv) {
struct argstruct args;
struct cdsstruct far *cds;
unsigned char tmpflag = 0;
int i;
unsigned short volatile newdataseg; /* 'volatile' just in case the compiler would try to optimize it out, since I set it through in-line assembly */
/* set all drive mappings as 'unused' */
for (i = 0; i < 26; i++) glob_data.ldrv[i] = 0xff;
/* parse command-line arguments */
zerobytes(&args, sizeof(args));
args.argc = argc;
args.argv = argv;
if (parseargv(&args) != 0) {
#include "msg/help.c"
return(1);
}
/* check DOS version - I require DOS 5.0+ */
_asm {
mov ax, 3306h
int 21h
mov tmpflag, bl
inc al /* if AL was 0xFF ("unsupported function"), it is 0 now */
jnz done
mov tmpflag, 0 /* if AL is 0 (hence was 0xFF), set dosver to 0 */
done:
}
if (tmpflag < 5) { /* tmpflag contains DOS version or 0 for 'unknown' */
#include "msg\\unsupdos.c"
return(1);
}
/* look whether or not it's ok to install a network redirector at int 2F */
_asm {
mov tmpflag, 0
mov ax, 1100h
int 2Fh
dec ax /* if AX was set to 1 (ie. "not ok to install"), it's zero now */
jnz goodtogo
mov tmpflag, 1
goodtogo:
}
if (tmpflag != 0) {
#include "msg\\noredir.c"
return(1);
}
/* is it all about unloading myself? */
if ((args.flags & ARGFL_UNLOAD) != 0) {
unsigned char etherdfsid, pktint;
unsigned short myseg, myoff, myhandle, mydataseg;
unsigned long pktdrvcall;
struct tsrshareddata far *tsrdata;
unsigned char far *int2fptr;
/* am I loaded at all? */
etherdfsid = findfreemultiplex(&tmpflag);
if (tmpflag == 0) { /* not loaded, cannot unload */
#include "msg\\notload.c"
return(1);
}
/* am I still at the top of the int 2Fh chain? */
_asm {
/* save AX, BX and ES */
push ax
push bx
push es
/* fetch int vector */
mov ax, 352Fh /* AH=35h 'GetVect' for int 2Fh */
int 21h
mov myseg, es
mov myoff, bx
/* restore AX, BX and ES */
pop es
pop bx
pop ax
}
int2fptr = (unsigned char far *)MK_FP(myseg, myoff) + 24; /* the interrupt handler's signature appears at offset 24 (this might change at each source code modification) */
/* look for the "MVet" signature */
if ((int2fptr[0] != 'M') || (int2fptr[1] != 'V') || (int2fptr[2] != 'e') || (int2fptr[3] != 't')) {
#include "msg\\othertsr.c";
return(1);
}
/* get the ptr to TSR's data */
_asm {
push ax
push bx
push cx
pushf
mov ah, etherdfsid
mov al, 1
mov cx, 4d86h
mov myseg, 0ffffh
int 2Fh /* AX should be 0, and BX:CX contains the address */
test ax, ax
jnz fail
mov myseg, bx
mov myoff, cx
mov mydataseg, dx
fail:
popf
pop cx
pop bx
pop ax
}
if (myseg == 0xffffu) {
#include "msg\\tsrcomfa.c"
return(1);
}
tsrdata = MK_FP(myseg, myoff);
mydataseg = myseg;
/* restore previous int 2f handler (under DS:DX, AH=25h, INT 21h)*/
myseg = tsrdata->prev_2f_handler_seg;
myoff = tsrdata->prev_2f_handler_off;
_asm {
/* save AX, DS and DX */
push ax
push ds
push dx
/* set DS:DX */
mov ax, myseg
push ax
pop ds
mov dx, myoff
/* call INT 21h,25h for int 2Fh */
mov ax, 252Fh
int 21h
/* restore AX, DS and DX */
pop dx
pop ds
pop ax
}
/* get the address of the packet driver routine */
pktint = tsrdata->pktint;
_asm {
/* save AX, BX and ES */
push ax
push bx
push es
/* fetch int vector */
mov ah, 35h /* AH=35h 'GetVect' */
mov al, pktint /* interrupt */
int 21h
mov myseg, es
mov myoff, bx
/* restore AX, BX and ES */
pop es
pop bx
pop ax
}
pktdrvcall = myseg;
pktdrvcall <<= 16;
pktdrvcall |= myoff;
/* unregister packet driver */
myhandle = tsrdata->pkthandle;
_asm {
/* save AX and BX */
push ax
push bx
/* prepare the release_type() call */
mov ah, 3 /* release_type() */
mov bx, myhandle
/* call the pktdrv int */
/* int to variable vector is a mess, so I have fetched its vector myself
* and pushf + cli + call far it now to simulate a regular int */
pushf
cli
call dword ptr pktdrvcall
/* restore AX and BX */
pop bx
pop ax
}
/* set all mapped drives as 'not available' */
for (i = 0; i < 26; i++) {
if (tsrdata->ldrv[i] == 0xff) continue;
cds = getcds(i);
if (cds != NULL) cds->flags = 0;
}
/* free TSR's data/stack seg and its PSP */
freeseg(mydataseg);
freeseg(tsrdata->pspseg);
/* all done */
if ((args.flags & ARGFL_QUIET) == 0) {
#include "msg\\unloaded.c"
}
return(0);
}
/* remember current int 2f handler, we might over-write it soon (also I
* use it to see if I'm already loaded) */
_asm {
mov ax, 352fh; /* AH=GetVect AL=2F */
push es /* save ES and BX (will be overwritten) */
push bx
int 21h
mov word ptr [glob_data + GLOB_DATOFF_PREV2FHANDLERSEG], es
mov word ptr [glob_data + GLOB_DATOFF_PREV2FHANDLEROFF], bx
pop bx
pop es
}
/* is the TSR installed already? */
glob_multiplexid = findfreemultiplex(&tmpflag);
if (tmpflag != 0) { /* already loaded */
#include "msg\\alrload.c"
return(1);
} else if (glob_multiplexid == 0) { /* no free multiplex id found */
#include "msg\\nomultpx.c"
return(1);
}
/* if any of the to-be-mapped drives is already active, fail */
for (i = 0; i < 26; i++) {
if (glob_data.ldrv[i] == 0xff) continue;
cds = getcds(i);
if (cds == NULL) {
#include "msg\\mapfail.c"
return(1);
}
if (cds->flags != 0) {
#include "msg\\drvactiv.c"
return(1);
}
}
/* allocate a new segment for all my internal needs, and use it right away
* as DS */
newdataseg = allocseg(DATASEGSZ);
if (newdataseg == 0) {
#include "msg\\memfail.c"
return(1);
}
/* copy current DS into the new segment and switch to new DS/SS */
_asm {
/* save registers on the stack */
push es
push cx
push si
push di
pushf
/* copy the memory block */
mov cx, DATASEGSZ /* copy cx bytes */
xor si, si /* si = 0*/
xor di, di /* di = 0 */
cld /* clear direction flag (increment si/di) */
mov es, newdataseg /* load es with newdataseg */
rep movsb /* execute copy DS:SI -> ES:DI */
/* restore registers (but NOT es, instead save it into AX for now) */
popf
pop di
pop si
pop cx
pop ax
/* switch to the new DS _AND_ SS now */
push es
push es
pop ds
pop ss
/* restore ES */
push ax
pop es
}
/* patch the TSR and pktdrv_recv() so they use my new DS */
if (updatetsrds() != 0) {
#include "msg\\relfail.c"
freeseg(newdataseg);
return(1);
}
/* remember the SDA address (will be useful later) */
glob_sdaptr = getsda();
/* init the packet driver interface */
glob_data.pktint = 0;
if (args.pktint == 0) { /* detect first packet driver within int 60h..80h */
for (i = 0x60; i <= 0x80; i++) {
if (pktdrv_init(i, args.flags & ARGFL_NOCKSUM) == 0) break;
}
} else { /* use the pktdrvr interrupt passed through command line */
pktdrv_init(args.pktint, args.flags & ARGFL_NOCKSUM);
}
/* has it succeeded? */
if (glob_data.pktint == 0) {
#include "msg\\pktdfail.c"
freeseg(newdataseg);
return(1);
}
pktdrv_getaddr(GLOB_LMAC);
/* should I auto-discover the server? */
if ((args.flags & ARGFL_AUTO) != 0) {
unsigned short *ax;
unsigned char *answer;
/* set (temporarily) glob_rmac to broadcast */
for (i = 0; i < 6; i++) GLOB_RMAC[i] = 0xff;
for (i = 0; glob_data.ldrv[i] == 0xff; i++); /* find first mapped disk */
/* send a discovery frame that will update glob_rmac */
if (sendquery(AL_DISKSPACE, i, 0, &answer, &ax, 1) != 6) {
#include "msg\\nosrvfnd.c"
pktdrv_free(glob_pktdrv_pktcall); /* free the pkt drv and quit */
freeseg(newdataseg);
return(1);
}
}
/* set all drives as being 'network' drives (also add the PHYSICAL bit,
* otherwise MS-DOS 6.0 will ignore the drive) */
for (i = 0; i < 26; i++) {
if (glob_data.ldrv[i] == 0xff) continue;
cds = getcds(i);
cds->flags = CDSFLAG_NET | CDSFLAG_PHY;
/* set 'current path' to root, to avoid inheriting any garbage */
cds->current_path[0] = 'A' + i;
cds->current_path[1] = ':';
cds->current_path[2] = '\\';
cds->current_path[3] = 0;
}
if ((args.flags & ARGFL_QUIET) == 0) {
char buff[20];
#include "msg\\instlled.c"
for (i = 0; i < 6; i++) {
byte2hex(buff + i + i + i, GLOB_LMAC[i]);
}
for (i = 2; i < 16; i += 3) buff[i] = ':';
buff[17] = '$';
outmsg(buff);
#include "msg\\pktdrvat.c"
byte2hex(buff, glob_data.pktint);
buff[2] = ')';
buff[3] = '\r';
buff[4] = '\n';
buff[5] = '$';
outmsg(buff);
for (i = 0; i < 26; i++) {
int z;
if (glob_data.ldrv[i] == 0xff) continue;
buff[0] = ' ';
buff[1] = 'A' + i;
buff[2] = ':';
buff[3] = ' ';
buff[4] = '-';
buff[5] = '>';
buff[6] = ' ';
buff[7] = '[';
buff[8] = 'A' + glob_data.ldrv[i];
buff[9] = ':';
buff[10] = ']';
buff[11] = ' ';
buff[12] = 'o';
buff[13] = 'n';
buff[14] = ' ';
buff[15] = '$';
outmsg(buff);
for (z = 0; z < 6; z++) {
byte2hex(buff + z + z + z, GLOB_RMAC[z]);
}
for (z = 2; z < 16; z += 3) buff[z] = ':';
buff[17] = '\r';
buff[18] = '\n';
buff[19] = '$';
outmsg(buff);
}
}
/* get the segment of the PSP (might come handy later) */
_asm {
mov ah, 62h /* get current PSP address */
int 21h /* returns the segment of PSP in BX */
mov word ptr [glob_data + GLOB_DATOFF_PSPSEG], bx /* copy PSP segment to glob_pspseg */
}
/* free the environment (env segment is at offset 2C of the PSP) */
_asm {
mov es, word ptr [glob_data + GLOB_DATOFF_PSPSEG] /* load ES with PSP's segment */
mov es, es:[2Ch] /* get segment of the env block */
mov ah, 49h /* free memory (DOS 2+) */
int 21h
}
/* set up the TSR (INT 2F catching) */
_asm {
cli
mov ax, 252fh /* AH=set interrupt vector AL=2F */
push ds /* preserve DS and DX */
push dx
push cs /* set DS to current CS, that is provide the */
pop ds /* int handler's segment */
mov dx, offset inthandler /* int handler's offset */
int 21h
pop dx /* restore DS and DX to previous values */
pop ds
sti
}
/* Turn self into a TSR and free memory I won't need any more. That is, I
* free all the libc startup code and my init functions by passing the
* number of paragraphs to keep resident to INT 21h, AH=31h. How to compute
* the number of paragraphs? Simple: look at the memory map and note down
* the size of the BEGTEXT segment (that's where I store all TSR routines).
* then: (sizeof(BEGTEXT) + sizeof(PSP) + 15) / 16
* PSP is 256 bytes of course. And +15 is needed to avoid truncating the
* last (partially used) paragraph. */
_asm {
mov ax, 3100h /* AH=31 'terminate+stay resident', AL=0 exit code */
mov dx, offset begtextend /* DX = offset of resident code end */
add dx, 256 /* add size of PSP (256 bytes) */
add dx, 15 /* add 15 to avoid truncating last paragraph */
shr dx, 1 /* convert bytes to number of 16-bytes paragraphs */
shr dx, 1 /* the 8086/8088 CPU supports only a 1-bit version */
shr dx, 1 /* of SHR, so I have to repeat it as many times as */
shr dx, 1 /* many bits I need to shift. */
int 21h
}
return(0); /* never reached, but compiler complains if not present */
}
| 2.171875 | 2 |
2024-11-18T22:48:55.776170+00:00 | 2021-03-20T01:32:33 | 7315d6a82194b343958d388d0eee7dd281f9f94a | {
"blob_id": "7315d6a82194b343958d388d0eee7dd281f9f94a",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-20T01:32:33",
"content_id": "3676cad51fa6896d23893942d79ce76bb51b9b72",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "fe7ab9b607890659f11c3c48350bb8d811a9bdc9",
"extension": "c",
"filename": "vfs.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5922,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/kernel/fs/vfs.c",
"provenance": "stackv2-0108.json.gz:83192",
"repo_name": "chiboubys/rock",
"revision_date": "2021-03-20T01:32:33",
"revision_id": "37070d2e249c7ec6209dece79e317b2aa34879d8",
"snapshot_id": "679721c18a0eaca55f3607d833b63b23bd26afbc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chiboubys/rock/37070d2e249c7ec6209dece79e317b2aa34879d8/kernel/fs/vfs.c",
"visit_date": "2023-05-09T06:13:54.006337"
} | stackv2 | #include <sched/scheduler.h>
#include <fs/vfs.h>
#include <debug.h>
#include <vec.h>
struct vfs_node vfs_root_node = { .absolute_path = "/",
.name = "/",
.relative_path = "/"
};
struct vfs_node *vfs_create_node(struct vfs_node *parent, char *name) {
char *absolute_path;
if(parent != &vfs_root_node) {
char *dir_path = str_congregate(parent->absolute_path, "/");
absolute_path = str_congregate(dir_path, name);
kfree(dir_path);
} else {
absolute_path = str_congregate(parent->absolute_path, name);
}
char *relative_path = NULL;
if((parent->fs != NULL) && (parent->fs->mount_gate != NULL))
relative_path = absolute_path + (strlen(parent->fs->mount_gate));
struct vfs_node new_node = { .parent = parent,
.absolute_path = absolute_path,
.relative_path = relative_path,
.name = name,
.fs = parent->fs
};
vec_push(struct vfs_node, parent->child_nodes, new_node);
return vec_search(struct vfs_node, parent->child_nodes, parent->child_nodes.element_cnt - 1);
}
struct vfs_node *vfs_create_node_deep(char *path) {
char *buffer = kmalloc(strlen(path) + 1);
strcpy(buffer, path);
struct vfs_node *node = &vfs_root_node;
struct vfs_node *parent;
char *sub_path, *save = buffer;
while((sub_path = strtok_r(save, "/", &save))) {
parent = node;
node = vfs_relative_path(node, sub_path);
if(node == NULL)
goto found;
}
kfree(buffer);
return NULL;
found:
do {
char *name = kmalloc(strlen(sub_path));
strcpy(name, sub_path);
parent = vfs_create_node(parent, name);
} while((sub_path = strtok_r(save, "/", &save)));
kfree(buffer);
return parent;
}
struct vfs_node *vfs_absolute_path(char *path) {
if(strcmp(path, "/") == 0)
return &vfs_root_node;
if(*path == '/')
path++;
char *buffer = kmalloc(strlen(path));
strcpy(buffer, path);
struct vfs_node *node = &vfs_root_node;
char *sub_path, *save = buffer;
while((sub_path = strtok_r(save, "/", &save))) {
node = vfs_relative_path(node, sub_path);
if(node == NULL) {
kfree(buffer);
return NULL;
}
}
kfree(buffer);
return node;
}
struct vfs_node *vfs_relative_path(struct vfs_node *parent, char *name) {
for(size_t i = 0; i < parent->child_nodes.element_cnt; i++) {
struct vfs_node *node = vec_search(struct vfs_node, parent->child_nodes, i);
if(strcmp(node->name, name) == 0) {
return node;
}
}
return NULL;
}
struct vfs_node *vfs_mkdir(struct vfs_node *parent, char *name) {
struct vfs_node *dir_node = vfs_create_node(parent, name);
vfs_create_node(dir_node, ".");
struct vfs_node *dotdot = vfs_create_node(dir_node, "..");
dotdot->parent = parent;
return dir_node;
}
static void vfs_remove_cluster(struct vfs_node *node) {
if(node->child_nodes.element_cnt != 0) {
for(size_t i = 0; i < node->child_nodes.element_cnt; i++) {
struct vfs_node *tmp = vec_search(struct vfs_node, node->child_nodes, i);
tmp->fs->unlink(tmp);
vfs_remove_cluster(tmp);
}
vec_delete(node->child_nodes);
} else {
node->fs->unlink(node);
vec_delete(node->child_nodes);
}
}
int vfs_remove_node(struct vfs_node *node) {
if(vfs_absolute_path(node->absolute_path) == NULL)
return -1;
vfs_remove_cluster(node);
return 0;
}
int vfs_mount_dev(char *dev, char *mount_gate) {
struct vfs_node *mount_node = vfs_absolute_path(mount_gate);
if(mount_node == NULL)
return -1;
struct devfs_node *devfs_node = path2devfs(dev);
if(devfs_node == NULL || devfs_node->device == NULL || devfs_node->device->fs == NULL)
return -1;
devfs_node->device->fs->mount_gate = mount_gate;
mount_node->fs = devfs_node->device->fs;
devfs_node->device->fs->refresh(mount_node);
kprintf("[FS] [%s] mounted to [%s]\n", dev, mount_gate);
return 0;
}
int vfs_mount_fs(struct filesystem *fs) {
struct vfs_node *vfs_node = vfs_absolute_path(fs->mount_gate);
if(vfs_node == NULL)
return -1;
vfs_node->fs = fs;
return 0;
}
int vfs_write(struct vfs_node *node, off_t off, off_t cnt, void *buf) {
if(node == NULL) {
return -1;
}
return node->fs->write(node, off, cnt, buf);
}
int vfs_read(struct vfs_node *node, off_t off, off_t cnt, void *buf) {
if(node == NULL) {
return -1;
}
return node->fs->read(node, off, cnt, buf);
}
int vfs_open(char *path, int flags) {
struct vfs_node *node = vfs_absolute_path(path);
if(node == NULL && flags & O_CREAT) {
node = vfs_create_node_deep(path);
if(node == NULL)
return -1;
int ret = node->fs->open(node, flags);
if(ret == -1)
vfs_remove_node(node);
return ret;
} else if(node == NULL) {
set_errno(ENOENT);
return -1;
}
int ret = node->fs->open(node, flags);
if(ret == -1) {
vfs_remove_node(node);
}
return ret;
}
int vfs_unlink(char *path) {
struct vfs_node *node = vfs_absolute_path(path);
if(node == NULL)
return -1;
vfs_remove_node(node);
return 0;
}
void syscall_chdir(struct regs *regs) {
struct core_local *local = get_core_local(CURRENT_CORE);
struct task *current_task = hash_search(struct task, tasks, local->pid);
struct vfs_node *working_dir = vfs_absolute_path((void*)regs->rdi);
current_task->working_dir = working_dir;
regs->rax = 0;
}
| 2.75 | 3 |
2024-11-18T22:48:56.406741+00:00 | 2020-09-17T11:02:42 | 51b459d66f4f07b349ef17cf1d218983e93b1296 | {
"blob_id": "51b459d66f4f07b349ef17cf1d218983e93b1296",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-17T11:02:42",
"content_id": "858878c8c826f979df416218b8a82c746ac128d6",
"detected_licenses": [
"MIT"
],
"directory_id": "1abdf5ae4b7b4fc4edfe2a1d232421a23f1c0911",
"extension": "c",
"filename": "args.c",
"fork_events_count": 4,
"gha_created_at": "2020-06-17T15:55:00",
"gha_event_created_at": "2020-09-17T11:02:43",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 273017497,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1917,
"license": "MIT",
"license_type": "permissive",
"path": "/srcs/vm/args.c",
"provenance": "stackv2-0108.json.gz:83968",
"repo_name": "merlijnve/corewar",
"revision_date": "2020-09-17T11:02:42",
"revision_id": "6dffb280a88df1c88ceb69d200ac84fe6e6cbb7e",
"snapshot_id": "5e2de0b841411742c03cb840efa3dbb8ff9c39a8",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/merlijnve/corewar/6dffb280a88df1c88ceb69d200ac84fe6e6cbb7e/srcs/vm/args.c",
"visit_date": "2022-12-13T20:52:52.390961"
} | stackv2 | /* ************************************************************************** */
/* */
/* :::::::: */
/* args.c :+: :+: */
/* +:+ */
/* By: wmisiedj <wmisiedj@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2020/09/13 13:48:52 by wmisiedj #+# #+# */
/* Updated: 2020/09/16 14:57:06 by joris ######## odam.nl */
/* */
/* ************************************************************************** */
#include "vm.h"
t_args_type get_arg(t_enbyte byte, t_inst inst, int argnr)
{
if (get_opinfo(inst)->has_enbyte)
{
if (argnr == 1)
return (byte.arg1);
if (argnr == 2)
return (byte.arg2);
if (argnr == 3)
return (byte.arg3);
}
return (get_opinfo(inst)->v_args[argnr - 1].arg1);
}
int arg_length(t_args_type type, t_inst inst)
{
if (type == kTReg)
return (REG_SIZE_ASM);
else if (type == kTDir)
return (get_opinfo(inst)->dir_size);
else if (type == kTInd)
return (IND_SIZE_ASM);
else if (type == kTNone)
return (0);
return (0);
}
int args_length(t_enbyte byte, t_inst inst)
{
int len;
int i;
len = 1;
i = 0;
if (is_opcode(inst))
{
while (i < get_opinfo(inst)->argc)
{
len += arg_length(get_arg(byte, inst, i + 1), inst);
i++;
}
len += get_opinfo(inst)->has_enbyte ? 1 : 0;
}
return (len);
}
/*
** IS_REGISTRY
** Checks if given argument is a valid registry
*/
int is_registry(int arg)
{
if (arg > 0 && arg <= REG_NUMBER)
return (true);
return (false);
}
| 2.578125 | 3 |
2024-11-18T22:48:56.462434+00:00 | 2021-06-06T19:16:29 | 1594419dcfa99456233ff83a9a663d856b46a4c1 | {
"blob_id": "1594419dcfa99456233ff83a9a663d856b46a4c1",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-06T19:16:29",
"content_id": "f5d23cfbdb0a053a1466f68da618a2a7efed4a6f",
"detected_licenses": [
"MIT"
],
"directory_id": "22315e5a136669b01aac65ade2dbe97f33eaff36",
"extension": "c",
"filename": "4.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 280022226,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 481,
"license": "MIT",
"license_type": "permissive",
"path": "/[06 2020]pseudocode/aula logica/lista 3/4.c",
"provenance": "stackv2-0108.json.gz:84096",
"repo_name": "frigo-augusto/College-work-and-exercises",
"revision_date": "2021-06-06T19:16:29",
"revision_id": "ce0bdce125dde2b67783e0c1bfe1f4797cb80e0d",
"snapshot_id": "67be3d503822006ef4331029dede26d9155f17f0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/frigo-augusto/College-work-and-exercises/ce0bdce125dde2b67783e0c1bfe1f4797cb80e0d/[06 2020]pseudocode/aula logica/lista 3/4.c",
"visit_date": "2023-05-24T06:06:06.154386"
} | stackv2 | #include <stdio.h>
int main()
{
int numero;
printf ("digite um numero");
scanf ("%d", &numero);
if (numero % 2 == 1)
{
while (numero != 1)
{
printf ("\n%d\n", numero);
numero = numero - 2;
}
printf ("\n1");
}
else
{
numero = numero - 1;
while (numero != 1)
{
printf ("\n%d\n", numero);
numero = numero - 2;
}
printf ("\n1");
}
} | 2.984375 | 3 |
2024-11-18T22:48:56.528312+00:00 | 2020-04-12T17:46:26 | 9cc6ba63ac527a21a2147974fceb4ebd9b5f0989 | {
"blob_id": "9cc6ba63ac527a21a2147974fceb4ebd9b5f0989",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-12T17:46:26",
"content_id": "23a65badf66d00267d8b3c3fe8ee525ec75ce6d1",
"detected_licenses": [
"MIT"
],
"directory_id": "f10b153bd2cb0312bab1cca55eab2b6f1d7104aa",
"extension": "c",
"filename": "point.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 164558648,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 130,
"license": "MIT",
"license_type": "permissive",
"path": "/point.c",
"provenance": "stackv2-0108.json.gz:84227",
"repo_name": "andreagen0r/deckmaster",
"revision_date": "2020-04-12T17:46:26",
"revision_id": "bb6ba1a2cdea998a820e9e355c788fc1b1750a35",
"snapshot_id": "b2c91f4c352e6db8bfd93ea33cb61ca8d25b621f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/andreagen0r/deckmaster/bb6ba1a2cdea998a820e9e355c788fc1b1750a35/point.c",
"visit_date": "2020-04-15T09:37:24.766219"
} | stackv2 | #include "point.h"
void point_print(const Point m_position)
{
printf("Posição: [%d, %d]\n", m_position.x, m_position.y);
}
| 2.125 | 2 |
2024-11-18T22:48:56.676450+00:00 | 2019-04-14T22:43:07 | 81bf021bff073030fab1e89e2ecad9ef1f26968e | {
"blob_id": "81bf021bff073030fab1e89e2ecad9ef1f26968e",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-14T22:43:07",
"content_id": "d14837d92ed280a999b7a1b3eff98f096a9f35eb",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "2ebad4048790924e4662894da4b1811cdd1824de",
"extension": "c",
"filename": "shmap.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 23966,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/shmap.c",
"provenance": "stackv2-0108.json.gz:84356",
"repo_name": "docterling/libsrt",
"revision_date": "2019-04-14T22:43:07",
"revision_id": "078b337aff3a09b41a51aec946382123bba7e3ef",
"snapshot_id": "9b416d3a889acb1079d3b5f5dc91439d16b0e475",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/docterling/libsrt/078b337aff3a09b41a51aec946382123bba7e3ef/src/shmap.c",
"visit_date": "2020-05-27T19:12:41.575082"
} | stackv2 | /*
* shmap.c
*
* Hash map handling
*
* Copyright (c) 2015-2019 F. Aragon. All rights reserved. Released under
* the BSD 3-Clause License (see the doc/LICENSE file included).
*/
#include "shmap.h"
#include "saux/shash.h"
#include "saux/sstringo.h"
/*
* Constants and macros
*/
#define SHM_MAX_ELEMS 0xffffffff
#define SHM_LOC_EMPTY 0 /* do not change this */
#define SHM_REHASH_DEFAULT_THRESHOLD_PCT 90 /* rehash at 90% of buckets */
#define shm_void (srt_hmap *)sd_void
/*
* Internal functions
*/
S_INLINE size_t h2bid(uint32_t h32, size_t hbits)
{
return h32 >> (32 - hbits);
}
static srt_bool eq_64(const void *key, const void *node)
{
return memcmp(key, node, sizeof(int64_t)) ? S_FALSE : S_TRUE;
}
static srt_bool eq_32(const void *key, const void *node)
{
return memcmp(key, node, sizeof(int32_t)) ? S_FALSE : S_TRUE;
}
static srt_bool eq_sso(const void *key, const void *node)
{
return sso_eq((const srt_string *)key, (const srt_stringo *)node);
}
static srt_bool eq_sso1(const void *key, const void *node)
{
return sso1_eq((const srt_string *)key, (const srt_stringo1 *)node);
}
static void shmcb_set_ii32(void *loc, const void *key, const void *value)
{
struct SHMapii *e = (struct SHMapii *)loc;
memcpy(&e->x.k, key, sizeof(e->x.k));
memcpy(&e->v, value, sizeof(e->v));
}
static void shmcb_set_uu32(void *loc, const void *key, const void *value)
{
struct SHMapuu *e = (struct SHMapuu *)loc;
memcpy(&e->x.k, key, sizeof(e->x.k));
memcpy(&e->v, value, sizeof(e->v));
}
static void shmcb_set_ii64(void *loc, const void *key, const void *value)
{
struct SHMapII *e = (struct SHMapII *)loc;
memcpy(&e->x.k, key, sizeof(e->x.k));
memcpy(&e->v, value, sizeof(e->v));
}
static void shmcb_set_is(void *loc, const void *key, const void *value)
{
struct SHMapIS *e = (struct SHMapIS *)loc;
memcpy(&e->x.k, key, sizeof(e->x.k));
sso1_set(&e->v, (const srt_string *)value);
}
static void shmcb_set_ip(void *loc, const void *key, const void *value)
{
struct SHMapIP *e = (struct SHMapIP *)loc;
memcpy(&e->x.k, key, sizeof(e->x.k));
e->v = value;
}
static void shmcb_set_si(void *loc, const void *key, const void *value)
{
struct SHMapSI *e = (struct SHMapSI *)loc;
sso1_set(&e->x.k, (const srt_string *)key);
memcpy(&e->v, value, sizeof(e->v));
}
static void shmcb_set_ss(void *loc, const void *key, const void *value)
{
struct SHMapSS *e = (struct SHMapSS *)loc;
sso_set(&e->kv, (const srt_string *)key, (const srt_string *)value);
}
static void shmcb_set_sp(void *loc, const void *key, const void *value)
{
struct SHMapSP *e = (struct SHMapSP *)loc;
sso1_set(&e->x.k, (const srt_string *)key);
e->v = value;
}
static void shmcb_set_i32(void *loc, const void *key)
{
struct SHMapi *e = (struct SHMapi *)loc;
memcpy(&e->k, key, sizeof(e->k));
}
static void shmcb_set_u32(void *loc, const void *key)
{
struct SHMapu *e = (struct SHMapu *)loc;
memcpy(&e->k, key, sizeof(e->k));
}
static void shmcb_set_i64(void *loc, const void *key)
{
struct SHMapI *e = (struct SHMapI *)loc;
memcpy(&e->k, key, sizeof(e->k));
}
static void shmcb_set_s(void *loc, const void *key)
{
struct SHMapS *e = (struct SHMapS *)loc;
sso1_set(&e->k, (const srt_string *)key);
}
static void shmcb_inc_ii32(void *loc, const void *value)
{
int32_t vi;
struct SHMapii *e = (struct SHMapii *)loc;
memcpy(&vi, value, sizeof(vi));
e->v += vi;
}
static void shmcb_inc_uu32(void *loc, const void *value)
{
uint32_t vi;
struct SHMapuu *e = (struct SHMapuu *)loc;
memcpy(&vi, value, sizeof(vi));
e->v += vi;
}
static void shmcb_inc_ii64(void *loc, const void *value)
{
int64_t vi;
struct SHMapII *e = (struct SHMapII *)loc;
memcpy(&vi, value, sizeof(vi));
e->v += vi;
}
static void shmcb_inc_si(void *loc, const void *value)
{
int64_t vi;
struct SHMapSI *e = (struct SHMapSI *)loc;
memcpy(&vi, value, sizeof(vi));
e->v += vi;
}
static void del_is(void *node)
{
sso1_free((srt_stringo1 *)&((struct SHMapIS *)node)->v);
}
static void del_sx(void *node)
{
sso1_free(&((struct SHMapS *)node)->k);
}
static void del_ss(void *node)
{
sso_free(&((struct SHMapSS *)node)->kv);
}
static void del_nop(void *node)
{
(void)node;
}
static uint32_t hash_32(const void *node)
{
return sh_hash32(S_LD_U32(node));
}
static uint32_t hash_64(const void *node)
{
return sh_hash64(S_LD_U64(node));
}
static uint32_t hash_sx(const void *node)
{
return SHM_SHASH(sso1_get((const srt_stringo1 *)node));
}
static uint32_t hash_ss(const void *node)
{
return SHM_SHASH(sso_get((const srt_stringo *)node));
}
static const void *n2key_direct(const void *node)
{
return node;
}
static const void *n2key_sx(const void *node)
{
return sso1_get((const srt_stringo1 *)node);
}
static const void *n2key_ss(const void *node)
{
return sso_get((const srt_stringo *)node);
}
static void aux_reg_hash(srt_hmap *hm, const void *key, uint32_t h32,
uint32_t loc)
{
uint8_t *eloc;
size_t bid, l, hmask;
struct SHMBucket *b = shm_get_buckets(hm);
bid = h2bid(h32, hm->hbits);
hmask = hm->hmask;
for (l = bid; b[l].loc; l = (l + 1) & hmask)
if (b[l].hash == h32) {
eloc = shm_get_buffer(hm)
+ (b[l].loc - 1) * hm->d.elem_size;
if (hm->eqf(key, eloc))
goto skip_bucket_inc; /* found, overwrite */
}
b[bid].cnt++;
skip_bucket_inc:
b[l].loc = loc + 1;
b[l].hash = h32;
}
static void aux_rehash(srt_hmap *hm)
{
shm_eloc_t_ i;
const srt_string *s;
uint8_t *data = shm_get_buffer(hm);
struct SHMBucket *b = shm_get_buckets(hm);
size_t nbuckets, elem_size = hm->d.elem_size, nelems = shm_size(hm);
uint64_t nb64 = (uint64_t)1 << hm->hbits;
nbuckets = (size_t)nb64;
S_ASSERT((uint64_t)nbuckets == nb64);
hm->hmask = hm->hbits == 32 ? (uint32_t)-1 : (uint32_t)(nbuckets - 1);
hm->rh_threshold = s_size_t_pct(nbuckets, hm->rh_threshold_pct);
/*
* Reset the hash table buckets, and rehash all elements
*/
memset(b, 0, sizeof(struct SHMBucket) * nbuckets);
switch (hm->ksize) {
case 4:
for (i = 0; i < nelems; i++, data += elem_size)
aux_reg_hash(hm, data, sh_hash32(S_LD_U32(data)), i);
break;
case 8:
for (i = 0; i < nelems; i++, data += elem_size)
aux_reg_hash(hm, data, sh_hash64(S_LD_U64(data)), i);
break;
case 0:
for (i = 0; i < nelems; i++, data += elem_size) {
s = sso_get((const srt_stringo *)data);
aux_reg_hash(hm, s, SHM_SHASH(s), i);
}
break;
default:
/* this should not happen */
return;
}
}
static srt_bool aux_insert_check(srt_hmap **hm)
{
srt_hmap *h2;
size_t h2bits, hs1, hs2, hsd, sxz, sxzm, sz;
RETURN_IF(!shm_grow(hm, 1), S_FALSE);
sz = shm_size(*hm);
/* Check if rehash is not required */
if (sz < (*hm)->rh_threshold)
return S_TRUE;
if ((*hm)->hbits == 32) {
(*hm)->rh_threshold = SHM_MAX_ELEMS;
RETURN_IF(sz == (*hm)->rh_threshold, S_FALSE);
return S_TRUE;
}
/* Rehash required: realloc for twice the bucket size */
if ((*hm)->d.f.ext_buffer) {
S_ERROR("out of memory on fixed-size allocated space");
shm_set_alloc_errors(*hm);
return S_FALSE;
}
sxz = shm_size(*hm) * (*hm)->d.elem_size;
sxzm = shm_max_size(*hm) * (*hm)->d.elem_size;
hs1 = (*hm)->d.header_size;
h2bits = (*hm)->hbits + 1;
hs2 = sh_hdr_size((*hm)->d.sub_type, (uint64_t)1 << h2bits);
h2 = (srt_hmap *)s_realloc(*hm, hs2 + sxzm);
RETURN_IF(!h2, S_FALSE); /* Not enough memory */
*hm = h2;
#if 1
/*
* Memory map:
* | headerA | buckets #A | data #A |
* <-- hs0 --> <----- sxzm ---->
* <--------- hs1 -------->
*
* | headerB | buckets #B = 2 * b#A | data #B |
* <-- hs0 --> <----- sxzm ---->
* <---------------- hs2 ----------->
* <-- ds1 -->
* <-ds2->
* <-- ds1'-->
*/
/* move ds1 from the head, to the tail */
hsd = hs2 - hs1;
if (sxz <= hsd)
memmove((uint8_t *)h2 + hs2, (uint8_t *)h2 + hs1, sxz);
else
memmove((uint8_t *)h2 + hs1 + sxz, (uint8_t *)h2 + hs1, hsd);
#else
/* not optimized: */
memmove((uint8_t *)h2 + hs2, (uint8_t *)h2 + hs1, sxz);
#endif
/* Reconfigure the data structure */
h2->d.header_size = hs2;
h2->hbits = (uint32_t)h2bits;
/* Rehash elements */
aux_rehash(h2);
return S_TRUE;
}
S_INLINE srt_bool shm_chk_t(const srt_hmap *h, int t)
{
return h && h->d.sub_type == t ? S_TRUE : S_FALSE;
}
typedef uint32_t (*hash_f)(const void *data);
/* 'hm' already checked externally */
const void *shm_at(const srt_hmap *hm, uint32_t h, const void *key,
uint32_t *tl)
{
const uint8_t *data, *eloc;
size_t bid = h2bid(h, hm->hbits), eoff, es, hbits, hcnt, hmask, hmax, l;
const struct SHMBucket *b = shm_get_buckets_r(hm);
RETURN_IF(!b[bid].cnt, NULL); /* Hash not in the HT */
hmax = b[bid].cnt;
data = shm_get_buffer_r(hm);
es = hm->d.elem_size;
hmask = hm->hmask;
hbits = hm->hbits;
for (hcnt = 0, l = bid; hcnt < hmax; l = (l + 1) & hmask) {
if (b[l].loc == SHM_LOC_EMPTY || h2bid(b[l].hash, hbits) != bid)
continue;
/* Possible match */
hcnt++;
if (b[l].hash == h) {
eoff = b[l].loc - 1;
eloc = data + eoff * es;
if (hm->eqf(key, eloc)) {
if (tl)
*tl = (uint32_t)l;
return eloc;
}
}
}
return NULL;
}
static srt_bool del(srt_hmap *hm, uint32_t h, const void *key)
{
struct SHMBucket *b;
const uint8_t *tloc;
uint32_t ht, l0, tl = 0;
size_t bid, e_off, es, hcnt, hmax, l, ss, hbits, hmask;
uint8_t *data, *dloc, *hole, *tail;
RETURN_IF(!hm, S_FALSE);
hbits = hm->hbits;
bid = h2bid(h, hbits);
b = shm_get_buckets(hm);
RETURN_IF(!b[bid].cnt, S_FALSE); /* Hash not in the HT */
hmax = b[bid].cnt;
data = shm_get_buffer(hm);
es = hm->d.elem_size;
hmask = hm->hmask;
for (hcnt = 0, l = bid; hcnt < hmax; l = (l + 1) & hmask) {
if (b[l].loc == SHM_LOC_EMPTY || h2bid(b[l].hash, hbits) != bid)
continue;
/* Possible match */
hcnt++;
if (b[l].hash == h) {
e_off = b[l].loc - 1;
dloc = data + e_off * es;
if (hm->eqf(key, dloc)) {
l0 = b[l].loc;
b[bid].cnt--;
b[l].loc = 0;
hm->delf(dloc);
/* Fill the hole with the latest elem */
ss = shm_size(hm);
if (ss > 1 && ss != l0) {
hole = data + e_off * es;
tail = data + (ss - 1) * es;
ht = hm->hashf(tail);
tloc = (const uint8_t *)shm_at(
hm, ht, hm->n2kf(tail), &tl);
(void)tloc;
#if 0
/*
* This should never happen. Otherwise
* it would mean memory corruption.
*/
if (tloc != tail || b[tl].loc == l0)
abort();
#endif
memcpy(hole, tail, es);
b[tl].loc = l0;
}
shm_set_size(hm, ss - 1);
return S_TRUE;
}
}
}
return S_FALSE;
}
S_INLINE void shm_tsetup(srt_hmap *h, int t)
{
switch (t) {
case SHM0_I32:
case SHM0_U32:
case SHM0_II32:
case SHM0_UU32:
h->ksize = 4;
h->eqf = eq_32;
h->delf = del_nop;
h->hashf = hash_32;
h->n2kf = n2key_direct;
break;
case SHM0_I:
case SHM0_II:
case SHM0_IS:
case SHM0_IP:
h->ksize = 8;
h->eqf = eq_64;
h->delf = t == SHM0_IS ? del_is : del_nop;
h->hashf = hash_64;
h->n2kf = n2key_direct;
break;
case SHM0_SI:
case SHM0_SP:
case SHM0_S:
h->ksize = 0;
h->eqf = eq_sso1;
h->delf = del_sx;
h->hashf = hash_sx;
h->n2kf = n2key_sx;
break;
case SHM0_SS:
h->ksize = 0;
h->eqf = eq_sso;
h->delf = del_ss;
h->hashf = hash_ss;
h->n2kf = n2key_ss;
break;
default:
break;
}
}
/*
* Public functions
*/
srt_hmap *shm_alloc_raw(int t, srt_bool ext_buf, void *buffer, size_t hdr_size,
size_t elem_size, size_t max_size, size_t hbits)
{
srt_hmap *h;
RETURN_IF(!elem_size || !buffer, shm_void);
h = (srt_hmap *)buffer;
sd_reset((srt_data *)h, hdr_size, elem_size, max_size, ext_buf,
S_FALSE);
h->d.sub_type = (uint8_t)t;
shm_tsetup(h, t);
h->rh_threshold_pct = SHM_REHASH_DEFAULT_THRESHOLD_PCT;
h->hbits = (uint32_t)hbits;
aux_rehash(h);
return h;
}
srt_hmap *shm_alloc_aux(int t, size_t init_size)
{
size_t elem_size = shm_elem_size(t), hbits = shm_s2hb(init_size),
hs = sh_hdr_size(t, (uint64_t)1 << hbits),
as = sd_alloc_size_raw(hs, elem_size, init_size, S_FALSE);
void *buf = s_malloc(as);
srt_hmap *h =
shm_alloc_raw(t, S_FALSE, buf, hs, elem_size, init_size, hbits);
if (!h || h == shm_void)
s_free(buf);
return h;
}
void shm_clear(srt_hmap *hm)
{
size_t es;
uint8_t *p, *pt;
if (!hm)
return;
p = shm_get_buffer(hm);
es = hm->d.elem_size;
pt = p + shm_size(hm) * es;
switch (hm->d.sub_type) {
case SHM0_SI:
case SHM0_IS:
case SHM0_SP:
case SHM0_SS:
case SHM0_S:
for (; p < pt; p += es)
hm->delf(p);
break;
}
shm_set_size(hm, 0);
}
void shm_free_aux(srt_hmap **hm, ...)
{
va_list ap;
srt_hmap **next = hm;
va_start(ap, hm);
while (!s_varg_tail_ptr_tag(next)) { /* last element tag */
shm_clear(*next); /* release associated dyn. memory */
sd_free((srt_data **)next);
next = (srt_hmap **)va_arg(ap, srt_hmap **);
}
va_end(ap);
}
srt_hmap *shm_dup(const srt_hmap *src)
{
srt_hmap *hm = NULL;
return shm_cpy(&hm, src);
}
S_INLINE size_t shm_current_alloc_size(const srt_hmap *h)
{
return h ? h->d.header_size + h->d.elem_size * shm_max_size(h) : 0;
}
static srt_bool shm_cpy_reconfig(srt_hmap **hm, const srt_hmap *src)
{
srt_hmap *hra;
uint8_t t = src->d.sub_type;
uint64_t hs64 = snextpow2(shm_size(src));
size_t tgt0_cas = shm_current_alloc_size(*hm),
src0_cas = shm_current_alloc_size(src), np2 = (size_t)hs64,
hbits = slog2(np2), hdr_size = sh_hdr_size(t, np2),
es = src->d.elem_size, elems = shm_size(src),
data_size = es * elems, min_alloc_size = hdr_size + data_size;
RETURN_IF((uint64_t)np2 != hs64, S_FALSE);
/* Target cleanup, before the copy */
shm_clear(*hm);
/* Make room for the copy */
if ((*hm)->d.f.ext_buffer) {
/* Using stack-allocated: check for enough space */
RETURN_IF(min_alloc_size > tgt0_cas, S_FALSE);
(*hm)->d.sub_type = src->d.sub_type;
(*hm)->d.elem_size = src->d.elem_size;
(*hm)->d.max_size = (tgt0_cas - hdr_size) / es;
} else {
/* Check if requiring extra expace */
if (min_alloc_size > tgt0_cas) {
hra = (srt_hmap *)s_realloc(*hm, src0_cas);
RETURN_IF(!hra, S_FALSE);
*hm = hra;
(*hm)->d.max_size = (src0_cas - hdr_size) / es;
} else {
(*hm)->d.max_size = (tgt0_cas - hdr_size) / es;
}
(*hm)->d.sub_type = src->d.sub_type;
(*hm)->d.elem_size = src->d.elem_size;
}
(*hm)->d.header_size = hdr_size;
(*hm)->hbits = (uint32_t)hbits;
(*hm)->eqf = src->eqf;
(*hm)->delf = src->delf;
(*hm)->n2kf = src->n2kf;
(*hm)->ksize = src->ksize;
return S_TRUE;
}
srt_hmap *shm_cpy(srt_hmap **hm, const srt_hmap *src)
{
uint8_t t;
uint8_t *data_tgt;
const uint8_t *data_src;
size_t i, hs, hdr0_size, es, ss;
struct SHMapS *h_s;
struct SHMapIS *h_is;
struct SHMapSI *h_si;
struct SHMapSP *h_sp;
struct SHMapSS *h_ss;
RETURN_IF(!hm || !src, NULL); /* BEHAVIOR */
RETURN_IF(*hm == src, *hm);
t = src->d.sub_type;
hs = shm_size(src);
es = src->d.elem_size;
ss = shm_size(src);
RETURN_IF(hs > SHM_MAX_ELEMS, NULL); /* BEHAVIOR */
if (*hm) {
/* De-allocate target nodes, if necessary */
RETURN_IF(!shm_cpy_reconfig(hm, src), NULL);
} else {
*hm = shm_alloc_aux(t, ss);
RETURN_IF(!*hm, NULL); /* BEHAVIOR: allocation error */
}
RETURN_IF(shm_max_size(*hm) < ss, *hm); /* BEHAVIOR: not enough space */
/* Copy data */
data_tgt = shm_get_buffer(*hm);
data_src = shm_get_buffer_r(src);
/* bulk copy */
memcpy(data_tgt, data_src, es * ss);
shm_set_size(*hm, ss);
/* cases potentially requiring adaptation */
switch (t) {
case SHM0_S:
h_s = (struct SHMapS *)data_tgt;
for (i = 0; i < ss; i++)
sso_dupa1(&h_s[i].k);
break;
case SHM0_IS:
h_is = (struct SHMapIS *)data_tgt;
for (i = 0; i < ss; sso_dupa1(&h_is[i++].v))
;
break;
case SHM0_SP:
h_sp = (struct SHMapSP *)data_tgt;
for (i = 0; i < ss; sso_dupa1(&h_sp[i++].x.k))
;
break;
case SHM0_SI:
h_si = (struct SHMapSI *)data_tgt;
for (i = 0; i < ss; sso_dupa1(&h_si[i++].x.k))
;
break;
case SHM0_SS:
h_ss = (struct SHMapSS *)data_tgt;
for (i = 0; i < ss; sso_dupa(&h_ss[i++].kv))
;
break;
default:
break;
}
/* rehash */
if ((*hm)->d.header_size == src->d.header_size) {
/* Same header size: hash table buckets bulk copy */
hdr0_size = sh_hdr0_size();
memcpy((uint8_t *)*hm + hdr0_size,
(const uint8_t *)src + hdr0_size,
src->d.header_size - hdr0_size);
} else {
/* Different bucket size, rehash required */
aux_rehash(*hm);
}
return *hm;
}
/*
* Insert
*/
typedef void (*shm_set1_f)(void *loc, const void *key);
static srt_bool shm_insert1(srt_hmap **hm, int t, const void *k, uint32_t h32,
shm_set1_f setf)
{
void *l;
size_t i;
RETURN_IF(!hm || !*hm || !shm_chk_t(*hm, t), S_FALSE);
RETURN_IF(!aux_insert_check(hm), S_FALSE);
l = (void *)shm_at(*hm, h32, k, NULL);
if (!l) {
i = shm_size(*hm);
aux_reg_hash(*hm, k, h32, (shm_eloc_t_)i);
shm_set_size(*hm, i + 1);
l = shm_get_buffer(*hm) + i * (*hm)->d.elem_size;
}
setf(l, k);
return S_TRUE;
}
typedef void (*shm_set_f)(void *loc, const void *key, const void *value);
static srt_bool shm_insert(srt_hmap **hm, int t, const void *k, uint32_t h32,
const void *v, shm_set_f setf)
{
void *l;
size_t i;
RETURN_IF(!hm || !*hm || !shm_chk_t(*hm, t), S_FALSE);
RETURN_IF(!aux_insert_check(hm), S_FALSE);
l = (void *)shm_at(*hm, h32, k, NULL);
if (!l) {
i = shm_size(*hm);
aux_reg_hash(*hm, k, h32, (shm_eloc_t_)i);
shm_set_size(*hm, i + 1);
l = shm_get_buffer(*hm) + i * (*hm)->d.elem_size;
}
setf(l, k, v);
return S_TRUE;
}
/*
* Increment
*/
typedef void (*shm_inc_f)(void *loc, const void *value);
static srt_bool shm_inc(srt_hmap **hm, int t, const void *k, uint32_t h32,
const void *v, shm_set_f setf, shm_inc_f incf)
{
void *l;
RETURN_IF(!hm || !*hm || !shm_chk_t(*hm, t), S_FALSE);
RETURN_IF(!aux_insert_check(hm), S_FALSE);
l = (void *)shm_at(*hm, h32, k, NULL);
if (!l) /* not found: create new elem */
return shm_insert(hm, t, k, h32, v, setf);
incf(l, v);
return S_TRUE;
}
/*
* Insert
*/
srt_bool shm_insert_ii32(srt_hmap **hm, int32_t k, int32_t v)
{
return shm_insert(hm, SHM0_II32, &k, sh_hash32((uint32_t)k), &v,
shmcb_set_ii32);
}
srt_bool shm_insert_uu32(srt_hmap **hm, uint32_t k, uint32_t v)
{
return shm_insert(hm, SHM0_UU32, &k, sh_hash32(k), &v, shmcb_set_uu32);
}
srt_bool shm_insert_ii(srt_hmap **hm, int64_t k, int64_t v)
{
return shm_insert(hm, SHM0_II, &k, sh_hash64((uint64_t)k), &v,
shmcb_set_ii64);
}
srt_bool shm_insert_is(srt_hmap **hm, int64_t k, const srt_string *v)
{
return shm_insert(hm, SHM0_IS, &k, sh_hash64((uint64_t)k), v,
shmcb_set_is);
}
srt_bool shm_insert_ip(srt_hmap **hm, int64_t k, const void *v)
{
return shm_insert(hm, SHM0_IP, &k, sh_hash64((uint64_t)k), v,
shmcb_set_ip);
}
srt_bool shm_insert_si(srt_hmap **hm, const srt_string *k, int64_t v)
{
return shm_insert(hm, SHM0_SI, k, SHM_SHASH(k), &v, shmcb_set_si);
}
srt_bool shm_insert_ss(srt_hmap **hm, const srt_string *k, const srt_string *v)
{
return shm_insert(hm, SHM0_SS, k, SHM_SHASH(k), v, shmcb_set_ss);
}
srt_bool shm_insert_sp(srt_hmap **hm, const srt_string *k, const void *v)
{
return shm_insert(hm, SHM0_SP, k, SHM_SHASH(k), v, shmcb_set_sp);
}
/*
* Increment
*/
srt_bool shm_inc_ii32(srt_hmap **hm, int32_t k, int32_t v)
{
return shm_inc(hm, SHM0_II32, &k, sh_hash32((uint32_t)k), &v,
shmcb_set_ii32, shmcb_inc_ii32);
}
srt_bool shm_inc_uu32(srt_hmap **hm, uint32_t k, uint32_t v)
{
return shm_inc(hm, SHM0_UU32, &k, sh_hash32(k), &v, shmcb_set_uu32,
shmcb_inc_uu32);
}
srt_bool shm_inc_ii(srt_hmap **hm, int64_t k, int64_t v)
{
return shm_inc(hm, SHM0_II, &k, sh_hash64((uint64_t)k), &v,
shmcb_set_ii64, shmcb_inc_ii64);
}
srt_bool shm_inc_si(srt_hmap **hm, const srt_string *k, int64_t v)
{
return shm_inc(hm, SHM0_SI, k, SHM_SHASH(k), &v, shmcb_set_si,
shmcb_inc_si);
}
srt_bool shm_insert_i32(srt_hmap **hm, int32_t k)
{
return shm_insert1(hm, SHM0_I32, &k, sh_hash32((uint32_t)k),
shmcb_set_i32);
}
srt_bool shm_insert_u32(srt_hmap **hm, uint32_t k)
{
return shm_insert1(hm, SHM0_U32, &k, sh_hash32((uint32_t)k),
shmcb_set_u32);
}
srt_bool shm_insert_i(srt_hmap **hm, int64_t k)
{
return shm_insert1(hm, SHM0_I, &k, sh_hash64((uint64_t)k),
shmcb_set_i64);
}
srt_bool shm_insert_s(srt_hmap **hm, const srt_string *k)
{
return shm_insert1(hm, SHM0_S, k, SHM_SHASH(k), shmcb_set_s);
}
/*
* Delete
*/
srt_bool shm_delete_i(srt_hmap *hm, int64_t k)
{
uint32_t k32;
if (hm->ksize == 4) {
k32 = (uint32_t)k;
return del(hm, sh_hash32(k32), &k32);
}
return del(hm, sh_hash64((uint64_t)k), &k);
}
srt_bool shm_delete_s(srt_hmap *hm, const srt_string *k)
{
return del(hm, SHM_SHASH(k), k);
}
/*
* Enumeration
*/
#define SHM_ITP_X(t, hm, f, begin, end) \
size_t cnt = 0, ms; \
const uint8_t *d0, *db, *de; \
RETURN_IF(!hm || t != hm->d.sub_type, 0); \
ms = shm_size(hm); \
RETURN_IF(begin > ms || begin >= end, 0); \
if (end > ms) \
end = ms; \
RETURN_IF(!f, end - begin); \
d0 = shm_get_buffer_r(hm); \
db = d0 + hm->d.elem_size * begin; \
de = d0 + hm->d.elem_size * end; \
for (; db < de; db += hm->d.elem_size, cnt++)
size_t shm_itp_ii32(const srt_hmap *m, size_t begin, size_t end,
srt_hmap_it_ii32 f, void *context)
{
const struct SHMapii *e;
SHM_ITP_X(SHM_II32, m, f, begin, end)
{
e = (const struct SHMapii *)db;
if (!f(e->x.k, e->v, context))
break;
}
return cnt;
}
size_t shm_itp_uu32(const srt_hmap *m, size_t begin, size_t end,
srt_hmap_it_uu32 f, void *context)
{
const struct SHMapuu *e;
SHM_ITP_X(SHM_UU32, m, f, begin, end)
{
e = (const struct SHMapuu *)db;
if (!f(e->x.k, e->v, context))
break;
}
return cnt;
}
size_t shm_itp_ii(const srt_hmap *m, size_t begin, size_t end, srt_hmap_it_ii f,
void *context)
{
const struct SHMapii *e;
SHM_ITP_X(SHM_II, m, f, begin, end)
{
e = (const struct SHMapii *)db;
if (!f(e->x.k, e->v, context))
break;
}
return cnt;
}
size_t shm_itp_is(const srt_hmap *m, size_t begin, size_t end, srt_hmap_it_is f,
void *context)
{
const struct SHMapIS *e;
SHM_ITP_X(SHM_IS, m, f, begin, end)
{
e = (const struct SHMapIS *)db;
if (!f(e->x.k, sso1_get((const srt_stringo1 *)&e->v), context))
break;
}
return cnt;
}
size_t shm_itp_ip(const srt_hmap *m, size_t begin, size_t end, srt_hmap_it_ip f,
void *context)
{
const struct SHMapIP *e;
SHM_ITP_X(SHM_IP, m, f, begin, end)
{
e = (const struct SHMapIP *)db;
if (!f(e->x.k, e->v, context))
break;
}
return cnt;
}
size_t shm_itp_si(const srt_hmap *m, size_t begin, size_t end, srt_hmap_it_si f,
void *context)
{
const struct SHMapSI *e;
SHM_ITP_X(SHM_SI, m, f, begin, end)
{
e = (const struct SHMapSI *)db;
if (!f(sso1_get((const srt_stringo1 *)&e->x.k), e->v, context))
break;
}
return cnt;
}
size_t shm_itp_ss(const srt_hmap *m, size_t begin, size_t end, srt_hmap_it_ss f,
void *context)
{
const struct SHMapSS *e;
SHM_ITP_X(SHM_SS, m, f, begin, end)
{
e = (const struct SHMapSS *)db;
if (!f(sso_get(&e->kv), sso_get_s2(&e->kv), context))
break;
}
return cnt;
}
size_t shm_itp_sp(const srt_hmap *m, size_t begin, size_t end, srt_hmap_it_sp f,
void *context)
{
const struct SHMapSP *e;
SHM_ITP_X(SHM_SP, m, f, begin, end)
{
e = (const struct SHMapSP *)db;
if (!f(sso1_get((const srt_stringo1 *)&e->x.k), e->v, context))
break;
}
return cnt;
}
| 2.171875 | 2 |
2024-11-18T22:48:57.040564+00:00 | 2021-04-26T04:32:19 | 4ef29fe0435a687a05ebea48a0634e28a0b57e65 | {
"blob_id": "4ef29fe0435a687a05ebea48a0634e28a0b57e65",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-26T04:32:19",
"content_id": "a3e432c92d0f1c968ec00494a197f99e970edb8d",
"detected_licenses": [
"MIT"
],
"directory_id": "7756fc66c114a9b6dfc499e9ff55a68d7226ea7a",
"extension": "h",
"filename": "RingBuffer.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 276566102,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 734,
"license": "MIT",
"license_type": "permissive",
"path": "/RingBuffer.h",
"provenance": "stackv2-0108.json.gz:84486",
"repo_name": "metarutaiga/StreamAL",
"revision_date": "2021-04-26T04:32:19",
"revision_id": "73029f0eccf99c2a375999ef26a44bc0e2eaf1b8",
"snapshot_id": "4a4b29fbb7a7b8cf2d06569a401a6a3d456463ac",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/metarutaiga/StreamAL/73029f0eccf99c2a375999ef26a44bc0e2eaf1b8/RingBuffer.h",
"visit_date": "2023-04-08T17:30:29.285665"
} | stackv2 | //==============================================================================
// RingBuffer
//
// Copyright (c) 2020 TAiGA
// https://github.com/metarutaiga/StreamAL
//==============================================================================
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifndef STREAMAL_EXPORT
#define STREAMAL_EXPORT
#endif
struct STREAMAL_EXPORT RingBuffer
{
RingBuffer();
~RingBuffer();
char* buffer;
size_t bufferSize;
bool Startup(size_t size);
void Shutdown();
uint64_t Gather(uint64_t index, void* data, size_t dataSize, bool clear);
uint64_t Scatter(uint64_t index, const void* data, size_t dataSize);
char* Address(uint64_t index, size_t* size);
};
| 2.15625 | 2 |
2024-11-18T22:48:57.601965+00:00 | 2019-08-06T01:18:46 | 0e8a9b3116806c82c9cd84db6bd0838a3e8b671a | {
"blob_id": "0e8a9b3116806c82c9cd84db6bd0838a3e8b671a",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-06T01:18:46",
"content_id": "5d9d3b4ce64d36cd8773b4f24a6fd5c2e9de3241",
"detected_licenses": [
"MIT"
],
"directory_id": "3cca2560a18d8e812573625dc291d6483ecf4a9f",
"extension": "c",
"filename": "main-old.c",
"fork_events_count": 0,
"gha_created_at": "2019-07-22T12:31:34",
"gha_event_created_at": "2019-07-22T12:31:35",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 198219493,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2765,
"license": "MIT",
"license_type": "permissive",
"path": "/main-old.c",
"provenance": "stackv2-0108.json.gz:84745",
"repo_name": "v64/nds_framebuffer_bitmaps",
"revision_date": "2019-08-06T01:18:46",
"revision_id": "444fcef303ab290a0e52d2457aebc147f0670b67",
"snapshot_id": "a71fe20d1f78e25a6a92e2ddffed1960ef800b50",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/v64/nds_framebuffer_bitmaps/444fcef303ab290a0e52d2457aebc147f0670b67/main-old.c",
"visit_date": "2022-02-14T07:02:05.708353"
} | stackv2 | typedef volatile unsigned int vu32;
typedef unsigned short u16;
typedef volatile unsigned short vu16;
typedef volatile unsigned char vu8;
#define REG_DISPCNT_MAIN (*(vu32*)0x04000000)
#define REG_DISPCNT_SUB (*(vu32*)0x04001000)
#define MODE_FB0 (0x00020000)
#define VRAM_A ((u16*)0x6800000)
#define VRAM_A_CR (*(vu8*)0x04000240)
#define VRAM_ENABLE (1<<7)
#define SCANLINECOUNTER *(vu16 *)0x4000006
#define COLOR(r,g,b) ((r) | (g)<<5 | (b)<<10)
#define OFFSET(r,c,w) ((r)*(w)+(c))
#define SCREENWIDTH (256)
#define SCREENHEIGHT (192)
void setPixel(int row, int col, u16 color);
void drawRect(int row, int col, int width, int height, u16 color);
void initialize_ball();
void update();
void draw();
void waitForVblank();
typedef struct BALL{
int row;
int col;
int size;
int rdel;
int cdel;
u16 color;
} BALL;
BALL ball;
BALL old_ball;
int main(void) {
// Set the main diplay to frame buffer mode 0 (FB0).
// In FB0 VRAM A is drawn to the screen.
REG_DISPCNT_MAIN = MODE_FB0;
// Enable VRAM A
VRAM_A_CR = VRAM_ENABLE;
initialize_ball();
// main loop
while(1) {
update();
waitForVblank();
draw();
}
return 0;
}
void initialize_ball() {
ball.row = 10;
ball.col= 10;
ball.size = 5;
ball.rdel= 1;
ball.cdel = 2;
ball.color = COLOR(15,27,7);
}
void update() {
old_ball = ball;
// move ball
ball.row += ball.rdel;
ball.col+= ball.cdel;
// check for collisions with the sides of the screen
if (ball.row + ball.size > SCREENHEIGHT) {
ball.row = SCREENHEIGHT - ball.size;
ball.rdel *= -1;
}
if (ball.col + ball.size > SCREENWIDTH) {
ball.col = SCREENWIDTH- ball.size;
ball.cdel *= -1;
}
if (ball.row < 0) {
ball.row = 0;
ball.rdel *= -1;
}
if (ball.col< 0) {
ball.col = 0;
ball.cdel *= -1;
}
}
void draw() {
// erase the ball
drawRect(old_ball.row,
old_ball.col,
old_ball.size,
old_ball.size,
0);
// draw it in its new position
drawRect(ball.row,
ball.col,
ball.size,
ball.size,
ball.color);
}
void setPixel(int row, int col, u16 color) {
VRAM_A[OFFSET(row, col, SCREENWIDTH)] = color;
}
void drawRect(int row, int col, int width, int height, u16 color) {
int r, c;
for (c=col; c<col+width; c++) {
for (r=row; r<row+height; r++) {
setPixel(r, c, color);
}
}
}
void waitForVblank() {
while (SCANLINECOUNTER > SCREENHEIGHT);
while (SCANLINECOUNTER < SCREENHEIGHT);
}
| 2.609375 | 3 |
2024-11-18T22:48:58.053107+00:00 | 2014-05-26T00:50:44 | 6dbdfef7ff19576bd3d373688cc6dc7334b3548f | {
"blob_id": "6dbdfef7ff19576bd3d373688cc6dc7334b3548f",
"branch_name": "refs/heads/master",
"committer_date": "2014-05-26T00:50:44",
"content_id": "064c63781553bedbbea1a223a428677d33804de9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d2afa552e34415891c4f13e77fc877f41272758c",
"extension": "h",
"filename": "Types.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 19499973,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2633,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Arduino/Types.h",
"provenance": "stackv2-0108.json.gz:85003",
"repo_name": "sernaleon/charlie",
"revision_date": "2014-05-26T00:50:44",
"revision_id": "f8ceebd00cc5f54f0183a19d42565e6a7e5482c0",
"snapshot_id": "6497ecca3891b25669af38c42d1b0c20ffd22f3b",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/sernaleon/charlie/f8ceebd00cc5f54f0183a19d42565e6a7e5482c0/Arduino/Types.h",
"visit_date": "2020-05-16T05:41:03.117147"
} | stackv2 | #ifndef _GR_TYPES
#define _GR_TYPES
#include "Arduino.h"
/**********************************************/
//
// SYSTEM CONSTANTS
//
/**********************************************/
#define KMAXSPEED 400
#define KSTRAIGHTSPEED 300
#define KTURNSPEED 200
#define MAX_ANALOG_RESOLUTION 1023
#define FRONTAL_TIMEOUT 2000
#define CNY70DIVIDER 30
//-------------------------
// INPUTS
//-------------------------
#define NUMINPUTS 22
//Push button (Pull-up)
#define I_BUTTON 13
//On/off infrared sensors
#define O_IRON_AN 29 // Analogical infrared (Pull-Up)
#define O_IRON_DG 27 // Digital infrared (Pull-Down)
//Analog infrared sensors
#define NUMFRONTS 12
#define I_IR10 53
#define I_IR11 51
#define I_IR12 49
#define I_IR13 47
#define I_IR14 45
#define I_IR15 43
#define I_IR16 41
#define I_IR17 39
#define I_IR18 37
#define I_IR19 35
#define I_IR20 33
#define I_IR21 31
//Digital infrared sensors
#define NUMMIDS 9
#define I_IR1 4
#define I_IR2 5
#define I_IR3 A0
#define I_IR4 A1
#define I_IR5 6
#define I_IR6 A2
#define I_IR7 A3
#define I_IR8 11
#define I_IR9 12
//-------------------------
// OUTPUTS
//-------------------------
#define NUMOUTPUTS 21
//Buzzer (Pull-Down)
#define O_BUZZER 23
//LEDs
#define NUMLEDS 14
#define O_LED4 52
#define O_LED5 50
#define O_LED6 48
#define O_LED7 46
#define O_LED8 44
#define O_LED9 42
#define O_LED10 36
#define O_LED11 34
#define O_LED12 32
#define O_LED13 30
#define O_LED14 28
#define O_LED15 26
#define O_LED16 24
#define O_LED17 22
//------------------------
// Motor
//------------------------
//A channel
#define O_Ain1 9
#define O_Ain2 7
//B channel
#define O_Bin1 10
#define O_Bin2 8
//------------------------
// Lists
//------------------------
const byte LEDS[NUMLEDS] = { O_LED4, O_LED5,O_LED6,O_LED7,O_LED9,O_LED10,O_LED11,O_LED12,O_LED14,O_LED15,O_LED16,O_LED17 ,O_LED8, O_LED13 };
const byte MIDDLESENSORS[NUMMIDS] = { I_IR1, I_IR2, I_IR3, I_IR4, I_IR5, I_IR6, I_IR7, I_IR8, I_IR9};
const byte FRONTSENSORS[NUMFRONTS] = { I_IR10, I_IR11, I_IR12, I_IR13, I_IR14, I_IR15, I_IR16, I_IR17, I_IR18, I_IR19, I_IR20, I_IR21 };
const byte INPUTS [NUMINPUTS]= { I_BUTTON, I_IR1, I_IR2, I_IR3, I_IR4, I_IR5, I_IR6, I_IR7, I_IR8, I_IR9, I_IR10, I_IR11, I_IR12, I_IR13, I_IR14, I_IR15, I_IR16, I_IR17, I_IR18, I_IR19, I_IR20, I_IR21 };
const byte OUTPUTS [NUMOUTPUTS] = { O_IRON_AN, O_IRON_DG , O_BUZZER, O_LED4, O_LED5,O_LED6,O_LED7,O_LED8,O_LED9,O_LED10,O_LED11,O_LED12,O_LED13,O_LED14,O_LED15,O_LED16,O_LED17,O_Ain1,O_Ain2,O_Bin1,O_Bin2 };
#endif
| 2.0625 | 2 |
2024-11-18T22:48:58.150192+00:00 | 2021-04-19T08:59:42 | c7dbfa6818e5db8d007fc813b381786d904c90d0 | {
"blob_id": "c7dbfa6818e5db8d007fc813b381786d904c90d0",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-19T08:59:42",
"content_id": "321761178426d3c7cf2c8558137f158576bb82c5",
"detected_licenses": [
"MIT"
],
"directory_id": "90e5d28f5d4cbd874bc5be69344d3d765be13573",
"extension": "h",
"filename": "ipc_jobqueue.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 344741141,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7078,
"license": "MIT",
"license_type": "permissive",
"path": "/csc2035-assignment1-init/ipc_jobqueue.h",
"provenance": "stackv2-0108.json.gz:85134",
"repo_name": "MohitKAgnihotri/bookish-bassoon-prdconntwrk",
"revision_date": "2021-04-19T08:59:42",
"revision_id": "90ea4dfccdf25d6e70faefd6b1816d3cd2c9023b",
"snapshot_id": "fceb974954085f8a5c4e1f0e4fe7421c083612b5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MohitKAgnihotri/bookish-bassoon-prdconntwrk/90ea4dfccdf25d6e70faefd6b1816d3cd2c9023b/csc2035-assignment1-init/ipc_jobqueue.h",
"visit_date": "2023-04-08T14:07:55.364315"
} | stackv2 | /******** DO NOT EDIT THIS FILE ********/
#ifndef _IPC_JOBQUEUE_H
#define _IPC_JOBQUEUE_H
#include <stdbool.h>
#include "jobqueue.h"
#include "ipc.h"
/*
* Introduction
*
* This header file defines an ipc_jobqueue type and its "interface", the
* functions that operate on the queue:
* ipc_jq_new(proc_t* proc);
* ipc_jq_capacity(ipc_jobqueue_t* ijq);
* ipc_jq_dequeue(ipc_jobqueue_t* ijq);
* ipc_jq_enqueue(ipc_jobqueue_t* ijq, job_t j);
* ipc_jq_is_empty(ipc_jobqueue_t* ijq);
* ipc_jq_is_full(ipc_jobqueue_t* ijq);
* ipc_jq_peekhead(ipc_jobqueue_t* ijq);
* ipc_jq_peektail(ipc_jobqueue_t* ijq);
* ipc_jq_delete(ipc_jobqueue_t* ijq);
*
* These are direct counterparts for jobqueue function (see jobqueue.h).
* This is because, except for ipc_jq_new and ipc_jq_delete, each ipc_jobqueue
* function is a wrapper for the corresponding jobqueue function. That is,
* ipc_jq_capacity calls jq_capacity and ipc_jq_dequeue calls jq_dequeue and
* so on to perform the actual queue operations.
*
* The difference between a jobqueue and an ipc_jobqueue is that a jobqueue
* is allocated on the heap in the address space of a single process, whereas
* an ipc_jobqueue is a wrapper for a jobqueue that is allocated in an area
* of shared memory that is set up as part of ipc object creation and is mapped
* to the address spaces of multiple processes. Therefore, a jobqueue is
* private to a single process, whereas a jobqueue wrapped by an
* ipc_jobqueue can be accessed by multiple processes and a change to the
* queue by one process is seen by the others.
*
* The usage of a jobqueue and an ipc_jobqueue is almost identical.
*
* Another difference between an ipc_jobqueue and a jobqueue is that, for
* simulation purposes, in each of the functions that for each of its functions
* (except new, capacity and delete), a critical work delay is injected
* by a call to do_critical_work with the proc field of the ipc_jobqueue object.
*
* IMPORTANT:
* Only operate on an ipc_jobqueue using the functions defined in
* this file. Using an ipc_jobqueue in any other way can result in undefined
* and erroneous behaviour.
*
* See jobqueue.h for details of jobqueue operations.
* See proc.h for the do_critical_work function.
*/
/*
* Type alias to define the ipc_jobqueue_t type as an alias for ipc_t.
*
* This means that the object used for the underlying queue (a jobqueue) is
* allocated in shared memory and accessible via the addr field of the
* ipc_t object.
*
* See: ipc.h
*/
typedef ipc_t ipc_jobqueue_t;
/*
* ipc_jq_new(proc_t* proc)
*
* Creates a new ipc_jobqueue (allocating resources for the queue).
*
* The ipc_jobqueue type is an alias for and ipc object where the addr
* field is for a jobqueue in shared memory.
*
* Parameters:
* proc - the non-null descriptor of a process sharing this queueu
*
* Return:
* On success: a well-formed ipc object that encapsulates the queue in
* shared memory. If proc is the init process, the jobqueue is initialised.
* On failure: NULL, and errno is set as specified in Errors.
*
* Errors:
* If the call fails, the NULL pointer will be returned and errno will be
* set as follows:
* EINVAL - invalid argument if proc is NULL
* Other values as specified by the system library functions used to
* implement the function (see ipc_new in ipc.h)
*
* See also:
* proc.h - for a description of the proc type
* ipc.h - for the ipc type for which the mutex is an alias
*/
ipc_jobqueue_t* ipc_jq_new(proc_t* proc);
/*
* ipc_jq_capacity(ipc_jobqueue_t* ijq)
*
* This is a wrapper for jq_capacity.
*
* See the specification of jq_capacity in jobqueue.h.
*
* If ijq is NULL a memory error will occur and the calling process will
* terminate. It is the responsibility of the programmer calling the function
* to ensure that jq is not NULL.
*/
size_t ipc_jq_capacity(ipc_jobqueue_t* ijq);
/*
* ipc_jq_dequeue(ipc_jobqueue_t* ijq)
*
* This is a wrapper for jq_dequeue.
*
* See the specification of jq_dequeue in jobqueue.h.
*
* If ijq is NULL a memory error will occur and the calling process will
* terminate. It is the responsibility of the programmer calling the function
* to ensure that ijq is not NULL.
*/
job_t ipc_jq_dequeue(ipc_jobqueue_t* ijq);
/*
* ipc_jq_enqueue(ipc_jobqueue_t* ijq, job-t j)
*
* This is a wrapper for jq_enqueue.
*
* See the specification of jq_enqueue in jobqueue.h.
*
* If ijq is NULL a memory error will occur and the calling process will
* terminate. It is the responsibility of the programmer calling the function
* to ensure that ijq is not NULL.
*/
void ipc_jq_enqueue(ipc_jobqueue_t* ijq, job_t j);
/*
* ipc_jq_is_empty(ipc_jobqueue_t* ijq)
*
* This is a wrapper for jq_is_empty.
*
* See the specification of jq_is_empty in jobqueue.h.
*
* If ijq is NULL a memory error will occur and the calling process will
* terminate. It is the responsibility of the programmer calling the function
* to ensure that ijq is not NULL.
*
* If ijq is NULL a memory error will occur and the calling process will
* terminate. It is the responsibility of the programmer calling the function
* to ensure that ijq is not NULL.
*/
bool ipc_jq_is_empty(ipc_jobqueue_t* ijq);
/*
* ipc_jq_is_full(ipc_jobqueue_t* ijq)
*
* This is a wrapper for jq_is_full.
*
* See the specification of jq_is_full in jobqueue.h.
*
* If ijq is NULL a memory error will occur and the calling process will
* terminate. It is the responsibility of the programmer calling the function
* to ensure that ijq is not NULL.
*/
bool ipc_jq_is_full(ipc_jobqueue_t* ijq);
/*
* ipc_jq_peekhead(ipc_jobqueue_t* ijq)
*
* This is a wrapper for jq_peekhead.
*
* See the specification of jq_peekhead in jobqueue.h.
*
* If ijq is NULL a memory error will occur and the calling process will
* terminate. It is the responsibility of the programmer calling the function
* to ensure that ijq is not NULL.
*/
job_t ipc_jq_peekhead(ipc_jobqueue_t* ijq);
/*
* ipc_jq_peektail(ipc_jobqueue_t* ijq)
*
* This is a wrapper for jq_peektail.
*
* See the specification of jq_peektail in jobqueue.h.
*
* If ijq is NULL a memory error will occur and the calling process will
* terminate. It is the responsibility of the programmer calling the function
* to ensure that ijq is not NULL.
*/
job_t ipc_jq_peektail(ipc_jobqueue_t* ijq);
/*
* ipc_jq_delete(ipc_jobqueue_t* ijq)
*
* Deletes a ipc_jobqueue, deallocating resources associated with the queue.
*
* Parameters:
* ijq - a non-null pointer to the ijq to delete
*
* Return:
* There is no return value for the function. If ijq is not NULL and the call
* succeeds, resources associated with the queue have been freed. If ijq is
* NULL this function has no effect.
*
* Errors:
* Various errors with access to any underlying shared memory object may occur
* in which case the process is likely to terminate with a memory error.
*/
void ipc_jq_delete(ipc_jobqueue_t* ijq);
#endif | 2.328125 | 2 |
2024-11-18T22:48:58.572185+00:00 | 2023-06-14T00:37:11 | 6ba84054de8a39217414c465d854415a6a7d2b59 | {
"blob_id": "6ba84054de8a39217414c465d854415a6a7d2b59",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-14T00:37:11",
"content_id": "2179b33d12c0f77c235220c045d198fe0d97444d",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "1ee5a51b6e253ce570a2f81eb6ed02093cd9c12c",
"extension": "c",
"filename": "lis_vector_opv.c",
"fork_events_count": 39,
"gha_created_at": "2014-12-15T00:57:06",
"gha_event_created_at": "2019-01-30T13:13:23",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 28014292,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11288,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/vector/lis_vector_opv.c",
"provenance": "stackv2-0108.json.gz:85392",
"repo_name": "anishida/lis",
"revision_date": "2023-06-14T00:37:11",
"revision_id": "23bded36b4a4664d9ab2babcaeb1f86ac7cb27a0",
"snapshot_id": "b728df8300baad6396c85c68a77920f40597a95a",
"src_encoding": "UTF-8",
"star_events_count": 98,
"url": "https://raw.githubusercontent.com/anishida/lis/23bded36b4a4664d9ab2babcaeb1f86ac7cb27a0/src/vector/lis_vector_opv.c",
"visit_date": "2023-07-07T09:38:40.904631"
} | stackv2 | /* Copyright (C) 2005 The Scalable Software Infrastructure Project. 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 project 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 SCALABLE SOFTWARE INFRASTRUCTURE PROJECT
``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 SCALABLE SOFTWARE INFRASTRUCTURE
PROJECT 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.
*/
#ifdef HAVE_CONFIG_H
#include "lis_config.h"
#else
#ifdef HAVE_CONFIG_WIN_H
#include "lis_config_win.h"
#endif
#endif
#include <math.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#ifdef USE_MPI
#include <mpi.h>
#endif
#include "lislib.h"
/********************************************************
* lis_vector_swap x <-> y
* lis_vector_copy y <- x
* lis_vector_axpy y <- y + alpha * x
* lis_vector_xpay y <- x + alpha * y
* lis_vector_axpyz z <- y + alpha * x
* lis_vector_scale x <- alpha * x
* lis_vector_pmul z_i <- x_i * y_i
* lis_vector_pdiv z_i <- x_i / y_i
* lis_vector_set_all x_i <- alpha
* lis_vector_abs x_i <- |x_i|
* lis_vector_reciprocal x_i <- 1 / x_i
* lis_vector_conjugate x_i <- conj(x_i)
* lis_vector_shift x_i <- x_i - sigma
* lis_vector_cgs classical Gram-Schmidt
********************************************************/
/********************/
/* x <-> y */
/********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_swap"
LIS_INT lis_vector_swap(LIS_VECTOR vx, LIS_VECTOR vy)
{
LIS_INT i,n;
LIS_SCALAR *x,*y,t;
LIS_DEBUG_FUNC_IN;
n = vx->n;
#ifndef NO_ERROR_CHECK
if( n!=vy->n )
{
LIS_SETERR(LIS_ERR_ILL_ARG,"length of vector x and y is not equal\n");
return LIS_ERR_ILL_ARG;
}
#endif
x = vx->value;
y = vy->value;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
t = y[i];
y[i] = x[i];
x[i] = t;
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/********************/
/* y <- x */
/********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_copy"
LIS_INT lis_vector_copy(LIS_VECTOR vx, LIS_VECTOR vy)
{
LIS_INT i,n;
LIS_SCALAR *x,*y;
LIS_DEBUG_FUNC_IN;
n = vx->n;
#ifndef NO_ERROR_CHECK
if( n!=vy->n )
{
LIS_SETERR(LIS_ERR_ILL_ARG,"length of vector x and y is not equal\n");
return LIS_ERR_ILL_ARG;
}
#endif
x = vx->value;
y = vy->value;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
y[i] = x[i];
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/**********************/
/* y <- y + alpha * x */
/**********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_axpy"
LIS_INT lis_vector_axpy(LIS_SCALAR alpha, LIS_VECTOR vx, LIS_VECTOR vy)
{
LIS_INT i,n;
LIS_SCALAR *x,*y;
LIS_DEBUG_FUNC_IN;
n = vx->n;
#ifndef NO_ERROR_CHECK
if( n!=vy->n )
{
LIS_SETERR(LIS_ERR_ILL_ARG,"length of vector x and y is not equal\n");
return LIS_ERR_ILL_ARG;
}
#endif
x = vx->value;
y = vy->value;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
y[i] += alpha * x[i];
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/**********************/
/* y <- x + alpha * y */
/**********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_xpay"
LIS_INT lis_vector_xpay(LIS_VECTOR vx, LIS_SCALAR alpha, LIS_VECTOR vy)
{
LIS_INT i,n;
LIS_SCALAR *x,*y;
LIS_DEBUG_FUNC_IN;
n = vx->n;
#ifndef NO_ERROR_CHECK
if( n!=vy->n )
{
LIS_SETERR(LIS_ERR_ILL_ARG,"length of vector x and y is not equal\n");
return LIS_ERR_ILL_ARG;
}
#endif
x = vx->value;
y = vy->value;
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
for(i=0; i<n; i++)
{
y[i] = x[i] + alpha * y[i];
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/**********************/
/* z <- y + alpha * x */
/**********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_axpyz"
LIS_INT lis_vector_axpyz(LIS_SCALAR alpha, LIS_VECTOR vx, LIS_VECTOR vy, LIS_VECTOR vz)
{
LIS_INT i,n;
LIS_SCALAR *x,*y,*z;
LIS_DEBUG_FUNC_IN;
n = vx->n;
#ifndef NO_ERROR_CHECK
if( n!=vy->n || n!=vz->n )
{
LIS_SETERR(LIS_ERR_ILL_ARG,"length of vector x and y and z is not equal\n");
return LIS_ERR_ILL_ARG;
}
#endif
x = vx->value;
y = vy->value;
z = vz->value;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
z[i] = alpha * x[i] + y[i];
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/********************/
/* y <- alpha * x */
/********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_scale"
LIS_INT lis_vector_scale(LIS_SCALAR alpha, LIS_VECTOR vx)
{
LIS_INT i,n;
LIS_SCALAR *x;
LIS_DEBUG_FUNC_IN;
n = vx->n;
x = vx->value;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
x[i] = alpha * x[i];
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/********************/
/* z_i <- x_i * y_i */
/********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_pmul"
LIS_INT lis_vector_pmul(LIS_VECTOR vx,LIS_VECTOR vy,LIS_VECTOR vz)
{
LIS_INT i,n;
LIS_SCALAR *x,*y,*z;
LIS_DEBUG_FUNC_IN;
n = vx->n;
#ifndef NO_ERROR_CHECK
if( n!=vy->n || n!=vz->n )
{
LIS_SETERR(LIS_ERR_ILL_ARG,"length of vector x and y and z is not equal\n");
return LIS_ERR_ILL_ARG;
}
#endif
x = vx->value;
y = vy->value;
z = vz->value;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
z[i] = x[i] * y[i];
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/********************/
/* z_i <- x_i / y_i */
/********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_pdiv"
LIS_INT lis_vector_pdiv(LIS_VECTOR vx,LIS_VECTOR vy,LIS_VECTOR vz)
{
LIS_INT i,n;
LIS_SCALAR *x,*y,*z;
LIS_DEBUG_FUNC_IN;
n = vx->n;
#ifndef NO_ERROR_CHECK
if( n!=vy->n || n!=vz->n )
{
LIS_SETERR(LIS_ERR_ILL_ARG,"length of vector x and y and z is not equal\n");
return LIS_ERR_ILL_ARG;
}
#endif
x = vx->value;
y = vy->value;
z = vz->value;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
z[i] = x[i] / y[i];
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/********************/
/* x_i <- alpha */
/********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_set_all"
LIS_INT lis_vector_set_all(LIS_SCALAR alpha, LIS_VECTOR vx)
{
LIS_INT i,n;
LIS_SCALAR *x;
LIS_DEBUG_FUNC_IN;
n = vx->n;
x = vx->value;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
x[i] = alpha;
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/********************/
/* x_i <- |x_i| */
/********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_abs"
LIS_INT lis_vector_abs(LIS_VECTOR vx)
{
LIS_INT i,n;
LIS_SCALAR *x;
LIS_DEBUG_FUNC_IN;
x = vx->value;
n = vx->n;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
x[i] = fabs(x[i]);
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/********************/
/* x_i <- 1 / x_i */
/********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_reciprocal"
LIS_INT lis_vector_reciprocal(LIS_VECTOR vx)
{
LIS_INT i,n;
LIS_SCALAR *x;
LIS_DEBUG_FUNC_IN;
x = vx->value;
n = vx->n;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
x[i] = 1.0 / x[i];
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/********************/
/* x_i <- conj(x_i) */
/********************/
#undef __FUNC__
#define __FUNC__ "lis_vector_conjugate"
LIS_INT lis_vector_conjugate(LIS_VECTOR vx)
{
LIS_INT i,n;
LIS_SCALAR *x;
LIS_DEBUG_FUNC_IN;
x = vx->value;
n = vx->n;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
#ifdef _COMPLEX
x[i] = conj(x[i]);
#endif
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/************************/
/* x_i <- alpha + x_i */
/************************/
#undef __FUNC__
#define __FUNC__ "lis_vector_shift"
LIS_INT lis_vector_shift(LIS_SCALAR sigma, LIS_VECTOR vx)
{
LIS_INT i,n;
LIS_SCALAR *x;
LIS_DEBUG_FUNC_IN;
x = vx->value;
n = vx->n;
#ifdef USE_VEC_COMP
#pragma cdir nodep
#pragma _NEC ivdep
#endif
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
x[i] = x[i] - sigma;
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
/*************************************/
/* QR <- X by Classical Gram-Schmidt */
/*************************************/
#undef __FUNC__
#define __FUNC__ "lis_vector_cgs"
LIS_INT lis_vector_cgs(LIS_INT n, LIS_VECTOR *x, LIS_VECTOR *q, LIS_VECTOR *r)
{
LIS_INT i, j, k;
LIS_VECTOR x_k;
LIS_REAL nrm2;
LIS_REAL tol;
lis_vector_duplicate(x[0], &x_k);
tol = 1e-6;
for (k=0;k<n;k++)
{
lis_vector_set_all(0.0,q[k]);
lis_vector_set_all(0.0,r[k]);
}
for (k=0;k<n;k++)
{
lis_vector_copy(x[k],x_k);
for (j=0;j<k;j++)
{
r[k]->value[j] = 0;
for (i=0;i<n;i++)
{
r[k]->value[j] += q[j]->value[i] * x[k]->value[i];
}
for (i=0;i<n;i++)
{
x_k->value[i] += q[j]->value[i] * x[k]->value[i];
}
}
lis_vector_nrm2(x_k, &nrm2);
if (nrm2<tol) break;
for (i=0;i<n;i++)
{
q[k]->value[i] = x_k->value[i] / nrm2;
}
}
lis_vector_destroy(x_k);
return 0;
}
| 2 | 2 |
2024-11-18T22:48:58.687948+00:00 | 2019-12-23T21:23:06 | 87d48df4ce9050160b1c8487e0833371a8daf0f4 | {
"blob_id": "87d48df4ce9050160b1c8487e0833371a8daf0f4",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-23T21:23:06",
"content_id": "6d8e1ed10caecca11c7946e3041a33aaa51f442d",
"detected_licenses": [
"BSD-3-Clause",
"MIT"
],
"directory_id": "5f794d8b53421198da244ab81c9cebd20c4af58e",
"extension": "h",
"filename": "lsquic_str.h",
"fork_events_count": 0,
"gha_created_at": "2019-12-29T08:21:27",
"gha_event_created_at": "2019-12-29T08:21:28",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 230722947,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1511,
"license": "BSD-3-Clause,MIT",
"license_type": "permissive",
"path": "/src/liblsquic/lsquic_str.h",
"provenance": "stackv2-0108.json.gz:85521",
"repo_name": "six-ddc/lsquic",
"revision_date": "2019-12-23T21:23:06",
"revision_id": "022d9812f39321d09c3a19090b9288af19877774",
"snapshot_id": "310c397914f50d192f5a4211e693cec206bf8143",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/six-ddc/lsquic/022d9812f39321d09c3a19090b9288af19877774/src/liblsquic/lsquic_str.h",
"visit_date": "2020-12-01T18:11:36.307282"
} | stackv2 | /* Copyright (c) 2017 - 2019 LiteSpeed Technologies Inc. See LICENSE. */
/*
* lsquic_str.h -- Some string routines.
*/
#ifndef LSQUIC_STR_H
#define LSQUIC_STR_H 1
struct lsquic_str
{
char *str;
size_t len;
};
typedef struct lsquic_str lsquic_str_t;
lsquic_str_t *
lsquic_str_new (const char *, size_t);
#define lsquic_str_len(lstr) (+(lstr)->len)
#define lsquic_str_setlen(lstr, len_) do { \
(lstr)->len = len_; \
} while (0)
void
lsquic_str_setto (lsquic_str_t *, const void *, size_t);
void
lsquic_str_append (lsquic_str_t *, const char *, size_t);
void
lsquic_str_d (lsquic_str_t *);
void
lsquic_str_delete (lsquic_str_t *);
char *
lsquic_str_prealloc (lsquic_str_t *, size_t);
#define lsquic_str_buf(lstr) ((char *) (lstr)->str)
#define lsquic_str_cstr(lstr) ((const char *) (lstr)->str)
#define lsquic_str_blank(lstr) do { \
(lstr)->str = NULL; \
(lstr)->len = 0; \
} while (0)
int
lsquic_str_bcmp (const void *, const void *);
lsquic_str_t *
lsquic_str_copy (lsquic_str_t *, const lsquic_str_t *);
#define lsquic_str_set(lstr, src, len_) do { \
(lstr)->str = src; \
(lstr)->len = len_; \
} while (0)
#endif
| 2.171875 | 2 |
2024-11-18T22:48:58.765773+00:00 | 2018-02-21T03:01:57 | ec309eafed886af5b4324cb17cc5c602188a9c1e | {
"blob_id": "ec309eafed886af5b4324cb17cc5c602188a9c1e",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-21T03:01:57",
"content_id": "25379d39ba7490e8e591d32a8551a281e34bb856",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "cbeb0f6e7dedf68242aed0081a3fc15171e55c62",
"extension": "c",
"filename": "pii.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5542,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/cbits/pii.c",
"provenance": "stackv2-0108.json.gz:85652",
"repo_name": "haskell-mafia/warden",
"revision_date": "2018-02-21T03:01:57",
"revision_id": "2bdba6f99d961fc42c5d62ba154469442561d865",
"snapshot_id": "57fc140f9ac11ded2e32ff3385d47cc75cafee8c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/haskell-mafia/warden/2bdba6f99d961fc42c5d62ba154469442561d865/cbits/pii.c",
"visit_date": "2021-09-07T09:39:07.086857"
} | stackv2 | #include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "pii.h"
#include "predicates.h"
/* Stuff we expect to find separating digit groups in phone numbers,
* credit card numbers, et cetera. */
static inline bool is_number_filler(char c) {
return (c == ' ' || c == '-' || c == '.');
}
/*
Email address checks.
*/
bool warden_check_email(const char *buf, size_t n) {
size_t i = 1;
/* local part */
if (n < 1 || buf[0] == '@') {
return FALSE;
}
while (i < n) {
char c = buf[i];
i++;
if (c == '(' || c == ')') {
return FALSE;
}
if (c == '@') {
break;
}
}
/* host part */
while (i < n) {
char c = buf[i];
i++;
if (c == '@' || c == ' ') {
return FALSE;
}
if (c == '.') {
break;
}
}
/* Domain/tld part. */
/* TLD must be at least two characters. */
if (i + 2 > n) {
return FALSE;
}
/* FIXME: make this bit more restrictive */
for ( ; i < n; i++) {
if (buf[i] == '@') {
return FALSE;
}
}
return TRUE;
}
/*
Phone number checks.
*/
/* Matches numbers of the form +xxxxxxxxxxx
Expects the initial '+' to be removed/already checked. */
static inline bool check_international_phone(const char *buf, size_t n) {
size_t i;
int phone_chars = 0;
/* We need exactly 11 digits, but don't care if there are
filler characters as well. */
for (i = 0; i < n; i++) {
if (is_digit(buf[i])) {
phone_chars++;
} else if (!is_number_filler(buf[i])) {
return FALSE;
}
}
return (phone_chars == 11);
}
static inline bool check_australian_phone(const char *buf, size_t n) {
size_t i;
int phone_chars = 0;
/* length already checked, >= 10 */
if (buf[0] != '0') {
return FALSE;
}
/* ensure valid area code */
if (buf[1] != '2' /* NSW/ACT */
&& buf[1] != '3' /* VIC/TAS */
&& buf[1] != '4' /* mobiles */
&& buf[1] != '7' /* QLD */
&& buf[1] != '8' /* SA/WA/NT */
) {
return FALSE;
}
/* Count the rest of the digits - we want exactly 8 more,
excluding filler. */
for (i = 2; i < n; i++) {
if (is_digit(buf[i])) {
phone_chars++;
} else if (!is_number_filler(buf[i])) {
return FALSE;
}
}
return (phone_chars == 8);
}
bool warden_check_phone_number(const char *buf, size_t n) {
/* Field too short, no point checking it. */
if (n < 10) {
return FALSE;
}
/* If it might be an international number, strip the + and
pass the rest for validation. */
if (buf[0] == '+') {
return check_international_phone(buf + 1, n - 1);
}
return check_australian_phone(buf, n);
}
/*
Address checks.
*/
#define N_STREET_TYPES 7
/* Only need to check unique prefixes here, e.g., "st" matches
* "street" as well. */
static char *street_types[N_STREET_TYPES] = {
"st",
"rd",
"road",
"lane",
"ln",
"cres",
"ave"
};
static inline bool check_street_type(const char *buf, size_t n) {
int i;
/* no street types shorter than this */
if (2 > n) {
return FALSE;
}
for (i = 0; i < N_STREET_TYPES; i++) {
size_t s = strlen(street_types[i]);
if (s > n) {
continue;
}
if (memcmp(buf, street_types[i], s) == 0) {
return TRUE;
}
}
return FALSE;
}
/* Check if a character is lowercase alpha. */
static inline bool is_alpha(char c) {
if (c >= 'a' && c <= 'z') {
return TRUE;
}
return FALSE;
}
bool warden_check_address(const char *buf, size_t n) {
size_t i;
if (n < 1) {
return FALSE;
}
/* First character should be part of a street number. */
if (!is_digit(buf[0])) {
return FALSE;
}
/* street number part */
for (i = 1; i < n; i++) {
if (!is_digit(buf[i]) && buf[i] != '/') {
if (buf[i] != ' ') {
return FALSE;
}
i++;
break;
}
}
/* street name part */
if (i >= n) {
return FALSE;
}
if (!is_alpha(buf[i])) {
return FALSE;
}
i++;
for ( ; i < n; i++) {
if (!is_alpha(buf[i])) {
if (buf[i] != ' ') {
return FALSE;
}
i++;
break;
}
}
/* Check that a valid street type is present as a suffix; we
don't care what else is at the end of the string. */
return check_street_type(buf + i, n - i);
}
/* Use the Luhn algorithm to check for potential credit card numbers,
* after performing some sanity checks on the length.
*
* https://en.wikipedia.org/wiki/Luhn_algorithm */
bool warden_check_creditcard(const char *buf, size_t n) {
char c;
size_t i;
int luhn_sum = 0;
int num_digits = 0;
bool doubling_digit = FALSE;
/* CC numbers are of varying length, but no major vendor is
* less than 12 bytes (Maestro). The longest is VISA (19),
* and we need some room for filler characters, but due to the
* potential for unpredictable amounts of padding we don't
* check the upper bound here. */
if (n < 12) {
return FALSE;
}
/* Walk backwards through the field accumulating a Luhn sum
* and exiting early if we see impossible things. */
for (i = n; i > 0; i--) {
c = buf[i-1];
/* If it's a digit, add its numeric value to the Luhn
* sum. */
if (is_digit(c)) {
int x = c - '0';
num_digits++;
/* We double every second digit from the right-hand-side
* (starting with the penultimate digit). */
if (doubling_digit) {
x *= 2;
if (x > 9) {
x -= 9;
}
}
luhn_sum += x;
doubling_digit = ~doubling_digit;
}
/* Letters and random punctuation don't belong here,
* but we expect hyphens or spaces. */
else if (!is_number_filler(c)) {
return FALSE;
}
}
/* Check digit must be correct and we must have seen at least
* twelve digits (to avoid cases like "0-----------"
* matching). */
return (luhn_sum % 10 == 0) && (num_digits >= 12);
}
| 2.75 | 3 |
2024-11-18T22:48:58.849583+00:00 | 2021-04-29T13:54:41 | 3adf02918dde4ee7e777f4e2314c6077b374109b | {
"blob_id": "3adf02918dde4ee7e777f4e2314c6077b374109b",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-30T06:13:20",
"content_id": "8683e76f6123db20ba66b1af90a82646c9eefde6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "969e182984952357a8c04365394d319ceac9bfd9",
"extension": "c",
"filename": "LQ_ImageProcess.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 404705581,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5165,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/LQ_CH32V103R8T6/lq_ch32v103lib-mw/LQ_CH32V103LIB-MW/User/LQ_ImageProcess.c",
"provenance": "stackv2-0108.json.gz:85780",
"repo_name": "88099981/omnidirectional",
"revision_date": "2021-04-29T13:54:41",
"revision_id": "aa3ca4eb13265edb3d2d9eb683853a779a39f7f8",
"snapshot_id": "07087999036179ad9b8d17aa3ed2d10e6912fd25",
"src_encoding": "GB18030",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/88099981/omnidirectional/aa3ca4eb13265edb3d2d9eb683853a779a39f7f8/LQ_CH32V103R8T6/lq_ch32v103lib-mw/LQ_CH32V103LIB-MW/User/LQ_ImageProcess.c",
"visit_date": "2023-07-22T11:02:44.828353"
} | stackv2 | /*LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL
【平 台】北京龙邱智能科技SPIN27PS/CH32V103R8T6核心板
【编 写】chiusir
【E-mail 】chiusir@163.com
【软件版本】V1.1 版权所有,单位使用请先联系授权
【最后更新】2020年10月28日
【相关信息参考下列地址】
【网 站】http://www.lqist.cn
【淘宝店铺】http://longqiu.taobao.com
------------------------------------------------
【IDE】CH32V103R8T6:MounRiver Studio及以上版本
【IDE】MM32SPIN27PS:IAR7.8/MDK5.2及以上版本
【Target 】 SPIN27PS/CH32V103R8T6
【SYS PLL】 80/96MHz
=================================================================
程序配套视频地址:https://space.bilibili.com/95313236
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ*/
#include "include.h"
/*************************************************************************
* 函数名称:void TFT_Show_Camera_Info(void)
* 功能说明:显示各种所需信息
* 参数说明:无
* 函数返回:无
* 修改时间:2020年11月18日
* 备 注: 四轮摄像头车
*************************************************************************/
void TFT_Show_Camera_Info (void)
{
char txt[16] = "X:";
int16_t mps = 0; // 速度:m/s,毫米数值
int16_t pulse100 = 0;
uint16_t bat = 0;
pulse100 = (int16_t) (RAllPulse / 100);
sprintf(txt, "AP:%05d00", pulse100); //
TFTSPI_P8X16Str(3, 4, txt, u16RED, u16BLUE); // 显示赛道偏差参数
// TFTSPI_Road(18, 0, LCDH, LCDW, (unsigned char *)Image_Use); // TFT1.8动态显示摄像头灰度图像
TFTSPI_BinRoad(18, 0, LCDH, LCDW, (unsigned char *) Bin_Image); // TFT1.8动态显示摄像头二进制图像
sprintf(txt, "%04d,%04d,%04d", OFFSET0, OFFSET1, OFFSET2);
TFTSPI_P8X16Str(0, 5, txt, u16RED, u16BLUE); // 显示赛道偏差参数
BatVolt = ADC_Read(6); // 刷新电池电压
bat = BatVolt * 11 / 25; // x/4095*3.3*100*5.7
sprintf(txt, "B:%d.%02dV %d.%02dm/s", bat / 100, bat % 100, mps / 1000, (mps / 10) % 100); // *3.3/4095*3
TFTSPI_P8X16Str(0, 6, txt, u16WHITE, u16BLUE); // 字符串显示
// 电机和舵机参数显示
sprintf(txt, "Sv:%04d Rno:%d", ServoDuty, CircleNumber);
TFTSPI_P8X16Str(1, 7, txt, u16RED, u16BLUE); // 显示舵机,电机1,编码器1数值
sprintf(txt, "M1:%04d, M2:%04d ", MotorDuty1, MotorDuty2);
TFTSPI_P8X16Str(0, 8, txt, u16RED, u16BLUE); // 电机1-2数值
sprintf(txt, "E1:%04d, E2:%04d ", ECPULSE1, ECPULSE2);
TFTSPI_P8X16Str(0, 9, txt, u16RED, u16BLUE); // 编码器1-2数值
}
/*************************************************************************
* 函数名称:void CameraCar(void)
* 功能说明:电磁车双电机差速控制
-->1.入门算法:简单的分段比例控制算法,教学演示控制算法;
2.进阶算法:PID典型应用控制算法,教学演示控制算法;
3.高端算法:改进粒子群协同控制算法;
* 参数说明:无
* 函数返回:无
* 修改时间:2020年10月28日
* 备 注:驱动2个电机
*************************************************************************/
void CameraCar (void)
{
// 摄像头初始化
CAMERA_Init(50);
TFTSPI_P8X16Str(2, 3, "LQ 9V034 Car", u16RED, u16GREEN);
TFTSPI_P8X16Str(1, 5, "K2 Show Video", u16RED, u16GREEN);
delayms(500);
TFTSPI_CLS(u16BLUE); // 清屏
RAllPulse = 0; // 全局变量,脉冲计数总数
while (1)
{
LED_Ctrl(LED1, RVS); // LED闪烁 指示程序运行状态
//if (Camera_Flag == 2)
{
Camera_Flag = 0; // 清除摄像头采集完成标志位 如果不清除,则不会再次采集数据
Get_Use_Image(); // 取出赛道及显示所需图像数据
Get_Bin_Image(2); // 转换为01格式数据,0、1原图;2、3边沿提取
Bin_Image_Filter(); // 滤波,三面被围的数据将被修改为同一数值
Seek_Road(); // 通过黑白区域面积差计算赛道偏差值
// 计算赛道偏差值,系数越大打角越早,数值跟舵机的范围有关,此处为±160左右,默认为7,
ServoDuty = Servo_Center_Mid - (OFFSET1 + OFFSET2 + OFFSET2) * 1 / 7;
// 圆环处理,如果面积为负数,数值越大说明越偏左边;
if((OFFSET2 < -300)||(OFFSET2 > 300))
ServoDuty = Servo_Center_Mid - OFFSET2 / 7;
ServoCtrl(ServoDuty); // 舵机PWM输出,转向
// SPEED正负标识方向,负数为正向
MotorDuty1 = MtTargetDuty + ECPULSE1 * 4 - (OFFSET1 + OFFSET2 + OFFSET2) / 10; // 电机PWM
MotorDuty2 = MtTargetDuty - ECPULSE2 * 4 + (OFFSET1 + OFFSET2 + OFFSET2) / 10; // 双电机差分,需要去掉abs
MotorCtrl(MotorDuty1, MotorDuty2); // 四轮电机驱动
// MotorCtrl(2500, 2500); // 电机PWM固定功率输出
}
}
}
| 2.109375 | 2 |
2024-11-18T22:48:59.221000+00:00 | 2023-08-09T19:05:42 | a7074029c4dd3eec51b967d09e30f8e28e8d8d81 | {
"blob_id": "a7074029c4dd3eec51b967d09e30f8e28e8d8d81",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-09T19:05:42",
"content_id": "81f21a6a21816115fcd52d0fc99049f65844cd10",
"detected_licenses": [
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "ff2180134ad76ce50d9b9a162edf035c3914ab4a",
"extension": "c",
"filename": "vfs_pipe.c",
"fork_events_count": 80,
"gha_created_at": "2019-02-19T18:47:09",
"gha_event_created_at": "2023-09-14T07:31:04",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 171529940,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13038,
"license": "Apache-2.0,BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/port/esp32/adapter/src/vfs_pipe.c",
"provenance": "stackv2-0108.json.gz:86299",
"repo_name": "iotivity/iotivity-lite",
"revision_date": "2023-08-09T19:05:42",
"revision_id": "1597367d65bad60a26511775ee47e5496186ddca",
"snapshot_id": "4ddddfc7d76766d1c5e94d81dd26e28f8cb4a940",
"src_encoding": "UTF-8",
"star_events_count": 143,
"url": "https://raw.githubusercontent.com/iotivity/iotivity-lite/1597367d65bad60a26511775ee47e5496186ddca/port/esp32/adapter/src/vfs_pipe.c",
"visit_date": "2023-08-16T18:09:54.615426"
} | stackv2 | /****************************************************************************
*
* Copyright (c) 2023 Jozef Kralik, 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.
*
****************************************************************************/
#include "debug_print.h"
#include "esp_attr.h"
#include "esp_vfs.h"
#include "esp_vfs_dev.h"
#include "port/oc_assert.h"
#include "port/oc_log_internal.h"
#include "sdkconfig.h"
#include "util/oc_macros_internal.h"
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#include <sys/errno.h>
#include <sys/fcntl.h>
#include <sys/lock.h>
#include <sys/param.h>
// TODO: make the number of UARTs chip dependent
#define PIPE_NUM 4
typedef struct
{
char buffer[2];
int used;
bool read_created;
bool write_created;
bool read_closed;
bool write_closed;
} vfs_pipe_context_t;
static portMUX_TYPE s_registered_ctx_lock = portMUX_INITIALIZER_UNLOCKED;
static vfs_pipe_context_t *s_ctx[PIPE_NUM] = { 0 };
typedef struct
{
esp_vfs_select_sem_t select_sem;
fd_set *readfds;
fd_set *writefds;
fd_set *errorfds;
fd_set readfds_orig;
fd_set writefds_orig;
fd_set errorfds_orig;
} pipe_select_args_t;
static pipe_select_args_t **s_registered_selects = NULL;
static int s_registered_select_num = 0;
static portMUX_TYPE s_registered_select_lock = portMUX_INITIALIZER_UNLOCKED;
static esp_err_t pipe_end_select(void *end_select_args);
static int
get_index(int fd)
{
return fd / 2;
}
static vfs_pipe_context_t *
get_ctx_locked(int fd)
{
assert(fd >= 0 && fd < PIPE_NUM);
return s_ctx[get_index(fd)];
}
static void
free_ctx_locked(int index)
{
if (s_ctx[index] == NULL)
return;
free(s_ctx[index]);
s_ctx[index] = NULL;
}
static int
parse_index(const char *path)
{
int index = -1;
const char *p = path + 1;
for (int i = 0; i < PIPE_NUM; ++i) {
char buf[12];
memset(buf, 0, sizeof(buf));
sprintf(buf, "%d", i);
if (strcmp(p, buf) == 0) {
index = i;
}
}
if (index == -1) {
errno = ENOENT;
return -1;
}
return index;
}
static vfs_pipe_context_t *
create_ctx_locked()
{
vfs_pipe_context_t *ctx = malloc(sizeof(vfs_pipe_context_t));
ctx->used = 0;
ctx->read_created = false;
ctx->write_created = false;
ctx->write_closed = true;
ctx->read_closed = true;
return ctx;
}
static int
pipe_open_read(const char *path, int flags, int mode)
{
int index = parse_index(path);
if (index < 0) {
return index;
}
portENTER_CRITICAL(&s_registered_ctx_lock);
bool created = false;
vfs_pipe_context_t *ctx = get_ctx_locked(index * 2);
if (ctx == NULL) {
ctx = create_ctx_locked();
created = true;
s_ctx[index] = ctx;
}
if (ctx->read_created) {
errno = ENOENT;
portEXIT_CRITICAL(&s_registered_ctx_lock);
if (created) {
free_ctx_locked(index);
}
print_error("pipe_open_read %s %d\n", path, errno);
return -1;
}
ctx->read_created = true;
ctx->read_closed = false;
portEXIT_CRITICAL(&s_registered_ctx_lock);
return 2 * index;
}
static int
pipe_open_write(const char *path, int flags, int mode)
{
int index = parse_index(path);
if (index < 0) {
return index;
}
portENTER_CRITICAL(&s_registered_ctx_lock);
bool created = false;
vfs_pipe_context_t *ctx = get_ctx_locked(index * 2);
if (ctx == NULL) {
ctx = create_ctx_locked();
created = true;
s_ctx[index] = ctx;
}
if (ctx->write_created) {
errno = ENOENT;
portEXIT_CRITICAL(&s_registered_ctx_lock);
if (created) {
free_ctx_locked(index);
}
print_error("pipe_open_write %d\n", errno);
return -1;
}
ctx->write_created = true;
ctx->write_closed = false;
portEXIT_CRITICAL(&s_registered_ctx_lock);
return 2 * index + 1;
}
static bool
prepare_notify_registered(pipe_select_args_t *args, int pipe_fd, bool read,
bool write)
{
bool notify = false;
if (args) {
if (read && FD_ISSET(pipe_fd, &args->readfds_orig)) {
FD_SET(pipe_fd, args->readfds);
notify = true;
}
if (write && FD_ISSET(pipe_fd, &args->writefds_orig)) {
FD_SET(pipe_fd, args->writefds);
notify = true;
}
}
return notify;
}
static void
select_notify(int pipe_fd, bool read, bool write)
{
portENTER_CRITICAL_ISR(&s_registered_select_lock);
for (int i = 0; i < s_registered_select_num; ++i) {
pipe_select_args_t *args = s_registered_selects[i];
if (prepare_notify_registered(args, pipe_fd, read, write)) {
esp_vfs_select_triggered(args->select_sem);
}
}
portEXIT_CRITICAL_ISR(&s_registered_select_lock);
}
static ssize_t
pipe_write(int fd, const void *data, size_t size)
{
portENTER_CRITICAL(&s_registered_ctx_lock);
vfs_pipe_context_t *ctx = get_ctx_locked(fd);
if (ctx == NULL) {
portEXIT_CRITICAL(&s_registered_ctx_lock);
errno = EINVAL;
return -1;
}
if (data == NULL || size == 0) {
portEXIT_CRITICAL(&s_registered_ctx_lock);
errno = EINVAL;
return -1;
}
if (size > (sizeof(ctx->buffer) - ctx->used)) {
portEXIT_CRITICAL(&s_registered_ctx_lock);
OC_DBG("pipe_write %d %d, (sizeof(ctx->buffer) - ctx->used)\n",
sizeof(ctx->buffer), ctx->used);
errno = EBUSY;
return -1;
}
memcpy(&ctx->buffer[ctx->used], data, size);
ctx->used += (int)size;
portEXIT_CRITICAL(&s_registered_ctx_lock);
select_notify(fd - 1, true, false);
return size;
}
static ssize_t
pipe_read(int fd, void *data, size_t size)
{
portENTER_CRITICAL(&s_registered_ctx_lock);
vfs_pipe_context_t *ctx = get_ctx_locked(fd);
if (ctx == NULL) {
portEXIT_CRITICAL(&s_registered_ctx_lock);
errno = EINVAL;
return -1;
}
size_t s = size;
if (data == NULL || s == 0) {
portEXIT_CRITICAL(&s_registered_ctx_lock);
errno = EINVAL;
return -1;
}
if (ctx->used == 0) {
portEXIT_CRITICAL(&s_registered_ctx_lock);
errno = EAGAIN;
return -1;
}
if (s > ctx->used) {
s = ctx->used;
}
memcpy(data, ctx->buffer, s);
ctx->used -= s;
memmove(ctx->buffer, &ctx->buffer[s], ctx->used);
portEXIT_CRITICAL(&s_registered_ctx_lock);
select_notify(fd + 1, false, true);
return s;
}
static int
pipe_fstat(int fd, struct stat *st)
{
assert(fd >= 0 && fd < 3);
st->st_mode = S_IFCHR;
return 0;
}
static int
pipe_close_read(int fd)
{
assert(fd >= 0 && fd < PIPE_NUM);
portENTER_CRITICAL(&s_registered_ctx_lock);
vfs_pipe_context_t *ctx = get_ctx_locked(fd);
if (ctx == NULL) {
portEXIT_CRITICAL(&s_registered_ctx_lock);
errno = EINVAL;
return -1;
}
if (ctx->read_closed) {
portEXIT_CRITICAL(&s_registered_ctx_lock);
errno = EINVAL;
return -1;
}
ctx->read_closed = true;
if (ctx->write_closed && ctx->read_closed) {
free_ctx_locked(get_index(fd));
}
portEXIT_CRITICAL(&s_registered_ctx_lock);
return 0;
}
static int
pipe_close_write(int fd)
{
assert(fd >= 0 && fd < PIPE_NUM);
portENTER_CRITICAL(&s_registered_ctx_lock);
vfs_pipe_context_t *ctx = get_ctx_locked(fd);
if (ctx == NULL) {
portEXIT_CRITICAL(&s_registered_ctx_lock);
errno = EINVAL;
return -1;
}
if (ctx->write_closed) {
portEXIT_CRITICAL(&s_registered_ctx_lock);
errno = EINVAL;
return -1;
}
select_notify(fd - 1, true, false);
ctx->write_closed = true;
if (ctx->write_closed && ctx->read_closed) {
free_ctx_locked(get_index(fd));
}
portEXIT_CRITICAL(&s_registered_ctx_lock);
return 0;
}
static esp_err_t
register_select(pipe_select_args_t *args)
{
esp_err_t ret = ESP_ERR_INVALID_ARG;
if (args) {
portENTER_CRITICAL(&s_registered_select_lock);
const int new_size = s_registered_select_num + 1;
if ((s_registered_selects =
realloc(s_registered_selects,
new_size * sizeof(pipe_select_args_t *))) == NULL) {
ret = ESP_ERR_NO_MEM;
} else {
s_registered_selects[s_registered_select_num] = args;
s_registered_select_num = new_size;
ret = ESP_OK;
}
portEXIT_CRITICAL(&s_registered_select_lock);
}
return ret;
}
static esp_err_t
unregister_select(pipe_select_args_t *args)
{
esp_err_t ret = ESP_OK;
if (args) {
ret = ESP_ERR_INVALID_STATE;
portENTER_CRITICAL(&s_registered_select_lock);
for (int i = 0; i < s_registered_select_num; ++i) {
if (s_registered_selects[i] == args) {
const int new_size = s_registered_select_num - 1;
// The item is removed by overwriting it with the last item. The
// subsequent rellocation will drop the last item.
s_registered_selects[i] = s_registered_selects[new_size];
s_registered_selects = realloc(s_registered_selects,
new_size * sizeof(pipe_select_args_t *));
if (s_registered_selects || new_size == 0) {
s_registered_select_num = new_size;
ret = ESP_OK;
} else {
ret = ESP_ERR_NO_MEM;
}
break;
}
}
portEXIT_CRITICAL(&s_registered_select_lock);
}
return ret;
}
static esp_err_t
pipe_start_select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, esp_vfs_select_sem_t select_sem,
void **end_select_args)
{
const int max_fds = MIN(nfds, PIPE_NUM);
*end_select_args = NULL;
for (int i = 0; i < max_fds; ++i) {
if (FD_ISSET(i, readfds)) {
if ((i % 2) != 0) {
return ESP_ERR_INVALID_STATE;
}
}
if (FD_ISSET(i, writefds)) {
if ((i % 2) != 1) {
return ESP_ERR_INVALID_STATE;
}
}
}
pipe_select_args_t *args = malloc(sizeof(pipe_select_args_t));
if (args == NULL) {
return ESP_ERR_NO_MEM;
}
args->select_sem = select_sem;
args->readfds = readfds;
args->writefds = writefds;
args->errorfds = exceptfds;
args->readfds_orig =
*readfds; // store the original values because they will be set to zero
args->writefds_orig = *writefds;
args->errorfds_orig = *exceptfds;
FD_ZERO(readfds);
FD_ZERO(writefds);
FD_ZERO(exceptfds);
bool notify = false;
portENTER_CRITICAL(&s_registered_ctx_lock);
for (int i = 0; i < max_fds; ++i) {
if (FD_ISSET(i, &args->readfds_orig)) {
vfs_pipe_context_t *ctx = get_ctx_locked(i);
if (ctx && ctx->used > 0 &&
prepare_notify_registered(args, i, true, false)) {
notify = true;
}
}
if (FD_ISSET(i, &args->writefds_orig)) {
vfs_pipe_context_t *ctx = get_ctx_locked(i);
if (ctx && ctx->used < sizeof(ctx->buffer) &&
prepare_notify_registered(args, i, false, true)) {
notify = true;
}
}
}
portEXIT_CRITICAL(&s_registered_ctx_lock);
esp_err_t ret = register_select(args);
if (ret != ESP_OK) {
free(args);
return ret;
}
if (notify) {
esp_vfs_select_triggered(args->select_sem);
}
*end_select_args = args;
return ESP_OK;
}
static esp_err_t
pipe_end_select(void *end_select_args)
{
pipe_select_args_t *args = end_select_args;
esp_err_t ret = unregister_select(args);
if (args) {
free(args);
}
return ret;
}
void
esp_vfs_dev_pipe_register(void)
{
esp_vfs_t vfs_read = {
.flags = ESP_VFS_FLAG_DEFAULT,
.open = &pipe_open_read,
.fstat = &pipe_fstat,
.close = &pipe_close_read,
.read = &pipe_read,
.start_select = &pipe_start_select,
.end_select = &pipe_end_select,
};
ESP_ERROR_CHECK(esp_vfs_register("/dev/pipe/read", &vfs_read, NULL));
esp_vfs_t vfs_write = {
.flags = ESP_VFS_FLAG_DEFAULT,
.open = &pipe_open_write,
.fstat = &pipe_fstat,
.close = &pipe_close_write,
.write = &pipe_write,
.start_select = &pipe_start_select,
.end_select = &pipe_end_select,
};
ESP_ERROR_CHECK(esp_vfs_register("/dev/pipe/write", &vfs_write, NULL));
}
int
vfs_pipe(int pipefd[2])
{
int index = -1;
portENTER_CRITICAL(&s_registered_ctx_lock);
for (int i = 0; i <= sizeof(s_ctx); ++i) {
if (s_ctx[i] == NULL) {
index = i;
break;
}
}
portEXIT_CRITICAL(&s_registered_ctx_lock);
if (index < 0) {
errno = ENFILE;
print_error("pipe %d\n", errno);
return -1;
}
char buf[32];
memset(buf, 0, sizeof(buf));
sprintf(buf, "/dev/pipe/read/%d", index);
int read_fd = open(buf, 0, 0);
if (read_fd < 0) {
return read_fd;
}
memset(buf, 0, sizeof(buf));
sprintf(buf, "/dev/pipe/write/%d", index);
int write_fd = open(buf, 0, 0);
if (write_fd < 0) {
close(read_fd);
return write_fd;
}
pipefd[0] = read_fd;
pipefd[1] = write_fd;
return 0;
}
| 2.125 | 2 |
2024-11-18T22:48:59.557091+00:00 | 2018-01-18T16:11:48 | fef719334ecd001fd0b5c14ddd55e016c183249a | {
"blob_id": "fef719334ecd001fd0b5c14ddd55e016c183249a",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-18T16:11:48",
"content_id": "78d7a7613aac5f3fbb31eac3d3dd92f4f50a8c8a",
"detected_licenses": [
"MIT"
],
"directory_id": "c5138b004e95b2d733ac377c45968d1e1b97cee4",
"extension": "c",
"filename": "argv.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 117814524,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1949,
"license": "MIT",
"license_type": "permissive",
"path": "/42sh/src/option/argv.c",
"provenance": "stackv2-0108.json.gz:86427",
"repo_name": "fflorens/portofolio42",
"revision_date": "2018-01-18T16:11:48",
"revision_id": "4368c33460129beaebea0c983a133f717bc9fe13",
"snapshot_id": "8ec337789d25375c5c2efc255d4418539225e362",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fflorens/portofolio42/4368c33460129beaebea0c983a133f717bc9fe13/42sh/src/option/argv.c",
"visit_date": "2021-09-05T08:16:10.833151"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* argv.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bgauci <bgauci@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/03/27 21:36:56 by bgauci #+# #+# */
/* Updated: 2014/03/27 21:36:57 by bgauci ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "option.h"
t_opt *init_opt(t_opt_fn def, int ac, char **av)
{
t_opt *opt;
t_opt_elem *new;
new = (t_opt_elem*)malloc(sizeof(*new));
if (new == NULL)
return (NULL);
new->name = NULL;
new->nbr_val = 2;
new->fn = def;
opt = (t_opt*)malloc(sizeof(*opt));
if (opt == NULL)
return (NULL);
opt->elem = NULL;
opt->def = new;
opt->ac = ac;
opt->av = av;
opt->value = NULL;
opt->i = 1;
opt->max_opt = 2;
return (opt);
}
void add_opt(t_opt *opt, const char *name, unsigned int nbr_val, t_opt_fn fn)
{
t_opt_elem *new;
new = (t_opt_elem*)malloc(sizeof(*new));
if (new == NULL)
return ;
new->name = name;
new->nbr_val = nbr_val + 1;
new->fn = fn;
new->next = opt->elem;
opt->elem = new;
if (opt->max_opt < new->nbr_val)
opt->max_opt = new->nbr_val;
}
void destroy_opt(t_opt **opt)
{
t_opt_elem *elem;
t_opt_elem *tmp;
elem = (*opt)->elem;
while (elem)
{
tmp = elem->next;
free(elem);
elem = tmp;
}
free((*opt)->value);
if ((*opt)->def)
free((*opt)->def);
free(*opt);
*opt = NULL;
}
| 2.640625 | 3 |
2024-11-18T22:49:00.456378+00:00 | 2019-08-01T20:54:28 | aaed97f6b70353d7b5682f0e3112d3ca43c80b88 | {
"blob_id": "aaed97f6b70353d7b5682f0e3112d3ca43c80b88",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-01T20:54:28",
"content_id": "3fc252e1a40cd1c2bf6e6ab12acbb8b249efeac8",
"detected_licenses": [
"MIT"
],
"directory_id": "dbd6410941af7bdc6d33ec3772b3e4b473b39777",
"extension": "h",
"filename": "debug.h",
"fork_events_count": 1,
"gha_created_at": "2019-05-13T20:02:29",
"gha_event_created_at": "2023-01-04T05:12:14",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 186487187,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 729,
"license": "MIT",
"license_type": "permissive",
"path": "/includes/debug.h",
"provenance": "stackv2-0108.json.gz:86557",
"repo_name": "awiggs/chip-gr8",
"revision_date": "2019-08-01T20:54:28",
"revision_id": "341de1ad2fdae6a4b7a06978c77a13781aa898fd",
"snapshot_id": "4a53541d3749a9db9d747cfb268867f6684d5e2c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/awiggs/chip-gr8/341de1ad2fdae6a4b7a06978c77a13781aa898fd/includes/debug.h",
"visit_date": "2023-01-07T05:45:57.144531"
} | stackv2 | #pragma once
#ifndef DEBUG_H
#define DEBUG_H
#define SAFE_MACRO(expr) do { expr } while(0)
#ifdef DEBUG
#define debugc(chr) SAFE_MACRO({ fputc(chr, stderr); })
#define debugs(str) SAFE_MACRO({ fputs(str, stderr); })
#define debugf(...) SAFE_MACRO({ fprintf(stderr, __VA_ARGS__); })
#else
#define debugc(chr) ;
#define debugs(str) ;
#define debugf(...) ;
#endif
/**
* A formatted print function that prints to standard error and then exits the
* program.
*/
#define panic(...) SAFE_MACRO({ \
fflush(stdout); \
fflush(stderr); \
fprintf(stderr, "\npanic! "); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
fflush(stderr); \
exit(1); \
})
#endif /* DEBUG_H */
| 2.234375 | 2 |
2024-11-18T22:49:00.614456+00:00 | 2013-12-19T17:40:58 | 998738714f37f7320851c7897be117f48b515162 | {
"blob_id": "998738714f37f7320851c7897be117f48b515162",
"branch_name": "refs/heads/master",
"committer_date": "2013-12-19T17:40:58",
"content_id": "d3cf72178dbab4bf98c0f5b3114812853025b016",
"detected_licenses": [
"MIT"
],
"directory_id": "c80c5e4af6193e3bf9bc4aceb8d54dc5d46c5778",
"extension": "c",
"filename": "bozv_entry_internal.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 14402574,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 990,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lib/entry/bozv_entry_internal.c",
"provenance": "stackv2-0108.json.gz:86814",
"repo_name": "debosvi/bozVideo",
"revision_date": "2013-12-19T17:40:58",
"revision_id": "6783bd02b646e9a422e19837c8619d6d20c39e52",
"snapshot_id": "c41eed2937103ed89bc13ee9d3937860bfc5f58b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/debosvi/bozVideo/6783bd02b646e9a422e19837c8619d6d20c39e52/src/lib/entry/bozv_entry_internal.c",
"visit_date": "2021-01-01T19:34:37.196528"
} | stackv2 | /**
* \file bozv_entry_internal.c
* \addtogroup BOZ_VIDEO_ENTRY_INTERNAL
* @{
*/
#include <stdio.h>
#include <stdlib.h>
#include "boz/bozv_entry_internal_p.h"
bozvideo_entry const g_video_main_entry_zero = BOZVIDEO_ENTRY_MAIN_ZERO;
bozvideo_entry g_video_entry_main;
static const char* bozv_entry_def_tmp_path = "/tmp/bozv_entries";
static const char* bozv_entry_def_root_path = "/opt/bozv_entries";
__attribute__((constructor))
static void init() {
fprintf(stderr, "boz video entry constructor\n");
g_video_entry_main = g_video_main_entry_zero;
g_video_entry_main.tmp_path = bozv_entry_def_tmp_path;
g_video_entry_main.root_path = bozv_entry_def_root_path;
{
char *root=getenv("BOZV_ENTRY_ROOT_PATH");
if(root)
g_video_entry_main.root_path = root;
}
}
__attribute__((destructor))
static void fini() {
fprintf(stderr, "boz video entry destructor\n");
g_video_entry_main = g_video_main_entry_zero;
}
/**
* @}
*/
| 2.234375 | 2 |
2024-11-18T22:49:00.820493+00:00 | 2021-04-18T15:25:49 | 0d5c08e8aebb39d687b1794b46d7c15346eed4a2 | {
"blob_id": "0d5c08e8aebb39d687b1794b46d7c15346eed4a2",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-18T15:25:49",
"content_id": "89e0e2af2e8d3cbb847c3865950397e5665d5135",
"detected_licenses": [
"MIT"
],
"directory_id": "7619be06d4e094579f41a3896dc6a043140471e6",
"extension": "c",
"filename": "led_interface.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 318034417,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 473,
"license": "MIT",
"license_type": "permissive",
"path": "/src/led_interface.c",
"provenance": "stackv2-0108.json.gz:86943",
"repo_name": "NakedSolidSnake/Raspberry_IPC_Signal",
"revision_date": "2021-04-18T15:25:49",
"revision_id": "174224aa219325027eed83bbb1cadc1e2752c96d",
"snapshot_id": "7f730c0ea4159a7f97f857ffe295901e1427240e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NakedSolidSnake/Raspberry_IPC_Signal/174224aa219325027eed83bbb1cadc1e2752c96d/src/led_interface.c",
"visit_date": "2023-04-08T15:41:22.936716"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <led_interface.h>
void recv_sig(int sig){}
bool LED_Run(void *object, LED_Interface *led)
{
int state = 0;
signal(SIGUSR1, recv_sig);
if (led->Init(object) == false)
return false;
while(true)
{
led->Set(object, (uint8_t)state);
state ^= 0x01;
pause();
}
return false;
}
| 2.421875 | 2 |
2024-11-18T22:49:01.377001+00:00 | 2015-01-27T08:04:31 | 4dd16bdfabaee48bc02c89b16b859d03291e617a | {
"blob_id": "4dd16bdfabaee48bc02c89b16b859d03291e617a",
"branch_name": "refs/heads/master",
"committer_date": "2015-01-27T08:04:31",
"content_id": "cd3965adadcc7e8d874ad3711dd775285bb0ae48",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "a04b98e08376e6dac2857b3f8e7aced8ace3961b",
"extension": "c",
"filename": "ref_time.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 29900014,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1518,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/utils/ref_time.c",
"provenance": "stackv2-0108.json.gz:87714",
"repo_name": "data-frog/dnsReflector",
"revision_date": "2015-01-27T08:04:31",
"revision_id": "e500010b745452becf48e619db387d1c30d9713c",
"snapshot_id": "fd4b0ace3aa22c6e125a8e194b3425604f6a99e4",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/data-frog/dnsReflector/e500010b745452becf48e619db387d1c30d9713c/src/utils/ref_time.c",
"visit_date": "2016-09-05T14:07:18.446381"
} | stackv2 | #include "ref_time.h"
void time_to_str(char *timebuf,const char*format )
{
time_t now;
struct tm *tm_now;
assert(timebuf!=NULL&&format!=NULL);
time(&now);
tm_now = localtime(&now);
strftime( timebuf, 100,format,tm_now );
return ;
}
int32_t
gmt2local (time_t t)
{
int dt, dir;
struct tm *gmt, *loc;
struct tm sgmt;
if (t == 0)
t = time (NULL);
gmt = &sgmt;
*gmt = *gmtime (&t);
loc = localtime (&t);
dt = (loc->tm_hour - gmt->tm_hour) * 60 * 60 +
(loc->tm_min - gmt->tm_min) * 60;
/*
* If the year or julian day is different, we span 00:00 GMT
* and must add or subtract a day. Check the year first to
* avoid problems when the julian day wraps.
*/
dir = loc->tm_year - gmt->tm_year;
if (dir == 0)
dir = loc->tm_yday - gmt->tm_yday;
dt += dir * 24 * 60 * 60;
return (dt);
}
/* *************************************** */
/*
* The time difference in microseconds
*/
long
delta_time (struct timeval *now, struct timeval *before)
{
time_t delta_seconds;
time_t delta_microseconds;
/*
* compute delta in second, 1/10's and 1/1000's second units
*/
delta_seconds = now->tv_sec - before->tv_sec;
delta_microseconds = now->tv_usec - before->tv_usec;
if (delta_microseconds < 0)
{
/* manually carry a one from the seconds field */
delta_microseconds += 1000000; /* 1e6 */
--delta_seconds;
}
return ((delta_seconds * 1000000) + delta_microseconds);
}
/* ******************************** */
| 2.671875 | 3 |
2024-11-18T22:49:04.126852+00:00 | 2020-07-24T12:00:48 | 9c2b3f619bf7c1784263b7e86490914da705daf6 | {
"blob_id": "9c2b3f619bf7c1784263b7e86490914da705daf6",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-24T12:00:48",
"content_id": "d2b4d68da7d73ac60c096851cd99ad1fa50a93e7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cd52ac9fe97112f4623ab3adcc4b85447a4d970e",
"extension": "h",
"filename": "common.h",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 264642941,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3254,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/sgrep/common.h",
"provenance": "stackv2-0108.json.gz:87842",
"repo_name": "peterrobinson/Anastasia2",
"revision_date": "2020-07-24T12:00:48",
"revision_id": "eceeb77827c0df545202634394cac53b8e5c792c",
"snapshot_id": "dc9c313d3c8be7c2de7193129a5e211f1e6db22e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/peterrobinson/Anastasia2/eceeb77827c0df545202634394cac53b8e5c792c/sgrep/common.h",
"visit_date": "2022-12-02T13:13:03.035158"
} | stackv2 |
typedef struct {
int start; /* Start index of a file */
int length; /* Length of a file */
char *name; /* Name of the file, NULL if stdin */
} OneFile;
struct FileListStruct {
SgrepData *sgrep;
int total_size; /* Total length of all files in bytes */
int num_files; /* How many files */
int allocated; /* How many OneFile entries allocated */
OneFile *files; /* Since this list must be binary searchable, files
* are kept in array instead of linked list */
int last_errno; /* Remember the last error in add() */
int progress_limit; /* When to show progress */
};
#ifdef WIN32
//this causes redefinition errors in other environments
typedef struct FileListStruct FileList;
#endif
enum SortTypes {SORT_BY_START,SORT_BY_END };
void delete_region_list(RegionList *l);
#define free_gclist(LIST) delete_region_list(LIST);
int sgrep_error(SgrepData *this_sgrep,char *format, ...);
int flist_files(const FileList *list);
RegionList *new_region_list(SgrepData *this_sgrep);
void delete_list_node(SgrepData *this_sgrep, ListNode *this_node);
void to_chars(RegionList *c,int chars, int end);
void string_cat(SgrepString *s, const char *str);
SgrepString *new_string(SgrepData *this_sgrep,size_t size);
void delete_string(SgrepString *s);
ParseTreeNode *parse_and_optimize(SgrepData *this_sgrep,const char *query, struct PHRASE_NODE **phrases);
void delete_flist(FileList *list);
void start_region_search(RegionList *l, ListIterator *handle);
FileList *new_flist(SgrepData *this_sgrep);
void flist_add_known(FileList *ifs, const char *name, int length);
void flist_ready(FileList *ifs);
void init_region_list(RegionList *l);
ListNode *get_start_sorted_list(RegionList *s);
ListNode *new_list_node(SgrepData *this_sgrep);
ListNode *copy_list_nodes(SgrepData *this_sgrep,const ListNode *n, ListNode **return_last);
ListNode **create_node_array(const RegionList *s, ListNode *n);
void gc_qsort(ListNode **inds,int s,int e, enum SortTypes st);
int flist_start(const FileList *list, int n);
int flist_total(const FileList *list);
void insert_list_node(RegionList *l);
void start_end_sorted_search(RegionList *l, ListIterator *handle);
void list_set_sorted(RegionList *l, enum RegionListSorted sorted);
enum RegionListSorted list_get_sorted(const RegionList *l);
void list_require_start_sorted_array(RegionList *l, struct SgrepStruct *this_sgrep);
void remove_duplicates(RegionList *s);
void start_region_search_from(RegionList *l, int index, ListIterator *handle);
ListNode *get_end_sorted_list(RegionList *s);
void string_cat_escaped(SgrepString *escaped, const char *str);
void real_string_push(SgrepString *s, SgrepChar ch);
SgrepString *expand_backslashes(SgrepData *this_sgrep,const char *s);
SgrepString *init_string(SgrepData *this_sgrep, size_t size, const char *src);
void push_front(SgrepString *s,const char *str);
int expand_backslash_escape(SgrepData *this_sgrep, const unsigned char *list, int *i);
void string_toupper(SgrepString *s, int from);
void string_tolower(SgrepString *s, int from);
const char *string_escaped(SgrepString *str);
int flist_exists(FileList *list, const char *name);
const char *flist_name(const FileList *list, int n);
int flist_length(const FileList *list, int n);
| 2.234375 | 2 |
2024-11-18T22:49:04.266370+00:00 | 2020-09-30T14:29:28 | e3cbd7dd69056711ab92b5b59fbdc1875d067faf | {
"blob_id": "e3cbd7dd69056711ab92b5b59fbdc1875d067faf",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-30T14:29:28",
"content_id": "918ab084f95479c5d5349ae47cd73b7eb75a3f91",
"detected_licenses": [
"BSL-1.0"
],
"directory_id": "ccdf93221618edacef1596908b83570d2b9f6d12",
"extension": "c",
"filename": "14-logical_oper.c",
"fork_events_count": 5,
"gha_created_at": "2020-07-28T16:03:14",
"gha_event_created_at": "2020-10-01T18:31:21",
"gha_language": "C",
"gha_license_id": "BSL-1.0",
"github_id": 283261989,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 380,
"license": "BSL-1.0",
"license_type": "permissive",
"path": "/14-logical_oper.c",
"provenance": "stackv2-0108.json.gz:88100",
"repo_name": "hDmtP/C-language-Tutorial",
"revision_date": "2020-09-30T14:29:28",
"revision_id": "be88d3d5f5074fdac11c66cdb07d588304d47648",
"snapshot_id": "e322c939c72ec6967833ad642cbbb55626e2de2d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/hDmtP/C-language-Tutorial/be88d3d5f5074fdac11c66cdb07d588304d47648/14-logical_oper.c",
"visit_date": "2022-12-22T08:02:00.619619"
} | stackv2 | #include<stdio.h>
int main(){
int age;
int viPass=0;
// viPass=14;
printf("Enter your age:\n");
scanf("%d", &age);
if ((age>=18 && age<=73) || viPass==14)
{
printf("You can drive\n");
}
if (age==50)
{
printf("Half-century");
}
else
{
printf("You cannot drive\n");
}
return 0;
} | 3.09375 | 3 |
2024-11-18T22:49:04.356250+00:00 | 2021-06-21T09:15:50 | 3b03d83790c42172f9010a9faa5f9977ec54dba0 | {
"blob_id": "3b03d83790c42172f9010a9faa5f9977ec54dba0",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-21T09:15:50",
"content_id": "a64306382407165eac83b26988a906cd88954b14",
"detected_licenses": [
"MIT"
],
"directory_id": "c450556dd5d69beb8622385aa86a57be16810ea9",
"extension": "c",
"filename": "Crypto_public.c",
"fork_events_count": 5,
"gha_created_at": "2017-05-24T11:49:02",
"gha_event_created_at": "2020-10-31T13:18:45",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 92286552,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2580,
"license": "MIT",
"license_type": "permissive",
"path": "/src/util/crypto/Crypto_public.c",
"provenance": "stackv2-0108.json.gz:88230",
"repo_name": "uos3/obc-firmware",
"revision_date": "2021-06-21T09:15:50",
"revision_id": "b41fc82bd2c9acc7488d931e0f987b777b5a0b95",
"snapshot_id": "ce6a9dd0ba1b22e511e236169242f499873bea34",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/uos3/obc-firmware/b41fc82bd2c9acc7488d931e0f987b777b5a0b95/src/util/crypto/Crypto_public.c",
"visit_date": "2022-04-28T01:24:28.046167"
} | stackv2 | /**
* @file Crypto_public.c
* @author Duncan Hamill (dh2g16@soton.ac.uk/duncanrhamill@googlemail.com)
* @brief Implementation of the crypto module. See corresponding header for
* more information.
*
* @version 0.1
* @date 2020-12-18
*
* @copyright Copyright (c) UoS3 2020
*/
/* -------------------------------------------------------------------------
* INCLUDES
* ------------------------------------------------------------------------- */
/* Standard includes */
#include <stdint.h>
#include <stdlib.h>
/* Internal includes */
#include "util/debug/Debug_public.h"
#include "util/crypto/Crypto_public.h"
#include "util/crypto/Crypto_private.h"
/* -------------------------------------------------------------------------
* FUNCTIONS
* ------------------------------------------------------------------------- */
bool Crypto_get_crc32(
uint8_t *p_data_in,
size_t length_in,
Crypto_Crc32 *p_crc_out
) {
/*
* See
* https://reveng.sourceforge.io/crc-catalogue/17plus.htm#crc.cat.crc-32c
*/
if (p_data_in == NULL || p_crc_out == NULL) {
DEBUG_ERR("NULL passed into Crypto_get_crc32");
return false;
}
uint8_t table_idx;
*p_crc_out = 0xFFFFFFFF;
/* Divide input data by the polynomial, byte at a time */
for (size_t i = 0; i < length_in; ++i) {
table_idx = (uint8_t)((*p_crc_out ^ p_data_in[i]) & 0xFF);
*p_crc_out = CRYPTO_CRC32_TABLE[table_idx] ^ (*p_crc_out >> 8);
}
/* XOR the final CRC with the value given in the CRC catalogue*/
*p_crc_out = *p_crc_out ^ 0xFFFFFFFF;
return true;
}
bool Crypto_get_crc16(
uint8_t *p_data_in,
size_t length_in,
Crypto_Crc16 *p_crc_out
) {
uint8_t table_idx;
if (p_data_in == NULL || p_crc_out == NULL) {
DEBUG_ERR("NULL passed into Crypto_get_crc16");
return false;
}
/* Set the initial value of the CRC */
*p_crc_out = 0xFFFF;
/* Based on the optimised CRC-16 implementation given in ECSS-E-70-41C
* B.1.6, but changed to perform the entire operation in one function
* rather than 2. */
for (size_t i = 0; i < length_in; ++i) {
/* Table index is based off of a shift of the CRC with an XOR of the
* current byte, plus an AND with a byte to ensure the index doesn't go
* over 256. */
table_idx = (uint8_t)(((*p_crc_out >> 8) ^ p_data_in[i]) & 0xFF);
*p_crc_out = (uint16_t)(
((*p_crc_out << 8) & 0xFF00) ^ CRYPTO_CRC16_TABLE[table_idx]
);
}
return true;
} | 2.65625 | 3 |
2024-11-18T22:49:04.864908+00:00 | 2020-03-09T14:28:42 | 6f3ad1d03e9613d678a3d6340b967ffa0fbb7848 | {
"blob_id": "6f3ad1d03e9613d678a3d6340b967ffa0fbb7848",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-09T14:28:42",
"content_id": "37c976e06a8274b8b7862738d66cffc4fda8fbcf",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "4208d1932398a1a567ceb0d2bfe7802fe2e61fab",
"extension": "c",
"filename": "ulility.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 156963211,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1370,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/utility/ulility.c",
"provenance": "stackv2-0108.json.gz:88489",
"repo_name": "mydavie/nick_liu_simulate",
"revision_date": "2020-03-09T14:28:42",
"revision_id": "5666c164644f08da065cfcdbc6b62576520dda41",
"snapshot_id": "6be9649e45924b14f01af48253794598a4ae5f27",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mydavie/nick_liu_simulate/5666c164644f08da065cfcdbc6b62576520dda41/utility/ulility.c",
"visit_date": "2020-04-05T15:20:25.426504"
} | stackv2 | #include "types.h"
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
void memory_dump_u64(char* type, uint32 cnt, void *buffer, uint32 size)
{
for (uint32 i = 0; i < size; i++) {
if (i % 32 == 0) {
printf("\n");
}
printf(" %lx", ((uint64 *)buffer)[i]);
}
printf("\n");
}
uint8 *align_memory_malloc(uint32 size,uint32 align_bytes)
{
uint8 *base_ptr = NULL;
uint8 *mem_ptr = NULL;
uint8 part_bytes;
printf("to allocate memory ");
base_ptr = (uint8 *)malloc(size + align_bytes);
if (base_ptr == NULL) {
printf("memory allocate fail %d\n", size + align_bytes);
return base_ptr;
}
assert(align_bytes <= 0xFF);
assert((align_bytes & (align_bytes - 1)) == 0);
part_bytes = align_bytes - (((uint64)base_ptr) & (align_bytes - 1));
if (part_bytes == 0) {
part_bytes = align_bytes;
}
mem_ptr = base_ptr + part_bytes;
(((uint8*) mem_ptr) - 1)[0] = part_bytes;
printf("actual %lx allocate %lx offset %d size %d\n",(uint64)mem_ptr, (uint64)base_ptr, part_bytes, size);
return mem_ptr;
}
void align_memory_free(uint8 *mem_ptr)
{
uint8 *base_addr = NULL;
printf("to free memory ");
base_addr = ((uint8*) mem_ptr) - (((uint8*) mem_ptr) - 1)[0];
printf("actual %lx release %lx offset %d\n",(uint64)mem_ptr,(uint64)base_addr, (((uint8*) mem_ptr) - 1)[0]);
free(base_addr);
}
| 3.015625 | 3 |
2024-11-18T22:49:05.236469+00:00 | 2020-02-06T16:20:58 | 8ed91f0166e84b74ef1ce16457022b75d5555021 | {
"blob_id": "8ed91f0166e84b74ef1ce16457022b75d5555021",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-06T16:20:58",
"content_id": "f59f8e247573a45ef97a5ecea9f2d8478e7c1331",
"detected_licenses": [
"MIT"
],
"directory_id": "39b51e717013f5ba077bcc7a4526b1f53372bc3a",
"extension": "c",
"filename": "my_add_str_to_array.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 238273955,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 410,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/my/my_add_str_to_array.c",
"provenance": "stackv2-0108.json.gz:88749",
"repo_name": "Cotax61/CoQuest",
"revision_date": "2020-02-06T16:20:58",
"revision_id": "ebd356dae70d6742e9ff04e04a2039c75fa04f8b",
"snapshot_id": "49eb492b4710bf8e7f76c7092ad534f8afa43c4e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Cotax61/CoQuest/ebd356dae70d6742e9ff04e04a2039c75fa04f8b/lib/my/my_add_str_to_array.c",
"visit_date": "2020-12-28T09:44:38.026253"
} | stackv2 | /*
** EPITECH PROJECT, 2020
** PSU_minishell1_2019
** File description:
** my_add_str_to_array
*/
#include <stdlib.h>
char **my_add_str_to_array(char **arr, char *str)
{
int i = 0;
char **new;
for (; arr[i] != NULL; i++);
new = malloc(sizeof(char *) * (i + 2));
new[i + 1] = NULL;
for (i = 0; arr[i]; i++)
new[i] = arr[i];
new[i] = str;
free(arr);
return (new);
} | 3.140625 | 3 |
2024-11-18T22:49:06.230841+00:00 | 2020-12-13T11:33:35 | 05ac13ba44e645e4d7e3328604796d893b7e2097 | {
"blob_id": "05ac13ba44e645e4d7e3328604796d893b7e2097",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-13T11:33:35",
"content_id": "130b7cbb0ffa3317085b558a9d0ca07a2cb61258",
"detected_licenses": [
"Unlicense"
],
"directory_id": "dd1f4465b61dff78f01f8703484d1510d1dea05b",
"extension": "c",
"filename": "pinger_archive.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 301236086,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2201,
"license": "Unlicense",
"license_type": "permissive",
"path": "/lib/pinger/pinger_archive.c",
"provenance": "stackv2-0108.json.gz:89652",
"repo_name": "SimoneRicci97/pinger",
"revision_date": "2020-12-13T11:33:35",
"revision_id": "f29ec34da1f10f8eeeb6eaab962f746ca8ae3e8e",
"snapshot_id": "c1e01530e87467734c8156e4644a26490a86b8a9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SimoneRicci97/pinger/f29ec34da1f10f8eeeb6eaab962f746ca8ae3e8e/lib/pinger/pinger_archive.c",
"visit_date": "2023-02-02T13:49:00.424625"
} | stackv2 | #include "pinger_archive.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uttime.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <htable.h>
#include <ping_list.h>
#include <pthread.h>
#define MV "/bin/mv"
#define USER_SH "./pinger_archive.sh"
void _tar(char* dir);
void _zip(char* dir);
void _user_archive(char* dir);
void _mvclear(char* dir);
void archive(void* archive_args_v) {
archive_args_t* archive_args = (archive_args_t*) archive_args_v;
int p = fork();
if(p > 0) {
int status;
waitpid(p, &status, 0);
} else if(p == 0) {
_user_archive(archive_args->dir);
} else {
perror("Running archive tool");
}
}
void reset(void* hosts_v) {
htable* hosts = (htable*) hosts_v;
pthread_mutex_lock(&hosts->mutex);
for(int i=0; i<hosts->size; i++) {
if(hosts->keys[i]) {
char* key = (char*) hosts->keys[i]->head->key;
chunk_list* cl = hosts->get(hosts, key, strlen(key));
cl->clear(cl);
fprintf(stderr, "Now size is %d\n", ((chunk_list*) hosts->get(hosts, key, strlen(key)))->size);
}
}
pthread_mutex_unlock(&hosts->mutex);
}
void _user_archive(char* dir) {
char* ua_args[3] = {USER_SH, get_formatted_datetime(), NULL};
execv(USER_SH, ua_args);
}
void _mvclear(char* dir) {
char source[128], dest[128];
snprintf(source, 128, "%s/*.log", dir);
snprintf(dest, 128, "%s/archived/", dir);
char* mvargs[4] = {MV, source, dest, NULL};
int p = fork();
if(p == 0) {
execv(MV, mvargs);
} else if(p > 0) {
int status;
waitpid(p, &status, 0);
} else {
perror("Cannot move files");
}
}
void _tar(char* dir) {
char archive_name[128];
char archive_content[128];
sprintf(archive_name, "%s/pinger.archive.%s.log.tar", dir, get_formatted_datetime());
sprintf(archive_content, "%s/*.log", dir);
char* tar_args[6] = {TAR, "-cf", archive_name, archive_content, NULL};
execv(TAR, tar_args);
}
void _zip(char* dir) {
char archive_name[128];
char archive_content[128];
sprintf(archive_name, "%s/pinger.archive.%s.log.zip", dir, get_formatted_datetime());
sprintf(archive_content, "%s/*.log", dir);
char* tar_args[5] = {ZIP, archive_name, archive_content, NULL};
execv(ZIP, tar_args);
}
| 2.34375 | 2 |
2024-11-18T22:49:13.130042+00:00 | 2020-07-24T14:16:46 | 3ab9ff170de891da307120990b19b54151855d0c | {
"blob_id": "3ab9ff170de891da307120990b19b54151855d0c",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-24T14:16:46",
"content_id": "a6145b5d8e67e6061de76f791e30c801aa3e182f",
"detected_licenses": [
"MIT"
],
"directory_id": "390ad8b344e6e0a07f73fc734c6d8b6921daf6a6",
"extension": "c",
"filename": "particles.c",
"fork_events_count": 4,
"gha_created_at": "2019-07-24T09:01:28",
"gha_event_created_at": "2019-08-28T22:47:02",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 198597879,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8046,
"license": "MIT",
"license_type": "permissive",
"path": "/src/particles.c",
"provenance": "stackv2-0108.json.gz:90040",
"repo_name": "alexlarsson/gnome-hexgl",
"revision_date": "2020-07-24T14:16:46",
"revision_id": "f47a351055a235730795341dcd6b2397cc4bfa0c",
"snapshot_id": "5012c4bd7ad5f75428f05bf97dd04b2bbbd36cca",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/alexlarsson/gnome-hexgl/f47a351055a235730795341dcd6b2397cc4bfa0c/src/particles.c",
"visit_date": "2021-07-20T02:22:35.794227"
} | stackv2 | #include "particles.h"
typedef struct {
int index;
graphene_vec3_t position;
graphene_vec3_t velocity;
graphene_vec3_t force;
graphene_vec3_t color;
graphene_vec3_t base_color;
float life;
} Particle;
struct _Particles {
GthreePointsMaterial *material;
GthreePoints *points;
GthreeTexture *map;
GthreeGeometry *geometry;
GthreeAttribute *position_attr;
GthreeAttribute *color_attr;
Particle *buffer;
int buffer_size;
int buffer_used;
float size;
float life;
float ageing;
float friction;
float spawn_rate;
float spawn_count;
graphene_vec3_t color1;
graphene_vec3_t color2;
graphene_vec3_t spawn_point;
graphene_vec3_t spawn_radius;
graphene_vec3_t velocity;
graphene_vec3_t velocity_randomness;
graphene_vec3_t force;
};
static void
particle_reset (Particle *particle)
{
graphene_vec3_init (&particle->position,
100000, 100000, 100000);
graphene_vec3_init (&particle->color, 0, 0, 1.0);
}
GthreeObject *
particles_get_object (Particles *particles)
{
return GTHREE_OBJECT (particles->points);
}
void
particles_set_spawn_point (Particles *particles,
const graphene_vec3_t *spawn_point)
{
particles->spawn_point = *spawn_point;
}
void
particles_set_spawn_radius (Particles *particles,
const graphene_vec3_t *spawn_radius)
{
particles->spawn_radius = *spawn_radius;
}
void
particles_set_velocity (Particles *particles,
const graphene_vec3_t *velocity)
{
particles->velocity = *velocity;
}
void
particles_set_velocity_randomness (Particles *particles,
const graphene_vec3_t *velocity_randomness)
{
particles->velocity_randomness = *velocity_randomness;
}
void
particles_set_life (Particles *particles, float life)
{
particles->life = life;
particles->ageing = 1 / particles->life;
}
void
particles_set_map (Particles *particles,
GthreeTexture *texture)
{
g_set_object (&particles->map, texture);
gthree_points_material_set_map (particles->material, particles->map);
}
void
particles_set_size (Particles *particles, float size)
{
particles->size = size;
gthree_points_material_set_size (particles->material, particles->size);
}
void
particles_set_color1 (Particles *particles, GdkRGBA *color)
{
graphene_vec3_init (&particles->color1, color->red, color->green, color->blue);
}
void
particles_set_color2 (Particles *particles, GdkRGBA *color)
{
graphene_vec3_init (&particles->color2, color->red, color->green, color->blue);
}
Particles *
particles_new (int max, float size)
{
Particles *particles = g_new0 (Particles, 1);
particles->buffer_size = max;
particles->buffer_used = 0;
particles->buffer = g_new0 (Particle, particles->buffer_size);
for (int i = 0; i < particles->buffer_size; i++)
{
Particle *p = &particles->buffer[i];
p->index = i;
particle_reset (p);
}
particles->size = size;
particles->life = 60;
particles->ageing = 1 / particles->life;
particles->friction = 1.0;
particles->spawn_rate = 0;
particles->spawn_count = 0;
graphene_vec3_init (&particles->spawn_point, 0, 0, 0);
graphene_vec3_init (&particles->spawn_radius, 0, 0, 0);
graphene_vec3_init (&particles->velocity, 0, 0, 0);
graphene_vec3_init (&particles->velocity_randomness, 0, 0, 0);
graphene_vec3_init (&particles->force, 0, 0, 0);
graphene_vec3_init (&particles->color1, 1.0, 0, 0);
graphene_vec3_init (&particles->color2, 0.0, 1.0, 0);
particles->position_attr = gthree_attribute_new ("position", GTHREE_ATTRIBUTE_TYPE_FLOAT,
particles->buffer_size, 3, FALSE);
gthree_attribute_set_dynamic (particles->position_attr, TRUE);
particles->color_attr = gthree_attribute_new ("color", GTHREE_ATTRIBUTE_TYPE_FLOAT,
particles->buffer_size, 3, FALSE);
gthree_attribute_set_dynamic (particles->color_attr, TRUE);
particles->material = gthree_points_material_new ();
gthree_points_material_set_size (particles->material, particles->size);
gthree_material_set_vertex_colors (GTHREE_MATERIAL (particles->material), TRUE);
gthree_material_set_depth_test (GTHREE_MATERIAL (particles->material), FALSE);
particles->geometry = gthree_geometry_new ();
gthree_geometry_add_attribute (particles->geometry, "position", particles->position_attr);
gthree_geometry_add_attribute (particles->geometry, "color", particles->color_attr);
particles->points = gthree_points_new (particles->geometry, GTHREE_MATERIAL (particles->material));
return particles;
}
void
particles_free (Particles *particles)
{
g_clear_object (&particles->map);
g_clear_object (&particles->geometry);
g_free (particles->buffer);
g_free (particles);
}
static void
init_random_vector (graphene_vec3_t *dst)
{
graphene_vec3_init (dst,
g_random_double_range (-1, 1),
g_random_double_range (-1, 1),
g_random_double_range (-1, 1));
}
void
particles_emit (Particles *particles,
int count)
{
int emitable = MIN (count, particles->buffer_size - particles->buffer_used);
for (int i = 0; i < emitable; i++)
{
int buffer_index = particles->buffer_used++;
Particle *p = &particles->buffer[buffer_index];
init_random_vector (&p->position);
graphene_vec3_multiply (&p->position, &particles->spawn_radius, &p->position);
graphene_vec3_add (&p->position, &particles->spawn_point, &p->position);
init_random_vector (&p->velocity);
graphene_vec3_multiply (&p->velocity, &particles->velocity_randomness, &p->velocity);
graphene_vec3_add (&p->velocity, &particles->velocity, &p->velocity);
p->force = particles->force;
graphene_vec3_interpolate (&particles->color1,
&particles->color2,
g_random_double_range (0, 1),
&p->base_color);
p->life = 1;
}
}
void
particles_update (Particles *particles,
float dt)
{
float l;
graphene_vec3_t df, dv;
particles->spawn_count += particles->spawn_rate;
if (particles->spawn_count >= 1.0f)
{
float count = floorf (particles->spawn_count);
particles->spawn_count -= count;
particles_emit (particles, count);
}
for (int i = 0; i < particles->buffer_used; i++)
{
Particle *p = &particles->buffer[i];
p->life -= particles->ageing;
if (p->life <= 0)
{
particle_reset (p);
// Swap this and last used so we don't get a hole in the buffer array with unused particles
if (i != particles->buffer_used -1)
{
Particle tmp = *p;
particles->buffer[i] = particles->buffer[particles->buffer_used-1];
particles->buffer[particles->buffer_used-1] = tmp;
}
particles->buffer_used--;
i--; // compensate for the i++ in the loop since we deleted one
continue;
}
l = p->life > 0.5 ? 1.0 : p->life + 0.5;
graphene_vec3_scale (&p->base_color, l, &p->color);
graphene_vec3_scale (&p->velocity, particles->friction, &p->velocity);
graphene_vec3_scale (&p->force, dt, &df);
graphene_vec3_add (&p->velocity, &df, &p->velocity);
graphene_vec3_scale (&p->velocity, dt, &dv);
graphene_vec3_add (&p->position, &dv, &p->position);
}
// Update buffer
for (int i = 0; i < particles->buffer_size; i++)
{
Particle *p = &particles->buffer[i];
gthree_attribute_set_vec3 (particles->position_attr, p->index, &p->position);
gthree_attribute_set_vec3 (particles->color_attr, p->index, &p->color);
}
gthree_attribute_set_needs_update (particles->position_attr);
gthree_attribute_set_needs_update (particles->color_attr);
gthree_geometry_invalidate_bounds (particles->geometry);
}
| 2.640625 | 3 |
2024-11-18T22:49:13.431799+00:00 | 2021-06-16T23:25:46 | ce2e457bb3a78b0a091c179514010f0babd7febb | {
"blob_id": "ce2e457bb3a78b0a091c179514010f0babd7febb",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-16T23:25:46",
"content_id": "7819de2486d880b8191b7276da8283f4cf210d9b",
"detected_licenses": [
"Zlib"
],
"directory_id": "c6952e1f7fd1e328f2fa2a415351ad0d8962b86c",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 377473988,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6512,
"license": "Zlib",
"license_type": "permissive",
"path": "/src/main.c",
"provenance": "stackv2-0108.json.gz:90296",
"repo_name": "ch98-1/oto-aliaser",
"revision_date": "2021-06-16T23:25:46",
"revision_id": "c525940fb4d08ed5825212052c0b6d2b1359c150",
"snapshot_id": "9d77c16694943ecb58abec49972f8309d9c5c4a9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ch98-1/oto-aliaser/c525940fb4d08ed5825212052c0b6d2b1359c150/src/main.c",
"visit_date": "2023-05-28T07:35:03.700818"
} | stackv2 | /* c standard libraries*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//max length of character readable per line
#define MAX_CHAR 4096
//dictionary
typedef struct dictionary_entry
{
char* in; //input of dictionary
char* out; //output of dictionary
}dict_e;
typedef struct dictionary
{
dict_e* d; //dictionary list
unsigned long int l; //length of dictionary
}dict;
dict add_entry(dict d, const char* in, const char* out); //add entry in to dictionary
dict read_dict(const char* file); //build dictionary
const char* find(dict d, const char* in); //find item in dictionary. returns null if not found
int free_dict(dict); //clean up dictionary
//oto reading and writing
typedef struct oto_entry
{
char* a; //filename without .wav
char* b; //aliase
char* c; //rest of the mess
}oto_e;
typedef struct oto
{
oto_e* o; //oto list
char platform;
char mac_header[MAX_CHAR];
unsigned long int l; //length of oto
}oto;
oto add_oto(oto o, const char* a, const char* b, const char* c); //add entry in to oto. a is filename without .wav, b is aliase, c is the rest
oto read_oto(const char* file, char platform); //read oto file
int write_oto(const char* file, oto o); //write oto file
int free_oto(oto o); //clean up oto
//other
int usage(char* program); //print usage
int main(int argc, char* argv[]) {
if (argc != 5 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "-hw") || !strcmp(argv[1], "-hm")) { //basic argument number check
usage(argv[0]);
exit(EXIT_SUCCESS);
}
char mode, platform; //mode and platform
int sl = strlen(argv[1]); //parse options
if (sl == 2){
mode = argv[1][1];
platform = 'w';
}
else if (sl == 3){
mode = argv[1][1];
platform = argv[1][2];
}
else{
usage(argv[0]);
exit(EXIT_SUCCESS);
}
if( mode == 'a'){ //check mode
printf("Working in add mode ");
}
else if (mode == 'r'){
printf("Working in replacement mode ");
}
else {
usage(argv[0]);
exit(EXIT_SUCCESS);
}
if( platform == 'w'){ //check platform
printf("for Windows\n");
}
else if (platform == 'm'){
printf("for Mac\n");
}
else {
usage(argv[0]);
exit(EXIT_SUCCESS);
}
//read dictionary
dict d = read_dict(argv[2]);
//read input file
oto o = read_oto(argv[3], platform);
//replace aliase
if (mode == 'a'){
unsigned long int i;
for(i = 0; i < o.l; i++){ //add based on file name for each entry
const char* tmp = find(d, o.o[i].a);
if(tmp != NULL){
strcpy(o.o[i].b, tmp);
}
}
}
else{
unsigned long int i;
for(i = 0; i < o.l; i++){ //replace based on existing aliase for each entry
const char* tmp = find(d, o.o[i].b);
if(tmp != NULL){
strcpy(o.o[i].b, tmp);
}
}
}
//write output file
write_oto(argv[4], o);
//free all
free_dict(d);
free_oto(o);
//exit
exit(EXIT_SUCCESS);
}
//print out the usage
int usage(char* program) {
printf("Usage:\n"
"%s [options][platform] <dictionary file> <input oto file> <output oto file>\n\n"
"options:\n"
"-a Add aliase from filename\n"
"-r Replace aliase using existing aliase\n"
"-h Print this help message\n\n"
"platforms:\n"
"m Mac\n"
"w Windows\n"
"If no platform is given, windows is assumed\n\n"
"example:\n"
"%s -aw hira2roma.csv oto.ini edited-oto.ini\n", program, program);
return 0;
}
//add entry in to dictionary
dict add_entry(dict d, const char* in, const char* out){
d.l++;
if (d.l == 1){ //allocate new memory for new entry in dictionary
d.d = malloc(sizeof(dict_e));
}
else{
d.d = realloc(d.d, sizeof(dict_e)*d.l);
}
d.d[d.l-1].in = malloc(sizeof(char)*(strlen(in)+1)); //create in
strcpy(d.d[d.l-1].in, in);//copy in
d.d[d.l-1].out = malloc(sizeof(char)*(strlen(out)+1)); //create out
strcpy(d.d[d.l-1].out, out);//copy out
return d;
}
//build dictionary
dict read_dict(const char* file){
dict d;
d.l = 0;
FILE* f_csv = fopen(file, "r");
char line[MAX_CHAR];//each line of the file
char in[MAX_CHAR];//in
char out[MAX_CHAR];//out
while(fgets(line, MAX_CHAR, f_csv) != NULL){
strcpy(in, strtok (line,","));
strcpy(out, strtok (NULL,",\r\n"));
d = add_entry(d, in, out);
}
fclose(f_csv);
return d;
}
//find item in dictionary. returns null if not found
const char* find(dict d, const char* in){
unsigned long int i;
for(i = 0; i < d.l; i++){ //search though each text entry
if (!strcmp(d.d[i].in, in)){
return d.d[i].out;
}
}
return NULL;
}
//clean up dictionary
int free_dict(dict d){
unsigned long int i;
for(i = 0; i < d.l; i++){ //free each text entry
free(d.d[i].in);
free(d.d[i].out);
}
free(d.d);
return 0;
}
//add entry in to oto. a is filename without .wav, b is aliase, c is the rest
oto add_oto(oto o, const char* a, const char* b, const char* c){
o.l++;
if (o.l == 1){ //allocate new memory for new entry in dictionary
o.o = malloc(sizeof(oto_e));
}
else{
o.o = realloc(o.o, sizeof(oto_e)*o.l);
}
o.o[o.l-1].a = malloc(sizeof(char)*(strlen(a)+1)); //create a
strcpy(o.o[o.l-1].a, a);//copy a
o.o[o.l-1].b = malloc(sizeof(char)*(strlen(b)+1)); //create b
strcpy(o.o[o.l-1].b, b);//copy b
o.o[o.l-1].c = malloc(sizeof(char)*(strlen(c)+1)); //create c
strcpy(o.o[o.l-1].c, c);//copy c
return o;
}
//read oto file
oto read_oto(const char* file, char platform){
oto o;
o.l = 0;
o.platform = platform;
FILE* f_oto = fopen(file, "r");
if (platform == 'm'){
fgets(o.mac_header, MAX_CHAR, f_oto);
}
char line[MAX_CHAR];//each line of the file
char a[MAX_CHAR];//a
char b[MAX_CHAR];//b
char c[MAX_CHAR];//c
while(fgets(line, MAX_CHAR, f_oto) != NULL){
strcpy(a, strtok (line,"."));
strtok (NULL,"=");
strcpy(b, strtok (NULL,","));
strcpy(c, strtok (NULL,"\r\n"));
o = add_oto(o, a, b, c);
}
fclose(f_oto);
return o;
}
//write oto file
int write_oto(const char* file, oto o){
FILE* f_oto = fopen(file, "w");
if (o.platform == 'm'){
fprintf(f_oto, "%s", o.mac_header);
}
unsigned long int i;
for(i = 0; i < o.l; i++){ //print each text entry
fprintf(f_oto, "%s.wav=%s,%s\n", o.o[i].a, o.o[i].b, o.o[i].c);
}
return 0;
}
//clean up oto
int free_oto(oto o){
unsigned long int i;
for(i = 0; i < o.l; i++){ //free each text entry
free(o.o[i].a);
free(o.o[i].b);
free(o.o[i].c);
}
free(o.o);
return 0;
}
| 2.9375 | 3 |
2024-11-18T22:49:13.511292+00:00 | 2014-01-10T14:45:01 | a7a6bdf07b65fcb35f62425390ec596208fd058f | {
"blob_id": "a7a6bdf07b65fcb35f62425390ec596208fd058f",
"branch_name": "refs/heads/master",
"committer_date": "2014-01-10T14:45:01",
"content_id": "307ba54052bdc39de4778c2207ece697fcff324f",
"detected_licenses": [
"MIT"
],
"directory_id": "8ae001e07dfaac2062e8c397a32df94a46075c93",
"extension": "c",
"filename": "line.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2277242,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1487,
"license": "MIT",
"license_type": "permissive",
"path": "/src/sparks/line.c",
"provenance": "stackv2-0108.json.gz:90426",
"repo_name": "ThQ/sparks",
"revision_date": "2014-01-10T14:45:01",
"revision_id": "cab5fa3de894712ab3659828501cd3e49480d846",
"snapshot_id": "d2dc98fcc088394eac2ee32613cdec74d7ef88be",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ThQ/sparks/cab5fa3de894712ab3659828501cd3e49480d846/src/sparks/line.c",
"visit_date": "2016-09-08T02:03:58.338707"
} | stackv2 | #include "sparks/line.h"
sparks_line_opt_t
sparks_line_opt_new ()
{
sparks_line_opt_t opt = {
.color = {.r=0.2, .g=0.27, .b=0.84, .a=1},
.symbol_size = 2,
.symbol_color = {.r=0.2, .g=0.27, .b=0.84},
.symbol = CIRCLE,
.width = 1.4
};
return opt;
}
void
sparks_draw_line (sparks_t* graph, sparks_data_t* data, unsigned int data_len,
sparks_line_opt_t opt)
{
sparks_grid_t grid = sparks_grid_new(graph);
sparks_data_t* d = data;
const sparks_data_t* d_max = d + data_len - 1;
double x = (double)graph->margins.left;
const double x_step = (double)grid.w / graph->data_length;
double y = (double)0;
bool begin_new_line = true;
cairo_set_line_width(graph->cr, opt.width);
cairo_set_source_rgba(graph->cr, opt.color.r, opt.color.g, opt.color.b,
opt.color.a);
while (d++ < d_max)
{
if (*d >= SPARKS_DATA_0)
{
y = (double)grid.y + grid.h - (grid.h * (int)(*d) / 127);
if (begin_new_line)
{
cairo_move_to(graph->cr, x, y);
}
else
{
cairo_line_to(graph->cr, x, y);
}
x += x_step;
begin_new_line = false;
}
else
{
cairo_stroke(graph->cr);
begin_new_line = true;
}
}
cairo_stroke(graph->cr);
}
void
sparks_draw_simple_line (sparks_t* graph, sparks_data_t* data, unsigned int len)
{
sparks_draw_line(graph, data, len, sparks_line_opt_new());
}
| 2.4375 | 2 |
2024-11-18T22:49:13.751672+00:00 | 2019-07-27T09:16:11 | 8a6cb5dca4c57946f96d7d49ca626cff8e9409c8 | {
"blob_id": "8a6cb5dca4c57946f96d7d49ca626cff8e9409c8",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-27T09:16:11",
"content_id": "83f2bdd7dde580ae82a48771664445bcf4a543aa",
"detected_licenses": [
"MIT"
],
"directory_id": "d1734f513382d99285dc1eb469817983b0c3feff",
"extension": "c",
"filename": "delay.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2436,
"license": "MIT",
"license_type": "permissive",
"path": "/Src/delay.c",
"provenance": "stackv2-0108.json.gz:90685",
"repo_name": "rkeck/STM32-CMSIS_Libraries",
"revision_date": "2019-07-27T09:16:11",
"revision_id": "7f2532d8b92cfcf84077903788182009baab9b8a",
"snapshot_id": "5182b049b586bbf3d62adf8db53e908d8655bbcd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rkeck/STM32-CMSIS_Libraries/7f2532d8b92cfcf84077903788182009baab9b8a/Src/delay.c",
"visit_date": "2021-03-22T12:46:42.324884"
} | stackv2 | #include "delay.h"
static __IO uint8_t _variant = 0; // variants, 0 - default
static __IO uint32_t delay_counter = 0; // variant 1
static __IO uint32_t sysTickCounter = 0; // variant 2
// -----------------------------------------------
// variant 1
// -----------------------------------------------
void SysTick_Init() {
_variant = 0;
SysTick_Config(SystemCoreClock / 1000);
}
uint32_t millis() {
return delay_counter;
}
uint32_t micros() {
return millis() * 1000 + 1000 - SysTick->VAL / 72; // 72 = (SystemCoreClock / 1000000)
}
void delay_ms(uint32_t delay) {
uint32_t start = millis();
while ((millis() - start) < delay) {
}
}
void delay_us(uint32_t delay) {
uint32_t start = micros();
while ((micros() - start) < delay) {
}
}
// -----------------------------------------------
// variant 2
// -----------------------------------------------
/******************************************
*SystemFrequency/1000 1ms *
*SystemFrequency/100000 10us *
*SystemFrequency/1000000.0 1us *
******************************************/
void G_SysTic_Init() {
_variant = 1;
SystemCoreClockUpdate();
while (SysTick_Config(SystemCoreClock / 1000000.0) != 0) {
}
}
void G_delay_ms(uint32_t delay) {
while (delay--) {
G_delay_us(1000);
}
}
void G_delay_us(uint32_t delay) {
sysTickCounter = delay;
while (sysTickCounter != 0);
}
// Interrupt Handler
void SysTick_Handler() {
if (_variant == 0) {
delay_counter++; // variant 1
} else if (_variant == 1) {
if (sysTickCounter != 0) { // variant 2
sysTickCounter--;
}
} else {} // variant 3
}
// -----------------------------------------------
// variant 3
// -----------------------------------------------
void DWT_Init(){
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; // Enable TRC
DWT->CYCCNT = 0; // Reset counter
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; // Enable counter
}
uint32_t DWT_tick() {
return DWT->CYCCNT;
}
void DWT_delay_ms(uint32_t delay){
DWT_delay_us(delay * 1000);
}
void DWT_delay_us(uint32_t delay){
uint32_t t0 = DWT->CYCCNT;
delay *= (SystemCoreClock / 1000000);
while((DWT->CYCCNT - t0) < delay);
}
uint32_t DWT_millis(void) {
return DWT_tick() / (SystemCoreClock / 1000);
}
uint32_t DWT_micros(void) {
return DWT_tick() / (SystemCoreClock / 1000000 + 1);
}
| 3 | 3 |
2024-11-18T22:49:14.077214+00:00 | 2021-05-26T19:58:18 | 3caff8c91f29b9efd45c233741bce3287bc62fd7 | {
"blob_id": "3caff8c91f29b9efd45c233741bce3287bc62fd7",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-26T19:58:18",
"content_id": "7101533a082e4ff20f36262c39db976850e97983",
"detected_licenses": [
"MIT"
],
"directory_id": "d843c88eb2a4939e90c850cbf112552d0ff4ee7c",
"extension": "c",
"filename": "elgamal.c",
"fork_events_count": 0,
"gha_created_at": "2019-10-16T21:45:46",
"gha_event_created_at": "2023-07-22T18:59:18",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 215650097,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15946,
"license": "MIT",
"license_type": "permissive",
"path": "/src/elgamal.c",
"provenance": "stackv2-0108.json.gz:91076",
"repo_name": "oblivious-file-sharing/libristretto-elgamal",
"revision_date": "2021-05-26T19:58:18",
"revision_id": "04b9219a84dda9812a72e8a184188b705daa8aeb",
"snapshot_id": "5e6ae88889b656d8328ca143e9e8159316e0914c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/oblivious-file-sharing/libristretto-elgamal/04b9219a84dda9812a72e8a184188b705daa8aeb/src/elgamal.c",
"visit_date": "2023-08-09T18:37:19.841636"
} | stackv2 | #include <ristretto_elgamal.h>
#include "word.h"
#include "field.h"
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
static void gf_invert_here(gf_25519_t *y, const gf_25519_t *x, int assert_nonzero) {
gf_25519_t t1, t2;
gf_sqr(&t1, x); // o^2
mask_t ret = gf_isr(&t2, &t1); // +-1/sqrt(o^2) = +-1/o
(void) ret;
(void) (assert_nonzero);
// if (assert_nonzero) assert(ret);
gf_sqr(&t1, &t2);
gf_mul(&t2, &t1, x); // not direct to y in case of alias.
gf_copy(y, &t2);
}
static void gf_batch_invert_here(
gf_25519_t *__restrict__ out,
const gf_25519_t *in,
unsigned int n
) {
gf_25519_t t1;
assert(n > 1);
gf_copy(&out[1], &in[0]);
int i;
for (i = 1; i < (int) (n - 1); i++) {
gf_mul(&out[i + 1], &out[i], &in[i]);
}
gf_mul(&out[0], &out[n - 1], &in[n - 1]);
gf_invert_here(&out[0], &out[0], 1);
for (i = n - 1; i > 0; i--) {
gf_mul(&t1, &out[i], &out[0]);
gf_copy(&out[i], &t1);
gf_mul(&t1, &out[0], &in[i]);
gf_copy(&out[0], &t1);
}
}
void KeyGen(
const char *filename_priv_1_key,
const char *filename_priv_2_key,
const char *filename_pub_1_key,
const char *filename_pub_2_key,
const char *filename_pub_key
) {
FILE *fp_priv_1_key = fopen(filename_priv_1_key, "wb");
FILE *fp_priv_2_key = fopen(filename_priv_2_key, "wb");
FILE *fp_pub_1_key = fopen(filename_pub_1_key, "wb");
FILE *fp_pub_2_key = fopen(filename_pub_2_key, "wb");
FILE *fp_pub_key = fopen(filename_pub_key, "wb");
if (fp_priv_1_key == NULL || fp_priv_2_key == NULL) {
perror("Cannot open the file for storing the private keys.\n");
exit(1);
}
if (fp_pub_1_key == NULL || fp_pub_2_key == NULL || fp_pub_key == NULL) {
perror("Cannot open the file for storing the public keys.\n");
exit(1);
}
/*
* Step 1: Generate random values, which are going to be the private key.
*/
ristretto255_point_t base;
ristretto255_point_copy(&base, &ristretto255_point_base);
unsigned char rand255_1[59][32];
unsigned char rand255_2[59][32];
FILE *rand_src = fopen("/dev/urandom", "rb");
if (rand_src == NULL) {
perror("cannot open the random source.\n");
exit(1);
}
for (int i = 0; i < 59; i++) {
fread(rand255_1[i], 32, 1, rand_src);
}
for (int i = 0; i < 59; i++) {
fread(rand255_2[i], 32, 1, rand_src);
}
ristretto255_scalar_t srv_1_sk[59];
ristretto255_scalar_t srv_2_sk[59];
ristretto255_point_t srv_1_pk[59];
ristretto255_point_t srv_2_pk[59];
ristretto255_point_t srv_pk[59];
ristretto255_point_add(&base, &base, &base); // 2
ristretto255_point_add(&base, &base, &base); // 4
ristretto255_point_add(&base, &base, &base); // 8
for (int i = 0; i < 59; i++) {
fread(rand255_1, sizeof(rand255_1), 1, rand_src);
fread(rand255_2, sizeof(rand255_2), 1, rand_src);
ristretto255_scalar_decode_long(&srv_1_sk[i], rand255_1[i], 32);
ristretto255_scalar_decode_long(&srv_2_sk[i], rand255_2[i], 32);
ristretto255_point_scalarmul(&srv_1_pk[i], &base, &srv_1_sk[i]);
ristretto255_point_scalarmul(&srv_2_pk[i], &base, &srv_2_sk[i]);
ristretto255_point_add(&srv_pk[i], &srv_1_pk[i], &srv_2_pk[i]);
}
for (int i = 0; i < 59; i++) {
fwrite(&srv_1_sk[i], sizeof(ristretto255_scalar_t), 1, fp_priv_1_key);
fwrite(&srv_2_sk[i], sizeof(ristretto255_scalar_t), 1, fp_priv_2_key);
fwrite(&srv_1_pk[i], sizeof(ristretto255_point_t), 1, fp_pub_1_key);
fwrite(&srv_2_pk[i], sizeof(ristretto255_point_t), 1, fp_pub_2_key);
fwrite(&srv_pk[i], sizeof(ristretto255_point_t), 1, fp_pub_key);
}
fclose(fp_priv_1_key);
fclose(fp_priv_2_key);
fclose(fp_pub_1_key);
fclose(fp_pub_2_key);
fclose(fp_pub_key);
fclose(rand_src);
}
void KeyGen_stage1(
const char *filename_priv_srv_key,
const char *filename_pub_srv_key
) {
FILE *fp_priv_srv_key = fopen(filename_priv_srv_key, "wb");
FILE *fp_pub_srv_key = fopen(filename_pub_srv_key, "wb");
if (fp_priv_srv_key == NULL) {
perror("Cannot open the file for storing the private key.\n");
exit(1);
}
if (fp_pub_srv_key == NULL) {
perror("Cannot open the file for storing the public key.\n");
exit(1);
}
/*
* Step 1: Generate random values, which are going to be the private key.
*/
ristretto255_point_t base;
ristretto255_point_copy(&base, &ristretto255_point_base);
unsigned char rand255[59][32];
FILE *rand_src = fopen("/dev/urandom", "rb");
if (rand_src == NULL) {
perror("cannot open the random source.\n");
exit(1);
}
for (int i = 0; i < 59; i++) {
fread(rand255[i], 32, 1, rand_src);
}
ristretto255_scalar_t srv_sk[59];
ristretto255_point_t srv_pk[59];
ristretto255_point_add(&base, &base, &base); // 2
ristretto255_point_add(&base, &base, &base); // 4
ristretto255_point_add(&base, &base, &base); // 8
for (int i = 0; i < 59; i++) {
fread(rand255, sizeof(rand255), 1, rand_src);
ristretto255_scalar_decode_long(&srv_sk[i], rand255[i], 32);
ristretto255_point_scalarmul(&srv_pk[i], &base, &srv_sk[i]);
}
for (int i = 0; i < 59; i++) {
fwrite(&srv_sk[i], sizeof(ristretto255_scalar_t), 1, fp_priv_srv_key);
fwrite(&srv_pk[i], sizeof(ristretto255_point_t), 1, fp_pub_srv_key);
}
fclose(fp_priv_srv_key);
fclose(fp_pub_srv_key);
fclose(rand_src);
}
void KeyGen_stage2(
const char *filename_pub_1_key,
const char *filename_pub_2_key,
const char *filename_pub_key
) {
FILE *fp_pub_1_key = fopen(filename_pub_1_key, "rb");
FILE *fp_pub_2_key = fopen(filename_pub_2_key, "rb");
FILE *fp_pub_key = fopen(filename_pub_key, "wb");
if (fp_pub_1_key == NULL || fp_pub_2_key == NULL) {
perror("Cannot open the file for reading the public keys.\n");
exit(1);
}
if (fp_pub_key == NULL) {
perror("Cannot open the file for storing the public keys.\n");
exit(1);
}
ristretto255_point_t srv_1_pk[59];
ristretto255_point_t srv_2_pk[59];
ristretto255_point_t srv_pk[59];
for (int i = 0; i < 59; i++) {
fread(&srv_1_pk[i], sizeof(ristretto255_point_t), 1, fp_pub_1_key);
fread(&srv_2_pk[i], sizeof(ristretto255_point_t), 1, fp_pub_2_key);
}
for (int i = 0; i < 59; i++) {
ristretto255_point_add(&srv_pk[i], &srv_1_pk[i], &srv_2_pk[i]);
}
for (int i = 0; i < 59; i++) {
fwrite(&srv_pk[i], sizeof(ristretto255_point_t), 1, fp_pub_key);
}
fclose(fp_pub_1_key);
fclose(fp_pub_2_key);
fclose(fp_pub_key);
}
void TablesGen(
const char *filename_pub_1_key,
const char *filename_pub_2_key,
const char *filename_pub_key,
const char *filename_pub_1_table_format,
const char *filename_pub_2_table_format,
const char *filename_pub_table_format
) {
/*
* Step 1: Generate random values, which are going to be the private key.
*/
ristretto255_point_t base;
ristretto255_point_copy(&base, &ristretto255_point_base);
ristretto255_point_t pk_1[59];
ristretto255_point_t pk_2[59];
ristretto255_point_t pk[59];
ristretto255_point_add(&base, &base, &base); // 2
ristretto255_point_add(&base, &base, &base); // 4
ristretto255_point_add(&base, &base, &base); // 8
FILE *fp_pub_1_key = fopen(filename_pub_1_key, "rb");
FILE *fp_pub_2_key = fopen(filename_pub_2_key, "rb");
FILE *fp_pub_key = fopen(filename_pub_key, "rb");
if (fp_pub_1_key == NULL || fp_pub_2_key == NULL || fp_pub_key == NULL) {
perror("Cannot open the file for reading the public keys.\n");
exit(1);
}
for (int i = 0; i < 59; i++) {
fread(&pk_1[i], sizeof(ristretto255_point_t), 1, fp_pub_1_key);
fread(&pk_2[i], sizeof(ristretto255_point_t), 1, fp_pub_2_key);
fread(&pk[i], sizeof(ristretto255_point_t), 1, fp_pub_key);
}
char filename[60][150];
#pragma omp parallel for
for (int i = 0; i < 59; i++) {
sprintf(filename[i], filename_pub_1_table_format, i);
TableGen(&pk_1[i], filename[i]);
}
sprintf(filename[59], filename_pub_1_table_format, 59);
TableGen(&base, filename[59]);
#pragma omp parallel for
for (int i = 0; i < 59; i++) {
sprintf(filename[i], filename_pub_2_table_format, i);
TableGen(&pk_2[i], filename[i]);
}
sprintf(filename[59], filename_pub_2_table_format, 59);
TableGen(&base, filename[59]);
#pragma omp parallel for
for (int i = 0; i < 59; i++) {
sprintf(filename[i], filename_pub_table_format, i);
TableGen(&pk[i], filename[i]);
}
sprintf(filename[59], filename_pub_table_format, 59);
TableGen(&base, filename[59]);
}
void LoadPrivKey(ristretto255_scalar_t *psk, const char *filename_priv_key) {
FILE *fp_priv_key = fopen(filename_priv_key, "rb");
if (fp_priv_key == NULL) {
perror("Cannot open the file for storing the private keys.\n");
exit(1);
}
for (int i = 0; i < 59; i++) {
fread(&psk[i], sizeof(ristretto255_scalar_t), 1, fp_priv_key);
}
fclose(fp_priv_key);
}
void LoadPubKey(ristretto255_point_t *ppk, const char *filename_pub_key) {
FILE *fp_pub_key = fopen(filename_pub_key, "rb");
if (fp_pub_key == NULL) {
perror("Cannot open the file for storing the public keys.\n");
exit(1);
}
for (int i = 0; i < 59; i++) {
fread(&ppk[i], sizeof(ristretto255_point_t), 1, fp_pub_key);
}
fclose(fp_pub_key);
}
void Encrypt(ristretto255_point_t ct[60], const ristretto255_point_t pt[59], const fastecexp_state st_pk[60],
FILE *rand_src) {
unsigned char rand255[32];
fread(rand255, 32, 1, rand_src);
TableCompute(&st_pk[59], &ct[59], rand255);
for (int i = 0; i < 59; i++) {
TableCompute(&st_pk[i], &ct[i], rand255);
}
for (int i = 0; i < 59; i++) {
ristretto255_point_add(&ct[i], &ct[i], &pt[i]);
}
}
/* Imporant: ct2 must differ from ct1 */
void
Rerand(ristretto255_point_t ct2[60], ristretto255_point_t ct1[60], const fastecexp_state st_pk[60], FILE *rand_src) {
unsigned char rand255[32];
fread(rand255, 32, 1, rand_src);
TableCompute(&st_pk[59], &ct2[59], rand255);
for (int i = 0; i < 59; i++) {
TableCompute(&st_pk[i], &ct2[i], rand255);
}
for (int i = 0; i < 60; i++) {
ristretto255_point_add(&ct2[i], &ct2[i], &ct1[i]);
}
}
void Rerand_to_cache(ristretto255_point_t ct[60], const fastecexp_state st_pk[60], FILE *rand_src) {
unsigned char rand255[32];
fread(rand255, 32, 1, rand_src);
TableCompute(&st_pk[59], &ct[59], rand255);
for (int i = 0; i < 59; i++) {
TableCompute(&st_pk[i], &ct[i], rand255);
}
}
void Rerand_use_cache(ristretto255_point_t ct[60], ristretto255_point_t cache[60]) {
for (int i = 0; i < 60; i++) {
ristretto255_point_add(&ct[i], &ct[i], &cache[i]);
}
}
void Decrypt(ristretto255_point_t pt[59], ristretto255_point_t ct[60], const ristretto255_scalar_t sk[59]) {
for (int i = 0; i < 59; i++) {
ristretto255_point_scalarmul(&pt[i], &ct[59], &sk[i]);
ristretto255_point_sub(&pt[i], &ct[i], &pt[i]);
}
}
/* now must rerandomize before decryption */
void PartDec1(ristretto255_point_t ct_short[1], ristretto255_point_t ct[60]) {
ristretto255_point_copy(&ct_short[0], &ct[59]);
}
void PartDec2(ristretto255_point_t pt[59], ristretto255_point_t ct_short[1], const ristretto255_scalar_t sk[59]) {
for (int i = 0; i < 59; i++) {
ristretto255_point_scalarmul(&pt[i], &ct_short[0], &sk[i]);
}
}
void PartDec3(ristretto255_point_t ct_dest[59], ristretto255_point_t ct_src[59]) {
for (int i = 0; i < 59; i++) {
ristretto255_point_sub(&ct_dest[i], &ct_src[i], &ct_dest[i]);
}
}
size_t Serialize_Honest_Size(int num_of_points) {
return SER_BYTES * 2 * num_of_points;
}
void Serialize_Honest(unsigned char *out, ristretto255_point_t *in, int num_of_points) {
uint8_t *serialized_output = out;
gf_25519_t *table = malloc(sizeof(gf_25519_t) * 2 * num_of_points);
gf_25519_t *zs = malloc(sizeof(gf_25519_t) * num_of_points);
gf_25519_t *zis = malloc(sizeof(gf_25519_t) * num_of_points);
if (zs == NULL || zis == NULL) {
perror("Cannot create space to store the z and its inverse.");
exit(1);
}
for (int i = 0; i < num_of_points; i++) {
gf_copy(&table[i * 2], &in[i].x);
gf_copy(&table[i * 2 + 1], &in[i].y);
gf_copy(&zs[i], &in[i].z);
}
gf_batch_invert_here(zis, zs, num_of_points);
int num_threads = omp_get_max_threads();
gf_25519_t product[num_threads];
#pragma omp parallel for
for (int i = 0; i < num_of_points; i++) {
int current_thread_num = omp_get_thread_num();
gf_25519_t *pp = &product[current_thread_num];
gf_mul(pp, &table[2 * i], &zis[i]);
gf_strong_reduce(pp);
gf_copy(&table[2 * i], pp);
gf_mul(pp, &table[2 * i + 1], &zis[i]);
gf_strong_reduce(pp);
gf_copy(&table[2 * i + 1], pp);
}
free(zis);
free(zs);
#pragma omp parallel for
for (int i = 0; i < 2 * num_of_points; i++) {
gf_serialize(&serialized_output[i * SER_BYTES], &table[i], 1);
}
}
size_t Serialize_Honest_Size_old(int num_of_points) {
return sizeof(gf_25519_t) * 2 * num_of_points;
}
void Serialize_Honest_old(unsigned char *out, ristretto255_point_t *in, int num_of_points) {
gf_25519_t *table = (gf_25519_t *) out;
gf_25519_t *zs = malloc(sizeof(gf_25519_t) * num_of_points);
gf_25519_t *zis = malloc(sizeof(gf_25519_t) * num_of_points);
if (zs == NULL || zis == NULL) {
perror("\033[0;31m[ERROR]\033[0m Cannot create space to store the z and its inverse.");
exit(1);
}
for (int i = 0; i < num_of_points; i++) {
gf_copy(&table[i * 2], &in[i].x);
gf_copy(&table[i * 2 + 1], &in[i].y);
gf_copy(&zs[i], &in[i].z);
}
gf_batch_invert_here(zis, zs, num_of_points);
int num_threads = omp_get_max_threads();
gf_25519_t product[num_threads];
#pragma omp parallel for
for (int i = 0; i < num_of_points; i++) {
int current_thread_num = omp_get_thread_num();
gf_25519_t *pp = &product[current_thread_num];
gf_mul(pp, &table[2 * i], &zis[i]);
gf_strong_reduce(pp);
gf_copy(&table[2 * i], pp);
gf_mul(pp, &table[2 * i + 1], &zis[i]);
gf_strong_reduce(pp);
gf_copy(&table[2 * i + 1], pp);
}
free(zis);
free(zs);
}
void Deserialize_Honest(ristretto255_point_t *out, unsigned char *in, int num_of_points) {
int num_threads = omp_get_max_threads();
gf_25519_t a[num_threads];
gf_25519_t b[num_threads];
#pragma omp parallel for
for (int i = 0; i < num_of_points; i++) {
int current_thread_num = omp_get_thread_num();
gf_deserialize(&a[current_thread_num], &in[i * SER_BYTES * 2], 1, 0);
gf_deserialize(&b[current_thread_num], &in[i * SER_BYTES * 2 + SER_BYTES], 1, 0);
gf_copy(&out[i].x, &a[current_thread_num]);
gf_copy(&out[i].y, &b[current_thread_num]);
gf_mul(&out[i].t, &out[i].x, &out[i].y);
gf_copy(&out[i].z, &ONE);
}
}
void Deserialize_Honest_old(ristretto255_point_t *out, unsigned char *in, int num_of_points) {
int num_threads = omp_get_max_threads();
gf_25519_t a[num_threads];
gf_25519_t b[num_threads];
#pragma omp parallel for
for (int i = 0; i < num_of_points; i++) {
int current_thread_num = omp_get_thread_num();
memcpy(&a[current_thread_num], &in[i * sizeof(gf_25519_t) * 2], sizeof(gf_25519_t));
memcpy(&b[current_thread_num], &in[i * sizeof(gf_25519_t) * 2 + sizeof(gf_25519_t)], sizeof(gf_25519_t));
gf_copy(&out[i].x, &a[current_thread_num]);
gf_copy(&out[i].y, &b[current_thread_num]);
gf_mul(&out[i].t, &out[i].x, &out[i].y);
gf_copy(&out[i].z, &ONE);
}
}
size_t Serialize_Malicious_Size(int num_of_points) {
return 32 * num_of_points;
}
void Serialize_Malicious(unsigned char *out, ristretto255_point_t *in, int num_of_points) {
#pragma omp parallel for
for (int i = 0; i < num_of_points; i++) {
ristretto255_point_encode(&out[32 * i], &in[i]);
}
}
ristretto_error_t Deserialize_Malicious(ristretto255_point_t *out, unsigned char *in, int num_of_points) {
int num_threads = omp_get_max_threads();
ristretto_error_t flag[num_threads];
ristretto_error_t flag_tmp[num_threads];
for (int i = 0; i < num_threads; i++) {
flag[i] = RISTRETTO_SUCCESS;
}
#pragma omp parallel for
for (int i = 0; i < num_of_points; i++) {
int current_thread_num = omp_get_thread_num();
flag_tmp[current_thread_num] = ristretto255_point_decode(&out[i], &in[i * 32], RISTRETTO_TRUE);
flag[current_thread_num] &= flag_tmp[current_thread_num];
}
ristretto_error_t final_flag = RISTRETTO_SUCCESS;
for (int i = 0; i < num_threads; i++) {
final_flag &= flag[i];
}
return final_flag;
}
| 2.328125 | 2 |
2024-11-18T22:49:14.313697+00:00 | 2021-10-13T21:26:59 | 861766ed6c2c4672cc0c98371c653224a72b2375 | {
"blob_id": "861766ed6c2c4672cc0c98371c653224a72b2375",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-13T21:26:59",
"content_id": "0a9ef0262bab77f6a8aa1e382bcdc2e737f7f3c9",
"detected_licenses": [
"MIT"
],
"directory_id": "8e8ef7dace635df3e6cff37c54ef0da93a241a34",
"extension": "c",
"filename": "struct_main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 228,
"license": "MIT",
"license_type": "permissive",
"path": "/src/c/struct_main.c",
"provenance": "stackv2-0108.json.gz:91332",
"repo_name": "passion4energy/fortran-c-cpp-interface",
"revision_date": "2021-10-13T21:26:59",
"revision_id": "5041b18bc880fdf977ea939bbf727a909fcbe020",
"snapshot_id": "83357779e5ae8b58650d2cdb0bf9ff57a8677ec0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/passion4energy/fortran-c-cpp-interface/5041b18bc880fdf977ea939bbf727a909fcbe020/src/c/struct_main.c",
"visit_date": "2023-08-15T04:39:50.804563"
} | stackv2 | #include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include "my_struct.h"
int main(void) {
struct params s;
s.my_int = 123;
s.my_bool = true;
strcpy(s.my_char, "Hello");
struct_check(&s);
return EXIT_SUCCESS;
}
| 2.125 | 2 |
2024-11-18T22:49:15.784645+00:00 | 2015-10-15T14:41:31 | 29047d64ffb5749b3526b4c20082a36cef5e7813 | {
"blob_id": "29047d64ffb5749b3526b4c20082a36cef5e7813",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-15T14:41:31",
"content_id": "3fe4d9a0af6e90412eb32bf310992ce77f08f972",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0d495507a85a46d6ca0b61a2c2bcc9e89302d7b7",
"extension": "c",
"filename": "decr.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44319578,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3032,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/decr.c",
"provenance": "stackv2-0108.json.gz:92370",
"repo_name": "mcilloni/crypto-demo",
"revision_date": "2015-10-15T14:41:31",
"revision_id": "08782bf09ac4f816f102e91b034d6450c7649428",
"snapshot_id": "441f65c20f8dd7066ffd31ff11832614d916ae78",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/mcilloni/crypto-demo/08782bf09ac4f816f102e91b034d6450c7649428/decr.c",
"visit_date": "2021-01-10T07:32:47.632911"
} | stackv2 | // Copyright 2015 Marco Cilloni
//
// 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 <assert.h>
#include <stdio.h>
#include <string.h>
#include "encrypt.h"
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#endif
void prepare_stdio_steams(void) {
#ifdef _WIN32
_setmode(fileno(stdin), _O_BINARY);
_setmode(fileno(stdout), _O_BINARY);
#else
freopen(NULL, "rb", stdin);
freopen(NULL, "wb", stdout);
#endif
}
#define N 512
byte* read_all_stdin(size_t *rlen) {
size_t read_tot = 0, size = 2*N;
intmax_t read;
byte *ret = malloc(size);
while((read = fread(ret + read_tot, 1, N, stdin)) > 0) {
read_tot += read;
if (read_tot + N > size) {
size *= 2;
ret = realloc(ret, size);
}
}
*rlen = read_tot;
if (!read_tot || read < 0) {
free(ret);
return NULL;
}
return ret;
}
// reads from stdin a little endian uint64_t value.
bool read_size(uint64_t *l) {
byte b[sizeof(uint64_t)];
if (fread(b, 1, sizeof(uint64_t), stdin) != sizeof(uint64_t)) {
return false;
}
*l = 0;
for (size_t i = 0; i < sizeof(uint64_t); ++i) {
*l |= b[i] << 8*i;
}
return true;
}
bool read_pair(const byte **pb, uint64_t *l) {
if (!read_size(l)) {
return false;
}
*pb = malloc((size_t) *l);
if (fread((void*) *pb, 1, (size_t) *l, stdin) < *l) {
free((void*) *pb);
return false;
}
return true;
}
bool read_encr_msg(enc_msg_t *enc) {
return read_pair(&enc->key, &enc->keylen)
&& read_pair(&enc->keyhash, &enc->keyhashlen)
&& read_pair(&enc->msg.txt, &enc->msg.len)
&& read_pair(&enc->msghash, &enc->msghashlen);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "usage: %s priv_file\n", argv[0]);
return EXIT_FAILURE;
}
char *priv_name = argv[1];
rsa_keypair_t kp;
FILE *priv = fopen(priv_name, "rb");
if (!priv) {
fputs("error: cannot open key file for reading\n", stderr);
return EXIT_FAILURE;
}
bool failed = !rsa_read_privkey(&kp.priv, priv);
fclose(priv);
if (failed) {
fputs("error: cannot read key\n", stderr);
return EXIT_FAILURE;
}
enc_msg_t enc;
msg_t dec;
prepare_stdio_steams();
if (!read_encr_msg(&enc)) {
fputs("error: cannot read input\n", stderr);
return EXIT_FAILURE;
}
if (!decrypt_message(kp.priv, enc, &dec)) {
fputs("error: corrupted message\n", stderr);
return EXIT_FAILURE;
}
fwrite(dec.txt, 1, dec.len, stdout);
return EXIT_SUCCESS;
}
| 2.3125 | 2 |
2024-11-18T22:49:16.438399+00:00 | 2019-08-15T03:54:35 | 0f511011af703d405e466b48b2b990436a604de7 | {
"blob_id": "0f511011af703d405e466b48b2b990436a604de7",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-15T03:54:35",
"content_id": "77bab8f5f5b9cd05b387cba2922881ba97a68ac4",
"detected_licenses": [
"MIT"
],
"directory_id": "a98e852f4ad3e83ec2443db85da938e362bd4a70",
"extension": "c",
"filename": "file-container.c",
"fork_events_count": 0,
"gha_created_at": "2016-08-29T21:36:34",
"gha_event_created_at": "2019-08-15T03:54:36",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 66882539,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4428,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lib/file-container.c",
"provenance": "stackv2-0108.json.gz:93014",
"repo_name": "ashon-ikon/file-inspector-c",
"revision_date": "2019-08-15T03:54:35",
"revision_id": "be35230b05d204e28bd3ae43ed554145a4bafb26",
"snapshot_id": "e55b24e35d8520ca2db2f790a417fbef8c971517",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ashon-ikon/file-inspector-c/be35230b05d204e28bd3ae43ed554145a4bafb26/src/lib/file-container.c",
"visit_date": "2020-07-29T01:24:42.877476"
} | stackv2 | /*
* File: file-container.c
* Author: Yinka Ashon
*
* 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 <stdlib.h>
#include "lib-common.h"
#include "file-container.h"
// Initial size of array
#define FI_INITIAL_FILES_ARRAY_SIZE (1024 * 1024)
/**
* Initializes the file array
* @param array
*/
struct FiFileContainer *fi_file_container_init()
{
struct FiFileContainer *container = malloc(sizeof *container);
if (! container) {
fi_log_message(FI_DEBUG_LEVEL_ASSERT, "Failed to allocate memory for files container");
return NULL;
}
container->array = fi_array_new_n(sizeof (struct FiFileInfo),
fi_file_copy_proxy,
FI_INITIAL_FILES_ARRAY_SIZE, NULL);
if (! container->array) {
fi_log_message(FI_DEBUG_LEVEL_ERROR,
"Failed to allocate container array memory");
return NULL;
}
return container;
}
void fi_file_container_destroy(struct FiFileContainer *container)
{
if (! container)
return;
struct FiFileInfo *file = NULL;
fi_array_each(container->array, struct FiFileInfo, file) {
fi_file_destroy(file);
}
fi_array_ref_dec(&container->array->ref);
fi_free(container);
}
/**
* @param arr
* @param info
* @return
*/
unsigned short fi_file_container_push(struct FiFileContainer *arr,
struct FiFileInfo *info)
{
if (! info || ! arr)
return FI_FUNC_FAIL;
return fi_array_push(arr->array, info);
}
/* ------------------------------------------------------------------
* ------------------------------------------------------------------
* Traversing
*/
/**
* Returns File Info
*
* @param arr
* @param i
* @return FileInfo
*/
struct FiFileInfo *fi_file_container_get_file_at(struct FiFileContainer *con, unsigned long i)
{
if (! con)
return NULL;
if (i < 0 || i > fi_file_container_size(con))
return NULL;
struct FiFileInfo *file = fi_array_get_ptr(con->array,
struct FiFileInfo, i);
return file;
}
/**
* Returns a copy of File Info (ref counter incremented)
*
* return value must be freed with "fi_file_destroy()" !
* @param arr
* @param i
* @return FileInfo
*/
struct FiFileInfo *fi_file_container_get_file_at_copy(struct FiFileContainer *con, unsigned long i)
{
struct FiFileInfo *file = fi_file_container_get_file_at(con, i);
if (! file)
return NULL;
fi_ref_inc(&file->ref);
return file;
}
struct FiFileInfo *fi_file_container_get_file_begin(struct FiFileContainer *con)
{
struct FiFileInfo *file = fi_array_get_ptr_being(con->array,
struct FiFileInfo);
return file;
}
struct FiFileInfo *fi_file_container_get_file_next(struct FiFileContainer *con)
{
struct FiFileInfo *file = fi_array_get_ptr_next(con->array,
struct FiFileInfo);
return file;
}
struct FiFileInfo *fi_file_container_get_file_end(struct FiFileContainer *con)
{
struct FiFileInfo *file = fi_array_get_ptr_end(con->array,
struct FiFileInfo);
if (file)
fi_ref_inc(&file->ref);
return file;
}
| 2.484375 | 2 |
2024-11-18T22:49:16.635872+00:00 | 2018-09-10T19:09:57 | 75953ffa113789c7caffc39d69883fffc3530328 | {
"blob_id": "75953ffa113789c7caffc39d69883fffc3530328",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-10T19:09:57",
"content_id": "7832cf63147b1b96569e50cd92917d712da227fe",
"detected_licenses": [
"MIT"
],
"directory_id": "cf1f306536e7859b0b1995c426ce32b09d275851",
"extension": "c",
"filename": "ts_options.c",
"fork_events_count": 6,
"gha_created_at": "2016-04-05T17:37:15",
"gha_event_created_at": "2018-09-10T19:13:06",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 55528632,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4178,
"license": "MIT",
"license_type": "permissive",
"path": "/tilesweep/src/ts_options.c",
"provenance": "stackv2-0108.json.gz:93144",
"repo_name": "seemk/TileSweep",
"revision_date": "2018-09-10T19:09:57",
"revision_id": "627999b38f59202678c4ea2a65d761e8e2a8f48a",
"snapshot_id": "a7c8c81513565e9a236bbd981207612191bd4d5a",
"src_encoding": "UTF-8",
"star_events_count": 17,
"url": "https://raw.githubusercontent.com/seemk/TileSweep/627999b38f59202678c4ea2a65d761e8e2a8f48a/tilesweep/src/ts_options.c",
"visit_date": "2018-12-07T07:40:06.556025"
} | stackv2 | #include "ts_options.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "ini/ini.h"
#include "parg/parg.h"
#include "platform.h"
int32_t compare_case_insensitive(const char* first, size_t len_first,
const char* second, size_t len_second) {
if (len_first != len_second) return 0;
for (size_t i = 0; i < len_first; i++) {
if (tolower(first[i]) != tolower(second[i])) {
return 0;
}
}
return 1;
}
static const ts_options default_opt = {.plugins = "/usr/local/lib/mapnik/input",
.fonts = "/usr/share/fonts",
.database = "tiles.db",
.host = "127.0.0.1",
.port = "8080",
.rendering = "1",
.mapnik_xml = "osm.xml",
.cache_size = "10M",
.cache_log_factor_str = "10.0",
.cache_decay_seconds_str = "120",
.rendering_enabled = 0};
static int64_t parse_cache_size(const char* cache_string) {
if (!cache_string) {
return 0;
}
int len = strlen(cache_string);
const int max_digits = 128;
int num_digits = 0;
int suffix_start = -1;
char digits[max_digits + 1];
memset(digits, 0, sizeof(digits));
for (int i = 0; i < strlen(cache_string); i++) {
char c = cache_string[i];
if (num_digits < max_digits && (isdigit(c) || c == '.')) {
digits[num_digits++] = c;
} else if (isalpha(c)) {
suffix_start = i;
break;
}
}
double mul = 1.0;
if (suffix_start == -1) {
return 0;
} else {
const char* suffix = cache_string + suffix_start;
int suffix_length = len - suffix_start;
if (compare_case_insensitive("m", 1, suffix, suffix_length)) {
mul = 1000000.0;
} else if (compare_case_insensitive("k", 1, suffix, suffix_length)) {
mul = 1000.0;
}
}
double base = atof(digits);
return base * mul;
}
static int ini_parse_callback(void* user, const char* section, const char* name,
const char* value) {
ts_options* opt = (ts_options*)user;
struct {
const char* name;
const char** dst;
} slots[] = {{"plugins", &opt->plugins},
{"fonts", &opt->fonts},
{"tile_db", &opt->database},
{"host", &opt->host},
{"port", &opt->port},
{"rendering", &opt->rendering},
{"mapnik_xml", &opt->mapnik_xml},
{"cache_size", &opt->cache_size},
{"cache_log_factor", &opt->cache_log_factor_str},
{"cache_decay_seconds", &opt->cache_decay_seconds_str}};
for (size_t i = 0; i < sizeof(slots) / sizeof(slots[0]); i++) {
if (strcmp(name, slots[i].name) == 0) *slots[i].dst = strdup(value);
}
return 1;
}
static void usage(void) {
ts_log("Usage: tilesweep [-c conf_path] [-h]");
exit(0);
}
ts_options ts_options_parse(int argc, char** argv) {
ts_options opt = default_opt;
struct parg_state args;
parg_init(&args);
const char* conf_path = NULL;
int c = -1;
while ((c = parg_getopt(&args, argc, argv, "c:h")) != -1) {
switch (c) {
case 'c':
conf_path = args.optarg;
break;
case 'h':
usage();
break;
case '?':
if (args.optopt == 'c') {
ts_log("Option '-c' requires an argument");
usage();
}
break;
case 1:
default:
break;
}
}
if (conf_path == NULL) {
usage();
}
if (ini_parse(conf_path, ini_parse_callback, &opt) < 0) {
ts_log("failed to load configuration file");
exit(1);
}
opt.cache_size_bytes = parse_cache_size(opt.cache_size);
opt.cache_log_factor = atof(opt.cache_log_factor_str);
opt.cache_decay_seconds = atoi(opt.cache_decay_seconds_str);
opt.rendering_enabled = strcmp(opt.rendering, "1") == 0;
ts_log("rendering %s", opt.rendering_enabled ? "enabled" : "disabled");
return opt;
}
| 2.15625 | 2 |
2024-11-18T22:49:16.810441+00:00 | 2021-01-25T13:19:28 | 6c7aa4337bc36e197b5e88fd7c7bb3c51541ad25 | {
"blob_id": "6c7aa4337bc36e197b5e88fd7c7bb3c51541ad25",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-25T13:19:28",
"content_id": "82db1d1991a2be9dd2d43145ec04d3fe166eb95e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0f64e993d8619ea9c9aa1cc706aea5d43b7b062c",
"extension": "c",
"filename": "my_putstr_nonprint.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 183701808,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 423,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/RPG/lib/my/my_putstr_nonprint.c",
"provenance": "stackv2-0108.json.gz:93403",
"repo_name": "Bluberia/RPG",
"revision_date": "2021-01-25T13:19:28",
"revision_id": "9dd37d861a0c8a061003d927f13b239c0b414bc5",
"snapshot_id": "326d11e89161fdcae314bf44fbbe6b013acd38f1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Bluberia/RPG/9dd37d861a0c8a061003d927f13b239c0b414bc5/RPG/lib/my/my_putstr_nonprint.c",
"visit_date": "2021-06-22T03:07:29.861963"
} | stackv2 | /*
** EPITECH PROJECT, 2017
** my_putstr
** File description:
** one_by_one character
*/
#include "my.h"
#include <unistd.h>
int my_putstr_nonprint(char const *str)
{
int i = 0;
int count = 0;
while (str[i] != '\0') {
if (32 < str[i] && str[i] < 127) {
my_putchar(str[i]);
count++;
i++;
} else {
my_putchar('\\');
my_putnbr_base(str[i], "0123456789");
i++;
count++;
}
}
return (count);
}
| 2.859375 | 3 |
2024-11-18T22:49:16.917001+00:00 | 2020-02-23T02:50:32 | 0a100915726e0c59b5efd8d4599ba956e7cd25d1 | {
"blob_id": "0a100915726e0c59b5efd8d4599ba956e7cd25d1",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-23T02:50:32",
"content_id": "93ef78bdb60e10a8e488e60902f4c61124b9f424",
"detected_licenses": [
"MIT"
],
"directory_id": "eda970cca03ab5dace29ebc2f9a0d06facb48c2b",
"extension": "h",
"filename": "serialtools.h",
"fork_events_count": 3,
"gha_created_at": "2019-03-29T23:32:19",
"gha_event_created_at": "2019-10-26T21:16:25",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 178488111,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2947,
"license": "MIT",
"license_type": "permissive",
"path": "/arduino/cetuspcr/serialtools.h",
"provenance": "stackv2-0108.json.gz:93534",
"repo_name": "cetuspcr/Cetus-PCR",
"revision_date": "2020-02-23T02:50:32",
"revision_id": "bbed1fd40257f5ba51bf4d9c9bc5fa328f28d7cb",
"snapshot_id": "d53bbd39c14869d06561f9a171b8023ed9c1f347",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cetuspcr/Cetus-PCR/bbed1fd40257f5ba51bf4d9c9bc5fa328f28d7cb/arduino/cetuspcr/serialtools.h",
"visit_date": "2020-05-03T07:03:43.045578"
} | stackv2 | #include <DallasTemperature.h>
#include <OneWire.h>
#define sensorsPin 2
#define lidHeater 3
#define cooler 4
#define peltierHeat 5
#define peltierCool 6
const byte cmdSize = 20;
char receivedChars[cmdSize];
boolean newData = false;
const char startMarker = '<';
const char endMarker = '>';
char *splitMarker = " ";
char *newCommand;
char *commandTitle;
int arguments[10];
bool isToPrintTemperature = false;
OneWire bus(sensorsPin);
DallasTemperature temperatureSensor(&bus);
void startup()
{
temperatureSensor.begin();
temperatureSensor.setResolution(10);
pinMode(peltierHeat, OUTPUT);
pinMode(peltierCool, OUTPUT);
Serial.println("Cetus is ready.");
}
void recieveCommand()
{
static byte index = 0;
static boolean isRecieving = false;
char newChar;
if (Serial.available() > 0 && newData == false)
{
newChar = Serial.read();
if (isRecieving == true)
{
if (newChar != endMarker)
{
receivedChars[index] = newChar;
index++;
}
else
{
receivedChars[cmdSize - 1] = '\0';
isRecieving = false;
index = 0;
newData = true;
}
}
else if (newChar == startMarker)
{
isRecieving = true;
}
}
}
void splitData()
{
if (newData == true)
{
int idxArg = 0;
for (int x = 0; x < sizeof(arguments) / sizeof(arguments[0]); x++)
{
arguments[x] = 0;
}
newCommand = strtok(receivedChars, splitMarker);
String commandTitle(newCommand);
while (newCommand != '\0')
{
newCommand = strtok(NULL, splitMarker);
arguments[idxArg] = atoi(newCommand);
idxArg += 2;
}
if (commandTitle == "peltier")
{
// <peltier state pwm_signal>
if (arguments[0] == 0)
{ // if heat
Serial.print("Heat: ");
Serial.println(arguments[2]);
analogWrite(peltierHeat, arguments[2]);
analogWrite(peltierCool, 0);
temperatureSensor.requestTemperatures();
Serial.print("tempSample ");
Serial.println(temperatureSensor.getTempCByIndex(0));
Serial.print("tempLid ");
Serial.println(temperatureSensor.getTempCByIndex(1));
}
else if (arguments[0] == 1)
{ // if cooling
Serial.print("Cooling: ");
Serial.println(arguments[2]);
analogWrite(peltierCool, arguments[2]);
analogWrite(peltierHeat, 0);
}
}
else if (commandTitle == "printTemps")
{
isToPrintTemperature = arguments[0];
}
Serial.println("nextpls");
newData = false;
}
}
| 2.546875 | 3 |
2024-11-18T22:49:17.243555+00:00 | 2022-10-04T09:14:42 | 188450902b1f69a27a20fe0009f9e1ccddfbef29 | {
"blob_id": "188450902b1f69a27a20fe0009f9e1ccddfbef29",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-04T09:14:42",
"content_id": "be0a4a617af292baaea7c8de17af9175d2d83d73",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "86a550d434047d421935772054c53a72c5690570",
"extension": "c",
"filename": "test_mmap.c",
"fork_events_count": 9,
"gha_created_at": "2012-12-22T02:46:04",
"gha_event_created_at": "2020-06-21T19:41:15",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 7281853,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2569,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/opt/test/mman/test_mmap.c",
"provenance": "stackv2-0108.json.gz:93921",
"repo_name": "Zeke-OS/zeke",
"revision_date": "2022-10-04T09:14:42",
"revision_id": "c6cd23959e3916c1aae04d909997f67c57c25e91",
"snapshot_id": "55cb5f3153a94cea21b6757bad9d3755f53e2339",
"src_encoding": "UTF-8",
"star_events_count": 81,
"url": "https://raw.githubusercontent.com/Zeke-OS/zeke/c6cd23959e3916c1aae04d909997f67c57c25e91/opt/test/mman/test_mmap.c",
"visit_date": "2022-10-15T13:16:43.112688"
} | stackv2 | #include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "punit.h"
char * data;
FILE * fp;
static void setup()
{
data = NULL;
fp = NULL;
}
static void teardown()
{
if (data)
munmap(data, 0);
if (fp)
fclose(fp);
}
static char * test_mmap_anon(void)
{
errno = 0;
data = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0);
pu_assert("a new memory region returned", data != MAP_FAILED);
pu_assert_equal("No errno was set", errno, 0);
memset(data, 0xff, 200);
pu_assert("memory is accessible", data[50] == 0xff);
return NULL;
}
static char * test_mmap_anon_fixed(void)
{
#define ADDR ((void *)0xA0000000)
static char msg[80];
int errno_save;
errno = 0;
data = mmap(ADDR, 4096, PROT_READ | PROT_WRITE, MAP_ANON | MAP_FIXED, -1, 0);
errno_save = errno;
pu_assert("a new memory region returned", data != MAP_FAILED);
pu_assert_equal("No errno was set", errno_save, 0);
sprintf(msg, "returned address equals %p", ADDR);
pu_assert(msg, data == ADDR);
memset(data, 0xff, 200);
pu_assert("memory is accessible", data[50] == 0xff);
return NULL;
#undef ADDR
}
static char * test_mmap_file(void)
{
FILE * fp;
int errno_save;
char str1[80];
char str2[80];
memset(str1, '\0', sizeof(str1));
memset(str2, '\0', sizeof(str2));
fp = fopen("/root/README.markdown", "r");
pu_assert("fp not NULL", fp != NULL);
errno = 0;
data = mmap(NULL, 2 * sizeof(str1), PROT_READ, MAP_PRIVATE, fileno(fp), 0);
errno_save = errno;
pu_assert("a new memory region returned", data != MAP_FAILED);
pu_assert_equal("No errno was set", errno_save, 0);
memcpy(str1, data, sizeof(str1) - 1);
fread(str2, sizeof(char), sizeof(str2) - 1, fp);
pu_assert("Strings are equal", strcmp(str1, str2) == 0);
return NULL;
}
static char * test_mmap_anon_huge(void)
{
const size_t size = 2097152;
errno = 0;
data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0);
pu_assert("a new memory region returned", data != MAP_FAILED);
pu_assert_equal("No errno was set", errno, 0);
memset(data, 0xff, size);
pu_assert("memory is accessible", data[50] == 0xff);
return NULL;
}
static void all_tests()
{
pu_def_test(test_mmap_anon, PU_RUN);
pu_def_test(test_mmap_anon_fixed, PU_RUN);
pu_def_test(test_mmap_file, PU_RUN);
pu_def_test(test_mmap_anon_huge, PU_RUN);
}
int main(int argc, char **argv)
{
return pu_run_tests(&all_tests);
}
| 2.859375 | 3 |
2024-11-18T22:49:17.533154+00:00 | 2017-09-30T07:39:15 | 711de7b615e6d20c2b7f64da4789146f24d230ef | {
"blob_id": "711de7b615e6d20c2b7f64da4789146f24d230ef",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-30T07:39:15",
"content_id": "a2d4d50fdcdf48e62c83f5f7bb59625eac59a280",
"detected_licenses": [
"MIT"
],
"directory_id": "7106fdd9e331abba900eee5e3c7b12d98461c01f",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 88414280,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1033,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0108.json.gz:94309",
"repo_name": "kirpichik/CmdKeys-In-C",
"revision_date": "2017-09-30T07:39:15",
"revision_id": "17a4b2b9f206ff1d588d47eb5196aad5bba5e4b1",
"snapshot_id": "12d0adf1e2e57709e7ccf382c797426d442ecf8d",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/kirpichik/CmdKeys-In-C/17a4b2b9f206ff1d588d47eb5196aad5bba5e4b1/main.c",
"visit_date": "2021-01-19T19:22:23.176838"
} | stackv2 | //
// main.c
// CmdKeys
//
// Created by Кирилл on 12.04.17.
// Copyright © 2017 Кирилл. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include "cmdkeys.h"
int main(const int argc, const char* argv[]) {
// Получаем структуру для удобной обработки
cmdkeys* keys = parseKeys(argc, argv);
// Выводим все ключи и их аргументы
printf("=== Keys: ===\n");
for (size_t i = 0; i < keys->keysArrSize; i++) {
printf("\"%s\" : ", keys->keys[i].name);
if (keys->keys[i].value)
printf("\"%s\"\n", keys->keys[i].value);
else
printf("enabled\n");
}
// Выводим оставшиеся аргументы
printf("=== Args: ===\n");
for (size_t i = 0; i < keys->globalArrSize; i++) {
printf("%s\n", keys->globalArgs[i]);
}
// Освобождаем структуру
freeCmdKeysStorage(keys);
return 0;
}
| 2.53125 | 3 |
2024-11-18T22:49:18.070813+00:00 | 2013-02-19T11:52:18 | e661df1eae58ffae2fd1ddeaa92d46c7b9054f61 | {
"blob_id": "e661df1eae58ffae2fd1ddeaa92d46c7b9054f61",
"branch_name": "refs/heads/master",
"committer_date": "2013-02-19T11:52:18",
"content_id": "0c4716e820f9504bd527c4faefea11241f0894bd",
"detected_licenses": [
"ISC"
],
"directory_id": "c1ea525a56131081fb463cacefc56a89cd0bd70e",
"extension": "c",
"filename": "printtoken.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 5648768,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1338,
"license": "ISC",
"license_type": "permissive",
"path": "/src/bin/spc/printtoken.c",
"provenance": "stackv2-0108.json.gz:94827",
"repo_name": "flimberger/sysprog",
"revision_date": "2013-02-19T11:52:18",
"revision_id": "264fd8fb8e6f6b9f0336e8d2ed3bbeef847e07a7",
"snapshot_id": "a53d039e19c894a025db44e2089a512f697f6137",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/flimberger/sysprog/264fd8fb8e6f6b9f0336e8d2ed3bbeef847e07a7/src/bin/spc/printtoken.c",
"visit_date": "2021-01-13T01:37:18.177932"
} | stackv2 | #include <stdio.h>
#include "defs.h"
#include "spc.h"
#include "error.h"
void
printtoken(Token *tp)
{
if (tp == NULL)
return;
switch (tp->symtype) {
case S_NONE:
fprintf(stderr, "Token %-10s char %4d line %3d Char %c\n", tokennames[tp->symtype], tp->col, tp->row, tp->data.lastchar);
break;
case S_END:
break;
case S_ERROR:
fprintf(stderr, "Token %-10s char %4d line %3d Char %c\n", tokennames[tp->symtype], tp->col, tp->row, tp->data.lastchar);
break;
case S_INTCONST:
fprintf(stderr, "Token %-10s char %4d line %3d Value %lld\n", tokennames[tp->symtype], tp->col, tp->row, tp->data.val);
break;
case S_ELSE:
case S_IF:
case S_INT:
case S_IDENT:
case S_PRINT:
case S_READ:
case S_WHILE:
fprintf(stderr, "Token %-10s char %4d line %3d Lexem %s\n", tokennames[tp->symtype], tp->col, tp->row, tp->data.sym->lexem);
break;
case S_PLUS:
case S_MINUS:
case S_DIV:
case S_MULT:
case S_LESS:
case S_GRTR:
case S_EQUAL:
case S_UNEQL:
case S_NOT:
case S_AND:
case S_TERM:
case S_PAROP:
case S_PARCL:
case S_CBOP:
case S_CBCL:
case S_BROP:
case S_BRCL:
fprintf(stderr, "Token %-10s char %4d line %3d Sign %s\n", tokennames[tp->symtype], tp->col, tp->row, tp->data.sign);
break;
default:
die(3, "Unknown Token %s on char %4d line %3d\n", tokennames[tp->symtype], tp->col, tp->row);
}
}
| 2.328125 | 2 |
2024-11-18T22:49:18.244784+00:00 | 2018-06-05T20:40:06 | 8994c50435e3b9589b99fd678f896921202003e3 | {
"blob_id": "8994c50435e3b9589b99fd678f896921202003e3",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-05T20:40:06",
"content_id": "b3b1e6e293bd186dc39e60b8c9aaf1f1011ecdec",
"detected_licenses": [
"MIT"
],
"directory_id": "4209239d8718071c798606f0d2bf9b20fca062f2",
"extension": "c",
"filename": "dump.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 135637170,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 947,
"license": "MIT",
"license_type": "permissive",
"path": "/extract/dump.c",
"provenance": "stackv2-0108.json.gz:94957",
"repo_name": "moefh/dstools",
"revision_date": "2018-06-05T20:40:06",
"revision_id": "532f1d09763cf2443f655c06798ebcf64c2f590f",
"snapshot_id": "ea6ad64fa87d99d6a4207dd31d7b4f496bea9988",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/moefh/dstools/532f1d09763cf2443f655c06798ebcf64c2f590f/extract/dump.c",
"visit_date": "2020-03-19T02:32:13.607260"
} | stackv2 | /* dump.h */
#include <stdint.h>
#include <stdio.h>
#include "dump.h"
static void dump_line(const uint8_t *data, uint32_t len, uint32_t addr, uint32_t global_addr)
{
printf("%08x | ", global_addr);
unsigned char str[16];
if (len > 16)
len = 16;
for (uint32_t i = 0; i < len; i++) {
if (i == 8)
printf(" ");
printf("%02x ", data[i]);
str[i] = (data[i] > 32 && data[i] < 127) ? data[i] : '.';
}
for (uint32_t i = len; i < 16; i++) {
if (i == 8)
printf(" ");
printf(" ");
}
printf("| %.*s", len, str);
for (uint32_t i = len; i < 16; i++)
printf(" ");
if (addr != global_addr)
printf(" | %08x", addr);
printf("\n");
}
void dump_mem(const void *data, size_t size, uint32_t global_addr)
{
const uint8_t *p = data;
uint32_t addr = 0;
for (size_t i = 0; i < size; i += 16) {
dump_line(p + i, size - i, addr, global_addr);
addr += 16;
global_addr += 16;
}
}
| 2.9375 | 3 |
2024-11-18T22:49:18.452716+00:00 | 2023-07-05T12:19:20 | 45d5339fe9e8ca1824693f9a5bb883b57e06bf3f | {
"blob_id": "45d5339fe9e8ca1824693f9a5bb883b57e06bf3f",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-05T12:19:20",
"content_id": "d84df774bece34c64477ba952fc70d04da25a37f",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "b71097386a6da0e3ca65f19a1906f0ebe11eac18",
"extension": "c",
"filename": "dsort.c",
"fork_events_count": 44,
"gha_created_at": "2011-09-07T11:19:46",
"gha_event_created_at": "2023-06-26T12:04:46",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 2341061,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8030,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/dsort.c",
"provenance": "stackv2-0108.json.gz:95086",
"repo_name": "hroptatyr/dateutils",
"revision_date": "2023-07-05T12:19:20",
"revision_id": "c57828809a018061147bc806a058aa4c4b9c449a",
"snapshot_id": "0584063e4a35c511ad3600c27efb2f4214af24c6",
"src_encoding": "UTF-8",
"star_events_count": 517,
"url": "https://raw.githubusercontent.com/hroptatyr/dateutils/c57828809a018061147bc806a058aa4c4b9c449a/src/dsort.c",
"visit_date": "2023-09-05T20:26:30.356886"
} | stackv2 | /*** dsort.c -- sort FILEs or stdin chronologically
*
* Copyright (C) 2011-2022 Sebastian Freundt
*
* Author: Sebastian Freundt <freundt@ga-group.nl>
*
* This file is part of dateutils.
*
* 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 author nor the names of any contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE 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.
*
**/
#if defined HAVE_CONFIG_H
# include "config.h"
#endif /* HAVE_CONFIG_H */
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <time.h>
#include "dt-core.h"
#include "dt-io.h"
#include "dt-locale.h"
#include "prchunk.h"
const char *prog = "dsort";
struct prln_ctx_s {
struct grep_atom_soa_s *ndl;
zif_t fromz;
int outfd;
};
struct sort_ctx_s {
unsigned int revp:1U;
unsigned int unqp:1U;
};
static void
safe_write(int fd, const char *buf, size_t bsz)
{
size_t tot = 0U;
for (ssize_t nwr;
tot < bsz && (nwr = write(fd, buf + tot, bsz - tot)) >= 0;
tot += nwr);
return;
}
static void
proc_line(struct prln_ctx_s ctx, char *line, size_t llen)
{
struct dt_dt_s d;
do {
char buf[64U];
char *sp, *tp;
char *bp = buf;
const char *const ep = buf + sizeof(buf);
/* find first occurrence then */
d = dt_io_find_strpdt2(
line, llen, ctx.ndl, &sp, &tp, ctx.fromz);
/* print line, first thing */
safe_write(ctx.outfd, line, llen);
/* extend by separator */
*bp++ = '\001';
/* check if line matches */
if (!dt_unk_p(d)) {
/* match! */
if (!dt_sandwich_only_t_p(d)) {
bp += dt_strfdt(bp, ep - bp, "%F", d);
}
*bp++ = '\001';
if (!dt_sandwich_only_d_p(d)) {
bp += dt_strfdt(bp, ep - bp, "%T", d);
}
} else {
/* just two empty fields then, innit? */
*bp++ = '\001';
}
/* finalise the line and print */
*bp++ = '\n';
safe_write(ctx.outfd, buf, bp - buf);
} while (0);
return;
}
static int
proc_file(struct prln_ctx_s prln, const char *fn)
{
size_t lno = 0;
void *pctx;
int fd;
if (fn == NULL) {
/* stdin then innit */
fd = STDIN_FILENO;
} else if ((fd = open(fn, O_RDONLY)) < 0) {
serror("Error: cannot open file `%s'", fn);
return -1;
}
/* using the prchunk reader now */
if ((pctx = init_prchunk(fd)) == NULL) {
serror("Error: cannot read from `%s'", fn ?: "<stdin>");
return -1;
}
while (prchunk_fill(pctx) >= 0) {
for (char *line; prchunk_haslinep(pctx); lno++) {
size_t llen = prchunk_getline(pctx, &line);
proc_line(prln, line, llen);
}
}
/* get rid of resources */
free_prchunk(pctx);
close(fd);
return 0;
}
/* helper children, sort(1) and cut(1) */
static pid_t
spawn_sort(int *restrict infd, const int outfd, struct sort_ctx_s sopt)
{
static char *cmdline[16U] = {"sort", "-t", "-k2"};
pid_t sortp;
/* to snarf off traffic from the child */
int intfd[2];
if (pipe(intfd) < 0) {
serror("pipe setup to/from sort failed");
return -1;
}
switch ((sortp = vfork())) {
case -1:
/* i am an error */
serror("vfork for sort failed");
return -1;
default:
/* i am the parent */
close(intfd[0]);
*infd = intfd[1];
/* close outfd here already */
close(outfd);
return sortp;
case 0:;
char **cp = cmdline + 3U;
/* i am the child */
if (sopt.revp) {
*cp++ = "-r";
}
if (sopt.unqp) {
*cp++ = "-u";
}
*cp++ = NULL;
/* stdout -> outfd */
dup2(outfd, STDOUT_FILENO);
/* *infd -> stdin */
dup2(intfd[0], STDIN_FILENO);
close(intfd[1]);
execvp("sort", cmdline);
serror("execvp(sort) failed");
_exit(EXIT_FAILURE);
}
}
static pid_t
spawn_cut(int *restrict infd)
{
static char *const cmdline[] = {"cut", "-d", "-f1", NULL};
pid_t cutp;
/* to snarf off traffic from the child */
int intfd[2];
if (pipe(intfd) < 0) {
serror("pipe setup to/from cut failed");
return -1;
}
switch ((cutp = vfork())) {
case -1:
/* i am an error */
serror("vfork for cut failed");
return -1;
default:;
/* i am the parent */
close(intfd[0]);
*infd = intfd[1];
return cutp;
case 0:;
/* i am the child */
dup2(intfd[0], STDIN_FILENO);
close(intfd[1]);
execvp("cut", cmdline);
serror("execvp(cut) failed");
_exit(EXIT_FAILURE);
}
}
#include "dsort.yucc"
int
main(int argc, char *argv[])
{
yuck_t argi[1U];
char **fmt;
size_t nfmt;
zif_t fromz = NULL;
int rc = 0;
struct sort_ctx_s sopt = {0U};
if (yuck_parse(argi, argc, argv)) {
rc = 1;
goto out;
}
/* init and unescape sequences, maybe */
fmt = argi->input_format_args;
nfmt = argi->input_format_nargs;
if (argi->backslash_escapes_flag) {
for (size_t i = 0; i < nfmt; i++) {
dt_io_unescape(fmt[i]);
}
}
if (argi->from_locale_arg) {
setilocale(argi->from_locale_arg);
}
/* try and read the from and to time zones */
if (argi->from_zone_arg &&
(fromz = dt_io_zone(argi->from_zone_arg)) == NULL) {
error("\
Error: cannot find zone specified in --from-zone: `%s'", argi->from_zone_arg);
rc = 1;
goto clear;
}
if (argi->base_arg) {
struct dt_dt_s base = dt_strpdt(argi->base_arg, NULL, NULL);
dt_set_base(base);
}
/* prepare a mini-argi for the sort invocation */
if (argi->reverse_flag) {
sopt.revp = 1U;
}
if (argi->unique_flag) {
sopt.unqp = 1U;
}
{
/* process all files */
struct grep_atom_s __nstk[16], *needle = __nstk;
size_t nneedle = countof(__nstk);
struct grep_atom_soa_s ndlsoa;
struct prln_ctx_s prln = {
.ndl = &ndlsoa,
.fromz = fromz,
};
pid_t cutp, sortp;
/* lest we overflow the stack */
if (nfmt >= nneedle) {
/* round to the nearest 8-multiple */
nneedle = (nfmt | 7) + 1;
needle = calloc(nneedle, sizeof(*needle));
}
/* and now build the needles */
ndlsoa = build_needle(needle, nneedle, fmt, nfmt);
/* spawn children */
with (int ifd, ofd) {
if ((cutp = spawn_cut(&ifd)) < 0) {
goto ndl_free;
}
if ((sortp = spawn_sort(&ofd, ifd, sopt)) < 0) {
goto ndl_free;
}
prln.outfd = ofd;
}
for (size_t i = 0U; i < argi->nargs || i == 0U; i++) {
if (proc_file(prln, argi->args[i]) < 0) {
rc = 1;
}
}
/* indicate we're no longer writing to the sort helper */
close(prln.outfd);
/* wait for sort first */
with (int st) {
while (waitpid(sortp, &st, 0) != sortp);
if (WIFEXITED(st) && WEXITSTATUS(st)) {
rc = rc ?: WEXITSTATUS(st);
}
}
/* wait for cut then */
with (int st) {
while (waitpid(cutp, &st, 0) != cutp);
if (WIFEXITED(st) && WEXITSTATUS(st)) {
rc = rc ?: WEXITSTATUS(st);
}
}
ndl_free:
if (needle != __nstk) {
free(needle);
}
}
clear:
dt_io_clear_zones();
if (argi->from_locale_arg) {
setilocale(NULL);
}
out:
yuck_free(argi);
return rc;
}
/* dsort.c ends here */
| 2.03125 | 2 |
2024-11-18T22:49:18.536729+00:00 | 2013-12-01T05:51:47 | f352f7ffd5f23a90fc383870359d11de4414b241 | {
"blob_id": "f352f7ffd5f23a90fc383870359d11de4414b241",
"branch_name": "refs/heads/master",
"committer_date": "2013-12-01T05:51:47",
"content_id": "f6876e44391bd0a81edc93601de939cda561eb70",
"detected_licenses": [
"MIT"
],
"directory_id": "5802a391b4435f75c91199d1f7622b107691477c",
"extension": "h",
"filename": "hasht.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 527,
"license": "MIT",
"license_type": "permissive",
"path": "/include/hasht.h",
"provenance": "stackv2-0108.json.gz:95216",
"repo_name": "xiaoxiaokongyi/mqtts",
"revision_date": "2013-12-01T05:51:47",
"revision_id": "cd6f11f8013d909545689a275e9bdb89fc4dee94",
"snapshot_id": "ad338a93ea003e56e8d37daa5e59c4d9e2edefac",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xiaoxiaokongyi/mqtts/cd6f11f8013d909545689a275e9bdb89fc4dee94/include/hasht.h",
"visit_date": "2020-03-08T08:50:50.853556"
} | stackv2 | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct hash_buckets_s {
char* key;
void* value;
struct hash_buckets_s* next;
} hash_buckets_t;
typedef struct hasht_s {
hash_buckets_t** buckets;
size_t size;
} hasht_t;
hasht_t* hasht_create(size_t size);
void hasht_free(hasht_t* hasht);
int hasht_insert(hasht_t* hasht, const char* key, void* value);
int hasht_remove(hasht_t* hasht, const char* key);
void* hasht_get(hasht_t* hasht, const char* key);
| 2.421875 | 2 |
2024-11-18T22:49:18.627283+00:00 | 2018-10-27T13:56:23 | b42e7b7e205314eeee559fec1b8826659291c08a | {
"blob_id": "b42e7b7e205314eeee559fec1b8826659291c08a",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-27T13:56:23",
"content_id": "4b43cbb7add2d7cc2a88d71108354000d7379c32",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "406480da140462d15533959895e6f9289190854c",
"extension": "c",
"filename": "runtime.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 25372,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/rts/runtime.c",
"provenance": "stackv2-0108.json.gz:95344",
"repo_name": "sailfish009/lasca-compiler",
"revision_date": "2018-10-27T13:56:23",
"revision_id": "8e2c00a570f309eb1accf7a34bd1b5c62e7358db",
"snapshot_id": "33ee6eb78e29511bb2b49703e732eb597ef955ad",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sailfish009/lasca-compiler/8e2c00a570f309eb1accf7a34bd1b5c62e7358db/rts/runtime.c",
"visit_date": "2020-12-03T00:53:27.110353"
} | stackv2 | #define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <gc.h>
#include <ffi.h>
#include <utf8proc.h>
#include "lasca.h"
#define STR(s) {.type = &String_LaType, .length = sizeof(s) - 1, .bytes = s}
// Primitive Types
const LaType Unknown_LaType = { .name = "Unknown" };
const LaType Unit_LaType = { .name = "Unit" };
const LaType Bool_LaType = { .name = "Bool" };
const LaType Byte_LaType = { .name = "Byte" };
const LaType Int16_LaType = { .name = "Int16" };
const LaType Int32_LaType = { .name = "Int32" };
const LaType Int_LaType = { .name = "Int" };
const LaType Float_LaType = { .name = "Float" };
const LaType String_LaType = { .name = "String" };
const LaType Closure_LaType = { .name = "Closure" };
const LaType Array_LaType = { .name = "Array" };
const LaType ByteArray_LaType = { .name = "ByteArray" };
const LaType _VAR = { .name = "Var" };
const LaType _FILE_HANDLE = { .name = "FileHandle" };
const LaType _PATTERN = { .name = "Pattern" };
const LaType _OPTION = { .name = "Option" };
const LaType* UNKNOWN = &Unknown_LaType;
const LaType* LAUNIT = &Unit_LaType;
const LaType* LABOOL = &Bool_LaType;
const LaType* LABYTE = &Byte_LaType;
const LaType* LAINT16 = &Int16_LaType;
const LaType* LAINT32 = &Int32_LaType;
const LaType* LAINT = &Int_LaType;
const LaType* LAFLOAT64 = &Float_LaType;
const LaType* LASTRING = &String_LaType;
const LaType* LACLOSURE = &Closure_LaType;
const LaType* LAARRAY = &Array_LaType;
const LaType* VAR = &_VAR;
const LaType* LABYTEARRAY = &ByteArray_LaType;
const LaType* LAFILE_HANDLE = &_FILE_HANDLE;
const LaType* LAPATTERN = &_PATTERN;
const LaType* LAOPTION = &_OPTION;
Bool TRUE_SINGLETON = {
.type = &Bool_LaType,
.num = 1
};
Bool FALSE_SINGLETON = {
.type = &Bool_LaType,
.num = 0
};
Unit UNIT_SINGLETON = {
.type = &Unit_LaType
};
String EMPTY_STRING = STR("\00");
String* UNIT_STRING;
Byte BYTE_ARRAY[256];
Int INT_ARRAY[100];
Float64 FLOAT64_ZERO = {
.type = &Float_LaType,
.num = 0.0
};
DataValue NONE = {
.type = &_OPTION,
.tag = 0,
.values = {}
};
Environment ENV;
Runtime* RUNTIME;
bool eqTypes(const LaType* lhs, const LaType* rhs) {
return lhs == rhs || strcmp(lhs->name, rhs->name) == 0;
}
Option* some(Box* value) {
assert(value != NULL);
DataValue* dv = gcMalloc(sizeof(DataValue) + sizeof(Box*));
dv->type = LAOPTION;
dv->tag = 1;
dv->values[0] = value;
return dv;
}
static uint64_t Lasca_Allocated = 0;
static uint64_t Lasca_Nr_gcMalloc = 0;
void *gcMalloc(size_t s) {
Lasca_Allocated += s;
Lasca_Nr_gcMalloc++;
return GC_malloc(s);
}
void *gcMallocAtomic(size_t s) {
Lasca_Allocated += s;
Lasca_Nr_gcMalloc++;
return GC_malloc_atomic(s);
}
void *gcRealloc(void* old, size_t s) {
return GC_realloc(old, s);
}
const char * __attribute__ ((const)) typeIdToName(const LaType* typeId) {
return typeId->name;
}
/* =============== Boxing ================== */
Box *box(const LaType* type_id, void *value) {
Box* ti = (Box*) value;
ti->type = type_id;
return ti;
}
Bool* __attribute__ ((pure)) boxBool(int8_t i) {
switch (i) {
case 0: return &FALSE_SINGLETON; break;
default: return &TRUE_SINGLETON; break;
}
}
Unknown* __attribute__ ((pure)) boxError(String *name) {
Unknown* value = gcMalloc(sizeof(Unknown));
value->type = UNKNOWN;
value->error = name;
return value;
}
Byte* __attribute__ ((pure)) boxByte(int8_t i) {
return &BYTE_ARRAY[i + 128];
}
Int* boxInt(int64_t i) {
if (i >= 0 && i < 100) return &INT_ARRAY[i];
else {
Int* ti = gcMallocAtomic(sizeof(Int));
ti->type = LAINT;
ti->num = i;
return ti;
}
}
Int16* boxInt16(int16_t i) {
Int16* ti = gcMallocAtomic(sizeof(Int16));
ti->type = LAINT16;
ti->num = i;
return ti;
}
Int32* boxInt32(int32_t i) {
Int32* ti = gcMallocAtomic(sizeof(Int32));
ti->type = LAINT32;
ti->num = i;
return ti;
}
Float64* __attribute__ ((pure)) boxFloat64(double i) {
if (i == 0.0) return &FLOAT64_ZERO;
Float64* ti = gcMallocAtomic(sizeof(Float64));
ti->type = LAFLOAT64;
ti->num = i;
return ti;
}
Closure* boxClosure(int64_t idx, int64_t argc, Box** args) {
Closure* cl = gcMalloc(sizeof(Closure));
// printf("boxClosure(%d, %d, %p)\n", idx, argc, args);
// fflush(stdout);
cl->type = LACLOSURE;
cl->funcIdx = idx;
cl->argc = argc;
cl->argv = args;
// printf("Enclose %d, argc = %d, args[0].type = %d, args[1].type = %d\n", idx, argc, args[0]->type, args[1]->type);
// fflush(stdout);
return cl;
}
void * unbox(const LaType* expected, const Box* ti) {
// printf("unbox(%d, %d) ", ti->type, (int64_t) ti->value);
/* In most cases we can use pointer comparison,
but when we use Lasca defined type in C code, we also define a LaType
and we need to compare actual qualified type names.
TODO/FIXME: think how to make it better, now it's O(typename_length), show be O(1)
Likely, not an issue anyway.
*/
if (eqTypes(ti->type, expected)) {
return (void*) ti;
} else if (eqTypes(ti->type, UNKNOWN)) {
String *name = ((Unknown *) ti)->error;
printf("AAAA!!! Undefined identifier %s\n", name->bytes);
exit(1);
} else {
printf("AAAA!!! Expected %s but got %s %p != %p\n", typeIdToName(expected), typeIdToName(ti->type), expected, ti->type);
exit(1);
}
}
/* ==================== Runtime Ops ============== */
Box* writeVar(DataValue* var, Box* value) {
assert(eqTypes(var->type, VAR));
Box* oldValue = var->values[0];
var->values[0] = value;
return oldValue;
}
static int64_t isBuiltinType(const Box* v) {
const LaType* t = v->type;
return eqTypes(t, LAUNIT) || eqTypes(t, LABOOL) || eqTypes(t, LABYTE)
|| eqTypes(t, LAINT) || eqTypes(t, LAINT16) || eqTypes(t, LAINT32) || eqTypes(t, LAFLOAT64)
|| eqTypes(t, LASTRING) || eqTypes(t, LACLOSURE) || eqTypes(t, LAARRAY) || eqTypes(t, LABYTEARRAY);
}
static int64_t isUserType(const Box* v) {
return !isBuiltinType(v);
}
#define DO_OP(op) if (eqTypes(lhs->type, LAINT)) { result = (Box*) boxInt(asInt(lhs)->num op asInt(rhs)->num); } \
else if (eqTypes(lhs->type, LABYTE)) { result = (Box*) boxByte(asByte(lhs)->num op asByte(rhs)->num); } \
else if (eqTypes(lhs->type, LAINT32)) { result = (Box*) boxInt32(asInt32(lhs)->num op asInt32(rhs)->num); } \
else if (eqTypes(lhs->type, LAINT16)) { result = (Box*) boxInt16(asInt16(lhs)->num op asInt16(rhs)->num); } \
else if (eqTypes(lhs->type, LAFLOAT64)) { result = (Box*) boxFloat64(asFloat(lhs)->num op asFloat(rhs)->num); } \
else { \
printf("AAAA!!! Type mismatch! Expected Int or Float for op but got %s\n", typeIdToName(lhs->type)); exit(1); }
Box* __attribute__ ((pure)) runtimeBinOp(int64_t code, Box* lhs, Box* rhs) {
if (!eqTypes(lhs->type, rhs->type)) {
printf("AAAA!!! Type mismatch in binop %"PRId64"! lhs = %s, rhs = %s\n", code, typeIdToName(lhs->type), typeIdToName(rhs->type));
exit(1);
}
Box* result = NULL;
if (code == ADD) { DO_OP(+); }
else if (code == SUB) { DO_OP(-); }
else if (code == MUL) {DO_OP(*);}
else if (code == DIV) {DO_OP(/);}
else {
int res = runtimeCompare(lhs, rhs);
bool b = (code == EQ && res == 0) || (code == NE && res != 0) ||
(code == LT && res == -1) || (code == LE && res != 1) ||
(code == GE && res != -1) || (code == GT && res == 1);
result = (Box*) boxBool(b);
}
return result;
}
Box* __attribute__ ((pure)) runtimeUnaryOp(int64_t code, Box* expr) {
Box* result = NULL;
switch (code) {
case 1:
if (eqTypes(expr->type, LAINT)) {
result = (Box*) boxInt(-asInt(expr)->num);
} else if (eqTypes(expr->type, LABYTE)) {
result = (Box*) boxByte(-asByte(expr)->num);
} else if (eqTypes(expr->type, LAINT32)) {
result = (Box*) boxInt32(-asInt32(expr)->num);
} else if (eqTypes(expr->type, LAINT16)) {
result = (Box*) boxInt16(-asInt16(expr)->num);
} else if (eqTypes(expr->type, LAFLOAT64)) {
result = (Box*) boxFloat64(-asFloat(expr)->num);
} else {
printf("AAAA!!! Type mismatch! Expected Int or Float for op but got %s\n", typeIdToName(expr->type));
exit(1);
}
break;
default:
printf("AAAA!!! Unsupported unary operation %"PRId64, code);
exit(1);
}
return result;
}
String UNIMPLEMENTED_SELECT = {
.length = 20,
.bytes = "Unimplemented select"
};
Box* runtimeApply(Box* val, int64_t argc, Box* argv[], Position pos) {
Functions* fs = RUNTIME->functions;
Closure *closure = unbox(LACLOSURE, val);
if (closure->funcIdx >= fs->size) {
printf("AAAA!!! No such function with id %"PRId64", max id is %"PRId64" at line: %"PRId64"\n", (int64_t) closure->funcIdx, fs->size, pos.line);
exit(1);
}
Function f = fs->functions[closure->funcIdx];
if (f.arity != argc + closure->argc) {
printf("AAAA!!! Function %s takes %"PRId64" params, but passed %"PRId64" enclosed params and %"PRId64" params instead at line: %"PRId64"\n",
f.name->bytes, f.arity, closure->argc, argc, pos.line);
exit(1);
}
ffi_cif cif;
ffi_type *args[f.arity];
void *values[f.arity];
Box* rc;
for (int i = 0; i < f.arity; i++) {
args[i] = &ffi_type_pointer;
values[i] = (i < closure->argc) ? &closure->argv[i] : &argv[i - closure->argc];
}
if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, f.arity, &ffi_type_pointer, args) != FFI_OK) {
printf("AAAA!!! Function %s ffi_prep_cif call failed\n", f.name->bytes);
exit(1);
}
ffi_call(&cif, f.funcPtr, &rc, values);
return rc;
}
Data* findDataType(const LaType* type) {
Types* types = RUNTIME->types;
for (int i = 0; i < types->size; i++) {
if (eqTypes(types->data[i]->type, type)) return types->data[i];
}
printf("AAAA! Couldn't find type %s", type->name);
exit(1);
}
Box* __attribute__ ((pure)) runtimeSelect(Box* tree, Box* ident, Position pos) {
Functions* fs = RUNTIME->functions;
// printf("isUserType %s %p %p\n", tree->type->name, tree->type, &Unknown_LaType);
if (isUserType(tree)) {
DataValue* dataValue = asDataValue(tree);
// if rhs is not a local ident, nor a function, try to find this field in lhs data structure
if (eqTypes(ident->type, UNKNOWN)) {
String* name = ((Unknown*)ident)->error; // should be identifier name
// printf("Ident name %s\n", name->bytes);
Data* data = findDataType(tree->type); // find struct in global array of structs
// printf("Found data type %s %s, tag %"PRId64"\n", data->name->bytes, tree->type->name, dataValue->tag);
Struct* constr = data->constructors[dataValue->tag];
int64_t numFields = constr->numFields;
for (int64_t i = 0; i < numFields; i++) {
String* field = constr->fields[i];
// printf("Check field %d %s\n", field->length, field->bytes);
if (field->length == name->length && strncmp(field->bytes, name->bytes, name->length) == 0) {
Box* value = dataValue->values[i];
// printf("Found value %s at index %"PRId64"\n", value->type->name, i);
// println(toString(value));
return value;
}
}
printf("Couldn't find field %s at line: %"PRId64"\n", name->bytes, pos.line);
} else if (eqTypes(ident->type, LACLOSURE)) {
// FIXME fix for closure? check arity?
Closure* f = asClosure(ident);
assert(fs->functions[f->funcIdx].arity == 1);
return runtimeApply(ident, 1, &tree, pos);
}
} else if (eqTypes(ident->type, LACLOSURE)) {
// FIXME fix for closure? check arity?
Closure* f = asClosure(ident);
assert(fs->functions[f->funcIdx].arity == 1);
return runtimeApply(ident, 1, &tree, pos);
}
return (Box*) boxError(&UNIMPLEMENTED_SELECT);
}
int8_t runtimeIsConstr(Box* value, Box* constrName) {
if (isUserType(value)) {
String* name = unbox(LASTRING, constrName);
Data* data = findDataType(value->type);
DataValue* dv = asDataValue(value);
String* realConstrName = data->constructors[dv->tag]->name;
if (strncmp(realConstrName->bytes, name->bytes, fmin(realConstrName->length, name->length)) == 0)
return true;
}
return false;
}
int8_t runtimeCheckTag(Box* value, int64_t tag) {
DataValue* dv = asDataValue(value);
return dv->tag == tag;
}
/* =================== Arrays ================= */
Array* createArray(size_t size) {
Array * array = gcMalloc(sizeof(Array) + sizeof(Box*) * size);
array->type = LAARRAY;
array->length = size;
return array;
}
Box* boxArray(size_t size, ...) {
va_list argp;
Array * array = createArray(size);
va_start (argp, size);
for (int64_t i = 0; i < size; i++) {
Box* arg = va_arg(argp, Box*);
array->data[i] = arg;
}
va_end (argp); /* Clean up. */
return box(LAARRAY, array);
}
String* __attribute__ ((pure)) makeString(const char * str) {
size_t len = strlen(str);
String* val = gcMalloc(sizeof(String) + len + 1); // null terminated
val->type = LASTRING;
val->length = len;
strncpy(val->bytes, str, len);
return val;
}
String* joinValues(int size, Box* values[], char* start, char* end) {
String* strings[size];
int startLen = strlen(start);
int endLen = strlen(end);
int resultSize = startLen + endLen + 1 + 2 * size;
for (int i = 0; i < size; i++) {
Box* elem = values[i];
String* value = toString(elem);
resultSize += value->length;
strings[i] = value;
}
char * result = malloc(resultSize);
strcpy(result, start);
for (int i = 0; i < size; i++) {
String* value = strings[i];
strcat(result, value->bytes);
if (i + 1 < size) strcat(result, ", ");
}
strcat(result, end);
String* string = makeString(result);
free(result);
return string;
}
String* __attribute__ ((pure)) arrayToString(const Box* arrayValue) {
Array* array = unbox(LAARRAY, arrayValue);
if (array->length == 0) {
return makeString("[]");
} else {
return joinValues(array->length, array->data, "[", "]");
}
}
String* typeOf(Box* value) {
return makeString(value->type->name);
}
String* __attribute__ ((pure)) byteArrayToString(const Box* arrayValue) {
String* array = unbox(LABYTEARRAY, arrayValue);
if (array->length == 0) {
return makeString("[]");
} else {
int len = 6 * array->length + 2 + 1; // max (4 + 2 (separator)) symbols per byte + [] + 0
String* res = gcMalloc(sizeof(String) + len);
res->type = LASTRING;
strcpy(res->bytes, "[");
char buf[7];
int curPos = 1;
for (int i = 0; i < array->length; i++) {
int l = (i < array->length - 1) ?
snprintf(buf, 7, "%"PRId8", ", array->bytes[i]) : snprintf(buf, 5, "%"PRId8, array->bytes[i]);
strcpy(res->bytes + curPos, buf);
curPos += l;
}
strcpy(res->bytes + curPos, "]");
res->length = curPos + 1;
return res;
}
}
bool isNull(Box* value) {
return value == NULL;
}
Box* unsafeNull() {
return NULL;
}
/* =============== Strings ============= */
String* __attribute__ ((pure)) toString(const Box* value) {
char buf[100]; // 100 chars is enough for all (c)
if (value == NULL) return makeString("<NULL>");
const LaType* type = value->type;
if (eqTypes(type, LAUNIT)) {
return UNIT_STRING;
} else if (eqTypes(type, LABOOL)) {
return makeString(asBool(value)->num == 0 ? "false" : "true");
} else if (eqTypes(type, LAINT)) {
snprintf(buf, 100, "%"PRId64, asInt(value)->num);
return makeString(buf);
} else if (eqTypes(type, LAINT16)) {
snprintf(buf, 100, "%"PRId16, asInt16(value)->num);
return makeString(buf);
} else if (eqTypes(type, LAINT32)) {
snprintf(buf, 100, "%"PRId32, asInt32(value)->num);
return makeString(buf);
} else if (eqTypes(type, LABYTE)) {
snprintf(buf, 100, "%"PRId8, asByte(value)->num);
return makeString(buf);
} else if (eqTypes(type, LAFLOAT64)) {
snprintf(buf, 100, "%12.9lf", asFloat(value)->num);
return makeString(buf);
} else if (eqTypes(type, LASTRING)) {
return asString(value);
} else if (eqTypes(type, LACLOSURE)) {
return makeString("<func>");
} else if (eqTypes(type, LAARRAY)) {
return arrayToString(value);
} else if (eqTypes(type, LABYTEARRAY)) {
return byteArrayToString(value);
} else if (eqTypes(type, VAR)) {
DataValue* dataValue = asDataValue(value);
return toString(dataValue->values[0]);
} else if (eqTypes(type, UNKNOWN)) {
String *name = ((Unknown *) value)->error;
printf("AAAA!!! Undefined identifier in toString %s\n", name->bytes);
exit(1);
} else {
if (isUserType(value)) {
DataValue* dataValue = asDataValue(value);
Data* metaData = findDataType(type);
Struct* constr = metaData->constructors[dataValue->tag];
int64_t startlen = constr->name->length + 2; // ending 0 and possibly "(" if constructor has parameters
char start[startlen];
snprintf(start, startlen, "%s", constr->name->bytes);
if (constr->numFields > 0) {
strcat(start, "(");
return joinValues(constr->numFields, dataValue->values, start, ")");
} else return makeString(start);
} else {
printf("Unsupported type %s", typeIdToName(value->type));
exit(1);
}
}
}
String* concat(Box* arrayString) {
Array* array = unbox(LAARRAY, arrayString);
String* result = &EMPTY_STRING;
if (array->length > 0) {
int64_t len = 0;
for (int64_t i = 0; i < array->length; i++) {
String* s = unbox(LASTRING, array->data[i]);
len += s->length;
}
String* val = gcMalloc(sizeof(String) + len + 1); // +1 for null-termination
val->type = LASTRING;
// val->length is 0, because gcMalloc allocates zero-initialized memory
// it's also zero terminated, because gcMalloc allocates zero-initialized memory
for (int64_t i = 0; i < array->length; i++) {
String* s = unbox(LASTRING, array->data[i]);
memcpy(&val->bytes[val->length], s->bytes, s->length);
val->length += s->length;
}
result = val;
}
return result;
}
int64_t lascaXXHash(const void* buffer, size_t length, unsigned long long const seed) {
return (int64_t) XXH64(buffer, length, seed);
}
unsigned long long xxHashSeed = 0;
XXH_errorcode lascaGetHashable(Box* value, XXH64_state_t* const state) {
if (value == NULL) return XXH64_update(state, NULL, 0);
const LaType* type = value->type;
if (eqTypes(type, LAUNIT)) {
return XXH64_update(state, &UNIT_SINGLETON, sizeof(UNIT_SINGLETON));
} else if (eqTypes(type, LABOOL)) {
return XXH64_update(state, (char*) &asBool(value)->num, sizeof(asBool(value)->num));
} else if (eqTypes(type, LAINT)) {
return XXH64_update(state, (char*) &asInt(value)->num, sizeof(asInt(value)->num));
} else if (eqTypes(type, LAINT16)) {
return XXH64_update(state, (char*) &asInt16(value)->num, sizeof(asInt16(value)->num));
} else if (eqTypes(type, LAINT32)) {
return XXH64_update(state, (char*) &asInt32(value)->num, sizeof(asInt32(value)->num));
} else if (eqTypes(type, LABYTE)) {
return XXH64_update(state, (char*) &asByte(value)->num, sizeof(asByte(value)->num));
} else if (eqTypes(type, LAFLOAT64)) {
return XXH64_update(state, (char*) &asFloat(value)->num, sizeof(asFloat(value)->num));
} else if (eqTypes(type, LASTRING)) {
String* s = asString(value);
return XXH64_update(state, s->bytes, s->length);
} else if (eqTypes(type, LACLOSURE)) {
return XXH64_update(state, (char*) &value, sizeof(Closure));
} else if (eqTypes(type, LAARRAY)) {
Array* array = asArray(value);
for (size_t i = 0; i < array->length; i++) {
lascaGetHashable(array->data[i], state);
}
return XXH_OK;
} else if (eqTypes(type, LABYTEARRAY)) {
String* s = asString(value);
return XXH64_update(state, s->bytes, s->length);
} else if (eqTypes(type, VAR)) {
DataValue* dataValue = asDataValue(value);
return lascaGetHashable(dataValue->values[0], state);
} else if (eqTypes(type, UNKNOWN)) {
String *name = ((Unknown *) value)->error;
printf("AAAA!!! Undefined identifier in toString %s\n", name->bytes);
exit(1);
} else {
if (isUserType(value)) {
DataValue* dataValue = asDataValue(value);
Data* metaData = findDataType(type);
Struct* constr = metaData->constructors[dataValue->tag];
for (size_t i = 0; i < constr->numFields; i++) {
lascaGetHashable(dataValue->values[i], state);
}
return XXH_OK;
} else {
printf("Unsupported type %s", typeIdToName(value->type));
exit(1);
}
}
}
int64_t lascaHashCode(Box* value) {
XXH64_state_t* const state = XXH64_createState();
XXH_errorcode const resetResult = XXH64_reset(state, xxHashSeed);
lascaGetHashable(value, state);
return (int64_t) XXH64_digest(state);
}
/* ============ System ================ */
void initEnvironment(int64_t argc, char* argv[]) {
// int64_t len = 0;
// for (int64_t i = 0; i< argc; i++) len += strlen(argv[i]);
// char buf[len + argc*2 + 10];
// for (int64_t i = 0; i < argc; i++) {
// strcat(buf, argv[i]);
// strcat(buf, " ");
// }
// printf("Called with %d \n", argc);
ENV.argc = argc;
Array* array = createArray(argc);
for (int64_t i = 0; i < argc; i++) {
Box* s = (Box *) makeString(argv[i]);
array->data[i] = s;
}
ENV.argv = box(LAARRAY, array);
}
Box* getArgs() {
return ENV.argv;
}
int8_t intToByte(int64_t n) {
return (int8_t) n;
}
int64_t byteToInt(int8_t n) {
return (int64_t) n;
}
int16_t intToInt16(int64_t n) {
return (int16_t) n;
}
int64_t int16ToInt(int16_t n) {
return (int64_t) n;
}
int32_t intToInt32(int64_t n) {
return (int32_t) n;
}
int64_t int32ToInt(int32_t n) {
return (int64_t) n;
}
double intToFloat64(int64_t n) {
return (double) n;
}
int64_t float64ToInt(double n) {
return (int64_t) n;
}
int64_t toInt(Box* s) {
String* str = unbox(LASTRING, s);
// println(s);
char cstr[str->length + 1];
memcpy(cstr, str->bytes, str->length); // TODO use VLA?
cstr[str->length] = 0;
// printf("cstr = %s\n", cstr);
char *ep;
long i = strtol(cstr, &ep, 10);
if (cstr == ep) {
printf("Couldn't convert %s to int64_t", cstr);
exit( EXIT_FAILURE );
}
return (int64_t) i;
}
void onexit() {
struct GC_prof_stats_s stats;
GC_get_prof_stats(&stats, sizeof(stats));
printf("GC stats:\n");
printf("\tFinal heap size is %lu MiB\n", (unsigned long)GC_get_heap_size() / 1024 / 1024);
printf("\tNumber of collections %lu\n", stats.gc_no);
printf("\tTotal allocated %zu MiB\n", GC_get_total_bytes() / 1024 / 1024);
printf("\tTotal allocated %"PRIu64" MiB\n", Lasca_Allocated / 1024 / 1024);
printf("\tNumber of allocations: %"PRIu64"\n", Lasca_Nr_gcMalloc);
printf("\tAverage alloc: %"PRIu64" bytes\n", Lasca_Allocated / Lasca_Nr_gcMalloc);
}
void initLascaRuntime(Runtime* runtime) {
GC_init();
GC_expand_hp(4*1024*1024);
xxHashSeed = 0xe606946923239b1c; // FIXME implement reading /dev/urandom
RUNTIME = runtime;
UNIT_STRING = makeString("()");
for (int i = 0; i < 256; i++) {
BYTE_ARRAY[i].type = LABYTE;
BYTE_ARRAY[i].num = i - 128;
}
for (int i = 0; i < 100; i++) {
INT_ARRAY[i].type = LAINT;
INT_ARRAY[i].num = i;
}
if (runtime->verbose) {
atexit(onexit);
printf("Init Lasca 0.0.2 runtime. Enjoy :)\n# funcs = %"PRId64
", # structs = %"PRId64", utf8proc version %s\n",
RUNTIME->functions->size, RUNTIME->types->size, utf8proc_version());
for (int i = 0; i < RUNTIME->types->size; i++) {
printf("Type %s\n", RUNTIME->types->data[i]->type->name);
}
}
}
| 2 | 2 |
2024-11-18T22:49:18.738908+00:00 | 2018-07-12T14:17:27 | dc9135385ababb0cd3952487052ada4e147287a3 | {
"blob_id": "dc9135385ababb0cd3952487052ada4e147287a3",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-12T14:17:27",
"content_id": "06a438395288120a1f70f16e064527d21acc4caf",
"detected_licenses": [
"MIT"
],
"directory_id": "deb4061ba61fce5a9438f2441b39340243bd033d",
"extension": "c",
"filename": "get_next_line.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 140722191,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1994,
"license": "MIT",
"license_type": "permissive",
"path": "/usefull/get_next_line.c",
"provenance": "stackv2-0108.json.gz:95601",
"repo_name": "Antoine340/42sh---simple-terminal",
"revision_date": "2018-07-12T14:17:27",
"revision_id": "18d60a86d4fa944779b323263f4ee52226e2313d",
"snapshot_id": "5529008e4d429feb2fc6bd15358e9af653a0f6a6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Antoine340/42sh---simple-terminal/18d60a86d4fa944779b323263f4ee52226e2313d/usefull/get_next_line.c",
"visit_date": "2020-03-22T21:55:37.017421"
} | stackv2 | /*
** get_next_line.c for get_next_line in /home/chenne_a/rendu/CPE_2015_getnextline
**
** Made by Arthur Chennetier
** Login <chenne_a@epitech.net>
**
** Started on Mon Jan 4 09:34:19 2016 Arthur Chennetier
** Last update Fri Jun 3 18:51:55 2016 arthur
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "get_next_line.h"
#include "minishell.h"
char *my_realloc(char *str, int size_t)
{
char *tmp;
int j;
j = 0;
if (size_t == 0)
{
free(str);
return (NULL);
}
tmp = malloc(sizeof(char) * size_t);
if (tmp == NULL)
return (NULL);
while (j < size_t && str[j] != '\0')
{
tmp[j] = str[j];
j = j + 1;
}
free(str);
tmp[j] = '\0';
return (tmp);
}
char *check_read(int *i, int *size, int fd, char *buffer)
{
if (*i == *size)
{
if ((*size = read(fd, buffer, READ_SIZE)) == -1 || *size == 0)
{
free(buffer);
return (NULL);
}
*i = 0;
}
return (buffer);
}
char get_next_char(const int fd)
{
char l;
static int i = 0;
static int size = -42;
static char *buffer;
if (size == -42)
{
if ((buffer = malloc(sizeof(char) * READ_SIZE)) == NULL)
exit(EXIT_FAILURE);
if ((size = read(fd, buffer, READ_SIZE)) == -1 || size == 0)
{
free(buffer);
return (4);
}
}
if ((buffer = check_read(&i, &size, fd, buffer)) == NULL)
return (4);
l = buffer[i];
i = i + 1;
if (l == '\n')
return (0);
return (l);
}
char *get_next_line(const int fd)
{
char *result;
int j;
static int indic = 0;
j = 0;
if (indic == 1 || READ_SIZE < 1)
return (NULL);
if ((result = malloc(sizeof(char) * READ_SIZE + 1)) == NULL)
exit(EXIT_FAILURE);
result[READ_SIZE] = '\0';
while ((result[j] = get_next_char(fd)) != 0)
{
if (j % READ_SIZE == 0 && j != 0)
result = my_realloc(result, READ_SIZE + j + 1);
if (result[j] == 4)
{
free(result);
exit(fail);
}
j = j + 1;
}
return (result);
}
| 3.15625 | 3 |
2024-11-18T22:49:19.889990+00:00 | 2021-04-26T14:17:48 | c5bb85c735ea2ed111acedb7f0f4ea862294af53 | {
"blob_id": "c5bb85c735ea2ed111acedb7f0f4ea862294af53",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-26T14:18:57",
"content_id": "eaa06bc0c6764eb3c0a634c5505353b489aae2fd",
"detected_licenses": [
"BSD-3-Clause",
"Apache-2.0"
],
"directory_id": "65163bfb788e003e95a2d7d5ee23feb8738bc2c7",
"extension": "c",
"filename": "ipcStockMessagesPojo.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 25249,
"license": "BSD-3-Clause,Apache-2.0",
"license_type": "permissive",
"path": "/source/libs/ipc/c/src/ipcStockMessagesPojo.c",
"provenance": "stackv2-0108.json.gz:95862",
"repo_name": "Dhanunjaya-rama/zilker-sdk",
"revision_date": "2021-04-26T14:17:48",
"revision_id": "c5663624a559901bbb2f47bc3ab80179be6892b2",
"snapshot_id": "1cb9068b82b614b575752525eac2b5e50f4ed843",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Dhanunjaya-rama/zilker-sdk/c5663624a559901bbb2f47bc3ab80179be6892b2/source/libs/ipc/c/src/ipcStockMessagesPojo.c",
"visit_date": "2023-04-19T21:50:43.975287"
} | stackv2 | /*
* Copyright 2021 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
/*-----------------------------------------------
* ipcStockMessagesPojo.c
*
*
* Define the standard/stock set of IPC messages that
* ALL services should handle. Over time this may grow,
* but serves the purpose of creating well-known IPC
* messages without linking in superfluous API libraries
* or relying on convention.
*
* Author: jelderton - 3/2/16
*-----------------------------------------------*/
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <stdio.h>
#include "icIpc/ipcStockMessagesPojo.h"
/*
* 'create' function for serviceStatusPojo
*/
serviceStatusPojo *create_serviceStatusPojo()
{
// allocate wrapper
serviceStatusPojo *retVal = (serviceStatusPojo *)malloc(sizeof(serviceStatusPojo));
memset(retVal, 0, sizeof(serviceStatusPojo));
// create dynamic data-types (arrays & maps)
retVal->statusMap = hashMapCreate();
return retVal;
}
/*
* 'destroy' function for serviceStatusPojo
*/
void destroy_serviceStatusPojo(serviceStatusPojo *pojo)
{
if (pojo == NULL)
{
return;
}
// destroy dynamic data-structures (arrays & maps)
hashMapDestroy(pojo->statusMap, NULL);
// now the wrapper
free(pojo);
}
/*
* extract value for 'key' of type 'char' from the hash map 'map' contained in 'serviceStatusPojo'
*/
char *get_string_from_serviceStatusPojo(serviceStatusPojo *pojo, const char *key)
{
if (pojo != NULL && key != NULL)
{
char *val = hashMapGet(pojo->statusMap, (void *)key, (uint16_t)strlen(key));
if (val != NULL)
{
return val;
}
}
return NULL;
}
/*
* set/add value for 'key' of type 'char' into the hash map 'map' contained in 'serviceStatusPojo
* NOTE: will clone key & value to keep memory management of internal icHashMap simple
*/
void put_string_in_serviceStatusPojo(serviceStatusPojo *pojo, const char *key, char *value)
{
if (pojo != NULL && key != NULL && value != NULL)
{
// create copy of 'key' and the supplied 'value' into the map.
// they will be released when our 'destroy_serviceStatusPojo' is called
//
uint16_t keyLen = (uint16_t)strlen(key);
hashMapPut(pojo->statusMap, (void *)strdup(key), keyLen, strdup(value));
}
}
/*
* set/add value for 'key' of type 'int32_t' into the hash map 'stats' contained in 'serviceStatusPojo
* NOTE: will clone key & value to keep memory management of internal icHashMap simple
*/
void put_int_in_serviceStatusPojo(serviceStatusPojo *pojo, const char *key, int32_t value)
{
if (pojo != NULL && key != NULL)
{
// create copy of 'key' and 'value', then place into the map.
// they will be released when our 'destroy_serviceStatusPojo' is called
//
uint16_t keyLen = (uint16_t)strlen(key);
char buffer[128];
sprintf(buffer, "%"PRIi32, value);
hashMapPut(pojo->statusMap, (void *)strdup(key), keyLen, strdup(buffer));
}
}
/*
* 'encode to JSON' function for serviceStatusPojo
*/
cJSON *encode_serviceStatusPojo_toJSON(serviceStatusPojo *pojo)
{
// create new JSON container object
cJSON *root = cJSON_CreateObject();
// create JSON object for serviceStatusPojo
cJSON *serviceStatusPojo_json = NULL;
serviceStatusPojo_json = cJSON_CreateObject();
if (pojo->statusMap != NULL)
{
// need 2 structures to allow proper decoding later on
// 1 - values
// 2 - keys
cJSON *mapVals_json = cJSON_CreateObject();
cJSON *mapKeys_json = cJSON_CreateArray();
// add each value & key
icHashMapIterator *map_loop = hashMapIteratorCreate(pojo->statusMap);
while (hashMapIteratorHasNext(map_loop) == true)
{
void *mapKey;
void *mapVal;
uint16_t mapKeyLen = 0;
// get the key & value
//
hashMapIteratorGetNext(map_loop, &mapKey, &mapKeyLen, &mapVal);
if (mapKey == NULL || mapVal == NULL)
{
continue;
}
// assume string, since thats all we have get/set functions for
//
char *c = (char *)mapVal;
cJSON_AddStringToObject(mapVals_json, mapKey, c);
cJSON_AddItemToArray(mapKeys_json, cJSON_CreateString(mapKey));
}
hashMapIteratorDestroy(map_loop);
// add both containers to the parent
//
cJSON_AddItemToObject(serviceStatusPojo_json, "mapVals", mapVals_json);
cJSON_AddItemToObject(serviceStatusPojo_json, "mapKeys", mapKeys_json);
}
cJSON_AddItemToObject(root, "serviceStatusPojo", serviceStatusPojo_json);
return root;
}
/*
* 'decode from JSON' function for serviceStatusPojo
*/
int decode_serviceStatusPojo_fromJSON(serviceStatusPojo *pojo, cJSON *buffer)
{
int rc = -1;
cJSON *item = NULL;
if (buffer != NULL)
{
// extract JSON object for serviceStatusPojo
cJSON *serviceStatusPojo_json = NULL;
serviceStatusPojo_json = cJSON_GetObjectItem(buffer, (const char *)"serviceStatusPojo");
if (serviceStatusPojo_json != NULL)
{
// get the 2 structures added during encoding:
// 1 - values
// 2 - keys
cJSON *mapVals_json = cJSON_GetObjectItem(serviceStatusPojo_json, "mapVals");
cJSON *mapKeys_json = cJSON_GetObjectItem(serviceStatusPojo_json, "mapKeys");
if (mapVals_json != NULL && mapKeys_json != NULL)
{
// loop through keys to extract values and types
//
int i;
int size = cJSON_GetArraySize(mapKeys_json);
for (i = 0 ; i < size ; i++)
{
// get the next key
//
cJSON *key = cJSON_GetArrayItem(mapKeys_json, i);
if (key == NULL || key->valuestring == NULL)
{
continue;
}
// pull it's value
//
item = cJSON_GetObjectItem(mapVals_json, key->valuestring);
if (item == NULL)
{
continue;
}
// assume string, since that's all we have get/set functions for
//
put_string_in_serviceStatusPojo(pojo, key->valuestring, item->valuestring);
}
}
}
}
return rc;
}
/*
* 'create' function for runtimeStatsPojo
*/
runtimeStatsPojo *create_runtimeStatsPojo()
{
// allocate wrapper
runtimeStatsPojo *retVal = (runtimeStatsPojo *)malloc(sizeof(runtimeStatsPojo));
memset(retVal, 0, sizeof(runtimeStatsPojo));
// create dynamic data-types (arrays & maps)
retVal->valuesMap = hashMapCreate();
retVal->typesMap = hashMapCreate();
return retVal;
}
/*
* 'destroy' function for runtimeStatsPojo
*/
void destroy_runtimeStatsPojo(runtimeStatsPojo *pojo)
{
if (pojo == NULL)
{
return;
}
// destroy dynamic data-structures (arrays & maps)
// destroy both hash-maps along with all keys/values
hashMapDestroy(pojo->valuesMap, NULL);
hashMapDestroy(pojo->typesMap, NULL);
// now the wrapper
free(pojo);
}
/*
* return number of items in the hash map 'map' contained in 'runtimeStatsPojo'
*/
uint16_t get_count_of_runtimeStatsPojo(runtimeStatsPojo *pojo)
{
return hashMapCount(pojo->valuesMap);
}
/*
* return the 'type' of data contained for a key. needed in situations where
* the data is unknown, and need way to determine which "get" function to use.
*
* returns one of: 'string', 'date', 'int', 'long', NULL
* caller should NOT remove the memory returned.
*/
char *get_valueType_from_runtimeStatsPojo(runtimeStatsPojo *pojo, const char *key)
{
// find corresponding 'type'
//
return (char *)hashMapGet(pojo->typesMap, (void *)key, (uint16_t)strlen(key));
}
/*
* extract value for 'key' of type 'char' from the hash map 'map' contained in 'runtimeStatsPojo'
*/
char *get_string_from_runtimeStatsPojo(runtimeStatsPojo *pojo, const char *key)
{
if (pojo != NULL && key != NULL)
{
char *val = hashMapGet(pojo->valuesMap, (void *)key, (uint16_t)strlen(key));
if (val != NULL)
{
return val;
}
}
return NULL;
}
/*
* extract value for 'key' of type 'uint64_t' from the hash map 'stats' contained in 'runtimeStatsPojo'
*/
uint64_t get_date_from_runtimeStatsPojo(runtimeStatsPojo *pojo, const char *key)
{
if (pojo != NULL && key != NULL)
{
uint64_t *val = hashMapGet(pojo->valuesMap, (void *)key, (uint16_t)strlen(key));
if (val != NULL)
{
return *val;
}
}
return (uint64_t)0;
}
/*
* extract value for 'key' of type 'int32_t' from the hash map 'stats' contained in 'runtimeStatsPojo'
*/
int32_t get_int_from_runtimeStatsPojo(runtimeStatsPojo *pojo, const char *key)
{
if (pojo != NULL && key != NULL)
{
int32_t *val = hashMapGet(pojo->valuesMap, (void *)key, (uint16_t)strlen(key));
if (val != NULL)
{
return *val;
}
}
return (int32_t)-1;
}
/*
* extract value for 'key' of type 'int64_t' from the hash map 'stats' contained in 'runtimeStatsPojo'
*/
int64_t get_long_from_runtimeStatsPojo(runtimeStatsPojo *pojo, const char *key)
{
if (pojo != NULL && key != NULL)
{
int64_t *val = hashMapGet(pojo->valuesMap, (void *)key, (uint16_t)strlen(key));
if (val != NULL)
{
return *val;
}
}
return (int64_t)-1;
}
/*
* set/add value for 'key' of type 'char' into the hash map 'map' contained in 'runtimeStatsPojo
* NOTE: will clone key & value to keep memory management of internal icHashMap simple
*/
void put_string_in_runtimeStatsPojo(runtimeStatsPojo *pojo, const char *key, char *value)
{
if (pojo != NULL && key != NULL && value != NULL)
{
// create copy of 'key' and the supplied 'value' into the map.
// they will be released when our 'destroy_runtimeStatsPojo' is called
//
uint16_t keyLen = (uint16_t)strlen(key);
hashMapPut(pojo->valuesMap, (void *)strdup(key), keyLen, strdup(value));
hashMapPut(pojo->typesMap, (void *)strdup(key), keyLen, strdup("string"));
}
}
/*
* set/add value for 'key' of type 'uint64_t' into the hash map 'stats' contained in 'runtimeStatsPojo
* NOTE: will clone key & value to keep memory management of internal icHashMap simple
*/
void put_date_in_runtimeStatsPojo(runtimeStatsPojo *pojo, const char *key, uint64_t value)
{
if (pojo != NULL && key != NULL)
{
// create copy of 'key' and 'value', then place into the map.
// they will be released when our 'destroy_runtimeStatsPojo' is called
//
uint16_t keyLen = (uint16_t)strlen(key);
uint64_t *valCopy = (uint64_t *)malloc(sizeof(uint64_t));
*valCopy = value;
hashMapPut(pojo->valuesMap, (void *)strdup(key), keyLen, valCopy);
hashMapPut(pojo->typesMap, (void *)strdup(key), keyLen, strdup("date"));
}
}
/*
* set/add value for 'key' of type 'int32_t' into the hash map 'stats' contained in 'runtimeStatsPojo
* NOTE: will clone key & value to keep memory management of internal icHashMap simple
*/
void put_int_in_runtimeStatsPojo(runtimeStatsPojo *pojo, const char *key, int32_t value)
{
if (pojo != NULL && key != NULL)
{
// create copy of 'key' and 'value', then place into the map.
// they will be released when our 'destroy_runtimeStatsPojo' is called
//
uint16_t keyLen = (uint16_t)strlen(key);
int32_t *valCopy = (int32_t *)malloc(sizeof(int32_t));
*valCopy = value;
hashMapPut(pojo->valuesMap, (void *)strdup(key), keyLen, valCopy);
hashMapPut(pojo->typesMap, (void *)strdup(key), keyLen, strdup("int"));
}
}
/*
* set/add value for 'key' of type 'int64_t' into the hash map 'stats' contained in 'runtimeStatsPojo
* NOTE: will clone key & value to keep memory management of internal icHashMap simple
*/
void put_long_in_runtimeStatsPojo(runtimeStatsPojo *pojo, const char *key, int64_t value)
{
if (pojo != NULL && key != NULL)
{
// create copy of 'key' and 'value', then place into the map.
// they will be released when our 'destroy_runtimeStatsPojo' is called
//
uint16_t keyLen = (uint16_t)strlen(key);
int64_t *valCopy = (int64_t *)malloc(sizeof(int64_t));
*valCopy = value;
hashMapPut(pojo->valuesMap, (void *)strdup(key), keyLen, valCopy);
hashMapPut(pojo->typesMap, (void *)strdup(key), keyLen, strdup("long"));
}
}
/*
* 'encode to JSON' function for runtimeStatsPojo
*/
cJSON *encode_runtimeStatsPojo_toJSON(runtimeStatsPojo *pojo)
{
// create new JSON container object
cJSON *root = cJSON_CreateObject();
// create JSON object for runtimeStatsPojo
cJSON *runtimeStatsPojo_json = NULL;
runtimeStatsPojo_json = cJSON_CreateObject();
if (pojo->serviceName != NULL)
{
cJSON_AddStringToObject(runtimeStatsPojo_json, "serviceName", pojo->serviceName);
}
cJSON_AddNumberToObject(runtimeStatsPojo_json, "collectionTime", (double)pojo->collectionTime);
if (pojo->valuesMap != NULL && pojo->typesMap != NULL)
{
// need 3 structures to allow proper decoding later on
// 1 - values
// 2 - types
// 3 - keys
cJSON *mapVals_json = cJSON_CreateObject();
cJSON *mapTypes_json = cJSON_CreateObject();
cJSON *mapKeys_json = cJSON_CreateArray();
// add each value & type
icHashMapIterator *map_loop = hashMapIteratorCreate(pojo->valuesMap);
while (hashMapIteratorHasNext(map_loop) == true)
{
void *mapKey;
void *mapVal;
uint16_t mapKeyLen = 0;
// get the key & value
//
hashMapIteratorGetNext(map_loop, &mapKey, &mapKeyLen, &mapVal);
if (mapKey == NULL || mapVal == NULL)
{
continue;
}
// find corresponding 'type'
//
char *kind = (char *)hashMapGet(pojo->typesMap, mapKey, mapKeyLen);
if (kind == NULL)
{
continue;
}
// convert for each possible 'type'
if (strcmp(kind, "string") == 0)
{
char *c = (char *)mapVal;
cJSON_AddStringToObject(mapVals_json, mapKey, c);
}
else if (strcmp(kind, "date") == 0)
{
uint64_t *t = (uint64_t *)mapVal;
cJSON_AddNumberToObject(mapVals_json, mapKey, *t);
}
else if (strcmp(kind, "int") == 0)
{
int32_t *n = (int32_t *)mapVal;
cJSON_AddNumberToObject(mapVals_json, mapKey, *n);
}
else if (strcmp(kind, "long") == 0)
{
int64_t *n = (int64_t *)mapVal;
cJSON_AddNumberToObject(mapVals_json, mapKey, *n);
}
// save the key & type for decode
//
cJSON_AddStringToObject(mapTypes_json, mapKey, kind);
cJSON_AddItemToArray(mapKeys_json, cJSON_CreateString(mapKey));
}
hashMapIteratorDestroy(map_loop);
// add all 3 containers to the parent
//
cJSON_AddItemToObject(runtimeStatsPojo_json, "mapVals", mapVals_json);
cJSON_AddItemToObject(runtimeStatsPojo_json, "mapTypes", mapTypes_json);
cJSON_AddItemToObject(runtimeStatsPojo_json, "mapKeys", mapKeys_json);
}
cJSON_AddItemToObject(root, "runtimeStatsPojo", runtimeStatsPojo_json);
return root;
}
/*
* 'decode from JSON' function for runtimeStatsPojo
*/
int decode_runtimeStatsPojo_fromJSON(runtimeStatsPojo *pojo, cJSON *buffer)
{
int rc = -1;
cJSON *item = NULL;
if (buffer != NULL)
{
// extract JSON object for runtimeStatsPojo
cJSON *runtimeStatsPojo_json = NULL;
runtimeStatsPojo_json = cJSON_GetObjectItem(buffer, (const char *)"runtimeStatsPojo");
if (runtimeStatsPojo_json != NULL)
{
item = cJSON_GetObjectItem(runtimeStatsPojo_json, "serviceName");
if (item != NULL && item->valuestring != NULL)
{
pojo->serviceName = strdup(item->valuestring);
rc = 0;
}
item = cJSON_GetObjectItem(runtimeStatsPojo_json, "collectionTime");
if (item != NULL)
{
pojo->collectionTime = (uint64_t)item->valuedouble;
rc = 0;
}
// get the 3 structures added during encoding:
// 1 - values
// 2 - types
// 3 - keys
cJSON *mapVals_json = cJSON_GetObjectItem(runtimeStatsPojo_json, "mapVals");
cJSON *mapTypes_json = cJSON_GetObjectItem(runtimeStatsPojo_json, "mapTypes");
cJSON *mapKeys_json = cJSON_GetObjectItem(runtimeStatsPojo_json, "mapKeys");
if (mapVals_json != NULL && mapTypes_json != NULL && mapKeys_json != NULL)
{
// loop through keys to extract values and types
//
int i;
int size = cJSON_GetArraySize(mapKeys_json);
for (i = 0 ; i < size ; i++)
{
// get the next key
//
cJSON *key = cJSON_GetArrayItem(mapKeys_json, i);
if (key == NULL || key->valuestring == NULL)
{
continue;
}
// pull it's type & value
//
cJSON *type = cJSON_GetObjectItem(mapTypes_json, key->valuestring);
if (type == NULL || type->valuestring == NULL)
{
continue;
}
item = cJSON_GetObjectItem(mapVals_json, key->valuestring);
if (item == NULL)
{
continue;
}
// convert for each possible 'type'
if (strcmp(type->valuestring, "string") == 0)
{
put_string_in_runtimeStatsPojo(pojo, key->valuestring, item->valuestring);
}
else if (strcmp(type->valuestring, "date") == 0)
{
put_date_in_runtimeStatsPojo(pojo, key->valuestring, (uint64_t)item->valuedouble);
}
else if (strcmp(type->valuestring, "int") == 0)
{
put_int_in_runtimeStatsPojo(pojo, key->valuestring, (int32_t)item->valueint);
}
else if (strcmp(type->valuestring, "long") == 0)
{
put_long_in_runtimeStatsPojo(pojo, key->valuestring, (int64_t)item->valuedouble);
}
}
}
}
}
return rc;
}
/*
* 'create' function for configRestoredInput
*/
configRestoredInput *create_configRestoredInput()
{
// allocate wrapper
//
configRestoredInput *retVal = (configRestoredInput *)malloc(sizeof(configRestoredInput));
memset(retVal, 0, sizeof(configRestoredInput));
return retVal;
}
/*
* 'destroy' function for configRestoredInput
*/
void destroy_configRestoredInput(configRestoredInput *pojo)
{
if (pojo == NULL)
{
return;
}
// destroy dynamic data-structures within the object
//
if (pojo->tempRestoreDir != NULL)
{
free(pojo->tempRestoreDir);
}
if (pojo->dynamicConfigPath != NULL)
{
free(pojo->dynamicConfigPath);
}
// now the wrapper
//
free(pojo);
}
/*
* 'encode to JSON' function for configRestoredInput
*/
cJSON *encode_configRestoredInput_toJSON(configRestoredInput *pojo)
{
// create new JSON container object
//
cJSON *root = cJSON_CreateObject();
// create JSON object for configRestoredInput
//
cJSON *configRestoredInput_json = NULL;
configRestoredInput_json = cJSON_CreateObject();
if (pojo->tempRestoreDir != NULL)
{
cJSON_AddStringToObject(configRestoredInput_json, "tempRestoreDir", pojo->tempRestoreDir);
}
if (pojo->dynamicConfigPath != NULL)
{
cJSON_AddStringToObject(configRestoredInput_json, "dynamicConfigPath", pojo->dynamicConfigPath);
}
cJSON_AddItemToObject(root, "configRestoredInput", configRestoredInput_json);
return root;
}
/*
* 'decode from JSON' function for configRestoredInput
*/
int decode_configRestoredInput_fromJSON(configRestoredInput *pojo, cJSON *buffer)
{
int rc = -1;
cJSON *item = NULL;
if (buffer != NULL)
{
// extract JSON object for configRestoredInput
//
cJSON *configRestoredInput_json = NULL;
configRestoredInput_json = cJSON_GetObjectItem(buffer, (const char *)"configRestoredInput");
if (configRestoredInput_json != NULL)
{
item = cJSON_GetObjectItem(configRestoredInput_json, "tempRestoreDir");
if (item != NULL && item->valuestring != NULL)
{
pojo->tempRestoreDir = strdup(item->valuestring);
rc = 0;
}
item = cJSON_GetObjectItem(configRestoredInput_json, "dynamicConfigPath");
if (item != NULL && item->valuestring != NULL)
{
pojo->dynamicConfigPath = strdup(item->valuestring);
rc = 0;
}
}
}
return rc;
}
/*
* 'create' function for configRestoredOutput
*/
configRestoredOutput *create_configRestoredOutput()
{
// allocate wrapper
configRestoredOutput *retVal = calloc(1, sizeof(configRestoredOutput));
pojo_init((Pojo *) retVal,
sizeof(configRestoredOutput),
(pojoDestructor) destroy_configRestoredOutput,
(pojoCloneFunc) clone_configRestoredOutput);
// create dynamic data-types (arrays & maps)
return retVal;
}
/*
* 'destroy' function for configRestoredOutput
*/
void destroy_configRestoredOutput(configRestoredOutput *pojo)
{
if (pojo == NULL)
{
return;
}
// destroy dynamic data-structures (arrays & maps)
// now the wrapper
pojo_free((Pojo *) pojo);
free(pojo);
}
/*
* create a deep clone of a configRestoredOutput object.
* should be release via destroy_configRestoredOutput()
*/
configRestoredOutput *clone_configRestoredOutput(configRestoredOutput *src)
{
if (src == NULL)
{
return NULL;
}
configRestoredOutput *copy = create_configRestoredOutput();
cJSON *json = encode_configRestoredOutput_toJSON(src);
decode_configRestoredOutput_fromJSON(copy, json);
cJSON_Delete(json);
return copy;
}
/*
* 'encode to JSON' function for configRestoredOutput
*/
cJSON *encode_configRestoredOutput_toJSON(configRestoredOutput *pojo)
{
// create new JSON container object
cJSON *root = cJSON_CreateObject();
// create JSON object for configRestoredOutput
cJSON *configRestoredOutput_json = NULL;
configRestoredOutput_json = cJSON_CreateObject();
cJSON_AddItemToObjectCS(configRestoredOutput_json, "action", cJSON_CreateNumber(pojo->action));
cJSON_AddItemToObjectCS(root, "configRestoredOutput", configRestoredOutput_json);
return root;
}
/*
* 'decode from JSON' function for configRestoredOutput
*/
int decode_configRestoredOutput_fromJSON(configRestoredOutput *pojo, cJSON *buffer)
{
int rc = -1;
cJSON *item = NULL;
if (buffer != NULL)
{
// extract JSON object for configRestoredOutput
cJSON *configRestoredOutput_json = NULL;
configRestoredOutput_json = cJSON_GetObjectItem(buffer, (const char *)"configRestoredOutput");
if (configRestoredOutput_json != NULL)
{
item = cJSON_GetObjectItem(configRestoredOutput_json, "action");
if (item != NULL)
{
pojo->action = (configRestoredAction)item->valueint;
rc = 0;
}
}
}
return rc;
}
| 2.203125 | 2 |
2024-11-18T22:49:19.947287+00:00 | 2018-10-28T07:14:20 | 89ff9df3fa660bde26e9833d0dcd2d5aee04d35e | {
"blob_id": "89ff9df3fa660bde26e9833d0dcd2d5aee04d35e",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-09T10:46:54",
"content_id": "f1f63875291d2dafdac1031996fa51ad67cc2fd1",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7cafcaef8a3caf17b11ca5a94d238ec0c89869c4",
"extension": "c",
"filename": "threads.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8182,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/helper/threads.c",
"provenance": "stackv2-0108.json.gz:95991",
"repo_name": "zjuan22/odp",
"revision_date": "2018-10-28T07:14:20",
"revision_id": "5d6ad599eb9f6b05d3890f2b0aae3746b8a2b73e",
"snapshot_id": "53485259ea6e389aa7782949e09cf7a0a4979001",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zjuan22/odp/5d6ad599eb9f6b05d3890f2b0aae3746b8a2b73e/helper/threads.c",
"visit_date": "2020-04-06T07:21:40.529979"
} | stackv2 | /* Copyright (c) 2013-2018, Linaro Limited
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "config.h"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <sched.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <odp_api.h>
#include <odp/helper/threads.h>
#include "odph_debug.h"
static struct {
int proc; /* true when process mode is required, false otherwise */
} helper_options;
/*
* wrapper for odpthreads, either implemented as linux threads or processes.
* (in process mode, if start_routine returns NULL, the process return FAILURE).
*/
static void *_odph_thread_run_start_routine(void *arg)
{
int status;
int ret;
odph_odpthread_params_t *thr_params;
odph_odpthread_start_args_t *start_args = arg;
thr_params = &start_args->thr_params;
/* ODP thread local init */
if (odp_init_local(thr_params->instance, thr_params->thr_type)) {
ODPH_ERR("Local init failed\n");
if (start_args->linuxtype == ODPTHREAD_PROCESS)
_exit(EXIT_FAILURE);
return (void *)-1;
}
ODPH_DBG("helper: ODP %s thread started as linux %s. (pid=%d)\n",
thr_params->thr_type == ODP_THREAD_WORKER ?
"worker" : "control",
(start_args->linuxtype == ODPTHREAD_PTHREAD) ?
"pthread" : "process",
(int)getpid());
status = thr_params->start(thr_params->arg);
ret = odp_term_local();
if (ret < 0)
ODPH_ERR("Local term failed\n");
/* for process implementation of odp threads, just return status... */
if (start_args->linuxtype == ODPTHREAD_PROCESS)
_exit(status);
/* threads implementation return void* pointers: cast status to that. */
return (void *)(intptr_t)status;
}
/*
* Create a single ODPthread as a linux process
*/
static int _odph_linux_process_create(odph_odpthread_t *thread_tbl,
int cpu,
const odph_odpthread_params_t *thr_params)
{
cpu_set_t cpu_set;
pid_t pid;
CPU_ZERO(&cpu_set);
CPU_SET(cpu, &cpu_set);
thread_tbl->start_args.thr_params = *thr_params; /* copy */
thread_tbl->start_args.linuxtype = ODPTHREAD_PROCESS;
thread_tbl->cpu = cpu;
pid = fork();
if (pid < 0) {
ODPH_ERR("fork() failed\n");
thread_tbl->start_args.linuxtype = ODPTHREAD_NOT_STARTED;
return -1;
}
/* Parent continues to fork */
if (pid > 0) {
thread_tbl->proc.pid = pid;
return 0;
}
/* Child process */
/* Request SIGTERM if parent dies */
prctl(PR_SET_PDEATHSIG, SIGTERM);
/* Parent died already? */
if (getppid() == 1)
kill(getpid(), SIGTERM);
if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set)) {
ODPH_ERR("sched_setaffinity() failed\n");
return -2;
}
_odph_thread_run_start_routine(&thread_tbl->start_args);
return 0; /* never reached */
}
/*
* Create a single ODPthread as a linux thread
*/
static int odph_linux_thread_create(odph_odpthread_t *thread_tbl,
int cpu,
const odph_odpthread_params_t *thr_params)
{
int ret;
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
CPU_SET(cpu, &cpu_set);
pthread_attr_init(&thread_tbl->thread.attr);
thread_tbl->cpu = cpu;
pthread_attr_setaffinity_np(&thread_tbl->thread.attr,
sizeof(cpu_set_t), &cpu_set);
thread_tbl->start_args.thr_params = *thr_params; /* copy */
thread_tbl->start_args.linuxtype = ODPTHREAD_PTHREAD;
ret = pthread_create(&thread_tbl->thread.thread_id,
&thread_tbl->thread.attr,
_odph_thread_run_start_routine,
&thread_tbl->start_args);
if (ret != 0) {
ODPH_ERR("Failed to start thread on cpu #%d\n", cpu);
thread_tbl->start_args.linuxtype = ODPTHREAD_NOT_STARTED;
return ret;
}
return 0;
}
/*
* create an odpthread set (as linux processes or linux threads or both)
*/
int odph_odpthreads_create(odph_odpthread_t *thread_tbl,
const odp_cpumask_t *mask,
const odph_odpthread_params_t *thr_params)
{
int i;
int num;
int cpu_count;
int cpu;
num = odp_cpumask_count(mask);
memset(thread_tbl, 0, num * sizeof(odph_odpthread_t));
cpu_count = odp_cpu_count();
if (num < 1 || num > cpu_count) {
ODPH_ERR("Invalid number of odpthreads:%d"
" (%d cores available)\n",
num, cpu_count);
return -1;
}
cpu = odp_cpumask_first(mask);
for (i = 0; i < num; i++) {
if (!helper_options.proc) {
if (odph_linux_thread_create(&thread_tbl[i],
cpu,
thr_params))
break;
} else {
if (_odph_linux_process_create(&thread_tbl[i],
cpu,
thr_params))
break;
}
cpu = odp_cpumask_next(mask, cpu);
}
thread_tbl[num - 1].last = 1;
return i;
}
/*
* wait for the odpthreads termination (linux processes and threads)
*/
int odph_odpthreads_join(odph_odpthread_t *thread_tbl)
{
pid_t pid;
int i = 0;
int terminated = 0;
/* child process return code (!=0 is error) */
int status = 0;
/* "child" thread return code (!NULL is error) */
void *thread_ret = NULL;
int ret;
int retval = 0;
/* joins linux threads or wait for processes */
do {
/* pthreads: */
switch (thread_tbl[i].start_args.linuxtype) {
case ODPTHREAD_PTHREAD:
/* Wait thread to exit */
ret = pthread_join(thread_tbl[i].thread.thread_id,
&thread_ret);
if (ret != 0) {
ODPH_ERR("Failed to join thread from cpu #%d\n",
thread_tbl[i].cpu);
retval = -1;
} else {
terminated++;
if (thread_ret != NULL) {
ODPH_ERR("Bad exit status cpu #%d %p\n",
thread_tbl[i].cpu, thread_ret);
retval = -1;
}
}
pthread_attr_destroy(&thread_tbl[i].thread.attr);
break;
case ODPTHREAD_PROCESS:
/* processes: */
pid = waitpid(thread_tbl[i].proc.pid, &status, 0);
if (pid < 0) {
ODPH_ERR("waitpid() failed\n");
retval = -1;
break;
}
terminated++;
/* Examine the child process' termination status */
if (WIFEXITED(status) &&
WEXITSTATUS(status) != EXIT_SUCCESS) {
ODPH_ERR("Child exit status:%d (pid:%d)\n",
WEXITSTATUS(status), (int)pid);
retval = -1;
}
if (WIFSIGNALED(status)) {
int signo = WTERMSIG(status);
ODPH_ERR("Child term signo:%d - %s (pid:%d)\n",
signo, strsignal(signo), (int)pid);
retval = -1;
}
break;
case ODPTHREAD_NOT_STARTED:
ODPH_DBG("No join done on not started ODPthread.\n");
break;
default:
ODPH_DBG("Invalid case statement value!\n");
break;
}
} while (!thread_tbl[i++].last);
return (retval < 0) ? retval : terminated;
}
/* man gettid() notes:
* Glibc does not provide a wrapper for this system call;
*/
static inline pid_t __gettid(void)
{
return (pid_t)syscall(SYS_gettid);
}
int odph_odpthread_setaffinity(const int cpu)
{
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(cpu, &cpuset);
/* determine main process or pthread based on
* equality of thread and thread group IDs.
*/
if (__gettid() == getpid()) {
return sched_setaffinity(
0, /* pid zero means calling process */
sizeof(cpu_set_t), &cpuset);
}
/* on error, they return a nonzero error number. */
return (0 == pthread_setaffinity_np(
pthread_self(), sizeof(cpu_set_t), &cpuset)) ? 0 : -1;
}
int odph_odpthread_getaffinity(void)
{
int cpu, result;
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
if (__gettid() == getpid()) {
result = sched_getaffinity(
0, sizeof(cpu_set_t), &cpuset);
} else {
result = pthread_getaffinity_np(
pthread_self(), sizeof(cpu_set_t), &cpuset);
}
/* ODP thread mean to run on single CPU core */
if ((result == 0) && (CPU_COUNT(&cpuset) == 1)) {
for (cpu = 0; cpu < CPU_SETSIZE; cpu++) {
if (CPU_ISSET(cpu, &cpuset))
return cpu;
}
}
return -1;
}
int odph_parse_options(int argc, char *argv[])
{
char *env;
int i, j;
helper_options.proc = 0;
/* Enable process mode using environment variable. Setting environment
* variable is easier for CI testing compared to command line
* argument. */
env = getenv("ODPH_PROC_MODE");
if (env && atoi(env))
helper_options.proc = 1;
/* Find and remove option */
for (i = 0; i < argc;) {
if (strcmp(argv[i], "--odph_proc") == 0) {
helper_options.proc = 1;
for (j = i; j < argc - 1; j++)
argv[j] = argv[j + 1];
argc--;
continue;
}
i++;
}
return argc;
}
| 2.671875 | 3 |
2024-11-18T22:49:20.153495+00:00 | 2021-09-03T03:06:50 | 47082a81e2d3a2a5e68ea272e8e2685372bd6b72 | {
"blob_id": "47082a81e2d3a2a5e68ea272e8e2685372bd6b72",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-03T03:06:50",
"content_id": "d44b5696ba36e70bd2bc495688fada2d0a93dd4c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e7053eb29b6a7fff81c7b1685b69e776e8ad81a0",
"extension": "h",
"filename": "pa2.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 399324510,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2409,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/pa2-malwake-git/pa2.h",
"provenance": "stackv2-0108.json.gz:96250",
"repo_name": "malwake-git/ECE368",
"revision_date": "2021-09-03T03:06:50",
"revision_id": "ea36be2ce4405a8da414daacf50d399123d75cd0",
"snapshot_id": "0a0b442361bad539bd87332c17f0ae3d053fcd2e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/malwake-git/ECE368/ea36be2ce4405a8da414daacf50d399123d75cd0/pa2-malwake-git/pa2.h",
"visit_date": "2023-07-25T17:59:36.292236"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
//#ifndef PA2_H
#define PA2_H
typedef struct tnode
{
int key;
int child;
int balance;
int height;
int nodes;
struct tnode *left;
struct tnode *right;
//struct tnode *next;
} TreeNode;
typedef struct _tnode
{
int key;
char ch;
} stnode;
typedef struct tstack
{
int top;
unsigned capacity;
int* array;
} Stack;
void freePreNode(TreeNode *tr);
void print2DUtil(TreeNode *root, int space);
TreeNode *create(int key);
stnode *createNode(int key,char ch);
int height(TreeNode *tr);
int maximum(int first, int second);
TreeNode *insert(TreeNode* tr, int key);
TreeNode *insertE1(TreeNode* tr, int key);
TreeNode *rightRotate(TreeNode *y);
TreeNode *leftRotate(TreeNode *y);
int findBalance(TreeNode *tr);
int key(TreeNode *Node);
TreeNode *Left_child (TreeNode *tr);
TreeNode *Right_child (TreeNode *tr);
TreeNode *rightBalance(TreeNode *tr, int balance);
TreeNode *leftBalance(TreeNode *tr, int balance);
TreeNode *balance(TreeNode *tr);
void postOrderNode(TreeNode * tn, FILE * fptr);
void preOrderNode(TreeNode * tn, FILE * filename);
bool printPreOrder(TreeNode * tn, const char * filename);
void deleteTreeNode(TreeNode * tr);
void preTree(TreeNode* tr);
void numChild(TreeNode *tr);
TreeNode *readFile(const char * filename);
TreeNode *readArray(FILE * fptr, TreeNode * tr);
//TreeNode *readArray(const char * filename);
TreeNode *deleteNode(TreeNode * tr, int key);
TreeNode* preNode(TreeNode* tr);
TreeNode* prepreNode(TreeNode* tr);
TreeNode *readFileE(const char * filename);
bool checkBalance(TreeNode *tr);
bool checkBST(TreeNode *tr);
TreeNode *readArraycheck(FILE * fptr);
TreeNode *insertE(TreeNode* tr, int key, int nodes);
TreeNode *createE(int key,int nodes);
TreeNode *readArraycheck2(FILE * fptr,int * array1, int * array2, Stack * stack1, Stack * stack2);
TreeNode *readFileE2(const char * filename);
TreeNode* constructTreeUtil(int pre[], int* preIndex,int low, int high,int size, int array2[]);
TreeNode* constructTree(int pre[], int size, int array2[]);
TreeNode *insertE3(TreeNode* tr,Stack* stack1, Stack* stack2);
Stack* createStack(unsigned capacity);
int isFull(Stack* stack);
int isEmpty(Stack* stack);
void push(Stack* stack,int item);
int pop(Stack* stack);
int peek(Stack* stack);
TreeNode *deleteNodeE(TreeNode * tr, int key);
//#endif
| 2.40625 | 2 |
2024-11-18T22:49:20.257724+00:00 | 2016-09-16T00:16:48 | 608d092915326843b78f42681ed58b56ef1e1821 | {
"blob_id": "608d092915326843b78f42681ed58b56ef1e1821",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-16T00:16:48",
"content_id": "7bdb9d87460888f416f5d153b4e874b35eba48db",
"detected_licenses": [
"MIT"
],
"directory_id": "d443c61143ded3a7fef7f7c8cee8f9e37c2e8579",
"extension": "c",
"filename": "duk_util_tinyrandom.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1947,
"license": "MIT",
"license_type": "permissive",
"path": "/src-input/duk_util_tinyrandom.c",
"provenance": "stackv2-0108.json.gz:96380",
"repo_name": "yang123vc/duktape",
"revision_date": "2016-09-16T00:16:48",
"revision_id": "1a67de5dfc99fb14129bbd6e823f62cec5f1e410",
"snapshot_id": "293fed48bb3b7fb96629bb4392c00bc32e1dae02",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yang123vc/duktape/1a67de5dfc99fb14129bbd6e823f62cec5f1e410/src-input/duk_util_tinyrandom.c",
"visit_date": "2020-12-26T05:01:28.775259"
} | stackv2 | /*
* A tiny random number generator.
*
* Currently used for Math.random().
*
* http://www.woodmann.com/forum/archive/index.php/t-3100.html
*/
#include "duk_internal.h"
#if !defined(DUK_USE_GET_RANDOM_DOUBLE)
#define DUK__UPDATE_RND(rnd) do { \
(rnd) += ((rnd) * (rnd)) | 0x05UL; \
(rnd) = ((rnd) & 0xffffffffUL); /* if duk_uint32_t is exactly 32 bits, this is a NOP */ \
} while (0)
#define DUK__RND_BIT(rnd) ((rnd) >> 31) /* only use the highest bit */
#if 1
DUK_INTERNAL duk_double_t duk_util_tinyrandom_get_double(duk_hthread *thr) {
duk_double_t t;
duk_small_int_t n;
duk_uint32_t rnd;
rnd = thr->heap->rnd_state;
n = 53; /* enough to cover the whole mantissa */
t = 0.0;
do {
DUK__UPDATE_RND(rnd);
t += DUK__RND_BIT(rnd);
t /= 2.0;
} while (--n);
thr->heap->rnd_state = rnd;
DUK_ASSERT(t >= (duk_double_t) 0.0);
DUK_ASSERT(t < (duk_double_t) 1.0);
return t;
}
#else
/* Not much faster, larger footprint. */
DUK_INTERNAL duk_double_t duk_util_tinyrandom_get_double(duk_hthread *thr) {
duk_double_t t;
duk_small_int_t i;
duk_uint32_t rnd;
duk_uint32_t rndbit;
duk_double_union du;
rnd = thr->heap->rnd_state;
du.ui[DUK_DBL_IDX_UI0] = 0x3ff00000UL;
du.ui[DUK_DBL_IDX_UI1] = 0x00000000UL;
DUK_ASSERT(DUK_DBL_IDX_UI0 ^ 1 == DUK_DBL_IDX_UI1); /* Indices are 0,1 or 1,0. */
DUK_ASSERT(DUK_DBL_IDX_UI1 ^ 1 == DUK_DBL_IDX_UI0);
/* Fill double representation mantissa bits with random number.
* With the implicit leading 1-bit we get a value in [1,2[.
*/
for (i = 0; i < 52; i++) {
DUK__UPDATE_RND(rnd);
rndbit = DUK__RND_BIT(rnd);
DUK_ASSERT((i >> 5) == 0 || (i >> 5) == 1);
du.ui[DUK_DBL_IDX_UI1 ^ (i >> 5)] |= rndbit << (i & 0x1fUL);
}
thr->heap->rnd_state = rnd;
t = du.d - 1.0; /* Subtract implicit 1-bit to get [0,1[. */
DUK_ASSERT(t >= (duk_double_t) 0.0);
DUK_ASSERT(t < (duk_double_t) 1.0);
return t;
}
#endif
#endif /* !DUK_USE_GET_RANDOM_DOUBLE */
| 2.84375 | 3 |
2024-11-18T22:49:21.426501+00:00 | 2016-05-29T14:46:07 | bd8941d0cfdb3601cc50980f60af8342a5b48408 | {
"blob_id": "bd8941d0cfdb3601cc50980f60af8342a5b48408",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-29T14:46:33",
"content_id": "59fe1446e3c0d216db5d209e6c98459cbf176c01",
"detected_licenses": [
"MIT"
],
"directory_id": "3ad74a657768fd573553aa9e23c6e4d6fa9c8eb6",
"extension": "c",
"filename": "utils.c",
"fork_events_count": 0,
"gha_created_at": "2016-05-30T15:00:02",
"gha_event_created_at": "2016-05-30T15:00:02",
"gha_language": null,
"gha_license_id": null,
"github_id": 60018472,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7744,
"license": "MIT",
"license_type": "permissive",
"path": "/src/utils.c",
"provenance": "stackv2-0108.json.gz:96766",
"repo_name": "subtly/mcu",
"revision_date": "2016-05-29T14:46:07",
"revision_id": "901fad7b72a035119fffe00d3d15a3ab4d50893a",
"snapshot_id": "7996ed835c8b09d0a783369fa790154ab15d960b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/subtly/mcu/901fad7b72a035119fffe00d3d15a3ab4d50893a/src/utils.c",
"visit_date": "2020-12-25T10:37:22.309005"
} | stackv2 | /*
The MIT License (MIT)
Copyright (c) 2015-2016 Douglas J. Bakkum
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 <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <inttypes.h>
#include "utils.h"
#include "flags.h"
static uint8_t buffer_hex_to_uint8[TO_UINT8_HEX_BUF_LEN];
static char buffer_uint8_to_hex[TO_UINT8_HEX_BUF_LEN];
void utils_clear_buffers(void)
{
memset(buffer_hex_to_uint8, 0, TO_UINT8_HEX_BUF_LEN);
memset(buffer_uint8_to_hex, 0, TO_UINT8_HEX_BUF_LEN);
}
uint8_t utils_limit_alphanumeric_hyphen_underscore_period(const char *str)
{
static char characters[] =
".-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
size_t i;
if (!strlens(str)) {
return DBB_ERROR;
}
for (i = 0 ; i < strlens(str); i++) {
if (!strchr(characters, str[i])) {
return DBB_ERROR;
}
}
return DBB_OK;
}
uint8_t *utils_hex_to_uint8(const char *str)
{
if (strlens(str) > TO_UINT8_HEX_BUF_LEN) {
return NULL;
}
memset(buffer_hex_to_uint8, 0, TO_UINT8_HEX_BUF_LEN);
uint8_t c;
size_t i;
for (i = 0; i < strlens(str) / 2; i++) {
c = 0;
if (str[i * 2] >= '0' && str[i * 2] <= '9') {
c += (str[i * 2] - '0') << 4;
}
if (str[i * 2] >= 'a' && str[i * 2] <= 'f') {
c += (10 + str[i * 2] - 'a') << 4;
}
if (str[i * 2] >= 'A' && str[i * 2] <= 'F') {
c += (10 + str[i * 2] - 'A') << 4;
}
if (str[i * 2 + 1] >= '0' && str[i * 2 + 1] <= '9') {
c += (str[i * 2 + 1] - '0');
}
if (str[i * 2 + 1] >= 'a' && str[i * 2 + 1] <= 'f') {
c += (10 + str[i * 2 + 1] - 'a');
}
if (str[i * 2 + 1] >= 'A' && str[i * 2 + 1] <= 'F') {
c += (10 + str[i * 2 + 1] - 'A');
}
buffer_hex_to_uint8[i] = c;
}
return buffer_hex_to_uint8;
}
char *utils_uint8_to_hex(const uint8_t *bin, size_t l)
{
if (l > (TO_UINT8_HEX_BUF_LEN / 2 - 1)) {
return NULL;
}
static char digits[] = "0123456789abcdef";
memset(buffer_uint8_to_hex, 0, TO_UINT8_HEX_BUF_LEN);
size_t i;
for (i = 0; i < l; i++) {
buffer_uint8_to_hex[i * 2] = digits[(bin[i] >> 4) & 0xF];
buffer_uint8_to_hex[i * 2 + 1] = digits[bin[i] & 0xF];
}
buffer_uint8_to_hex[l * 2] = '\0';
return buffer_uint8_to_hex;
}
void utils_reverse_hex(char *h, int len)
{
char copy[len];
strncpy(copy, h, len);
int i;
for (i = 0; i < len; i += 2) {
h[i] = copy[len - i - 2];
h[i + 1] = copy[len - i - 1];
}
}
void utils_uint64_to_varint(char *vi, int *l, uint64_t i)
{
int len;
char v[VARINT_LEN];
if (i < 0xfd) {
sprintf(v, "%02" PRIx64 , i);
len = 2;
} else if (i <= 0xffff) {
sprintf(v, "%04" PRIx64 , i);
sprintf(vi, "fd");
len = 4;
} else if (i <= 0xffffffff) {
sprintf(v, "%08" PRIx64 , i);
sprintf(vi, "fe");
len = 8;
} else {
sprintf(v, "%016" PRIx64 , i);
sprintf(vi, "ff");
len = 16;
}
// reverse order
if (len > 2) {
utils_reverse_hex(v, len);
strncat(vi, v, len);
} else {
strncpy(vi, v, len);
}
*l = len;
}
int utils_varint_to_uint64(const char *vi, uint64_t *i)
{
char v[VARINT_LEN] = {0};
int len;
if (!vi) {
len = 0;
} else if (!strncmp(vi, "ff", 2)) {
len = 16;
} else if (!strncmp(vi, "fe", 2)) {
len = 8;
} else if (!strncmp(vi, "fd", 2)) {
len = 4;
} else {
len = 2;
}
if (len == 0) {
// continue
} else if (len > 2) {
strncpy(v, vi + 2, len);
utils_reverse_hex(v, len);
} else {
strncpy(v, vi, len);
}
*i = strtoull(v, NULL, 16);
return len;
}
#ifdef TESTING
#include <assert.h>
#include "commander.h"
#include "yajl/src/api/yajl_tree.h"
static char decrypted_report[COMMANDER_REPORT_SIZE];
const char *utils_read_decrypted_report(void)
{
return decrypted_report;
}
void utils_decrypt_report(const char *report)
{
int decrypt_len;
char *dec;
memset(decrypted_report, 0, sizeof(decrypted_report));
yajl_val json_node = yajl_tree_parse(report, NULL, 0);
if (!json_node) {
strcpy(decrypted_report, "/* error: Failed to parse report. */");
return;
}
size_t i, r = json_node->u.object.len;
for (i = 0; i < r; i++) {
const char *ciphertext_path[] = { cmd_str(CMD_ciphertext), (const char *) 0 };
const char *echo_path[] = { "echo", (const char *) 0 };
const char *ciphertext = YAJL_GET_STRING(yajl_tree_get(json_node, ciphertext_path,
yajl_t_string));
const char *echo = YAJL_GET_STRING(yajl_tree_get(json_node, echo_path, yajl_t_string));
if (ciphertext) {
dec = aes_cbc_b64_decrypt((const unsigned char *)ciphertext, strlens(ciphertext),
&decrypt_len, PASSWORD_STAND);
if (!dec) {
strcpy(decrypted_report, "/* error: Failed to decrypt. */");
goto exit;
}
sprintf(decrypted_report, "/* ciphertext */ %.*s", decrypt_len, dec);
free(dec);
goto exit;
} else if (echo) {
dec = aes_cbc_b64_decrypt((const unsigned char *)echo, strlens(echo), &decrypt_len,
PASSWORD_VERIFY);
if (!dec) {
strcpy(decrypted_report, "/* error: Failed to decrypt echo. */");
goto exit;
}
sprintf(decrypted_report, "/* echo */ %.*s", decrypt_len, dec);
free(dec);
goto exit;
}
}
strcpy(decrypted_report, report);
exit:
yajl_tree_free(json_node);
return;
}
void utils_send_cmd(const char *command, PASSWORD_ID enc_id)
{
if (enc_id == PASSWORD_NONE) {
utils_decrypt_report(commander(command));
} else {
int encrypt_len;
char *enc = aes_cbc_b64_encrypt((const unsigned char *)command, strlens(command),
&encrypt_len,
enc_id);
char cmd[COMMANDER_REPORT_SIZE] = {0};
assert(encrypt_len < COMMANDER_REPORT_SIZE);
memcpy(cmd, enc, encrypt_len);
free(enc);
utils_decrypt_report(commander(cmd));
}
}
void utils_send_print_cmd(const char *command, PASSWORD_ID enc_id)
{
printf("\nutils send: %s\n", command);
utils_send_cmd(command, enc_id);
printf("utils recv: %s\n\n", decrypted_report);
}
#endif
| 2.421875 | 2 |
2024-11-18T22:49:22.978261+00:00 | 2018-03-16T04:29:12 | e946d8c37934e499a8cf5093dfca3c42c3141066 | {
"blob_id": "e946d8c37934e499a8cf5093dfca3c42c3141066",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-16T04:29:12",
"content_id": "adae9a48c51fe6229775097b2177c083597693e7",
"detected_licenses": [
"ISC"
],
"directory_id": "b15d1d9b90000548c8a21676e6d45418a81916c5",
"extension": "c",
"filename": "surf_makeseed.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 125463464,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 713,
"license": "ISC",
"license_type": "permissive",
"path": "/Lab1c/skalibs-2.3.9.0/src/librandom/surf_makeseed.c",
"provenance": "stackv2-0108.json.gz:97801",
"repo_name": "jonwoong/CS-111",
"revision_date": "2018-03-16T04:29:12",
"revision_id": "e3eb37d5a39ecfdcbf6e1497e6239710325ff62d",
"snapshot_id": "6cfc652b781c796a44dd18254fd0c33a98f49751",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jonwoong/CS-111/e3eb37d5a39ecfdcbf6e1497e6239710325ff62d/Lab1c/skalibs-2.3.9.0/src/librandom/surf_makeseed.c",
"visit_date": "2021-04-09T10:31:09.464262"
} | stackv2 | /* ISC license. */
#include <unistd.h>
#include <skalibs/uint32.h>
#include <skalibs/tai.h>
#include <skalibs/sha1.h>
#include <skalibs/surf.h>
void surf_makeseed (char *s)
{
SHA1Schedule bak = SHA1_INIT() ;
{
tain_t now ;
char tmp[20 + TAIN_PACK] ;
uint32 x = getpid() ;
uint32_pack(tmp, x) ;
x = getppid() ;
uint32_pack(tmp + 4, x) ;
tain_now(&now) ;
tain_pack(tmp + 8, &now) ;
sha1_update(&bak, tmp, 8 + TAIN_PACK) ;
sha1_final(&bak, tmp) ;
sha1_init(&bak) ;
sha1_update(&bak, tmp, 20) ;
}
{
char i = 0 ;
for (; i < 8 ; i++)
{
SHA1Schedule ctx = bak ;
sha1_update(&ctx, &i, 1) ;
sha1_final(&ctx, s + 20*i) ;
}
}
}
| 2.3125 | 2 |
2024-11-18T22:49:23.176192+00:00 | 2020-12-10T16:42:33 | 54ee80ed00c88720489aa6d68077db63e851c0e5 | {
"blob_id": "54ee80ed00c88720489aa6d68077db63e851c0e5",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-10T16:42:33",
"content_id": "b8d1bac8ee3a9597fd598ac2fb4817f44ba77508",
"detected_licenses": [
"MIT"
],
"directory_id": "df01134eae43f2434b59771681ec59160bb4e875",
"extension": "c",
"filename": "test_frame.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16513,
"license": "MIT",
"license_type": "permissive",
"path": "/test/test_frame.c",
"provenance": "stackv2-0108.json.gz:97932",
"repo_name": "adamatom/Websocket",
"revision_date": "2020-12-10T16:42:33",
"revision_id": "de767149899e9be366951f2260a69411f1f45841",
"snapshot_id": "94ef7c43a2134cce80429391ed1ae4cefcc3bbba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/adamatom/Websocket/de767149899e9be366951f2260a69411f1f45841/test/test_frame.c",
"visit_date": "2023-03-17T15:14:38.692173"
} | stackv2 | #include <stdio.h>
#include <arpa/inet.h>
#include <criterion/criterion.h>
#include "alloc.h"
#include "frame.h"
#include "rpmalloc.h"
static void setup(void) {
#ifdef USE_RPMALLOC
rpmalloc_initialize();
#endif
}
static void teardown(void) {
#ifdef USE_RPMALLOC
rpmalloc_finalize();
#endif
}
static inline char *mask(char key[4], char *payload, size_t length) {
size_t i, j;
for (i = 0, j = 0; i < length; i++, j++){
payload[i] = payload[i] ^ key[j % 4];
}
return payload;
}
static inline uint64_t htons64(uint64_t value) {
static const int num = 42;
/**
* If this check is true, the system is using the little endian
* convention. Else the system is using the big endian convention, which
* means that we do not have to represent our integers in another way.
*/
if (*(char *)&num == 42) {
return ((uint64_t)htonl((value) & 0xFFFFFFFFLL) << 32) | htonl((value) >> 32);
} else {
return value;
}
}
TestSuite(WSS_parse_frame, .init = setup, .fini = teardown);
Test(WSS_parse_frame, null_payload) {
size_t offset = 0;
cr_assert(NULL == WSS_parse_frame(NULL, 0, &offset));
}
Test(WSS_parse_frame, empty_payload) {
size_t offset = 0;
cr_assert(NULL != WSS_parse_frame("", 0, &offset));
cr_assert(offset == 2);
}
Test(WSS_parse_frame, small_client_frame) {
size_t offset = 0;
char *payload = "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58";
uint16_t length = strlen(payload);
wss_frame_t *frame = WSS_parse_frame(payload, length, &offset);
cr_assert(NULL != frame);
cr_assert(offset == length);
cr_assert(strncmp(frame->payload, "Hello", frame->payloadLength) == 0);
WSS_free_frame(frame);
}
Test(WSS_parse_frame, medium_client_frame) {
size_t offset = 0;
char header[2] = "\x81\xFE";
char key[4] = "\x37\xfa\x21\x3d";
char *payload = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin hendrerit ornare tortor ut euismod. Nunc finibus convallis sem, at imperdiet ligula commodo id. Nam bibendum nec augue in posuere mauris.";
uint16_t length = strlen(payload);
char *payload_copy = WSS_copy(payload, length);
char *payload_frame = WSS_malloc((2+2+4+length+1)*sizeof(char));
uint16_t len = htons(length);
memcpy(payload_frame, header, 2);
memcpy(payload_frame+2, &len, 2);
memcpy(payload_frame+2+2, key, 4);
memcpy(payload_frame+2+2+4, mask(key, payload_copy, length), length);
wss_frame_t *frame = WSS_parse_frame(payload_frame, length+8, &offset);
cr_assert(NULL != frame);
cr_assert(offset == 208);
cr_assert(strncmp(frame->payload, payload, frame->payloadLength) == 0);
WSS_free_frame(frame);
WSS_free((void **)&payload_copy);
WSS_free((void **)&payload_frame);
}
Test(WSS_parse_frame, large_client_frame) {
int i;
size_t offset = 0;
char header[2] = "\x81\xFF";
char key[4] = "\x37\xfa\x21\x3d";
char *p = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin hendrerit ornare tortor ut euismod. Nunc finibus convallis sem, at imperdiet ligula commodo id. Nam bibendum nec augue in posuere mauris.";
char *payload = WSS_malloc(66001);
size_t plen = strlen(p);
size_t poff = 0;
for (i = 0; i < 330; i++) {
memcpy(payload+poff, p, plen);
poff+=plen;
}
uint64_t length = strlen(payload);
char *payload_copy = WSS_copy(payload, length);
char *payload_frame = WSS_malloc((2+2+4+length+1)*sizeof(char));
uint64_t len = htons64(length);
memcpy(payload_frame, header, 2);
memcpy(payload_frame+2, &len, sizeof(uint64_t));
memcpy(payload_frame+2+sizeof(uint64_t), key, 4);
memcpy(payload_frame+2+sizeof(uint64_t)+4, mask(key, payload_copy, length), length);
wss_frame_t *frame = WSS_parse_frame(payload_frame, length+6+sizeof(uint64_t), &offset);
cr_assert(NULL != frame);
cr_assert(offset == 66014);
cr_assert(strncmp(frame->payload, payload, frame->payloadLength) == 0);
WSS_free_frame(frame);
WSS_free((void **)&payload);
WSS_free((void **)&payload_copy);
WSS_free((void **)&payload_frame);
}
TestSuite(WSS_stringify_frame, .init = setup, .fini = teardown);
Test(WSS_stringify_frame, null_frame) {
char *message;
cr_assert(0 == WSS_stringify_frame(NULL, &message));
cr_assert(NULL == message);
}
Test(WSS_stringify_frame, small_client_frame) {
size_t offset = 0;
char *message;
char *payload = "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58";
uint16_t length = strlen(payload);
wss_frame_t *frame = WSS_parse_frame(payload, length, &offset);
cr_assert(NULL != frame);
cr_assert(offset == length);
cr_assert(strncmp(frame->payload, "Hello", frame->payloadLength) == 0);
offset = WSS_stringify_frame(frame, &message);
cr_assert(offset == (size_t)length-4);
cr_assert(strncmp(message, "\x81\x05", 2) == 0);
cr_assert(strncmp(frame->payload, message+2, 5) == 0);
WSS_free((void **)&message);
WSS_free_frame(frame);
}
Test(WSS_stringify_frame, small_client_frame_rsv) {
size_t offset = 0;
char *message;
char *payload = "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58";
uint16_t length = strlen(payload);
wss_frame_t *frame = WSS_parse_frame(payload, length, &offset);
cr_assert(NULL != frame);
cr_assert(offset == length);
cr_assert(strncmp(frame->payload, "Hello", frame->payloadLength) == 0);
frame->rsv1 = true;
frame->rsv2 = true;
frame->rsv3 = true;
offset = WSS_stringify_frame(frame, &message);
cr_assert(offset == (size_t)length-4);
cr_assert(strncmp(message, "\xF1\x05", 2) == 0);
cr_assert(strncmp(frame->payload, message+2, 5) == 0);
WSS_free((void **)&message);
WSS_free_frame(frame);
}
Test(WSS_stringify_frame, medium_client_frame) {
size_t offset = 0;
char header[2] = "\x81\xFE";
char *message;
char key[4] = "\x37\xfa\x21\x3d";
char *payload = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin hendrerit ornare tortor ut euismod. Nunc finibus convallis sem, at imperdiet ligula commodo id. Nam bibendum nec augue in posuere mauris.";
uint16_t length = strlen(payload);
char *payload_copy = WSS_copy(payload, length);
char *payload_frame = WSS_malloc((2+2+4+length+1)*sizeof(char));
uint16_t len = htons(length);
memcpy(payload_frame, header, 2);
memcpy(payload_frame+2, &len, 2);
memcpy(payload_frame+2+2, key, 4);
memcpy(payload_frame+2+2+4, mask(key, payload_copy, length), length);
wss_frame_t *frame = WSS_parse_frame(payload_frame, length+8, &offset);
cr_assert(NULL != frame);
cr_assert(offset == 208);
cr_assert(strncmp(frame->payload, payload, frame->payloadLength) == 0);
offset = WSS_stringify_frame(frame, &message);
cr_assert(offset == (size_t)length+2+sizeof(uint16_t));
cr_assert(strncmp(message, "\x81\x7E", 2) == 0);
uint16_t str_len;
memcpy(&str_len, message+2, sizeof(uint16_t));
cr_assert(str_len == len);
cr_assert(strncmp(frame->payload, message+2+sizeof(uint16_t), length) == 0);
WSS_free_frame(frame);
WSS_free((void **)&message);
WSS_free((void **)&payload_copy);
WSS_free((void **)&payload_frame);
}
Test(WSS_stringify_frame, large_client_frame) {
int i;
size_t offset = 0;
char *message;
char header[2] = "\x81\xFF";
char key[4] = "\x37\xfa\x21\x3d";
char *p = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin hendrerit ornare tortor ut euismod. Nunc finibus convallis sem, at imperdiet ligula commodo id. Nam bibendum nec augue in posuere mauris.";
char *payload = WSS_malloc(66001);
size_t plen = strlen(p);
size_t poff = 0;
for (i = 0; i < 330; i++) {
memcpy(payload+poff, p, plen);
poff+=plen;
}
uint64_t length = strlen(payload);
char *payload_copy = WSS_copy(payload, length);
char *payload_frame = WSS_malloc((2+2+4+length+1)*sizeof(char));
uint64_t len = htons64(length);
memcpy(payload_frame, header, 2);
memcpy(payload_frame+2, &len, sizeof(uint64_t));
memcpy(payload_frame+2+sizeof(uint64_t), key, 4);
memcpy(payload_frame+2+sizeof(uint64_t)+4, mask(key, payload_copy, length), length);
wss_frame_t *frame = WSS_parse_frame(payload_frame, length+6+sizeof(uint64_t), &offset);
cr_assert(NULL != frame);
cr_assert(offset == 66014);
cr_assert(strncmp(frame->payload, payload, frame->payloadLength) == 0);
offset = WSS_stringify_frame(frame, &message);
cr_assert(offset == (size_t)length+2+sizeof(uint64_t));
cr_assert(strncmp(message, "\x81\x7F", 2) == 0);
uint64_t str_len;
memcpy(&str_len, message+2, sizeof(uint64_t));
cr_assert(str_len == len);
cr_assert(strncmp(frame->payload, message+2+sizeof(uint64_t), length) == 0);
WSS_free_frame(frame);
WSS_free((void **)&message);
WSS_free((void **)&payload);
WSS_free((void **)&payload_copy);
WSS_free((void **)&payload_frame);
}
TestSuite(WSS_pong_frame, .init = setup, .fini = teardown);
Test(WSS_pong_frame, null_frame) {
cr_assert(NULL == WSS_pong_frame(NULL));
}
Test(WSS_pong_frame, pong_from_ping) {
wss_frame_t *ping = WSS_ping_frame();
size_t ping_payload_len = ping->payloadLength;
char *ping_payload = WSS_copy(ping->payload, ping_payload_len);
wss_frame_t *pong = WSS_pong_frame(ping);
cr_assert(NULL != pong);
cr_assert(true == pong->fin);
cr_assert(false == pong->rsv1);
cr_assert(false == pong->rsv2);
cr_assert(false == pong->rsv3);
cr_assert(PONG_FRAME == pong->opcode);
cr_assert(0 == pong->mask);
cr_assert(0 == pong->maskingKey[0]);
cr_assert(0 == pong->maskingKey[1]);
cr_assert(0 == pong->maskingKey[2]);
cr_assert(0 == pong->maskingKey[3]);
cr_assert(pong->payloadLength == ping_payload_len);
cr_assert(strncmp(pong->payload, ping_payload, ping_payload_len) == 0);
WSS_free((void **)&ping_payload);
}
TestSuite(WSS_stringify_frames, .init = setup, .fini = teardown);
Test(WSS_stringify_frames, null_frame) {
char *message;
cr_assert(0 == WSS_stringify_frames(NULL, 0, &message));
cr_assert(NULL == message);
}
Test(WSS_stringify_frames, null_last_frame) {
size_t offset = 0;
char *message;
char *payload = "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58";
uint16_t length = strlen(payload);
wss_frame_t *frames[2];
wss_frame_t *frame = WSS_parse_frame(payload, length, &offset);
cr_assert(NULL != frame);
cr_assert(offset == length);
cr_assert(strncmp(frame->payload, "Hello", frame->payloadLength) == 0);
frames[0] = frame;
frames[1] = NULL;
cr_assert(0 == WSS_stringify_frames(frames, 2, &message));
cr_assert(NULL == message);
WSS_free_frame(frame);
}
Test(WSS_stringify_frames, small_client_frame) {
size_t offset = 0;
char *message;
char *payload = "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58";
uint16_t length = strlen(payload);
wss_frame_t *frame = WSS_parse_frame(payload, length, &offset);
cr_assert(NULL != frame);
cr_assert(offset == length);
cr_assert(strncmp(frame->payload, "Hello", frame->payloadLength) == 0);
offset = WSS_stringify_frames(&frame, 1, &message);
cr_assert(offset == (size_t)length-4);
cr_assert(strncmp(message, "\x81\x05", 2) == 0);
cr_assert(strncmp(frame->payload, message+2, 5) == 0);
WSS_free((void **)&message);
WSS_free_frame(frame);
}
TestSuite(WSS_create_frames, .init = setup, .fini = teardown);
Test(WSS_create_frames, null_config) {
wss_frame_t **frames;
cr_assert(0 == WSS_create_frames(NULL, CLOSE_FRAME, "", 0, &frames));
cr_assert(NULL == frames);
}
Test(WSS_create_frames, null_message_with_length) {
wss_frame_t **frames;
wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t));
cr_assert(WSS_SUCCESS == WSS_config_load(conf, "resources/test_wss.json"));
cr_assert(0 == WSS_create_frames(conf, CLOSE_FRAME, NULL, 1, &frames));
cr_assert(NULL == frames);
WSS_config_free(conf);
WSS_free((void**) &conf);
}
Test(WSS_create_frames, zero_length) {
wss_frame_t **frames;
wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t));
cr_assert(WSS_SUCCESS == WSS_config_load(conf, "resources/test_wss.json"));
cr_assert(1 == WSS_create_frames(conf, TEXT_FRAME, "", 0, &frames));
cr_assert(frames[0]->payloadLength == 0);
WSS_config_free(conf);
WSS_free((void**) &conf);
}
Test(WSS_create_frames, multiple_frames) {
char *message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin hendrerit ornare tortor ut euismod. Nunc finibus convallis sem, at imperdiet ligula commodo id. Nam bibendum nec augue in posuere mauris.";
wss_frame_t **frames;
wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t));
cr_assert(WSS_SUCCESS == WSS_config_load(conf, "resources/test_wss.json"));
cr_assert(2 == WSS_create_frames(conf, TEXT_FRAME, message, strlen(message), &frames));
cr_expect(frames[0]->payloadLength == conf->size_frame);
cr_expect(frames[1]->payloadLength == strlen(message)-conf->size_frame);
cr_expect(strncmp(frames[0]->payload, message, frames[0]->payloadLength) == 0);
cr_expect(strncmp(frames[1]->payload, message+conf->size_frame, frames[1]->payloadLength) == 0);
WSS_config_free(conf);
WSS_free((void**) &conf);
}
Test(WSS_create_frames, empty_close_frame) {
char *message = "";
wss_frame_t **frames;
wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t));
cr_assert(WSS_SUCCESS == WSS_config_load(conf, "resources/test_wss.json"));
cr_assert(1 == WSS_create_frames(conf, CLOSE_FRAME, message, 0, &frames));
cr_assert(frames[0]->payloadLength == 2);
cr_assert(frames[0]->opcode == CLOSE_FRAME);
cr_assert(memcmp(frames[0]->payload, "\x03\xE8", frames[0]->payloadLength) == 0);
WSS_config_free(conf);
WSS_free((void**) &conf);
}
Test(WSS_create_frames, protocol_error_close_frame) {
char *message = "\x03";
wss_frame_t **frames;
wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t));
cr_assert(WSS_SUCCESS == WSS_config_load(conf, "resources/test_wss.json"));
cr_assert(1 == WSS_create_frames(conf, CLOSE_FRAME, message, strlen(message), &frames));
cr_assert(frames[0]->payloadLength == 2);
cr_assert(frames[0]->opcode == CLOSE_FRAME);
cr_assert(memcmp(frames[0]->payload, "\x03\xEA", frames[0]->payloadLength) == 0);
WSS_config_free(conf);
WSS_free((void**) &conf);
}
Test(WSS_create_frames, close_frame_with_opcode) {
char *message = "\x03\xEA";
wss_frame_t **frames;
wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t));
cr_assert(WSS_SUCCESS == WSS_config_load(conf, "resources/test_wss.json"));
cr_assert(1 == WSS_create_frames(conf, CLOSE_FRAME, message, strlen(message), &frames));
cr_assert(frames[0]->payloadLength == 2);
cr_assert(frames[0]->opcode == CLOSE_FRAME);
cr_assert(memcmp(frames[0]->payload, message, strlen(message)) == 0);
WSS_config_free(conf);
WSS_free((void**) &conf);
}
Test(WSS_create_frames, close_frame_with_opcode_and_reason) {
char *message = "\x03\xEDThis is a test";
wss_frame_t **frames;
wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t));
cr_assert(WSS_SUCCESS == WSS_config_load(conf, "resources/test_wss.json"));
cr_assert(1 == WSS_create_frames(conf, CLOSE_FRAME, message, strlen(message), &frames));
cr_assert(frames[0]->payloadLength == 16);
cr_assert(frames[0]->opcode == CLOSE_FRAME);
cr_assert(memcmp(frames[0]->payload, message, strlen(message)) == 0);
WSS_config_free(conf);
WSS_free((void**) &conf);
}
TestSuite(WSS_closing_frame, .init = setup, .fini = teardown);
Test(WSS_closing_frame, create_different_closing_frames) {
uint16_t code, nw_code;
wss_frame_t *frame;
for (int i = 0; i <= 15; i++) {
code = CLOSE_NORMAL+i;
nw_code = htons(code);
frame = WSS_closing_frame(code, NULL);
if (i == 4) {
cr_assert(frame == NULL);
} else {
cr_assert(frame != NULL);
cr_expect(frame->opcode == CLOSE_FRAME);
cr_expect(memcmp(frame->payload, &nw_code, sizeof(nw_code)) == 0);
cr_expect(frame->payloadLength > 2);
}
WSS_free_frame(frame);
}
}
| 2.53125 | 3 |
2024-11-18T20:50:25.583168+00:00 | 2020-11-30T19:41:24 | 88d0d29e4a158358e20f55b54dde5c91a2712cd8 | {
"blob_id": "88d0d29e4a158358e20f55b54dde5c91a2712cd8",
"branch_name": "refs/heads/main",
"committer_date": "2020-11-30T19:41:24",
"content_id": "73fde9afb7df87e02b0c2e09ca68c668cd348c55",
"detected_licenses": [
"MIT"
],
"directory_id": "024a4654ae6a6a7232e25eb8db0da5db12a04fe8",
"extension": "h",
"filename": "LiquidCrystal.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 317322006,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1782,
"license": "MIT",
"license_type": "permissive",
"path": "/LiquidCrystal.h",
"provenance": "stackv2-0110.json.gz:212793",
"repo_name": "Luana-Coder/code-lua",
"revision_date": "2020-11-30T19:41:24",
"revision_id": "64e595bfa03667251649b6b051496620f4adbcb1",
"snapshot_id": "baefeeb758de3dc20eb2dd64a7b6b84759c61412",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Luana-Coder/code-lua/64e595bfa03667251649b6b051496620f4adbcb1/LiquidCrystal.h",
"visit_date": "2023-01-23T14:18:06.742679"
} | stackv2 | # code-lua
Primeiro repositório
#include<LiquidCrystal.h>
const int rs = 8;
const int e = 9;
const int d4 = 4;
const int d5 = 5;
const int d6 = 6;
const int d7 = 7;
LiquidCrystal lcd (rs, e, d4, d5, d6, d7);
//**************DECLARAÇÃO DAS VARIÁVEIS*************
bool posicao = 0;
bool ledA = 0;
bool ledB = 0;
int valorAnterior = 1023;
void setup()
{
lcd.begin(16, 2); //inicia o display
lcd.home();
lcd.print ("> LED A OFF");
lcd.setCursor(0, 1);
lcd.print (" LED B OFF");
pinMode (22, OUTPUT);
pinMode (26, OUTPUT);
}
void loop()
{
//************TRATAMENTO DOS BOTÕES***************
int valor = analogRead(A0); //A (ZER0)
if (valor > 100 && valor < 200) //botão cima
{
posicao = 0;
}
if (valor > 300 && valor < 400) //botão baixo
{
posicao = 1;
}
if (valor > 700 && valor < 800 && valorAnterior > 1000) //botão SELECT
{
if (posicao == 0)
{
ledA = !ledA;
}
if (posicao == 1)
{
ledB = !ledB;
}
}
valorAnterior = valor;
//***************FIM DO TRATAMENTO*************
//************INDICAÇÃO DAS LINHAS*************
if (posicao == 0)
{
lcd.home();
lcd.print (">");
lcd.setCursor(0, 1);
lcd.print (" ");
}
if (posicao == 1)
{
lcd.setCursor(0, 1);
lcd.print (">");
lcd.home();
lcd.print (" ");
}
//********STATUS DO LED NO DISPLAY**************
if (ledA == LOW)
{
lcd.setCursor (8, 0);
lcd.print("OFF");
}
else
{
lcd.setCursor (8, 0);
lcd.print("ON ");
}
if (ledB == LOW)
{
lcd.setCursor (8, 1);
lcd.print("OFF");
}
else
{
lcd.setCursor (8, 1);
lcd.print("ON ");
}
//****************ATUALIZA OS LEDS***************
digitalWrite(22, ledA);
digitalWrite(26, ledB);
}
| 3.046875 | 3 |
2024-11-18T20:50:27.694482+00:00 | 2022-05-26T09:31:58 | c11a8481d9db58ff278db3c1c945a56c53ce0cdb | {
"blob_id": "c11a8481d9db58ff278db3c1c945a56c53ce0cdb",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-26T10:31:53",
"content_id": "0138d722001141841694ec15abe7f80a0005a970",
"detected_licenses": [
"MIT"
],
"directory_id": "20f252ce1eb1f1c6ce1408a1ac1e058386c47971",
"extension": "h",
"filename": "hash_table.h",
"fork_events_count": 0,
"gha_created_at": "2022-04-02T06:36:31",
"gha_event_created_at": "2022-04-02T06:36:32",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 476969646,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2416,
"license": "MIT",
"license_type": "permissive",
"path": "/nanolib/include/hash_table.h",
"provenance": "stackv2-0110.json.gz:213314",
"repo_name": "nanomq/nanomq",
"revision_date": "2022-05-26T09:31:58",
"revision_id": "4b373d2d81b0a0cef87964598a3e56f69637a067",
"snapshot_id": "68819eb82d019467e1d8134b63d1bcf813d601b8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/nanomq/nanomq/4b373d2d81b0a0cef87964598a3e56f69637a067/nanolib/include/hash_table.h",
"visit_date": "2022-05-26T13:02:13.700891"
} | stackv2 | #ifndef HASH_TABLE_H
#define HASH_TABLE_H
#include "cvector.h"
#include "dbg.h"
#include <stdbool.h>
#include <stdint.h>
struct topic_queue {
char * topic;
struct topic_queue *next;
};
typedef struct topic_queue topic_queue;
struct msg_queue {
char * msg;
struct msg_queue *next;
};
typedef struct msg_queue msg_queue;
// atpair is alias topic pair
typedef struct dbhash_atpair_s dbhash_atpair_t;
struct dbhash_atpair_s {
uint32_t alias;
char * topic;
};
typedef struct dbhash_ptpair_s dbhash_ptpair_t;
// ptpair is pipe topic pair
struct dbhash_ptpair_s {
uint32_t pipe;
char * topic;
};
/**
* @brief alias_cmp - A callback to compare different alias
* @param x - normally x is pointer of dbhash_atpair_t
* @param y - normally y is pointer of alias
* @return 0, minus or plus
*/
static inline int
alias_cmp(void *x_, void *y_)
{
uint32_t * alias = (uint32_t *) y_;
dbhash_atpair_t *ele_x = (dbhash_atpair_t *) x_;
return *alias - ele_x->alias;
}
void dbhash_init_alias_table(void);
void dbhash_destroy_alias_table(void);
// This function do not verify value of alias and topic,
// therefore you should make sure alias and topic is
// not illegal.
void dbhash_insert_atpair(uint32_t pipe_id, uint32_t alias, const char *topic);
const char *dbhash_find_atpair(uint32_t pipe_id, uint32_t alias);
void dbhash_del_atpair_queue(uint32_t pipe_id);
void dbhash_init_pipe_table(void);
void dbhash_destroy_pipe_table(void);
void dbhash_insert_topic(uint32_t id, char *val);
bool dbhash_check_topic(uint32_t id, char *val);
struct topic_queue *dbhash_get_topic_queue(uint32_t id);
void dbhash_del_topic(uint32_t id, char *topic);
void dbhash_del_topic_queue(uint32_t id);
bool dbhash_check_id(uint32_t id);
void dbhash_print_topic_queue(uint32_t id);
topic_queue **dbhash_get_topic_queue_all(size_t *sz);
dbhash_ptpair_t *dbhash_ptpair_alloc(uint32_t p, char *t);
void dbhash_ptpair_free(dbhash_ptpair_t *pt);
dbhash_ptpair_t **dbhash_get_ptpair_all(void);
size_t dbhash_get_pipe_cnt(void);
void dbhash_init_cached_table(void);
void dbhash_destroy_cached_table(void);
void dbhash_cache_topic_all(uint32_t pid, uint32_t cid);
void dbhash_restore_topic_all(uint32_t cid, uint32_t pid);
struct topic_queue *dbhash_get_cached_topic(uint32_t cid);
void dbhash_del_cached_topic_all(uint32_t key);
bool dbhash_cached_check_id(uint32_t key);
#endif
| 2.265625 | 2 |
2024-11-18T20:50:27.823966+00:00 | 2017-10-13T13:38:16 | 4c5da0d69895e1cc2b82882329fec8a6d24773d5 | {
"blob_id": "4c5da0d69895e1cc2b82882329fec8a6d24773d5",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-13T13:38:16",
"content_id": "db5439373a24ed4b24191187a707ec9987d3cb0a",
"detected_licenses": [
"MIT"
],
"directory_id": "0e316b5db63e39f8782ae01ee6ff116da23523f8",
"extension": "c",
"filename": "CSMA-CA.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 76007968,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4664,
"license": "MIT",
"license_type": "permissive",
"path": "/Unclassified/CSMA-CA/CSMA-CA.c",
"provenance": "stackv2-0110.json.gz:213442",
"repo_name": "ianhom/LEON",
"revision_date": "2017-10-13T13:38:16",
"revision_id": "133a79b5d708cd26e0395a779cf5c36f7cb50b86",
"snapshot_id": "0a73f110cf912384e60aa135e4686309d9e33019",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/ianhom/LEON/133a79b5d708cd26e0395a779cf5c36f7cb50b86/Unclassified/CSMA-CA/CSMA-CA.c",
"visit_date": "2020-06-11T04:07:30.069883"
} | stackv2 | /******************************************************************************
* file :CSMA-CA.c
* Brief :802.15.4 CSMA-CA algorithm - Ver. Beta
* Version:V0.10
* Author :Ian
* Date :2015年3月19日
* History: Date Editor Version Record
2015-03-19 Ian V0.10 Create, only CSMA-CA without
time slots is realized.
******************************************************************************/
#include "common.h"
#include "csma_ca.h"
static T_CSMA_CA_DATA *sg_ptCsma = {NULL}; /* Pointer for CSMA-CA data struct */
/*************************************************************************
* Function :RESULT CSMA_CA_Init(T_CSMA_CA_DATA* ptCsma)
* Description :Init CSMA-CA, Get & check necessary data struct
* Input Param :T_CSMA_CA_DATA* ptCsma Data struct for CSMA-CA
* Output Param:None
* Return :SW_ERR: Failed operation
SW_OK : Successful operation
**************************************************************************/
RESULT CSMA_CA_Init(T_CSMA_CA_DATA* ptCsma)
{
if ((NULL == ptCsma)\
||(NULL == ptCsma->pfCCA)\
||(NULL == ptCsma->pfRandom)) /* If the pointer is invalid, or if CCA/Random is not available */
{
return SW_ERR; /* return error */
}
sg_ptCsma = ptCsma; /* Get the data struct for the module */
return SW_OK;
}
/*************************************************************************
* Function :RESULT CSMA_CA()
* Description :Perform CSMA-CA, check a channel is available or not
* Input Param :None
* Output Param:None
* Return :SW_ERR: Failed operation
SW_OK : Successful operation
**************************************************************************/
RESULT CSMA_CA()
{
uint8_t ucBE,ucNB,ucRand,ucChClr;
switch(sg_ptCsma->ucSlotted) /* Check if it is slotted mode of csma */
{
case CSMA_CA_WITH_SLOTTED: /* If it is slotted mode */
{
/* To be continued.. */
break;
}
case CSMA_CA_WITHOUT_SLOTTED: /* If it is not slotted mode */
{
ucNB = 0; /* Set init value of NB */
ucBE = MAC_BE_MIN; /* Set init value of BE */
for (;ucNB <= MAC_NB_MAX;)/* If Number of backoff does not reach MAX.*/
{
ucRand = sg_ptCsma->pfRandom()%((1<<ucBE)-1); /* Get Random uint backoff delay */
printf("Random value is %d , Max value is %d\n",ucRand, ((1<<ucBE) -1));
CSMA_Backoff_Delay(ucRand); /* Delay random uint backoff period */
ucChClr = sg_ptCsma->pfCCA(); /* Perform a CCA */
if (CHANNEL_CLR == ucChClr) /* If the channel is clear */
{
printf("CSMA-CA is ok!\n");
return SW_OK; /* Get the channel */
}
else /* If the channel is busy */
{
ucNB++; /* Update NB value */
ucBE++; /* Update BE value */
ucBE = ((ucBE<MAC_BE_MAX)?ucBE : MAC_BE_MAX); /* Get the Min. value*/
printf("CSMA-CA is trying!, NB=%d, BE=%d\n",ucNB,ucBE);
}
}
printf("CSMA-CA is failed!\n");
return SW_ERR; /* Max number of backoff is over, fail to get clear channel */
break;
}
default: /* Invalid mode */
{
break;
}
}
return SW_ERR; /* failed operation */
}
/*************************************************************************
* Function :void CSMA_Backoff_Delay(uint8_t ucNum)
* Description :Perform CSMA-CA Backoff
* Input Param :uint8_t ucNum Number of backoff period
* Output Param:None
* Return :None
**************************************************************************/
void CSMA_Backoff_Delay(uint8_t ucNum)
{
if(0 == ucNum)
{
return; /* if the number of backoff unit is 0, no delay is needed */
}
else
{
Delay_ns(ucNum*BACKOFF_PERIOD_IN_US);
}
return;
}
/*************************************************************************
* Function :void Delay_ns(uint16_t ucNum)
* Description :Wait for ucNum of backoff period
* Input Param :uint8_t ucNum Number of backoff period
* Output Param:None
* Return :None
**************************************************************************/
void Delay_ns(uint16_t ucNum)
{
uint16_t wTemp;
for (wTemp = 0; wTemp < ucNum; wTemp++)
{
; /* Just wait */
}
return;
}
/* End of file */
| 2.578125 | 3 |
2024-11-18T20:50:27.882927+00:00 | 2021-08-30T11:38:31 | d9241aa4414d9035f307f583a7390415916d5862 | {
"blob_id": "d9241aa4414d9035f307f583a7390415916d5862",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-30T11:38:31",
"content_id": "a9ade2b59ae72e129ecab8842c1f366410942ce3",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "e31db985210aa40f6822a5eb9ab648b9ad083268",
"extension": "c",
"filename": "retention.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3687,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/libpgmoneta/retention.c",
"provenance": "stackv2-0110.json.gz:213571",
"repo_name": "zhuomingliang/pgmoneta",
"revision_date": "2021-08-30T11:38:31",
"revision_id": "9aa8cfc5922c4fa65cd20eb529d7025057d9a217",
"snapshot_id": "99953fecc10ddef7a2468d009f0ebd5bf6f7c19c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zhuomingliang/pgmoneta/9aa8cfc5922c4fa65cd20eb529d7025057d9a217/src/libpgmoneta/retention.c",
"visit_date": "2023-07-12T18:13:14.504127"
} | stackv2 | /*
* Copyright (C) 2021 Red Hat
*
* 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.
*/
/* pgmoneta */
#include <pgmoneta.h>
#include <delete.h>
#include <info.h>
#include <logging.h>
#include <retention.h>
#include <utils.h>
/* system */
#include <stdatomic.h>
#include <stdlib.h>
#include <unistd.h>
void
pgmoneta_retention(char** argv)
{
char* d;
int number_of_backups = 0;
struct backup** backups = NULL;
time_t t;
char check_date[128];
struct tm* time_info;
struct configuration* config;
pgmoneta_start_logging();
config = (struct configuration*)shmem;
pgmoneta_set_proc_title(1, argv, "retention", NULL);
for (int i = 0; i < config->number_of_servers; i++)
{
int retention;
t = time(NULL);
retention = config->servers[i].retention;
if (retention <= 0)
{
retention = config->retention;
}
memset(&check_date[0], 0, sizeof(check_date));
t = t - (retention * 24 * 60 * 60);
time_info = localtime(&t);
strftime(&check_date[0], sizeof(check_date), "%Y%m%d%H%M%S", time_info);
number_of_backups = 0;
backups = NULL;
d = NULL;
d = pgmoneta_append(d, config->base_dir);
d = pgmoneta_append(d, "/");
d = pgmoneta_append(d, config->servers[i].name);
d = pgmoneta_append(d, "/backup/");
pgmoneta_get_backups(d, &number_of_backups, &backups);
if (number_of_backups > 0)
{
for (int j = 0; j < number_of_backups; j++)
{
if (strcmp(backups[j]->label, &check_date[0]) < 0)
{
if (!backups[j]->keep)
{
if (!atomic_load(&config->servers[i].delete))
{
pgmoneta_delete(i, backups[j]->label);
pgmoneta_log_info("Retention: %s/%s", config->servers[i].name, backups[j]->label);
}
}
}
else
{
break;
}
}
}
pgmoneta_delete_wal(i);
for (int j = 0; j < number_of_backups; j++)
{
free(backups[j]);
}
free(backups);
free(d);
}
pgmoneta_stop_logging();
exit(0);
}
| 2.0625 | 2 |
2024-11-18T20:50:27.934465+00:00 | 2015-12-02T18:36:01 | 96d1dc75743ea5cc2906c10897172a1131bf219d | {
"blob_id": "96d1dc75743ea5cc2906c10897172a1131bf219d",
"branch_name": "refs/heads/master",
"committer_date": "2015-12-02T18:36:01",
"content_id": "c4845f3ddb73495a6288a7103861e3560267126e",
"detected_licenses": [
"MIT"
],
"directory_id": "b16c52e9470b3b62dbdf52d640b9603a6ac66f0d",
"extension": "c",
"filename": "6.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 46982348,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 565,
"license": "MIT",
"license_type": "permissive",
"path": "/6.c",
"provenance": "stackv2-0110.json.gz:213699",
"repo_name": "marcteves/cs11-class-project",
"revision_date": "2015-12-02T18:36:01",
"revision_id": "e364cc957ac76667612126b00d725b8ff00b7f94",
"snapshot_id": "5a07a323336f73689a6b2971682a71dd491ed2dc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marcteves/cs11-class-project/e364cc957ac76667612126b00d725b8ff00b7f94/6.c",
"visit_date": "2021-01-10T07:53:39.638194"
} | stackv2 | #include <stdio.h>
#define true 1
#define false 0
void main(){
long bulbs;
int i;
int state = false; //I assumed all the bulbs are initially on.
//At walk 1, the bulb will be off
printf("Problem 6: How many bulbs (0 < n <1 000 000 000) are present, Mr. Mabu?");
scanf("%ld", &bulbs);
for (i = 2; i <= bulbs; i++){
if (bulbs % i == 0){ //flip the switch
if (state){ //if it's on
state = false;
} else { //if it's off
state = true;
}
}
}
if (state){
printf("Bulb %d is on.", bulbs);
} else {
printf("Blub %d is off.", bulbs);
}
} | 3.484375 | 3 |
2024-11-18T20:50:28.070014+00:00 | 2023-08-11T13:02:43 | 8def664239077a516e8db9a408958cde6b09ab74 | {
"blob_id": "8def664239077a516e8db9a408958cde6b09ab74",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-11T13:02:43",
"content_id": "96a6595f5b6e01de0d9475d084dc39770ead52d2",
"detected_licenses": [
"MIT"
],
"directory_id": "751d837b8a4445877bb2f0d1e97ce41cd39ce1bd",
"extension": "c",
"filename": "write-program-in-your-favorite-language-in-another-language.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 115886967,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1866,
"license": "MIT",
"license_type": "permissive",
"path": "/codegolf/write-program-in-your-favorite-language-in-another-language.c",
"provenance": "stackv2-0110.json.gz:213828",
"repo_name": "qeedquan/challenges",
"revision_date": "2023-08-11T13:02:43",
"revision_id": "56823e77cf502bdea68cce0e1221f5add3d64d6a",
"snapshot_id": "d55146f784a3619caa4541ac6f2b670b0a3dd8ba",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/qeedquan/challenges/56823e77cf502bdea68cce0e1221f5add3d64d6a/codegolf/write-program-in-your-favorite-language-in-another-language.c",
"visit_date": "2023-08-11T20:35:09.726571"
} | stackv2 | /*
The determined Real Programmer can write Fortran programs in any language.
from Real Programmers Don't Use Pascal
Your task is to write program in your programming language of choice, but you are allowed to use only another language. That is, throw away all coding conventions from one language and replace them with coding conventions from other language. The more the better. Make your program look as if it was written in another language.
For example, Python fan who hates Java could write following Python program in Java:
void my_function() {
int i = 9 ;
while(i>0) {
System.out.println("Hello!") ;
i = i - 1 ;}}
Pascal enthusiast forced to use C could write this:
#define begin {
#define end }
#define then
#define writeln(str) puts(str)
if (i == 10) then
begin
writeln("I hate C");
end
You have to write complete program. The program desn't have to do anything useful.
Good Luck. This is a popularity contest so the code with the most votes wins!
*/
#include <stdio.h>
#define IF if(
#define THEN ){
#define ELSE } else {
#define ELIF } else if (
#define FI ;}
#define BEGIN {
#define END }
#define SWITCH switch(
#define IN ){
#define ENDSW }
#define FOR for(
#define WHILE while(
#define DO ){
#define OD ;}
#define REP do{
#define PER }while(
#define DONE );
#define LOOP for(;;){
#define POOL }
#define PROCEDURE int
#define MAIN main(void)
#define RETURN return
#define WRITELN(x) puts(x)
PROCEDURE MAIN
BEGIN
WRITELN("I hate C++");
RETURN(0);
END
| 3.1875 | 3 |
2024-11-18T20:50:28.502959+00:00 | 2021-01-16T22:31:24 | d1df666e18c977dc9ca49b5128c26a5f7c189119 | {
"blob_id": "d1df666e18c977dc9ca49b5128c26a5f7c189119",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-16T22:31:24",
"content_id": "c8d1b4b26afac0b16b2f950cf18de77733d5a7e3",
"detected_licenses": [
"MIT"
],
"directory_id": "7bcb5763ec32f184c3adf062104b96c34f6f6095",
"extension": "c",
"filename": "ut_vec2.c",
"fork_events_count": 2,
"gha_created_at": "2014-05-06T15:33:30",
"gha_event_created_at": "2017-02-12T10:39:30",
"gha_language": "C",
"gha_license_id": null,
"github_id": 19499817,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4398,
"license": "MIT",
"license_type": "permissive",
"path": "/test/ut_vec2.c",
"provenance": "stackv2-0110.json.gz:214084",
"repo_name": "rdentato/clibutl",
"revision_date": "2021-01-16T22:31:24",
"revision_id": "2a10396dee6d6011e6fb3f8924535fb6a69427ed",
"snapshot_id": "adc03dfb163e1a8110056898a98470ea2bf55522",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/rdentato/clibutl/2a10396dee6d6011e6fb3f8924535fb6a69427ed/test/ut_vec2.c",
"visit_date": "2021-08-24T16:26:35.934019"
} | stackv2 | /*
** (C) by Remo Dentato (rdentato@gmail.com)
**
** This software is distributed under the terms of the MIT license:
** https://opensource.org/licenses/MIT
**
** ___ __
** __/ /_ / )
** ___ __(_ ___) /
** / / / )/ / / /
** / (_/ // (__/ /
** (____,__/(_____(__/
** https://github.com/rdentato/clibutl
**
*/
#define UTL_MEMCHECK
#include "utl.h"
#include <math.h>
typedef struct point_s {
float x,y;
} point_t;
typedef struct {
char *k;
int v;
} mapSI_t;
int intcmp(void *a, void *b, void *aux)
{
return (*((int *)a) - *((int *)b));
}
uint32_t inthash(void *a, void *aux)
{
return utlhashint32(a);
}
uint32_t strhash(void *a, void *aux)
{
return utlhashstring(a);
}
/*
int pntcmp(void *a, void *b)
{
float delta;
point_t *a_pnt = a, *b_pnt = b;
delta = a_pnt->x - b_pnt->x;
if (delta < 0.0) return -1;
if (delta > 0.0) return 1;
delta = a_pnt->y - b_pnt->y;
if (delta < 0.0) return -1;
if (delta > 0.0) return 1;
return 0;
}
*/
void logtable(vec_t v)
{
uint8_t *p = v->vec;
uint32_t *q;
int32_t delta;
uint32_t k;
for (k=0; k<vecmax(v);k++) {
q = (uint32_t *)p;
if (q[1] == 0xFFFFFFFF) delta = -1;
else delta = k-(q[1] & (vecmax(v)-1));
logprintf("[%3d] -> h: %08X (%4d) key: %d",k,q[1],delta,q[0]);
p+=v->esz;
}
}
int main(int argc, char *argv[])
{
vec_t v;
int *pk;
int32_t *pi;
int32_t k;
int kk=-1;
/*
uint64_t *pu;
point_t p,q;
point_t *pq;
*/
logopen("l_vec2.log","w");
v=vecnew(int,intcmp);
logcheck(veccount(v) == 0);
vecadd(int,v,37);
logcheck(veccount(v) == 1);
pk=vecgetptr(v,0);
logcheck(pk && *pk == 37);
vecadd(int,v,5);
vecadd(int,v,79);
pk=vecgetptr(v,0);
logexpect(pk && *pk == 5,"[0]->%d",*pk);
pk=vecgetptr(v,1);
logexpect(pk && *pk == 37,"[1]->%d",*pk);
pk=vecgetptr(v,2);
logexpect(pk && *pk == 79,"[2]->%d",*pk);
logcheck(veccount(v) ==3);
pk = vecfirstptr(v);
logcheck(pk && *pk == 5);
pk = vecnextptr(v);
logcheck(pk && *pk == 37);
pk = vecnextptr(v);
logcheck(pk && *pk == 79);
pk = vecnextptr(v);
logcheck(!pk);
kk = vecfirst(int,v,-1);
logcheck(kk == 5);
kk = vecnext(int,v,-1);
logcheck(kk == 37);
kk = vecnext(int,v,-1);
logcheck(kk == 79);
kk = vecnext(int,v,-1);
logcheck(kk == -1);
vecfree(v);
srand(time(0));
v=vecnew(int,intcmp);
#define N 1000
vecset(int,v,N,0);
vecclear(v);
logprintf("cnt: %d max: %d",veccount(v),vecmax(v));
if (N <= 10000) {
logclock {
for (k=1;k<=N;k++)
//vecset(int,v,k-1,k);
vecadd(int,v, ((rand()&0x07) << 24) + k);
}
logcheck(veccount(v) == N);
}
logprintf("Added elements: %d",veccount(v));
#if 1
pk = vecgetptr(v,3);
if (pk) kk = *pk;
logprintf("Searching and removing %d",kk);
logcheck(vecsearch(int,v,kk));
logcheck(vecremove(int,v,kk));
logcheck(veccount(v) == (N-1));
logprintf("Current elements: %d",veccount(v));
logcheck(vecsearch(int,v,-98) == NULL);
vecfree(v);
/* * HASH * */
v = vecnew(int32_t,intcmp,inthash);
logcheck(v) ;
logprintf("cnt: %d max: %d esz:%d",veccount(v), vecmax(v), v->esz);
vecadd(int32_t,v,37);
logcheck(veccount(v) == 1) ;
vecadd(int32_t,v,493);
logcheck(veccount(v) == 2) ;
for (k = 0; k<20; k++) vecadd(int32_t,v,k ) ;
logcheck(veccount(v) == 22) ;
vecadd(int32_t,v,-1);
logcheck(veccount(v) == 23) ;
logprintf("cnt: %d max: %d esz:%d",veccount(v), vecmax(v), v->esz);
logtable(v);
pi = vecsearch(int32_t,v,12);
if (logcheck(pi && *pi==12))
logprintf("found: %d at %d",*pi,(int)((char *)pi - (char *)(v->vec))/v->esz);
pi = vecsearch(int32_t,v,98);
logcheck(!pi);
vecremove(int32_t,v,493);
logcheck(veccount(v) == 22) ;
logtable(v);
vecremove(int32_t,v,2);
logcheck(veccount(v) == 21) ;
logtable(v);
vecfree(v);
v = vecnew(int32_t,intcmp,inthash);
logcheck(v) ;
logprintf("cnt: %d max: %d esz:%d",veccount(v), vecmax(v), v->esz);
logclock {
for (k=1;k<=N;k++)
//vecset(int,v,k-1,k);
vecadd(int,v, ((rand()&0x07) << 24) + k);
}
logcheck(veccount(v) == N);
logprintf("Added elements: %d",veccount(v));
vecfree(v);
#endif
logclose();
exit(0);
}
| 2.734375 | 3 |
2024-11-18T20:50:28.755159+00:00 | 2023-03-14T10:21:50 | 89d19324b65662fdc19f72f5c7c5065f997a4680 | {
"blob_id": "89d19324b65662fdc19f72f5c7c5065f997a4680",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-14T10:21:50",
"content_id": "e63534c55aad7501c29fda8e3c8725847695dcb5",
"detected_licenses": [
"MIT"
],
"directory_id": "b609e7f0080632e06d7d99c852c85d4013b6860a",
"extension": "c",
"filename": "math_ex.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 194587140,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 837,
"license": "MIT",
"license_type": "permissive",
"path": "/Src/MATH_EX/math_ex.c",
"provenance": "stackv2-0110.json.gz:214342",
"repo_name": "Majid-Derhambakhsh/MPU6050",
"revision_date": "2023-03-14T10:21:50",
"revision_id": "886579a0714d467eaa8de050aed9ff2839ed7056",
"snapshot_id": "dd73736db5237273b9b77181a133532e3a9dbc8f",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/Majid-Derhambakhsh/MPU6050/886579a0714d467eaa8de050aed9ff2839ed7056/Src/MATH_EX/math_ex.c",
"visit_date": "2023-03-18T20:38:43.675585"
} | stackv2 | /*
------------------------------------------------------------------------------
~ File : math_ex.c
~ Author : Majid Derhambakhsh
~ Version: V0.0.0
~ Created: 06/12/2019 07:20:00 PM
~ Brief :
~ Support: Majid.do16@gmail.com
------------------------------------------------------------------------------
~ Description:
~ Attention :
------------------------------------------------------------------------------
*/
#include "math_ex.h"
/* ------------------------------- Function ------------------------------- */
int32_t Map(int32_t x, int32_t in_min, int32_t in_max, int32_t out_min, int32_t out_max) /* Function for calculating the mean arterial pressure (MAP) */
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; /* Calculate and return value */
/* Function End */
}
| 2.5625 | 3 |
2024-11-18T20:50:28.854251+00:00 | 2020-08-13T12:38:11 | 18b3e612f466d6fa46e7f2edea7661b364e8f188 | {
"blob_id": "18b3e612f466d6fa46e7f2edea7661b364e8f188",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-13T12:38:11",
"content_id": "1f4fd05f9ca12a61e2a38bc9e2654d9237d00cf1",
"detected_licenses": [
"Unlicense"
],
"directory_id": "a96447662f4eee7dce022f475f16eb03d530ad44",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 243522371,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14402,
"license": "Unlicense",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0110.json.gz:214470",
"repo_name": "cb0s/ASCII-Snake",
"revision_date": "2020-08-13T12:38:11",
"revision_id": "95dac2bfdc791da4f0c285c2ea5dbf0e6c8eb922",
"snapshot_id": "d591e4d8f5e6b557bf87c7a63afb3faaf4483b8e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cb0s/ASCII-Snake/95dac2bfdc791da4f0c285c2ea5dbf0e6c8eb922/main.c",
"visit_date": "2022-11-29T20:40:26.470561"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdbool.h>
#ifdef _WIN32
#include <windows.h>
#include <conio.h>
#endif
// Height of the field
#define HEIGHT 25
// Width of the field
#define WIDTH 60
// Drawings per second
#define FPS 6
// Sleeps for a given period of milliseconds
void wait(unsigned int ms)
{
#ifdef _WIN32
Sleep(ms);
#else
struct timespec ts;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000000; // equals (ms % 1_000) / 1_000_000
nanosleep(&ts, &ts);
#endif
}
long getNanoTime()
{
struct timespec ts;
int i = timespec_get(&ts, TIME_UTC);
return (long)ts.tv_sec * 1000000000L + ts.tv_nsec;
}
// Tells how the game looks and whether inputs must be read
typedef enum { EXIT = 0, MAIN_MENU = 1, SNAKE_GAME = 2, SNAKE_GAME_SPAWNPROCESS = 3, PAUSE = 4, GAME_OVER = 5 } GameState;
typedef enum { AIR = 0, WALL = 1, SNAKE_HEAD = 2, SNAKE_PART = 3, FOOD = 4 } GameElementID;
typedef enum { NORTH = 0, EAST = 1, SOUTH = 2, WEST = 3 } Direction;
typedef struct {
short score;
short highscore;
} ScoreBoard;
typedef struct {
GameState state;
Direction dir;
} Input;
typedef struct {
short x;
short y;
} Position;
struct SnakePart {
Position pos;
struct SnakePart *previous;
};
typedef struct SnakePart SnakePart;
typedef struct {
ScoreBoard* score;
Input* inp;
SnakePart* snake;
char* image;
GameElementID* field;
} Setup;
// Creates new SnakeElement in memory and returns its pointer
SnakePart* createSnakePart(Position pos, SnakePart *previous)
{
SnakePart *part = (SnakePart*) malloc(sizeof(SnakePart));
if (part == NULL) exit(-1);
part->pos = pos;
part->previous = previous;
return part;
}
Position *updatePos(Position *pos, Direction dir)
{
switch (dir)
{
case NORTH:
pos->y--;
break;
case EAST:
pos->x++;
break;
case SOUTH:
pos->y++;
break;
case WEST:
pos->x--;
break;
default:
break;
}
// That there will be no error regarding error bounds!
if (pos->x >= WIDTH) pos->x = WIDTH - 1;
else if (pos->x < 0) pos->x = 0;
if (pos->y >= HEIGHT) pos->y = HEIGHT - 1;
else if (pos->y < 0) pos->y = 0;
return pos;
}
// Evaluates Direction for an element based on the position of the previous one
// Note that part->previous MUST NOT BE NULL!
Direction evalDir(SnakePart* part)
{
if (part->pos.x == part->previous->pos.x)
{
if (part->pos.y > part->previous->pos.y) return NORTH;
else return SOUTH;
}
else
{
if (part->pos.x > part->previous->pos.x) return WEST;
else return EAST;
}
}
Direction getReverse(Direction dir)
{
switch (dir)
{
case NORTH:
return SOUTH;
case EAST:
return WEST;
case SOUTH:
return NORTH;
case WEST:
return EAST;
default:
return -1;
}
}
char getChar(GameElementID id)
{
char c = 0x0;
switch (id)
{
case AIR:
c = 0x20; // Equivalent to Space in ASCII
break;
case WALL:
c = 0x23; // Equivalent to # in ASCII
break;
case SNAKE_HEAD:
c = 0x7F;
break;
case SNAKE_PART:
c = 0xDB;
break;
case FOOD:
c = 0xFE;
break;
default:
c = 21; // Equivalent to ! in ASCII
break;
}
return c;
}
void insertString(char *dest, char src[], int lastPos)
{
short length = 0, index;
while (src[length]) length++;
for (index = 0; index < length; index++)
*(dest + lastPos - (length - index)) = src[index];
}
// Initializes all values with 0
void init_field(GameElementID* field)
{
// Init with AIR
{
short i; // WIDTH * HEIGHT can exceed sizeof(byte)
for (i = 0; i < WIDTH * HEIGHT; i++)
*(field + i) = AIR;
}
// Set Outer Borders
{
byte x, y;
for (x = 0; x < WIDTH; x++) {
*(field + x) = WALL;
*(field + (HEIGHT - 1) * WIDTH + x) = WALL;
}
for (y = 1; y < HEIGHT-1; y++)
{
*(field + y*WIDTH) = WALL;
*(field + (y + 1) * WIDTH - 1) = WALL;
}
}
}
Input *getInputs(Input *inp)
{
Input newInp = { inp->state, inp->dir };
while (_kbhit())
{
switch (getch())
{
case 'w':
if (inp->dir != SOUTH)
newInp.dir = NORTH;
break;
case 'a':
if (inp->dir != EAST)
newInp.dir = WEST;
break;
case 's':
if (inp->dir != NORTH)
newInp.dir = SOUTH;
break;
case 'd':
if (inp->dir != WEST)
newInp.dir = EAST;
break;
case 'q':
newInp.state = EXIT;
break;
case 'p':
if (inp->state == MAIN_MENU) newInp.state = SNAKE_GAME;
break;
case 0x1B:
if (inp->state == PAUSE)
newInp.state = SNAKE_GAME;
else if (inp->state == GAME_OVER)
newInp.state = MAIN_MENU;
else if (inp->state == MAIN_MENU)
newInp.state = EXIT;
else
newInp.state = PAUSE;
break;
}
}
inp->dir = newInp.dir;
inp->state = newInp.state;
return inp;
}
Setup* setUp(short highscore)
{
GameElementID* field = malloc(sizeof(GameElementID) * WIDTH * HEIGHT);
init_field(field);
char* image = malloc(sizeof(char) * (WIDTH) * (HEIGHT + 1));
Position pos = { 10, 10 };
SnakePart* snake = createSnakePart(*updatePos(&pos, SOUTH), createSnakePart(pos, NULL));
ScoreBoard* score = (ScoreBoard*) malloc(sizeof(ScoreBoard));
if (score == NULL) exit(-1);
score->highscore = highscore;
score->score = 0;
Input* input = (Input*) malloc(sizeof(Input));
if (input == NULL) exit(-1);
input->dir = SOUTH;
input->state = MAIN_MENU;
Setup* setup = (Setup*)malloc(sizeof(Setup));
if (setup == NULL || input == NULL || score == NULL || snake == NULL || image == NULL || field == NULL) exit(-1);
setup->field = field;
setup->image = image;
setup->inp = input;
setup->score = score;
setup->snake = snake;
return setup;
}
void cleanUp(SnakePart *snake, GameElementID *field, char *image, ScoreBoard *score, Input *input)
{
SnakePart* previous = snake;
SnakePart* previous2 = previous;
while (previous->previous != NULL)
{
previous2 = previous->previous;
free(previous);
previous = previous2;
}
free(field);
free(image);
free(input);
}
SnakePart* updateSnakePos(SnakePart *snake, Direction dir) // Could probably also be solved with recursion...
{
SnakePart *previous = snake;
while (previous->previous != NULL)
{
updatePos(&previous->pos, evalDir(previous));
previous = previous->previous;
}
updatePos(&previous->pos, dir);
return previous;
}
GameState checkSnake(SnakePart* head, SnakePart* tail, GameElementID* field, ScoreBoard* score)
{
GameElementID id = *(field + head->pos.y * WIDTH + head->pos.x);
switch (id)
{
case FOOD:
score->score++;
if (score->score > score->highscore) score->highscore++;
return SNAKE_GAME_SPAWNPROCESS;
case SNAKE_PART:
case WALL:
return GAME_OVER;
}
return SNAKE_GAME;
}
void updateField(GameElementID *field, SnakePart *snake, Position lastPos)
{
srand(getNanoTime());
*(field + lastPos.y * WIDTH + lastPos.x) = AIR;
short pointerDelta = 0;
short counter = 1;
do
{
counter++;
pointerDelta = snake->pos.y * WIDTH + snake->pos.x;
*(field + pointerDelta) = SNAKE_PART;
} while ((snake = snake->previous)->previous != NULL);
*(field + snake->pos.y * WIDTH + snake->pos.x) = SNAKE_HEAD;
// Spawn Actual Fruits
bool spawn = ((rand()) % 30) == 0;
if (spawn)
{
srand(getNanoTime());
counter = (rand()) % ((HEIGHT-2) * (WIDTH-2) - counter);
short i, a;
for (i = 0, a = 0; a < counter; i++)
if (*(field + i) == AIR) a++;
*(field + --i) = FOOD;
}
}
int draw(Input *lastInput, short currentFrame, SnakePart *snake, GameElementID *field, char *image, ScoreBoard *score)
{
// UPDATE
// Clean up for potential new game!
bool isMainMenu = lastInput->state == MAIN_MENU;
lastInput = getInputs(lastInput);
if (lastInput->state == SNAKE_GAME || lastInput->state == SNAKE_GAME_SPAWNPROCESS)
{
Position pos = snake->pos;
SnakePart* head = updateSnakePos(snake, lastInput->dir);
lastInput->state = checkSnake(head, snake, field, score);
updateField(field, snake, pos);
// Actual update of screen image buffer
short x, y;
for (y = 0; y < HEIGHT; y++)
{
for (x = 0; x < WIDTH; x++)
{
*(image + y * (WIDTH + 1) + x) = getChar(*(field + y * WIDTH + x));
}
*(image + y * (WIDTH + 1) + WIDTH) = '\n';
}
}
else if (lastInput->state == MAIN_MENU)
{
strcpy_s(image, WIDTH * (HEIGHT + 1), "\
\n\
### ### ## ## ## ## \n\
#### #### #### ## ### ## \n\
## ## ## ## ## ## ## ## ## ## \n\
## ## ## ## ## ## ## ## ## ## \n\
## ## ## ## ## ## ## ## ## ## \n\
## #### ## ############ ## ## ## ## \n\
## ## ## ## ## ## ## ### \n\
## ## ## ## ## ## ## \n\
\n\
### ### ########## ## ## ## ## \n\
#### #### ## ### ## ## ## \n\
## ## ## ## ## ## ## ## ## ## \n\
## ## ## ## ###### ## ## ## ## ## \n\
## ## ## ## ## ## ## ## ## ## \n\
## #### ## ## ## ## ## ## ## \n\
## ## ## ## ## ### ## ## \n\
## ## ########## ## ## ###### \n\
\n\
\n\
###########################################################\n\
# Welcome to ASCII-Snake! Press: #\n\
# (p) to play #\n\
# (q) to quit #\n\
###########################################################");
}
else if (lastInput->state == GAME_OVER)
{
strcpy_s(image, WIDTH * (HEIGHT+1), "\
\n\
######## ## ### ### ##########\n\
### ## #### #### #### ## \n\
## ## ## ## ## ## ## ## \n\
## ## ## ## ## ## ## ###### \n\
## ###### ## ## ## ## ## ## ## \n\
## # ############ ## #### ## ## \n\
### ### ## ## ## ## ## ## \n\
######## ## ## ## ## ##########\n\
\n\
###### ## ## ########## ######## ##\n\
## ## ## ## ## ## ## ##\n\
## ## ## ## ## ## ## ##\n\
## ## ## ## ###### ## ## ##\n\
## ## ## ## ## ######## ##\n\
## ## ## ## ## ## ## ##\n\
## ## #### ## ## ## \n\
###### ## ########## ## ## ##\n\
\n\
\n\
##########################################################\n\
# Score: Point(s) #\n\
# Highscore: Point(s) #\n\
# Press (q) to quit or (Esc) to return to the Main-Menu! #\n\
##########################################################");
char buffer[5] = { 0x0, 0x0, 0x0, 0x0 };
sprintf_s(buffer, 5, "%d", score->score);
insertString(image, buffer, 1286);
int i;
for (i = 0; i < 5; i++) buffer[i] = 0x0;
sprintf_s(buffer, 5, "%d", score->score > score->highscore ? score->score : score->highscore);
insertString(image, buffer, 1345);
}
// RENDER
// TODO: Try to improve this!
// Clear Screen!
system("@cls||clear");
if (lastInput->state == PAUSE) printf("[PAUSED]\n");
printf("%s", image);
if (lastInput->state != GAME_OVER && lastInput->state != MAIN_MENU && lastInput->state != EXIT)
{
char c[] = "\
Score: Point(s)\n\
High-Score: Point(s)";
char buffer[5] = { 0x0, 0x0, 0x0, 0x0 };
sprintf_s(buffer, 5, "%d", score->score);
insertString(c, buffer, 17);
int i;
for (i = 0; i < 5; i++) buffer[i] = 0x0;
sprintf_s(buffer, 5, "%d", score->score > score->highscore ? score->score : score->highscore);
insertString(c, buffer, 44);
printf("%s", c);
}
if (lastInput->state == MAIN_MENU && !(isMainMenu))
{
cleanUp(snake, field, image, score, lastInput);
lastInput = NULL;
}
return lastInput;
}
int main()
{
printf("Starting ASCII-Snake");
// Showing Loading Animation
{
time_t msec;
short i;
for (i = 0; i < 10; i++)
{
printf(".");
msec = time(NULL) * 1000;
wait(200 + (rand() * msec) % 600);
}
printf("\n");
}
printf("Loaded!\n");
wait(200);
{
// TODO: Loading Animation + Actual init in parallel!
GameElementID* field = NULL;
char* image = NULL;
SnakePart* snake = NULL;
ScoreBoard* score = NULL;
Input* inp = NULL;
{
Setup* setup = setUp(0);
field = setup->field;
image = setup->image;
snake = setup->snake;
score = setup->score;
inp = setup->inp;
}
GameState currentState = SNAKE_GAME;
unsigned short targetDelta = 1000 / FPS;
short currentFrame = 0;
long start;
short highscore = 0;
while (currentState)
{
start = getNanoTime();
inp = draw(inp, currentFrame, snake, field, image, score);
if (inp == NULL)
{
field = NULL;
image = NULL;
snake = NULL;
score = NULL;
{
Setup* setup = setUp(highscore);
field = setup->field;
image = setup->image;
snake = setup->snake;
score = setup->score;
inp = setup->inp;
}
}
currentState = inp->state;
if (currentFrame - FPS >= -1) currentFrame = 0;
else currentFrame++;
if (currentState == SNAKE_GAME_SPAWNPROCESS)
{
Position pos = { snake->pos.x, snake->pos.y };
Direction dir = getReverse(evalDir(snake));
snake = createSnakePart(*updatePos(&pos, dir), snake);
}
highscore = score->highscore;
wait((int) (targetDelta - (getNanoTime()-start)/1000000000L));
}
// Clean up potential mess
cleanUp(snake, field, image, score, inp);
printf("\n\nYour Highscore was: %d Point(s)\n", highscore);
printf("Exiting");
// Showing Loading Animation
{
time_t msec;
short i;
for (i = 0; i < 10; i++)
{
printf(".");
wait(500);
}
printf("\n");
}
}
return 0;
}
| 2.78125 | 3 |
2024-11-18T20:50:29.024157+00:00 | 2015-11-09T08:54:39 | 192ff17834c94e1fae949e73832f036a81a8c59b | {
"blob_id": "192ff17834c94e1fae949e73832f036a81a8c59b",
"branch_name": "refs/heads/master",
"committer_date": "2015-11-09T08:54:39",
"content_id": "0780ee0fe25187070a6c950f60998159300102ae",
"detected_licenses": [
"MIT"
],
"directory_id": "3587670c1656e087f4a73596e7e31ca4c8f33c8b",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5597,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0110.json.gz:214732",
"repo_name": "ashishverma2614/nRF51-diwali-lamp",
"revision_date": "2015-11-09T08:54:39",
"revision_id": "7f47826566fd13a3f0ca7733aabf7179f1dccf56",
"snapshot_id": "d09f5fa7848bc0baafa564366583a9eb71dc32d7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ashishverma2614/nRF51-diwali-lamp/7f47826566fd13a3f0ca7733aabf7179f1dccf56/main.c",
"visit_date": "2021-05-04T00:41:11.687255"
} | stackv2 | /*
nRF51-diwali/main.c
Hacking a cheap Diwali LED Lamp with nRF51822 BLE.
Author: Mahesh Venkitachalam
Website: electronut.in
Reference:
http://infocenter.nordicsemi.com/index.jsp?topic=%2Fcom.nordic.infocenter.sdk51.v9.0.0%2Findex.html
*/
#include "ble_init.h"
extern ble_nus_t m_nus;
// Create the instance "PWM1" using TIMER2.
APP_PWM_INSTANCE(PWM1,2);
// These are based on default values sent by Nordic nRFToolbox app
// Modify as neeeded
#define FORWARD "FastForward"
#define REWIND "Rewind"
#define STOP "Stop"
#define PAUSE "Pause"
#define PLAY "Play"
#define START "Start"
#define END "End"
#define RECORD "Rec"
#define SHUFFLE "Shuffle"
// events
typedef enum _AppEventType {
eAppEvent_Start,
eAppEvent_Stop,
eAppEvent_Slower,
eAppEvent_Faster
} AppEventType;
// structure handle pending events
typedef struct _AppEvent
{
bool pending;
AppEventType event;
int data;
} AppEvent;
AppEvent appEvent;
uint32_t delay = 20;
// Function for handling the data from the Nordic UART Service.
static void nus_data_handler(ble_nus_t * p_nus, uint8_t * p_data,
uint16_t length)
{
if (strstr((char*)(p_data), REWIND)) {
appEvent.event = eAppEvent_Slower;
appEvent.pending = true;
}
else if (strstr((char*)(p_data), FORWARD)) {
appEvent.event = eAppEvent_Faster;
appEvent.pending = true;
}
else if (strstr((char*)(p_data), STOP)) {
appEvent.event = eAppEvent_Stop;
appEvent.pending = true;
}
else if (strstr((char*)(p_data), PLAY)) {
appEvent.event = eAppEvent_Start;
appEvent.pending = true;
}
}
// A flag indicating PWM status.
static volatile bool pwmReady = false;
// PWM callback function
void pwm_ready_callback(uint32_t pwm_id)
{
pwmReady = true;
}
// Function for initializing services that will be used by the application.
void services_init()
{
uint32_t err_code;
ble_nus_init_t nus_init;
memset(&nus_init, 0, sizeof(nus_init));
nus_init.data_handler = nus_data_handler;
err_code = ble_nus_init(&m_nus, &nus_init);
APP_ERROR_CHECK(err_code);
}
#define APP_TIMER_PRESCALER 0 /**< Value of the RTC1 PRESCALER register. */
#define APP_TIMER_MAX_TIMERS 6 /**< Maximum number of simultaneously created timers. */
#define APP_TIMER_OP_QUEUE_SIZE 4 /**< Size of timer operation queues. */
// Application main function.
int main(void)
{
uint32_t err_code;
// set up timers
APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_MAX_TIMERS,
APP_TIMER_OP_QUEUE_SIZE, false);
// initlialize BLE
ble_stack_init();
gap_params_init();
services_init();
advertising_init();
conn_params_init();
// start BLE advertizing
err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
APP_ERROR_CHECK(err_code);
// init GPIOTE
err_code = nrf_drv_gpiote_init();
APP_ERROR_CHECK(err_code);
// init PPI
err_code = nrf_drv_ppi_init();
APP_ERROR_CHECK(err_code);
// intialize UART
uart_init();
// prints to serial port
printf("starting...\n");
// set up LED
uint32_t pinLED = 28;
//nrf_gpio_pin_dir_set(pinLED, NRF_GPIO_PIN_DIR_OUTPUT);
// 2-channel PWM
app_pwm_config_t pwm1_cfg =
APP_PWM_DEFAULT_CONFIG_1CH(5000L, pinLED);
pwm1_cfg.pin_polarity[0] = APP_PWM_POLARITY_ACTIVE_LOW;
printf("before pwm init\n");
/* Initialize and enable PWM. */
err_code = app_pwm_init(&PWM1,&pwm1_cfg,pwm_ready_callback);
APP_ERROR_CHECK(err_code);
printf("after pwm init\n");
//app_pwm_enable(&PWM1);
printf("entering loop\n");
int dir = 1;
int val = 0;
appEvent.pending = false;
while(1) {
// PWM stop/start requires some tricks
// because app_pwm_disable() has a bug.
// See:
// https://devzone.nordicsemi.com/question/41179/how-to-stop-pwm-and-set-pin-to-clear/
// is event flag set?
if (appEvent.pending) {
switch(appEvent.event) {
case eAppEvent_Start:
{
nrf_drv_gpiote_out_task_enable(pinLED);
app_pwm_enable(&PWM1);
}
break;
case eAppEvent_Stop:
{
app_pwm_disable(&PWM1);
nrf_drv_gpiote_out_task_disable(pinLED);
nrf_gpio_cfg_output(pinLED);
nrf_gpio_pin_set(pinLED);
}
break;
case eAppEvent_Faster:
{
if (delay > 5) {
delay -= 5;
}
}
break;
case eAppEvent_Slower:
{
if( delay < 80) {
delay += 5;
}
}
break;
}
// reset flag
appEvent.pending = false;
}
while (app_pwm_channel_duty_set(&PWM1, 0, val) == NRF_ERROR_BUSY);
// change direction at edges
if(val > 99) {
dir = -1;
}
else if (val < 1){
dir = 1;
}
// increment/decrement
val += dir*2;
// delay
nrf_delay_ms(delay);
}
}
| 2.203125 | 2 |
2024-11-18T20:50:29.124375+00:00 | 2017-10-11T15:07:19 | 24e76f2db5d404d01b60ae74e7ca6c59c1da794b | {
"blob_id": "24e76f2db5d404d01b60ae74e7ca6c59c1da794b",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-11T15:07:19",
"content_id": "0c52545bac4f17e05d31e6e5569a375b7bcd23bb",
"detected_licenses": [
"MIT"
],
"directory_id": "a8518e223b82b8b5df6168e0bd6598d178e52300",
"extension": "c",
"filename": "basm_core.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 53080263,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 67942,
"license": "MIT",
"license_type": "permissive",
"path": "/bsvm2/bgbasm3/asm/basm_core.c",
"provenance": "stackv2-0110.json.gz:214864",
"repo_name": "cr88192/bgbtech_engine2",
"revision_date": "2017-10-11T15:07:19",
"revision_id": "e6c0e11f0b70ac8544895a10133a428d5078d413",
"snapshot_id": "22b9ab421ffb973095d861429703e71fc89e88fe",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cr88192/bgbtech_engine2/e6c0e11f0b70ac8544895a10133a428d5078d413/bsvm2/bgbasm3/asm/basm_core.c",
"visit_date": "2020-12-25T16:54:08.057153"
} | stackv2 | // #include <bgbasm.h>
#if 1
extern char *basm_ops_x86[];
extern int basm_opidx_x86[];
extern int basm_opnums_x86[];
extern char basm_opcat_x86[];
extern char *basm_opdecl_x86[];
extern char *basm_regs_x86[];
extern int basm_regidx_x86[];
#endif
#if 1
extern char *basm_ops_arm[];
extern int basm_opidx_arm[];
extern int basm_opnums_arm[];
extern char basm_opcat_arm[];
extern char *basm_opdecl_arm[];
extern char *basm_regs_arm[];
extern int basm_regidx_arm[];
#endif
#if 1
extern char *basm_ops_thumb[];
extern int basm_opidx_thumb[];
extern int basm_opnums_thumb[];
extern char basm_opcat_thumb[];
extern char *basm_opdecl_thumb[];
extern char *basm_regs_thumb[];
extern int basm_regidx_thumb[];
#endif
#if 1
char **basm_ops;
int *basm_opidx;
int *basm_opnums;
char *basm_opcat;
char **basm_opdecl;
char **basm_regs;
int *basm_regidx;
#endif
int basm_cpu;
FILE *basm_log=NULL;
void BASM_SetCPU(BASM_Context *ctx, int cpu)
{
ctx->fl&=~(BASM_FL_X86_64|BASM_FL_X86_16|BASM_FL_ARM|BASM_FL_THUMB);
ctx->fl&=~(BASM_FL_DATA|BASM_FL_ADDRSZ|BASM_FL_GAS);
ctx->fl&=~(BASM_FL_BUNDLE);
if((cpu==BASM_CPU_X64) || (cpu==BASM_CPU_NACL_X64))
ctx->fl|=BASM_FL_X86_64;
if(cpu==BASM_CPU_ARM)
ctx->fl|=BASM_FL_ARM;
if(cpu==BASM_CPU_THUMB)
ctx->fl|=BASM_FL_ARM|BASM_FL_THUMB;
if((cpu==BASM_CPU_NACL_X86) || (cpu==BASM_CPU_NACL_X64))
ctx->fl|=BASM_FL_BUNDLE;
ctx->cpu=cpu;
basm_cpu=cpu;
switch(cpu)
{
case BASM_CPU_X86:
case BASM_CPU_X64:
case BASM_CPU_NACL_X86:
case BASM_CPU_NACL_X64:
basm_ops=basm_ops_x86;
basm_opidx=basm_opidx_x86;
basm_opnums=basm_opnums_x86;
basm_opcat=basm_opcat_x86;
basm_opdecl=basm_opdecl_x86;
basm_regs=basm_regs_x86;
basm_regidx=basm_regidx_x86;
break;
case BASM_CPU_ARM:
basm_ops=basm_ops_arm;
basm_opidx=basm_opidx_arm;
basm_opnums=basm_opnums_arm;
basm_opcat=basm_opcat_arm;
basm_opdecl=basm_opdecl_arm;
basm_regs=basm_regs_arm;
basm_regidx=basm_regidx_arm;
break;
case BASM_CPU_THUMB:
basm_ops=basm_ops_thumb;
basm_opidx=basm_opidx_thumb;
basm_opnums=basm_opnums_thumb;
basm_opcat=basm_opcat_thumb;
basm_opdecl=basm_opdecl_thumb;
basm_regs=basm_regs_thumb;
basm_regidx=basm_regidx_thumb;
break;
default:
break;
}
}
void basm_warning(char *str, ...)
{
char tb[4096];
va_list lst;
if(!basm_log)basm_log=fopen("bgbasm_log.txt", "wt");
va_start(lst, str);
vsprintf(tb, str, lst);
va_end(lst);
if(basm_log)
{
fputs(tb, basm_log);
fflush(basm_log);
}
fputs(tb, stderr);
fflush(stderr);
}
void basm_error(char *str, ...)
{
char tb[4096];
va_list lst;
if(!basm_log)basm_log=fopen("bgbasm_log.txt", "wt");
va_start(lst, str);
vsprintf(tb, str, lst);
va_end(lst);
if(basm_log)
{
fputs(tb, basm_log);
fflush(basm_log);
}
fputs(tb, stderr);
fflush(stderr);
}
BASM_API BASM_Context *BASM_NewContext()
{
BASM_Context *tmp;
tmp=(BASM_Context *)malloc(sizeof(BASM_Context));
memset(tmp, 0, sizeof(BASM_Context));
tmp->label_name=(char **)malloc(256*sizeof(char *));
tmp->label_pos=(int *)malloc(256*sizeof(int));
tmp->goto_name=(char **)malloc(256*sizeof(char *));
tmp->goto_pos=(int *)malloc(256*sizeof(int));
tmp->goto_type=(byte *)malloc(256*sizeof(byte));
tmp->const_name=(char **)malloc(256*sizeof(char *));
tmp->const_value=(long long *)malloc(256*sizeof(long long));
tmp->proxy_name=(char **)malloc(256*sizeof(char *));
tmp->m_labels=256;
tmp->m_gotos=256;
tmp->m_const=256;
tmp->m_proxy=256;
tmp->llbl_name=(char **)malloc(256*sizeof(char *));
tmp->llbl_pos=(int *)malloc(256*sizeof(int));
return(tmp);
}
BASM_API void BASM_DestroyContext(BASM_Context *ctx)
{
if(!ctx)return;
free(ctx->label_name);
free(ctx->label_pos);
free(ctx->goto_name);
free(ctx->goto_pos);
free(ctx->goto_type);
free(ctx->const_name);
free(ctx->const_value);
free(ctx->proxy_name);
free(ctx->llbl_name);
free(ctx->llbl_pos);
free(ctx);
}
BASM_API void *BASM_TempAllocTy(BASM_Context *ctx, char *ty, int sz)
{
void *p;
if(!ctx->alloc_rov)
{
ctx->alloc_srov=malloc(1<<18);
ctx->alloc_erov=ctx->alloc_srov+(1<<18);
ctx->alloc_rov=ctx->alloc_srov;
ctx->alloc_block[ctx->alloc_nblock++]=
ctx->alloc_rov;
}
if((ctx->alloc_rov+sz)>=(ctx->alloc_erov-4096))
{
printf("BASM_TempAlloc: Expand\n");
ctx->alloc_srov=malloc(1<<18);
ctx->alloc_erov=ctx->alloc_srov+(1<<18);
ctx->alloc_rov=ctx->alloc_srov;
ctx->alloc_block[ctx->alloc_nblock++]=
ctx->alloc_rov;
}
p=ctx->alloc_rov;
ctx->alloc_rov+=(sz+15)&(~15);
memset(p, 0, sz);
return(p);
}
BASM_API void *BASM_TempAlloc(BASM_Context *ctx, int sz)
{ return(BASM_TempAllocTy(ctx, NULL, sz)); }
BASM_API void BASM_OutPadText(BASM_Context *ctx, int i)
{
static byte seqs[9][16]={
{ 0x90, }, { 0x66, 0x90, }, { 0x0F, 0x1F, 0x00, },
{ 0x0F, 0x1F, 0x40, 0x00, }, { 0x0F, 0x1F, 0x44, 0x00, 0x00, },
{ 0x66, 0x0F, 0x1F, 0x44, 0x00, 0x00, },
{ 0x0F, 0x1F, 0x80, 0x00, 0x00, 0x00, 0x00, },
{ 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, },
{ 0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, },
};
int j;
if(i<=0)return;
#if 0
j=i;
while(j>1)
{
BASM_OutByte(ctx, 0x66);
BASM_OutByte(ctx, 0x90);
j-=2;
}
if(j)BASM_OutByte(ctx, 0x90);
return;
#endif
#if 1
if(i>9)
{
if(i==10)
{
BASM_OutPadText(ctx, 7);
BASM_OutPadText(ctx, 3);
return;
}
if(i==14)
{
BASM_OutPadText(ctx, 7);
BASM_OutPadText(ctx, 7);
return;
}
BASM_OutPadText(ctx, 8);
BASM_OutPadText(ctx, i-8);
return;
}
for(j=0; j<i; j++)
BASM_OutByte(ctx, seqs[i][j]);
#endif
}
BASM_API void BASM_OutPadZero(BASM_Context *ctx, int i)
{
while(i--)BASM_OutByte(ctx, 0x00);
}
BASM_API void BASM_OutPadVLI(BASM_Context *ctx, int i)
{
switch(i)
{
case 0: break;
case 1: BASM_OutByte(ctx, 0x00); break;
case 2: BASM_OutByte(ctx, 0x80); BASM_OutByte(ctx, 0x00); break;
case 3: BASM_OutByte(ctx, 0xC0); BASM_OutPadZero(ctx, 2); break;
case 4: BASM_OutByte(ctx, 0xE0); BASM_OutPadZero(ctx, 3); break;
case 5: BASM_OutByte(ctx, 0xF0); BASM_OutPadZero(ctx, 4); break;
case 6: BASM_OutByte(ctx, 0xF8); BASM_OutPadZero(ctx, 5); break;
case 7: BASM_OutByte(ctx, 0xFC); BASM_OutPadZero(ctx, 6); break;
case 8: BASM_OutByte(ctx, 0xFE); BASM_OutPadZero(ctx, 7); break;
case 9: BASM_OutByte(ctx, 0xFF); BASM_OutByte(ctx, 0x00);
BASM_OutPadZero(ctx, 7); break;
case 10: BASM_OutByte(ctx, 0xFF); BASM_OutByte(ctx, 0x80);
BASM_OutPadZero(ctx, 8); break;
case 11: BASM_OutByte(ctx, 0xFF); BASM_OutByte(ctx, 0xC0);
BASM_OutPadZero(ctx, 9); break;
case 12: BASM_OutByte(ctx, 0xFF); BASM_OutByte(ctx, 0xE0);
BASM_OutPadZero(ctx, 10); break;
case 13: BASM_OutByte(ctx, 0xFF); BASM_OutByte(ctx, 0xE0);
BASM_OutPadZero(ctx, 11); break;
case 14: BASM_OutByte(ctx, 0xFF); BASM_OutByte(ctx, 0xF0);
BASM_OutPadZero(ctx, 12); break;
case 15: BASM_OutByte(ctx, 0xFF); BASM_OutByte(ctx, 0xF8);
BASM_OutPadZero(ctx, 13); break;
}
}
BASM_API void BASM_OutPad(BASM_Context *ctx, int i)
{
int j, k;
if(i<=0)return;
if(ctx->fl&4)
{ BASM_OutPadZero(ctx, i); }
else
{ BASM_OutPadText(ctx, i); }
}
#if 0
BASM_API void BASM_Align(BASM_Context *ctx, int i)
{
int j, k;
if(ctx->fl&4)
{
j=ctx->dp-ctx->data;
k=j; if(j%i)j+=i-(j%i);
if(j>=ctx->data_sz)
{
while(j>=ctx->data_sz)
ctx->data_sz+=ctx->data_sz>>1;
ctx->data=(byte *)realloc(ctx->data, ctx->data_sz);
// ctx->dp=ctx->data+j;
}
while(k<j) { *ctx->dp++=0; k++; }
}else
{
#if 1
j=ctx->ip-ctx->text;
if(j%i)BASM_OutPadText(ctx, i-(j%i));
#else
j=ctx->ip-ctx->text;
k=j; if(j%i)j+=i-(j%i);
if((j+3)>=ctx->text_sz)
{
while((j+3)>=ctx->text_sz)
ctx->text_sz+=ctx->text_sz>>1;
ctx->text=(byte *)realloc(ctx->text, ctx->text_sz);
// ctx->ip=ctx->text+j;
}
while(k<j) { *ctx->ip++=0; k++; }
#endif
}
}
#endif
BASM_API int BASM_GetSectionOffset(BASM_Context *ctx)
{
int j, k;
if(ctx->fl&4)
{
j=ctx->dp-ctx->data;
return(j);
}else
{
j=ctx->ip-ctx->text;
return(j);
}
}
BASM_API void BASM_BundleAlign(BASM_Context *ctx)
{
if(!(ctx->fl&BASM_FL_BUNDLE))
return;
if(ctx->fl&BASM_FL_DATA)
return;
BASM_Align(ctx, 32);
}
BASM_API void BASM_Align(BASM_Context *ctx, int i)
{
int j, k;
if(ctx->fl&4)
{
j=ctx->dp-ctx->data;
if(j%i)BASM_OutPadZero(ctx, i-(j%i));
}else
{
j=ctx->ip-ctx->text;
if(j%i)BASM_OutPadText(ctx, i-(j%i));
}
}
BASM_API void BASM_AlignVLI(BASM_Context *ctx, int i)
{
int j, k;
if(ctx->fl&4)
{
j=ctx->dp-ctx->data;
if(j%i)BASM_OutPadVLI(ctx, i-(j%i));
}else
{
j=ctx->ip-ctx->text;
if(j%i)BASM_OutPadVLI(ctx, i-(j%i));
}
}
BASM_API void BASM_OutByte(BASM_Context *ctx, int i)
{
int j;
if(ctx->fl&4)
{
j=ctx->dp-ctx->data;
if((j+3)>=ctx->data_sz)
{
ctx->data_sz+=ctx->data_sz>>1;
ctx->data=(byte *)realloc(ctx->data, ctx->data_sz);
ctx->dp=ctx->data+j;
}
*ctx->dp++=i;
}else
{
j=ctx->ip-ctx->text;
if((j+3)>=ctx->text_sz)
{
ctx->text_sz+=ctx->text_sz>>1;
ctx->text=(byte *)realloc(ctx->text, ctx->text_sz);
ctx->ip=ctx->text+j;
}
*ctx->ip++=i;
}
}
BASM_API void BASM_OutWord(BASM_Context *ctx, int i)
{
BASM_OutByte(ctx, i&0xFF);
BASM_OutByte(ctx, (i>>8)&0xFF);
}
BASM_API void BASM_OutDWord(BASM_Context *ctx, int i)
{
BASM_OutByte(ctx, i&0xFF);
BASM_OutByte(ctx, (i>>8)&0xFF);
BASM_OutByte(ctx, (i>>16)&0xFF);
BASM_OutByte(ctx, (i>>24)&0xFF);
}
BASM_API void BASM_OutQWord(BASM_Context *ctx,
long long i)
{
BASM_OutByte(ctx, i&0xFF);
BASM_OutByte(ctx, (i>>8)&0xFF);
BASM_OutByte(ctx, (i>>16)&0xFF);
BASM_OutByte(ctx, (i>>24)&0xFF);
BASM_OutByte(ctx, (i>>32)&0xFF);
BASM_OutByte(ctx, (i>>40)&0xFF);
BASM_OutByte(ctx, (i>>48)&0xFF);
BASM_OutByte(ctx, (i>>56)&0xFF);
}
BASM_API void BASM_OutUVLIP(BASM_Context *ctx,
unsigned long long i, int pad)
{
if(i<((1LL<<7)-pad))
{
BASM_OutByte(ctx, i&0x7F); return;
}
if(i<((1LL<<14)-pad))
{
BASM_OutByte(ctx, 0x80|((i>>8)&0x3F));
BASM_OutByte(ctx, i&0xFF);
return;
}
if(i<((1LL<<21)-pad))
{
BASM_OutByte(ctx, 0xC0|((i>>16)&0x1F));
BASM_OutByte(ctx, (i>>8)&0xFF);
BASM_OutByte(ctx, i&0xFF);
return;
}
if(i<((1LL<<28)-pad))
{
BASM_OutByte(ctx, 0xE0|((i>>24)&0x0F));
BASM_OutByte(ctx, (i>>16)&0xFF);
BASM_OutByte(ctx, (i>>8)&0xFF);
BASM_OutByte(ctx, i&0xFF);
return;
}
if(i<((1LL<<35)-pad))
{
BASM_OutByte(ctx, 0xF0|((i>>32)&0x07));
BASM_OutByte(ctx, (i>>24)&0xFF);
BASM_OutByte(ctx, (i>>16)&0xFF);
BASM_OutByte(ctx, (i>>8)&0xFF);
BASM_OutByte(ctx, i&0xFF);
return;
}
if(i<((1LL<<42)-pad))
{
BASM_OutByte(ctx, 0xF8|((i>>40)&0x03));
BASM_OutByte(ctx, (i>>32)&0xFF);
BASM_OutByte(ctx, (i>>24)&0xFF);
BASM_OutByte(ctx, (i>>16)&0xFF);
BASM_OutByte(ctx, (i>>8)&0xFF);
BASM_OutByte(ctx, i&0xFF);
return;
}
if(i<((1LL<<49)-pad))
{
BASM_OutByte(ctx, 0xFC|((i>>48)&0x01));
BASM_OutByte(ctx, (i>>40)&0xFF);
BASM_OutByte(ctx, (i>>32)&0xFF);
BASM_OutByte(ctx, (i>>24)&0xFF);
BASM_OutByte(ctx, (i>>16)&0xFF);
BASM_OutByte(ctx, (i>>8)&0xFF);
BASM_OutByte(ctx, i&0xFF);
return;
}
if(i<((1LL<<56)-pad))
{
BASM_OutByte(ctx, 0xFE);
BASM_OutByte(ctx, (i>>48)&0xFF);
BASM_OutByte(ctx, (i>>40)&0xFF);
BASM_OutByte(ctx, (i>>32)&0xFF);
BASM_OutByte(ctx, (i>>24)&0xFF);
BASM_OutByte(ctx, (i>>16)&0xFF);
BASM_OutByte(ctx, (i>>8)&0xFF);
BASM_OutByte(ctx, i&0xFF);
return;
}
if(i<((1LL<<63)-pad))
{
BASM_OutByte(ctx, 0xFF);
BASM_OutByte(ctx, (i>>56)&0x7F);
BASM_OutByte(ctx, (i>>48)&0xFF);
BASM_OutByte(ctx, (i>>40)&0xFF);
BASM_OutByte(ctx, (i>>32)&0xFF);
BASM_OutByte(ctx, (i>>24)&0xFF);
BASM_OutByte(ctx, (i>>16)&0xFF);
BASM_OutByte(ctx, (i>>8)&0xFF);
BASM_OutByte(ctx, i&0xFF);
return;
}
// BASM_OutByte(ctx, 0x80|((i>>64)&0x3F));
BASM_OutByte(ctx, 0xFF);
BASM_OutByte(ctx, 0x80);
BASM_OutByte(ctx, (i>>56)&0xFF);
BASM_OutByte(ctx, (i>>48)&0xFF);
BASM_OutByte(ctx, (i>>40)&0xFF);
BASM_OutByte(ctx, (i>>32)&0xFF);
BASM_OutByte(ctx, (i>>24)&0xFF);
BASM_OutByte(ctx, (i>>16)&0xFF);
BASM_OutByte(ctx, (i>>8)&0xFF);
BASM_OutByte(ctx, i&0xFF);
return;
}
BASM_API void BASM_OutUVLI(BASM_Context *ctx, unsigned long long i)
{
BASM_OutUVLIP(ctx, i, 0);
}
BASM_API void BASM_OutSVLI(BASM_Context *ctx, long long i)
{
i=(i<0)?(((-i)<<1)-1):(i<<1);
BASM_OutUVLIP(ctx, i, 0);
}
BASM_API void BASM_OutSVLIP(BASM_Context *ctx, long long i, int pad)
{
i=(i<0)?(((-i)<<1)-1):(i<<1);
BASM_OutUVLIP(ctx, i, pad);
}
BASM_API void BASM_OutStr8(BASM_Context *ctx, char *str)
{
unsigned char *s;
s=(unsigned char *)str;
while(*s)BASM_OutByte(ctx, *s++);
}
BASM_API void BASM_OutStr16(BASM_Context *ctx, char *str)
{
char *s;
int i, j;
// s=str; while(*s)BASM_OutWord(ctx, *s++);
s=str;
while(*s)
{
i=BASM_Parse_ParseChar(&s);
if(i>=0x10000)
{
//encode as UTF-16 surrogate pairs
j=i-0x10000;
BASM_OutWord(ctx, 0xD800+((j>>10)&0x3FF));
BASM_OutWord(ctx, 0xDC00+(j&0x3FF));
continue;
}
//chars <= 0xFFFF and CESU-8
BASM_OutWord(ctx, i);
}
}
BASM_API void BASM_OutStr8Z(BASM_Context *ctx, char *str)
{ BASM_OutStr8(ctx, str); BASM_OutByte(ctx, 0); }
BASM_API void BASM_OutStr16Z(BASM_Context *ctx, char *str)
{ BASM_OutStr16(ctx, str); BASM_OutWord(ctx, 0); }
BASM_API void BASM_OutBytes(BASM_Context *ctx, byte *buf, int sz)
{
int i;
for(i=0; i<sz; i++)
BASM_OutByte(ctx, buf[i]);
}
BASM_API void BASM_OutSection(BASM_Context *ctx, char *str)
{
if(!basm_stricmp(str, ".text"))ctx->fl&=~4;
if(!basm_stricmp(str, ".data"))ctx->fl|=4;
if(!basm_stricmp(str, ".bss"))ctx->fl|=4;
}
BASM_API void BASM_OutBits(BASM_Context *ctx, int bits)
{
if(bits==16) ctx->fl|=2;
if(bits==32) ctx->fl&=~3;
if(bits==64) ctx->fl|=1;
}
BASM_API void BASM_OutRelPtrDisp(BASM_Context *ctx, char *lbl, int disp)
{
if(!lbl) { BASM_OutDWord(ctx, disp); return; }
BASM_OutDWord(ctx, disp+4);
BASM_EmitGoto(ctx, lbl, BASM_JMP_NEAR32);
}
BASM_API void BASM_OutRelSPtrDisp(BASM_Context *ctx, char *lbl, int disp)
{
if(!lbl) { BASM_OutWord(ctx, disp); return; }
BASM_OutWord(ctx, disp+2);
BASM_EmitGoto(ctx, lbl, BASM_JMP_NEAR16);
}
//static int is_s8(int i)
//{
// if(i<-128)return(0);
// if(i>127)return(0);
// return(1);
//}
void BASM_ModRM16(BASM_Context *ctx, int reg,
int rm, int sc, int idx, int disp, char *lbl)
{
int i;
i=-1;
if(sc && (sc!=1))
{
basm_error("BASM_ModRM16: Invalid 16-bit Mem Reference (Scale)\n");
*(int *)-1=-1;
return;
}
if(sc)
{
if((rm==BASM_REG_X86_BX) && (idx==BASM_REG_X86_SI))i=0;
if((rm==BASM_REG_X86_BX) && (idx==BASM_REG_X86_DI))i=1;
if((rm==BASM_REG_X86_BP) && (idx==BASM_REG_X86_SI))i=2;
if((rm==BASM_REG_X86_BP) && (idx==BASM_REG_X86_DI))i=3;
if((rm==BASM_REG_X86_SI) && (idx==BASM_Z))i=4;
if((rm==BASM_REG_X86_DI) && (idx==BASM_Z))i=5;
if((rm==BASM_REG_X86_BP) && (idx==BASM_Z))i=6;
if((rm==BASM_REG_X86_BX) && (idx==BASM_Z))i=7;
}
if((i<0) && sc && ((rm!=BASM_Z) || (idx!=BASM_Z)))
{
basm_error("BASM_ModRM16: Invalid 16-bit Mem Reference (Regs)\n");
*(int *)-1=-1;
return;
}
if(i>=0)
{
if(!disp && (i!=6))
{
BASM_OutByte(ctx, ((reg&7)<<3)|i);
return;
}
if((disp>=-128) && (disp<=127))
{
BASM_OutByte(ctx, 0x40|((reg&7)<<3)|i);
BASM_OutByte(ctx, disp);
return;
}
BASM_OutByte(ctx, 0x80|((reg&7)<<3)|i);
BASM_OutWord(ctx, disp);
return;
}
if(disp || lbl)
{
BASM_OutByte(ctx, ((reg&7)<<3)|6);
BASM_OutWord(ctx, disp);
BASM_EmitGoto(ctx, lbl, BASM_JMP_ABS16);
return;
}else
{
BASM_OutByte(ctx, 0xC0|((reg&7)<<3)|(rm&7));
return;
}
}
void BASM_Sib(BASM_Context *ctx, int rm, int sc, int idx)
{
if(idx==BASM_Z)idx=4;
switch(sc)
{
case 0:
case 1:
BASM_OutByte(ctx, ((idx&7)<<3)|(rm&7));
break;
case 2:
BASM_OutByte(ctx, 0x40|((idx&7)<<3)|(rm&7));
break;
case 4:
BASM_OutByte(ctx, 0x80|((idx&7)<<3)|(rm&7));
break;
case 8:
BASM_OutByte(ctx, 0xC0|((idx&7)<<3)|(rm&7));
break;
}
}
BASM_API void BASM_LabelDisp(BASM_Context *ctx, char *lbl, int disp)
{
int i;
if(!lbl)
{
BASM_OutDWord(ctx, disp);
return;
}
if(!strcmp(lbl, "$."))
{
i=ctx->ip-ctx->base_ip;
BASM_OutDWord(ctx, disp+i+4);
return;
}
if(*lbl=='$')
{
i=ctx->ip-ctx->base_ip;
BASM_OutDWord(ctx, disp+i+4);
BASM_EmitGoto(ctx, lbl+1, BASM_JMP_NEAR32);
return;
}
if(*lbl=='@')lbl++; //ABS reference
//default: ABS reference
BASM_OutDWord(ctx, disp);
BASM_EmitGoto(ctx, lbl, BASM_JMP_ABS32);
}
void BASM_LabelDispRel(BASM_Context *ctx, char *lbl, int disp)
{
if(!lbl || (lbl && !strcmp(lbl, "$")))
{
BASM_OutDWord(ctx, disp);
return;
}
//default: REL reference
BASM_OutDWord(ctx, disp);
BASM_EmitGoto(ctx, lbl, BASM_JMP_NEAR32);
}
void BASM_ModRM64(BASM_Context *ctx, int reg,
int rm, int sc, int idx, int disp, char *lbl)
{
//RIP-relative address
if(rm==BASM_REG_X86_RIP)
{
BASM_OutByte(ctx, ((reg&7)<<3)|5);
BASM_OutDWord(ctx, disp);
BASM_EmitGoto(ctx, lbl, BASM_JMP_NEAR32);
return;
}
//scaled index, using ESP in referencing memory
//or an absolute offset
if((idx!=BASM_Z) || ((sc || disp || lbl) && ((rm&7)==4)) ||
(disp && !lbl && (sc>=0)) || (lbl && (*lbl=='@')))
{
if(rm==BASM_Z)
{
BASM_OutByte(ctx, ((reg&7)<<3)|4);
BASM_Sib(ctx, 5, sc, idx);
BASM_LabelDisp(ctx, lbl, disp);
return;
}
if(disp || lbl || ((rm&7)==5))
{
if(!lbl && (disp>=-128) && (disp<127))
{
BASM_OutByte(ctx, 0x40|((reg&7)<<3)|4);
BASM_Sib(ctx, rm, sc, idx);
BASM_OutByte(ctx, disp);
return;
}
BASM_OutByte(ctx, 0x80|((reg&7)<<3)|4);
BASM_Sib(ctx, rm, sc, idx);
BASM_LabelDisp(ctx, lbl, disp);
return;
}
BASM_OutByte(ctx, ((reg&7)<<3)|4);
BASM_Sib(ctx, rm, sc, idx);
return;
}
//[EBP] (along with [R13]/[RJX]) needs an offset
if((sc && !disp && !lbl) && ((rm&7)==5))
{
BASM_OutByte(ctx, 0x40|((reg&7)<<3)|(rm&7));
BASM_OutByte(ctx, 0);
return;
}
if(disp || lbl)
{
if(rm==BASM_Z)
{
BASM_OutByte(ctx, ((reg&7)<<3)|5);
// BASM_OutDWord(ctx, disp);
// BASM_EmitGoto(ctx, lbl, BASM_JMP_NEAR32);
BASM_LabelDispRel(ctx, lbl, disp);
return;
}
if(!lbl && (disp>=-128) && (disp<127))
{
BASM_OutByte(ctx, 0x40|((reg&7)<<3)|(rm&7));
BASM_OutByte(ctx, disp);
return;
}
BASM_OutByte(ctx, 0x80|((reg&7)<<3)|(rm&7));
BASM_LabelDisp(ctx, lbl, disp);
}else
{
if(sc) BASM_OutByte(ctx, ((reg&7)<<3)|(rm&7));
else BASM_OutByte(ctx, 0xC0|((reg&7)<<3)|(rm&7));
return;
}
}
BASM_API void BASM_ModRM(BASM_Context *ctx, int reg,
int rm, int sc, int idx, int disp, char *lbl)
{
if(((ctx->fl&2) && !(ctx->fl&8)) ||
(!(ctx->fl&2) && (ctx->fl&8)))
{
BASM_ModRM16(ctx, reg, rm, sc, idx, disp, lbl);
return;
}
if(ctx->fl&1)
{
BASM_ModRM64(ctx, reg, rm, sc, idx, disp, lbl);
return;
}
//scaled index, using ESP in referencing memory
//or an absolute offset on x86-64
if((idx!=BASM_Z) || ((sc || disp || lbl) && ((rm&7)==4)))
{
if(rm==BASM_Z)
{
BASM_OutByte(ctx, ((reg&7)<<3)|4);
BASM_Sib(ctx, 5, sc, idx);
BASM_LabelDisp(ctx, lbl, disp);
return;
}
if(disp || lbl || ((rm&7)==5))
{
if(!lbl && (disp>=-128) && (disp<127))
{
BASM_OutByte(ctx, 0x40|((reg&7)<<3)|4);
BASM_Sib(ctx, rm, sc, idx);
BASM_OutByte(ctx, disp);
return;
}
BASM_OutByte(ctx, 0x80|((reg&7)<<3)|4);
BASM_Sib(ctx, rm, sc, idx);
BASM_LabelDisp(ctx, lbl, disp);
return;
}
BASM_OutByte(ctx, ((reg&7)<<3)|4);
BASM_Sib(ctx, rm, sc, idx);
return;
}
//[EBP] needs an offset
if((sc && !disp && !lbl) && ((rm&7)==5))
{
BASM_OutByte(ctx, 0x40|((reg&7)<<3)|(rm&7));
BASM_OutByte(ctx, 0);
return;
}
if(disp || lbl)
{
if(rm==BASM_Z)
{
BASM_OutByte(ctx, ((reg&7)<<3)|5);
BASM_LabelDisp(ctx, lbl, disp);
return;
}
if(!lbl && (disp>=-128) && (disp<127))
{
BASM_OutByte(ctx, 0x40|((reg&7)<<3)|(rm&7));
BASM_OutByte(ctx, disp);
return;
}
BASM_OutByte(ctx, 0x80|((reg&7)<<3)|(rm&7));
BASM_LabelDisp(ctx, lbl, disp);
}else
{
if(sc)
{
BASM_OutByte(ctx, ((reg&7)<<3)|(rm&7));
}else
{
BASM_OutByte(ctx, 0xC0|((reg&7)<<3)|(rm&7));
}
return;
}
}
#ifndef BASM_HEXVAL_DEF
#define BASM_HEXVAL_DEF
static int hexval(int i)
{
if((i>='0') && (i<='9'))return(i-'0');
if((i>='A') && (i<='F'))return(i-'A'+10);
if((i>='a') && (i<='f'))return(i-'a'+10);
return(-1);
}
static int hexbyte(char *s)
{
int i, j;
i=hexval(s[0]);
j=hexval(s[1]);
if((i<0) || (j<0))return(-1);
return((i<<4)+j);
}
#endif
static int hexword(char *s)
{
int i, j;
i=hexbyte(s+0);
j=hexbyte(s+2);
if((i<0) || (j<0))return(-1);
return((i<<8)+j);
}
static int hexdword(char *s)
{
int i, j;
i=hexword(s+0);
j=hexword(s+4);
if((i<0) || (j<0))return(-1);
return((i<<16)+j);
}
static int altval(int i)
{
if((i>='i') && (i<='x'))return(i-'i');
return(-1);
}
static int altbyte(char *s)
{
int i, j;
i=altval(s[0]);
j=altval(s[1]);
if((i<0) || (j<0))return(-1);
return((i<<4)+j);
}
BASM_API int BASM_RegREXW(int reg)
{
if(reg==BASM_Z)return(0);
if((reg&255)>=64)return(0);
return(((reg>>4)&15)==3);
}
BASM_API int BASM_Reg16P(int reg)
{
if(reg==BASM_Z)return(0);
if((reg&255)>=64)return(0);
return(((reg>>4)&15)==1);
}
BASM_API int BASM_Reg32P(int reg)
{
if(reg==BASM_Z)return(0);
if((reg&255)>=64)return(0);
return(((reg>>4)&15)==2);
}
BASM_API void BASM_AddrOverride(BASM_Context *ctx, int breg)
{
// ctx->fl|=8;
if(BASM_Reg16P(breg) && !(ctx->fl&2))ctx->fl|=8;
if(BASM_Reg32P(breg) && (ctx->fl&2))ctx->fl|=8;
if(ctx->fl&8)BASM_OutByte(ctx, 0x67);
}
BASM_API void BASM_SegOverride(BASM_Context *ctx)
{
if(ctx->seg==BASM_REG_X86_CS)BASM_OutByte(ctx, 0x2E);
if(ctx->seg==BASM_REG_X86_SS)BASM_OutByte(ctx, 0x36);
if(ctx->seg==BASM_REG_X86_DS)BASM_OutByte(ctx, 0x3E);
if(ctx->seg==BASM_REG_X86_ES)BASM_OutByte(ctx, 0x26);
if(ctx->seg==BASM_REG_X86_FS)BASM_OutByte(ctx, 0x64);
if(ctx->seg==BASM_REG_X86_GS)BASM_OutByte(ctx, 0x65);
}
BASM_API char *BASM_OutSufBytes(BASM_Context *ctx, char *s)
{
int i;
while(*s)
{
i=hexbyte(s);
if(i<0)break;
s+=2; while(*s && (*s<=' '))s++;
BASM_OutByte(ctx, i);
}
return(s);
}
BASM_API char *BASM_OutBodyBytes(BASM_Context *ctx, char *s, int rex)
{
int i, j, k, l;
while(*s && (*s<=' '))s++;
while(*s)
{
if((*s=='V') || (*s=='W') || (*s=='S') || (*s=='T'))
{
if((*s=='V') && !(ctx->fl&2))BASM_OutByte(ctx, 0x67);
if((*s=='W') && !(ctx->fl&2))BASM_OutByte(ctx, 0x66);
if((*s=='S') && (ctx->fl&2))BASM_OutByte(ctx, 0x67);
if((*s=='T') && (ctx->fl&2))BASM_OutByte(ctx, 0x66);
s++; continue;
}
if((*s=='X') && (ctx->fl&1))
{
if(rex)BASM_OutByte(ctx, 0x40|(rex&0x0F));
s++; continue;
}
// if(*s=='X') { s++; continue; }
if((*s=='X') && !(ctx->fl&1))
{
if(rex)
{
//BGB: PREX, N/E on standard x86
i=0xD0;
j=(((rex&7)<<5)|(i>>3))^0xE0;
k=((rex&8)<<4)|(((rex>>4)&15)<<3)|(i&7);
BASM_OutByte(ctx, 0x8F);
BASM_OutByte(ctx, j^0xE0);
BASM_OutByte(ctx, k^0x78);
}
s++; continue;
}
if(*s=='H')
{
s++;
i=altval(*s++);
k=((rex&4)<<5)|(((rex>>4)&15)<<3)|(i&7);
BASM_OutByte(ctx, 0xC5);
BASM_OutByte(ctx, k^0xF8);
continue;
}
if(*s=='I')
{
s++;
i=altbyte(s); s+=2;
j=((rex&7)<<5)|(i>>3);
k=((rex&8)<<4)|(((rex>>4)&15)<<3)|(i&7);
BASM_OutByte(ctx, 0xC4);
BASM_OutByte(ctx, j^0xE0);
BASM_OutByte(ctx, k^0x78);
continue;
}
if(*s=='J')
{
s++;
i=altbyte(s); s+=2;
j=((rex&7)<<5)|(i>>3);
k=((rex&8)<<4)|(((rex>>4)&15)<<3)|(i&7);
BASM_OutByte(ctx, 0x8F);
BASM_OutByte(ctx, j^0xE0);
BASM_OutByte(ctx, k^0x78);
continue;
}
if((*s=='K') && rex)
{
s++;
i=altbyte(s); s+=2;
j=((rex&7)<<5)|(i>>3);
k=((rex&8)<<4)|(((rex>>4)&15)<<3)|(i&7);
BASM_OutByte(ctx, 0xC4);
BASM_OutByte(ctx, j^0xE0);
BASM_OutByte(ctx, k^0x78);
continue;
}
if((*s=='L') && rex)
{
s++;
i=altbyte(s); s+=2;
j=(((rex&7)<<5)|(i>>3))^0xE0;
k=((rex&8)<<4)|(((rex>>4)&15)<<3)|(i&7);
BASM_OutByte(ctx, 0x8F);
BASM_OutByte(ctx, j^0xE0);
BASM_OutByte(ctx, k^0x78);
continue;
}
if(*s=='K') { s+=3; continue; }
if(*s=='L') { s+=3; continue; }
if((*s=='G') && (s[1]=='t')) //Thumb
{
s+=2;
i=hexbyte(s);
if(i<0)break;
s+=2;
j=hexbyte(s);
if(j<0)break;
s+=2;
BASM_OutByte(ctx, j);
BASM_OutByte(ctx, i);
continue;
}
if(*s=='G') //ARM
{
s+=2;
i=hexdword(s);
if(i<0)break;
s+=8;
i|=(ctx->fl<<8)&0xF0100000;
BASM_OutDWord(ctx, i);
#if 0
i=hexbyte(s);
if(i<0)break;
s+=2;
j=hexbyte(s);
if(j<0)break;
s+=2;
k=hexbyte(s);
if(k<0)break;
s+=2;
l=hexbyte(s);
if(l<0)break;
s+=2;
BASM_OutByte(ctx, l);
BASM_OutByte(ctx, k);
BASM_OutByte(ctx, j);
BASM_OutByte(ctx, i);
#endif
continue;
}
i=hexbyte(s);
if(i<0)break;
s+=2; while(*s && (*s<=' '))s++;
BASM_OutByte(ctx, i);
}
return(s);
}
BASM_API char *BASM_OutImm(BASM_Context *ctx, char *s,
long long imm, char *lbl)
{
if(*s==',')
{
if(!strncmp(s, ",ib", 3))
{
BASM_OutByte(ctx, imm);
s+=3;
}else if(!strncmp(s, ",iw", 3))
{
BASM_OutWord(ctx, imm);
s+=3;
}else if(!strncmp(s, ",id", 3))
{
BASM_OutDWord(ctx, imm);
BASM_EmitGoto(ctx, lbl, BASM_JMP_ABS32);
s+=3;
}else if(!strncmp(s, ",iq", 3))
{
BASM_OutQWord(ctx, imm);
BASM_EmitGoto(ctx, lbl, BASM_JMP_ABS64);
s+=3;
}else if(!strncmp(s, ",rb", 3))
{
BASM_OutByte(ctx, imm);
BASM_EmitGoto(ctx, lbl, BASM_JMP_SHORT);
s+=3;
}else if(!strncmp(s, ",rw", 3))
{
BASM_OutWord(ctx, imm);
BASM_EmitGoto(ctx, lbl, BASM_JMP_NEAR16);
s+=3;
}else if(!strncmp(s, ",rd", 3))
{
BASM_OutDWord(ctx, imm);
BASM_EmitGoto(ctx, lbl, BASM_JMP_NEAR32);
s+=3;
}
}
if(*s=='|')
{
if(!strncmp(s, "|ia", 3))
{
*(ctx->ip-4)|=(imm&255);
*(ctx->ip-3)|=((imm>>8)&255);
*(ctx->ip-2)|=((imm>>16)&255);
BASM_EmitGoto(ctx, lbl, BASM_JMP_ARM_NEAR24);
s+=3;
}else if(!strncmp(s, "|ib", 3))
{
*(ctx->ip-4)|=(imm&255);
s+=3;
}else if(!strncmp(s, "|ic", 3))
{
*(ctx->ip-4)|=(imm&255);
*(ctx->ip-3)|=((imm>>8)&255);
*(ctx->ip-2)|=((imm>>16)&255);
*(ctx->ip-1)|=((imm>>24)&255);
BASM_EmitGoto(ctx, lbl, BASM_JMP_ABS32);
s+=3;
}else if(!strncmp(s, "|id", 3))
{
*(ctx->ip-4)|=(imm&255);
*(ctx->ip-3)|=((imm>>8)&255);
*(ctx->ip-2)|=((imm>>16)&255);
*(ctx->ip-1)|=((imm>>24)&255);
BASM_EmitGoto(ctx, lbl, BASM_JMP_ABS32);
s+=3;
}else if(!strncmp(s, "|io", 3))
{
*(ctx->ip-4)|=(imm&255);
*(ctx->ip-3)|=((imm>>8)&15);
s+=3;
}else if(!strncmp(s, "|is", 3))
{
*(ctx->ip-3)|=(imm&15);
s+=3;
}else if(!strncmp(s, "|irb", 3))
{
*(ctx->ip-4)|=(imm&255);
*(ctx->ip-3)|=((imm>>8)&15);
s+=3;
}else if(!strncmp(s, "|ja", 3))
{
*(ctx->ip-2)|=(imm&255);
BASM_EmitGoto(ctx, lbl, BASM_JMP_ARM_NEAR24);
s+=3;
}else if(!strncmp(s, "|jb", 3))
{
*(ctx->ip-2)|=(imm&255);
s+=3;
}else if(!strncmp(s, "|jc", 3))
{
*(ctx->ip-2)|=(imm&127);
s+=3;
}else if(!strncmp(s, "|jd", 3))
{
*(ctx->ip-2)|=(imm&255);
*(ctx->ip-1)|=((imm>>8)&7);
BASM_EmitGoto(ctx, lbl, BASM_JMP_THUMB_NEAR11);
s+=3;
}else if(!strncmp(s, "|je", 3))
{
*(ctx->ip-2)|=((imm>>11)&255);
*(ctx->ip-1)|=((imm>>19)&7);
s+=3;
}else if(!strncmp(s, "|jf", 3))
{
*(ctx->ip-2)|=(imm&255);
*(ctx->ip-1)|=((imm>>8)&7);
BASM_EmitGoto(ctx, lbl, BASM_JMP_THUMB_NEAR22);
s+=3;
}else if(!strncmp(s, "|ji", 3))
{
*(ctx->ip-2)|=(imm&3)<<6;
*(ctx->ip-1)|=((imm>>2)&1);
s+=3;
}else if(!strncmp(s, "|jj", 3))
{
*(ctx->ip-2)|=(imm&3)<<6;
*(ctx->ip-1)|=((imm>>2)&7);
s+=3;
}else if(!strncmp(s, "|jk", 3))
{
*(ctx->ip-2)|=(imm&7);
s+=3;
}else if(!strncmp(s, "|jl", 3))
{
*(ctx->ip-2)|=(imm&255);
*(ctx->ip-1)|=((imm>>8)&7)<<4;
*(ctx->ip-4)|=((imm>>11)&15);
*(ctx->ip-3)|=((imm>>15)&1)<<2;
s+=3;
}
}
return(s);
}
BASM_API char *BASM_OutMOffs(BASM_Context *ctx,
char *s, int disp, char *lbl)
{
if(*s==',')
{
if(!strncmp(s, ",mw", 3))
{
BASM_OutWord(ctx, disp);
BASM_EmitGoto(ctx, lbl, BASM_JMP_ABS16);
s+=3;
}else if(!strncmp(s, ",md", 3))
{
BASM_OutDWord(ctx, disp);
BASM_EmitGoto(ctx, lbl, BASM_JMP_ABS32);
s+=3;
}
}
return(s);
}
BASM_API char *BASM_OutModRM(BASM_Context *ctx, char *s, int reg,
int breg, int sc, int ireg, int disp, char *lbl)
{
int i;
if(ctx->fl&BASM_FL_ARM)
return(s);
if(*s=='|')
{
s+=2;
*(ctx->ip-1)|=(reg&7);
}
if((s[0]=='/') && (s[1]=='r'))
{
// if(!sc)sc=1;
BASM_ModRM(ctx, reg, breg, sc, ireg, disp, lbl);
s+=2;
}
if(*s=='/')
{
s++;
i=(*s++)-'0';
BASM_ModRM(ctx, BASM_REG_X86_OP0+i, breg, sc, ireg, disp, lbl);
}
return(s);
}
BASM_API char *BASM_OutArmReg(BASM_Context *ctx, char *s, int reg)
{
int i;
if(!(ctx->fl&BASM_FL_ARM))
return(s);
if(*s=='|')
{
if(!strncmp(s, "|ra", 3))
{
*(ctx->ip-4)|=(reg&15);
s+=3;
}else if(!strncmp(s, "|rb", 3))
{
*(ctx->ip-4)|=(reg&15)<<4;
s+=3;
}else if(!strncmp(s, "|rc", 3))
{
*(ctx->ip-3)|=(reg&15);
s+=3;
}else if(!strncmp(s, "|rd", 3))
{
*(ctx->ip-3)|=(reg&15)<<4;
s+=3;
}else if(!strncmp(s, "|re", 3))
{
*(ctx->ip-2)|=(reg&15);
s+=3;
}else if(!strncmp(s, "|rf", 3))
{
*(ctx->ip-2)|=(reg&15)<<4;
s+=3;
}else if(!strncmp(s, "|rg", 3))
{
*(ctx->ip-2)|=(reg&7);
s+=3;
}else if(!strncmp(s, "|rh", 3))
{
*(ctx->ip-2)|=(reg&7)<<3;
s+=3;
}else if(!strncmp(s, "|ri", 3))
{
*(ctx->ip-2)|=(reg&3)<<6;
*(ctx->ip-1)|=((reg>>2)&1);
s+=3;
}else if(!strncmp(s, "|rj", 3))
{
*(ctx->ip-2)|=(reg&7)<<1;
s+=3;
}else if(!strncmp(s, "|rk", 3))
{
*(ctx->ip-2)|=(reg&15)<<3;
s+=3;
}else if(!strncmp(s, "|rl", 3))
{
*(ctx->ip-2)|=(reg&7);
*(ctx->ip-1)|=((reg>>3)&1)<<7;
s+=3;
}else if(!strncmp(s, "|rz", 3))
{
s+=3;
}
}
return(s);
}
BASM_API int BASM_SizeOpStr(BASM_Context *ctx, char *str)
{
char *s;
int sz;
int i;
s=str; sz=0;
while(*s)
{
if(*s=='|')
{
if(s[1]=='r')
{ s+=2; continue; }
break;
}
if(*s=='/')
{
if(s[1]=='r')
{
sz+=6; //worst case
s+=2;
continue;
}
break;
}
if(*s==',')
{
if((s[1]=='i') || (s[1]=='r') || (s[1]=='m'))
{
if(s[2]=='b')
{ s+=3; sz+=1; continue; }
if(s[2]=='w')
{ s+=3; sz+=2; continue; }
if(s[2]=='d')
{ s+=3; sz+=4; continue; }
if(s[2]=='q')
{ s+=3; sz+=8; continue; }
}
break;
}
if(*s=='X')
{
if(ctx->fl&BASM_FL_X86_64)
sz++;
s++;
continue;
}
if((*s=='V') || (*s=='W'))
{
if(!(ctx->fl&BASM_FL_X86_16))
sz++;
s++;
continue;
}
if((*s=='S') || (*s=='T'))
{
if(ctx->fl&BASM_FL_X86_16)
sz++;
s++;
continue;
}
i=hexbyte(s);
if(i<0)break;
sz++; s+=2; while(*s && (*s<=' '))s++;
}
return(sz);
}
BASM_API void BASM_BundleAlignOpStr(BASM_Context *ctx, char *str)
{
int sz;
int j, k;
if(!(ctx->fl&BASM_FL_BUNDLE))
return;
if(ctx->fl&BASM_FL_DATA)
return;
sz=BASM_SizeOpStr(ctx, str);
j=ctx->ip-ctx->text; k=j+sz;
if((j&(~31))!=(k&(~31)))
{
if(j%32)BASM_OutPadText(ctx, 32-(j%32));
}
}
BASM_API void BASM_OutOpStr(BASM_Context *ctx, char *s)
{
BASM_BundleAlignOpStr(ctx, s);
BASM_AddrOverride(ctx, BASM_Z);
s=BASM_OutBodyBytes(ctx, s, 0);
}
BASM_API void BASM_OutOpStrReg(BASM_Context *ctx, char *s, int reg)
{
int i;
BASM_BundleAlignOpStr(ctx, s);
BASM_AddrOverride(ctx, BASM_Z);
i=(BASM_RegREXW(reg)?8:0)|((reg&8)?4:0)|((reg&8)?1:0);
if(reg&256)i|=256;
s=BASM_OutBodyBytes(ctx, s, i);
s=BASM_OutModRM(ctx, s, reg, reg, 0, BASM_Z, 0, NULL);
s=BASM_OutArmReg(ctx, s, reg);
s=BASM_OutSufBytes(ctx, s);
while(*s==';')
{
s++;
s=BASM_OutBodyBytes(ctx, s, 0);
s=BASM_OutArmReg(ctx, s, reg);
}
}
BASM_API void BASM_OutOpStrImm(BASM_Context *ctx,
char *s, long long imm, char *lbl)
{
BASM_BundleAlignOpStr(ctx, s);
BASM_AddrOverride(ctx, BASM_Z);
s=BASM_OutBodyBytes(ctx, s, 0);
s=BASM_OutImm(ctx, s, imm, lbl);
s=BASM_OutSufBytes(ctx, s);
while(*s==';')
{
s++;
s=BASM_OutBodyBytes(ctx, s, 0);
s=BASM_OutImm(ctx, s, imm, lbl);
}
}
BASM_API void BASM_OutOpStrMem(BASM_Context *ctx, char *s,
char *lbl, int breg, int ireg, int sc, int disp)
{
int i;
BASM_BundleAlignOpStr(ctx, s);
BASM_SegOverride(ctx);
BASM_AddrOverride(ctx, breg);
i=((breg!=BASM_Z) && (breg&8))?1:0;
i|=((ireg!=BASM_Z) && (ireg&8))?2:0;
s=BASM_OutBodyBytes(ctx, s, i);
s=BASM_OutModRM(ctx, s, 0, breg, sc, ireg, disp, lbl);
s=BASM_OutMOffs(ctx, s, disp, lbl);
s=BASM_OutSufBytes(ctx, s);
}
BASM_API void BASM_OutOpStrRegReg(BASM_Context *ctx,
char *s, int r0, int r1)
{
int i;
BASM_BundleAlignOpStr(ctx, s);
BASM_AddrOverride(ctx, BASM_Z);
i=(BASM_RegREXW(r0)?8:0)|((r0&8)?4:0)|((r1&8)?1:0);
if((r0&256) || (r1&256))i|=256;
s=BASM_OutBodyBytes(ctx, s, i);
s=BASM_OutModRM(ctx, s, r0, r1, 0, BASM_Z, 0, NULL);
s=BASM_OutArmReg(ctx, s, r0);
s=BASM_OutArmReg(ctx, s, r1);
s=BASM_OutSufBytes(ctx, s);
while(*s==';')
{
s++;
s=BASM_OutBodyBytes(ctx, s, 0);
s=BASM_OutArmReg(ctx, s, r0);
s=BASM_OutArmReg(ctx, s, r1);
}
}
BASM_API void BASM_OutOpStrRegImm(BASM_Context *ctx, char *s, int reg,
long long imm, char *lbl)
{
int i;
BASM_BundleAlignOpStr(ctx, s);
BASM_AddrOverride(ctx, BASM_Z);
i=(BASM_RegREXW(reg)?8:0)|((reg&8)?4:0)|((reg&8)?1:0);
if(reg&256)i|=256;
s=BASM_OutBodyBytes(ctx, s, i);
s=BASM_OutModRM(ctx, s, reg, reg, 0, BASM_Z, 0, NULL);
s=BASM_OutArmReg(ctx, s, reg);
s=BASM_OutImm(ctx, s, imm, lbl);
s=BASM_OutSufBytes(ctx, s);
while(*s==';')
{
s++;
s=BASM_OutBodyBytes(ctx, s, 0);
s=BASM_OutArmReg(ctx, s, reg);
s=BASM_OutImm(ctx, s, imm, lbl);
}
}
BASM_API void BASM_OutOpStrRegMem(BASM_Context *ctx, char *s, int reg,
char *lbl, int breg, int ireg, int sc, int disp)
{
int i;
BASM_BundleAlignOpStr(ctx, s);
BASM_SegOverride(ctx);
BASM_AddrOverride(ctx, breg);
i=(BASM_RegREXW(reg)?8:0)|((reg&8)?4:0);
i|=((breg!=BASM_Z) && (breg&8))?1:0;
i|=((ireg!=BASM_Z) && (ireg&8))?2:0;
if(reg&256)i|=256;
s=BASM_OutBodyBytes(ctx, s, i);
s=BASM_OutModRM(ctx, s, reg, breg, sc, ireg, disp, lbl);
s=BASM_OutMOffs(ctx, s, disp, lbl);
s=BASM_OutSufBytes(ctx, s);
}
BASM_API void BASM_OutOpStrMemImm(BASM_Context *ctx, char *s, int w,
char *lbl, int breg, int ireg, int sc, int disp,
long long imm, char *lbl2)
{
char *t;
int i;
BASM_BundleAlignOpStr(ctx, s);
BASM_SegOverride(ctx);
BASM_AddrOverride(ctx, breg);
if(breg==BASM_REG_X86_RIP)
{
t=s;
while(*t && (*t!=','))t++;
if(*t==',')
{
t++;
if(!strncmp(t, "ib", 2))disp--;
if(!strncmp(t, "iw", 2))disp-=2;
if(!strncmp(t, "id", 2))disp-=4;
if(!strncmp(t, "iq", 2))disp-=8;
if(!strncmp(t, "rb", 2))disp--;
if(!strncmp(t, "rw", 2))disp-=2;
if(!strncmp(t, "rd", 2))disp-=4;
}
}
i=(w==64)?8:0;
i|=((breg!=BASM_Z) && (breg&8))?1:0;
i|=((ireg!=BASM_Z) && (ireg&8))?2:0;
s=BASM_OutBodyBytes(ctx, s, i);
s=BASM_OutModRM(ctx, s, 0, breg, sc, ireg, disp, lbl);
s=BASM_OutMOffs(ctx, s, disp, lbl);
s=BASM_OutImm(ctx, s, imm, lbl2);
s=BASM_OutSufBytes(ctx, s);
}
BASM_API void BASM_OutOpStrRegRegImm(BASM_Context *ctx, char *s,
int r0, int r1, long long imm, char *lbl)
{
int i;
BASM_BundleAlignOpStr(ctx, s);
BASM_AddrOverride(ctx, BASM_Z);
i=(BASM_RegREXW(r0)?8:0)|((r0&8)?4:0)|((r1&8)?1:0);
if((r0&256) || (r1&256))i|=256;
s=BASM_OutBodyBytes(ctx, s, i);
s=BASM_OutModRM(ctx, s, r0, r1, 0, BASM_Z, 0, NULL);
s=BASM_OutArmReg(ctx, s, r0);
s=BASM_OutArmReg(ctx, s, r1);
s=BASM_OutImm(ctx, s, imm, lbl);
s=BASM_OutSufBytes(ctx, s);
while(*s==';')
{
s++;
s=BASM_OutBodyBytes(ctx, s, 0);
s=BASM_OutArmReg(ctx, s, r0);
s=BASM_OutArmReg(ctx, s, r1);
s=BASM_OutImm(ctx, s, imm, lbl);
}
}
BASM_API void BASM_OutOpStrRegMemImm(BASM_Context *ctx, char *s, int reg,
char *lbl, int breg, int ireg, int sc, int disp,
long long imm, char *lbl2)
{
int i;
BASM_BundleAlignOpStr(ctx, s);
BASM_SegOverride(ctx);
BASM_AddrOverride(ctx, breg);
i=(BASM_RegREXW(reg)?8:0)|((reg&8)?4:0);
i|=((breg!=BASM_Z) && (breg&8))?1:0;
i|=((ireg!=BASM_Z) && (ireg&8))?2:0;
if(reg&256)i|=256;
s=BASM_OutBodyBytes(ctx, s, i);
s=BASM_OutModRM(ctx, s, reg, breg, sc, ireg, disp, lbl);
s=BASM_OutMOffs(ctx, s, disp, lbl);
s=BASM_OutImm(ctx, s, imm, lbl2);
s=BASM_OutSufBytes(ctx, s);
}
BASM_API void BASM_OutOpStrRegRegReg(BASM_Context *ctx, char *s,
int r0, int r1, int r2)
{
int i;
BASM_BundleAlignOpStr(ctx, s);
BASM_AddrOverride(ctx, BASM_Z);
i=(BASM_RegREXW(r0)?8:0)|((r0&8)?4:0)|((r1&8)?1:0);
if((r0&256) || (r1&256))i|=256;
i|=(r2&15)<<4;
s=BASM_OutBodyBytes(ctx, s, i);
s=BASM_OutModRM(ctx, s, r0, r1, 0, BASM_Z, 0, NULL);
s=BASM_OutArmReg(ctx, s, r0);
s=BASM_OutArmReg(ctx, s, r1);
s=BASM_OutArmReg(ctx, s, r2);
s=BASM_OutSufBytes(ctx, s);
while(*s==';')
{
s++;
s=BASM_OutBodyBytes(ctx, s, 0);
s=BASM_OutArmReg(ctx, s, r0);
s=BASM_OutArmReg(ctx, s, r1);
s=BASM_OutArmReg(ctx, s, r2);
}
}
BASM_API void BASM_OutOpStrRegMemReg(BASM_Context *ctx, char *s, int reg,
char *lbl, int breg, int ireg, int sc, int disp, int reg2)
{
int i;
BASM_BundleAlignOpStr(ctx, s);
BASM_SegOverride(ctx);
BASM_AddrOverride(ctx, breg);
i=(BASM_RegREXW(reg)?8:0)|((reg&8)?4:0);
i|=((breg!=BASM_Z) && (breg&8))?1:0;
i|=((ireg!=BASM_Z) && (ireg&8))?2:0;
if(reg&256)i|=256;
i|=(reg2&15)<<4;
s=BASM_OutBodyBytes(ctx, s, i);
s=BASM_OutModRM(ctx, s, reg, breg, sc, ireg, disp, lbl);
s=BASM_OutMOffs(ctx, s, disp, lbl);
s=BASM_OutSufBytes(ctx, s);
}
BASM_API int BASM_OpSingleP(int i)
{
if(basm_opcat[i*16+0])return(0);
if(basm_opcat[i*16+1])return(0);
if(basm_opcat[i*16+2])return(0);
return(1);
}
BASM_API int BASM_GetRegWidth(int reg)
{
int w;
w=0;
if((reg&255)<64)
{
if(((reg>>4)&15)==0)w=8;
if(((reg>>4)&15)==1)w=16;
if(((reg>>4)&15)==2)w=32;
if(((reg>>4)&15)==3)w=64;
return(w);
}
if( (reg==BASM_REG_X86_CS) || (reg!=BASM_REG_X86_SS) ||
(reg==BASM_REG_X86_DS) || (reg!=BASM_REG_X86_ES) ||
(reg==BASM_REG_X86_FS) || (reg!=BASM_REG_X86_GS))return(16);
return(0);
}
#if 0
int BASM_OpArgRegP(int i, int j, int reg)
{
int w;
if((basm_opcat[i*16+j]==OPCAT_AL) && (reg==BASM_REG_X86_AL))return(1);
if((basm_opcat[i*16+j]==OPCAT_CL) && (reg==BASM_REG_X86_CL))return(1);
if((basm_opcat[i*16+j]==OPCAT_DL) && (reg==BASM_REG_X86_DL))return(1);
if((basm_opcat[i*16+j]==OPCAT_BL) && (reg==BASM_REG_X86_BL))return(1);
if((basm_opcat[i*16+j]==OPCAT_AX) && (reg==BASM_REG_X86_AX))return(1);
if((basm_opcat[i*16+j]==OPCAT_CX) && (reg==BASM_REG_X86_CX))return(1);
if((basm_opcat[i*16+j]==OPCAT_DX) && (reg==BASM_REG_X86_DX))return(1);
if((basm_opcat[i*16+j]==OPCAT_BX) && (reg==BASM_REG_X86_BX))return(1);
if((basm_opcat[i*16+j]==OPCAT_EAX) && (reg==BASM_REG_X86_EAX))return(1);
if((basm_opcat[i*16+j]==OPCAT_ECX) && (reg==BASM_REG_X86_ECX))return(1);
if((basm_opcat[i*16+j]==OPCAT_EDX) && (reg==BASM_REG_X86_EDX))return(1);
if((basm_opcat[i*16+j]==OPCAT_EBX) && (reg==BASM_REG_X86_EBX))return(1);
if((basm_opcat[i*16+j]==OPCAT_RAX) && (reg==BASM_REG_X86_RAX))return(1);
if((basm_opcat[i*16+j]==OPCAT_RCX) && (reg==BASM_REG_X86_RCX))return(1);
if((basm_opcat[i*16+j]==OPCAT_RDX) && (reg==BASM_REG_X86_RDX))return(1);
if((basm_opcat[i*16+j]==OPCAT_RBX) && (reg==BASM_REG_X86_RBX))return(1);
if((basm_opcat[i*16+j]==OPCAT_SR) &&
((reg==BASM_REG_X86_CS) || (reg==BASM_REG_X86_SS) ||
(reg==BASM_REG_X86_DS) || (reg==BASM_REG_X86_ES) ||
(reg==BASM_REG_X86_FS) || (reg==BASM_REG_X86_GS)))
return(1);
if((basm_opcat[i*16+j]==OPCAT_CS) && (reg==BASM_REG_X86_CS))return(1);
if((basm_opcat[i*16+j]==OPCAT_SS) && (reg==BASM_REG_X86_SS))return(1);
if((basm_opcat[i*16+j]==OPCAT_DS) && (reg==BASM_REG_X86_DS))return(1);
if((basm_opcat[i*16+j]==OPCAT_ES) && (reg==BASM_REG_X86_ES))return(1);
if((basm_opcat[i*16+j]==OPCAT_FS) && (reg==BASM_REG_X86_FS))return(1);
if((basm_opcat[i*16+j]==OPCAT_GS) && (reg==BASM_REG_X86_GS))return(1);
if((basm_opcat[i*16+j]>=OPCAT_MM0) &&
(basm_opcat[i*16+j]<=OPCAT_MM7))
{
if((reg<BASM_REG_X86_MM0) || (reg>BASM_REG_X86_MM7))
return(0);
if((basm_opcat[i*16+j]-OPCAT_MM0)==(reg-BASM_REG_X86_MM0))
return(1);
return(0);
}
if((basm_opcat[i*16+j]==OPCAT_CR) &&
((reg>=BASM_REG_X86_CR0)&&(reg<=BASM_REG_X86_CR15)))
return(1);
if((basm_opcat[i*16+j]==OPCAT_DR) &&
((reg>=BASM_REG_X86_DR0)&&(reg<=BASM_REG_X86_DR15)))
return(1);
if((basm_opcat[i*16+j]==OPCAT_TR) &&
((reg>=BASM_REG_X86_TR0)&&(reg<=BASM_REG_X86_TR15)))
return(1);
if((basm_opcat[i*16+j]==OPCAT_FREG) &&
((reg>=BASM_REG_X86_MM0)&&(reg<=BASM_REG_X86_MM7)))
return(1);
if((basm_opcat[i*16+j]==OPCAT_FRM) &&
((reg>=BASM_REG_X86_MM0)&&(reg<=BASM_REG_X86_MM7)))
return(1);
if((basm_opcat[i*16+j]==OPCAT_XREG) &&
((reg>=BASM_REG_X86_XMM0)&&(reg<=BASM_REG_X86_XMM15)))
return(1);
if((basm_opcat[i*16+j]==OPCAT_XRM) &&
((reg>=BASM_REG_X86_XMM0)&&(reg<=BASM_REG_X86_XMM15)))
return(1);
w=0;
if((reg&255)<64)
{
if(((reg>>4)&15)==0)w=8;
if(((reg>>4)&15)==1)w=16;
if(((reg>>4)&15)==2)w=32;
if(((reg>>4)&15)==3)w=64;
}
if((basm_opcat[i*16+j]==OPCAT_REG8 ) && (w==8 ))return(1);
if((basm_opcat[i*16+j]==OPCAT_REG16) && (w==16))return(1);
if((basm_opcat[i*16+j]==OPCAT_REG32) && (w==32))return(1);
if((basm_opcat[i*16+j]==OPCAT_REG64) && (w==64))return(1);
if((basm_opcat[i*16+j]==OPCAT_RM8 ) && (w==8 ))return(1);
if((basm_opcat[i*16+j]==OPCAT_RM16) && (w==16))return(1);
if((basm_opcat[i*16+j]==OPCAT_RM32) && (w==32))return(1);
if((basm_opcat[i*16+j]==OPCAT_RM64) && (w==64))return(1);
return(0);
}
#endif
#if 1
int BASM_OpArgRegP(int i, int j, int reg)
{
int v, w, ret;
v=basm_opcat[i*16+j];
if( (basm_cpu==BASM_CPU_ARM) ||
(basm_cpu==BASM_CPU_THUMB))
{
switch(v)
{
case OPCAT_CS: ret=(reg==BASM_REG_ARM_PC); break;
case OPCAT_SS: ret=(reg==BASM_REG_ARM_SP); break;
default:
ret=0; break;
}
if(ret)return(ret);
}
ret=0;
switch(v)
{
case OPCAT_AL: ret=(reg==BASM_REG_X86_AL); break;
case OPCAT_CL: ret=(reg==BASM_REG_X86_CL); break;
case OPCAT_DL: ret=(reg==BASM_REG_X86_DL); break;
case OPCAT_BL: ret=(reg==BASM_REG_X86_BL); break;
case OPCAT_AX: ret=(reg==BASM_REG_X86_AX); break;
case OPCAT_CX: ret=(reg==BASM_REG_X86_CX); break;
case OPCAT_DX: ret=(reg==BASM_REG_X86_DX); break;
case OPCAT_BX: ret=(reg==BASM_REG_X86_BX); break;
case OPCAT_EAX: ret=(reg==BASM_REG_X86_EAX); break;
case OPCAT_ECX: ret=(reg==BASM_REG_X86_ECX); break;
case OPCAT_EDX: ret=(reg==BASM_REG_X86_EDX); break;
case OPCAT_EBX: ret=(reg==BASM_REG_X86_EBX); break;
case OPCAT_RAX: ret=(reg==BASM_REG_X86_RAX); break;
case OPCAT_RCX: ret=(reg==BASM_REG_X86_RCX); break;
case OPCAT_RDX: ret=(reg==BASM_REG_X86_RDX); break;
case OPCAT_RBX: ret=(reg==BASM_REG_X86_RBX); break;
case OPCAT_SR:
if( ((reg==BASM_REG_X86_CS) || (reg==BASM_REG_X86_SS) ||
(reg==BASM_REG_X86_DS) || (reg==BASM_REG_X86_ES) ||
(reg==BASM_REG_X86_FS) || (reg==BASM_REG_X86_GS)))
ret=1;
break;
case OPCAT_CS: ret=(reg==BASM_REG_X86_CS); break;
case OPCAT_SS: ret=(reg==BASM_REG_X86_SS); break;
case OPCAT_DS: ret=(reg==BASM_REG_X86_DS); break;
case OPCAT_ES: ret=(reg==BASM_REG_X86_ES); break;
case OPCAT_FS: ret=(reg==BASM_REG_X86_FS); break;
case OPCAT_GS: ret=(reg==BASM_REG_X86_GS); break;
case OPCAT_MM0: ret=(reg==BASM_REG_X86_MM0); break;
case OPCAT_MM1: ret=(reg==BASM_REG_X86_MM1); break;
case OPCAT_MM2: ret=(reg==BASM_REG_X86_MM2); break;
case OPCAT_MM3: ret=(reg==BASM_REG_X86_MM3); break;
case OPCAT_MM4: ret=(reg==BASM_REG_X86_MM4); break;
case OPCAT_MM5: ret=(reg==BASM_REG_X86_MM5); break;
case OPCAT_MM6: ret=(reg==BASM_REG_X86_MM6); break;
case OPCAT_MM7: ret=(reg==BASM_REG_X86_MM7); break;
case OPCAT_CR:
if((reg>=BASM_REG_X86_CR0) && (reg<=BASM_REG_X86_CR15))ret=1;
break;
case OPCAT_DR:
if((reg>=BASM_REG_X86_DR0) && (reg<=BASM_REG_X86_DR15))ret=1;
break;
case OPCAT_TR:
if((reg>=BASM_REG_X86_TR0) && (reg<=BASM_REG_X86_TR15))ret=1;
break;
case OPCAT_FREG:
case OPCAT_FRM:
if((reg>=BASM_REG_X86_MM0) && (reg<=BASM_REG_X86_MM7))ret=1;
if(ret) { *(int *)-1=-1; }
break;
case OPCAT_XREG:
case OPCAT_XRM:
if((reg>=BASM_REG_X86_XMM0) && (reg<=BASM_REG_X86_XMM15))ret=1;
break;
case OPCAT_REG8: ret=(((reg>>4)&15)==0); break;
case OPCAT_REG16: ret=(((reg>>4)&15)==1); break;
case OPCAT_REG32: ret=(((reg>>4)&15)==2); break;
case OPCAT_REG64: ret=(((reg>>4)&15)==3); break;
case OPCAT_RM8: ret=(((reg>>4)&15)==0); break;
case OPCAT_RM16: ret=(((reg>>4)&15)==1); break;
case OPCAT_RM32: ret=(((reg>>4)&15)==2); break;
case OPCAT_RM64: ret=(((reg>>4)&15)==3); break;
default: ret=0; break;
}
return(ret);
// if(ret)return(1);
#if 0
w=0;
if((reg&255)<64)
{
if(((reg>>4)&15)==0)w=8;
if(((reg>>4)&15)==1)w=16;
if(((reg>>4)&15)==2)w=32;
if(((reg>>4)&15)==3)w=64;
}
#endif
#if 0
switch((reg>>4)&15)
{
case 0: w=8; break;
case 1: w=16; break;
case 2: w=32; break;
case 3: w=64; break;
default: w=0; break;
}
switch(v)
{
case OPCAT_REG8: ret=(w==8); break;
case OPCAT_REG16: ret=(w==16); break;
case OPCAT_REG32: ret=(w==32); break;
case OPCAT_REG64: ret=(w==64); break;
case OPCAT_RM8: ret=(w==8); break;
case OPCAT_RM16: ret=(w==16); break;
case OPCAT_RM32: ret=(w==32); break;
case OPCAT_RM64: ret=(w==64); break;
}
#endif
// return(ret);
}
#endif
#if 1
int BASM_OpArgMemP(int i, int j, int w, int fl)
{
int v, ret;
v=basm_opcat[i*16+j];
ret=0;
switch(v)
{
case OPCAT_RM8:
ret=!(fl&4);
if(w && (w!=8) && (w!=80))ret=0;
break;
case OPCAT_RM16:
ret=!(fl&4) && !(w&&(w!=16));
break;
case OPCAT_RM32:
ret=!(fl&4) && !(w&&(w!=32));
break;
case OPCAT_RM64:
ret=!(fl&4) && !(w&&(w!=32));
break;
case OPCAT_MEM: ret=!(fl&4); break;
case OPCAT_FRM: ret=!(fl&4); break;
case OPCAT_XRM: ret=!(fl&4); break;
case OPCAT_MOFFS16:
ret=!(fl&7);
break;
case OPCAT_MOFFS32:
ret=!(fl&5);
break;
case OPCAT_MOFFS64:
ret=!(fl&1);
break;
default: ret=0; break;
}
return(ret);
}
#endif
#if 0
int BASM_OpArgMemP(int i, int j, int w, int fl)
{
if( (basm_opcat[i*16+j]!=OPCAT_RM8 ) &&
(basm_opcat[i*16+j]!=OPCAT_RM16) &&
(basm_opcat[i*16+j]!=OPCAT_RM32) &&
(basm_opcat[i*16+j]!=OPCAT_RM64) &&
(basm_opcat[i*16+j]!=OPCAT_MEM) &&
(basm_opcat[i*16+j]!=OPCAT_FRM) &&
(basm_opcat[i*16+j]!=OPCAT_XRM) &&
(basm_opcat[i*16+j]!=OPCAT_MOFFS16) &&
(basm_opcat[i*16+j]!=OPCAT_MOFFS32) &&
(basm_opcat[i*16+j]!=OPCAT_MOFFS64))return(0);
if((fl&1) && (basm_opcat[i*16+j]==OPCAT_MOFFS16))return(0);
if((fl&1) && (basm_opcat[i*16+j]==OPCAT_MOFFS32))return(0);
if((fl&1) && (basm_opcat[i*16+j]==OPCAT_MOFFS64))return(0);
if((fl&2) && (basm_opcat[i*16+j]==OPCAT_MOFFS16))return(0);
if((fl&4) && (basm_opcat[i*16+j]==OPCAT_MOFFS32))return(0);
if((fl&4) && (basm_opcat[i*16+j]!=OPCAT_MOFFS64))return(0);
if(w)
{
if((basm_opcat[i*16+j]==OPCAT_RM8 ) && (w!=8 ) && (w!=80))
return(0);
if((basm_opcat[i*16+j]==OPCAT_RM16) && (w!=16))return(0);
if((basm_opcat[i*16+j]==OPCAT_RM32) && (w!=32))return(0);
if((basm_opcat[i*16+j]==OPCAT_RM64) && (w!=64))return(0);
}
return(1);
}
#endif
int BASM_OpArgImmP(int i, int j, int w, long long imm)
{
if(!w)
{
w=8;
if((imm<(-128)) || (imm>127))w=16;
if((imm<(-32768)) || (imm>32767))w=32;
if((imm<(-(1LL<<31))) || (imm>((1LL<<31)-1)))w=64;
}
if((basm_opcat[i*16+j]==OPCAT_IMM0) && (imm==0))return(1);
if((basm_opcat[i*16+j]==OPCAT_IMM1) && (imm==1))return(1);
if((basm_opcat[i*16+j]==OPCAT_IMM2) && (imm==2))return(1);
if((basm_opcat[i*16+j]==OPCAT_IMM3) && (imm==3))return(1);
if((basm_opcat[i*16+j]==OPCAT_IMM4) && (imm==4))return(1);
if((basm_opcat[i*16+j]==OPCAT_IMM5) && (imm==5))return(1);
if((basm_opcat[i*16+j]==OPCAT_IMM6) && (imm==6))return(1);
if((basm_opcat[i*16+j]==OPCAT_IMM7) && (imm==7))return(1);
if((basm_opcat[i*16+j]==OPCAT_UIMM8 ) && (imm>=0) && (imm<=255))
return(1);
if((basm_opcat[i*16+j]==OPCAT_UIMM16) && (imm>=0) && (imm<=65535))
return(1);
// if((basm_opcat[i*16+j]==OPCAT_UIMM8 ) && (w==8 ))return(1);
// if((basm_opcat[i*16+j]==OPCAT_UIMM16) && (w<=16))return(1);
if((basm_opcat[i*16+j]==OPCAT_IMM8 ) && (w==8 ))return(1);
if((basm_opcat[i*16+j]==OPCAT_IMM16) && (w<=16))return(1);
if((basm_opcat[i*16+j]==OPCAT_IMM32) && (w<=32))return(1);
if((basm_opcat[i*16+j]==OPCAT_IMM64) && (w<=64))return(1);
if((basm_opcat[i*16+j]==OPCAT_REL8 ) && (w==8 ))return(1);
if((basm_opcat[i*16+j]==OPCAT_REL16) && (w<=16))return(1);
if((basm_opcat[i*16+j]==OPCAT_REL32) && (w<=32))return(1);
if((basm_opcat[i*16+j]==OPCAT_REL64) && (w<=64))return(1);
return(0);
}
int BASM_OpArchP(BASM_Context *ctx, int i)
{
int j;
if((basm_opcat[i*16+7]&OPFL_LONG) && !(ctx->fl&1))return(0);
if((basm_opcat[i*16+7]&OPFL_LEG) && (ctx->fl&1))return(0);
if(ctx->cpu==BASM_CPU_THUMB)
{
j=ctx->ip-ctx->text;
if(basm_opcat[i*16+7]&OPFL_EVEN)
{ if((j&3)!=0)return(0); }
if(basm_opcat[i*16+7]&OPFL_ODD)
{ if((j&3)!=2)return(0); }
if(j&1)printf("BASM_OpArchP: Misaligned Thumb Op\n");
}
return(1);
}
int BASM_OpRegP(int i, int reg)
{
if(!BASM_OpArgRegP(i, 0, reg))return(0);
if(basm_opcat[i*16+1])return(0);
if(basm_opcat[i*16+2])return(0);
return(1);
}
int BASM_OpImmP(int i, int w, long long imm)
{
int j;
if(basm_opcat[i*16+1])return(0);
if(basm_opcat[i*16+2])return(0);
j=BASM_OpArgImmP(i, 0, w, imm);
return(j);
}
int BASM_OpMemP(int i, int w)
{
if(!BASM_OpArgMemP(i, 0, w, 0))return(0);
if(basm_opcat[i*16+1])return(0);
if(basm_opcat[i*16+2])return(0);
return(1);
}
int BASM_OpRegRegP(int i, int r0, int r1)
{
if(!BASM_OpArgRegP(i, 0, r0))return(0);
if(!BASM_OpArgRegP(i, 1, r1))return(0);
if(basm_opcat[i*16+2])return(0);
return(1);
}
int BASM_OpRegImmP(int i, int reg, long long imm)
{
int w;
w=BASM_GetRegWidth(reg);
if(w==8) imm=(char)imm;
if(w==16) imm=(short)imm;
if(w==32) imm=(int)imm;
w=0;
if(!BASM_OpArgRegP(i, 0, reg))return(0);
if(!BASM_OpArgImmP(i, 1, w, imm))return(0);
if(basm_opcat[i*16+2])return(0);
return(1);
}
int BASM_OpRegMemP(int i, int reg, int fl)
{
if(!BASM_OpArgRegP(i, 0, reg))return(0);
if(!BASM_OpArgMemP(i, 1, 0, fl))return(0);
if(basm_opcat[i*16+2])return(0);
return(1);
}
int BASM_OpMemRegP(int i, int reg, int fl)
{
if(!BASM_OpArgMemP(i, 0, 0, fl))return(0);
if(!BASM_OpArgRegP(i, 1, reg))return(0);
if(basm_opcat[i*16+2])return(0);
return(1);
}
int BASM_OpMemImmP(int i, int w, long long imm)
{
if(w==8)imm=(char)imm;
if(w==16)imm=(short)imm;
if(w==32)imm=(int)imm;
if(!BASM_OpArgMemP(i, 0, w, 0))return(0);
if(!BASM_OpArgImmP(i, 1, w, imm))return(0);
if(basm_opcat[i*16+2])return(0);
return(1);
}
int BASM_OpRegRegImmP(int i, int r0, int r1, long long imm)
{
if(!BASM_OpArgRegP(i, 0, r0))return(0);
if(!BASM_OpArgRegP(i, 1, r1))return(0);
if(!BASM_OpArgImmP(i, 2, 0, imm))return(0);
if(basm_opcat[i*16+3])return(0);
return(1);
}
int BASM_OpRegMemImmP(int i, int reg, int fl, long long imm)
{
if(!BASM_OpArgRegP(i, 0, reg))return(0);
if(!BASM_OpArgMemP(i, 1, 0, fl))return(0);
if(!BASM_OpArgImmP(i, 2, 0, imm))return(0);
if(basm_opcat[i*16+3])return(0);
return(1);
}
int BASM_OpMemRegImmP(int i, int reg, int fl, long long imm)
{
if(!BASM_OpArgMemP(i, 0, 0, fl))return(0);
if(!BASM_OpArgRegP(i, 1, reg))return(0);
if(!BASM_OpArgImmP(i, 2, 0, imm))return(0);
if(basm_opcat[i*16+3])return(0);
return(1);
}
int BASM_OpRegRegRegP(int i, int r0, int r1, int r2)
{
if(!BASM_OpArgRegP(i, 0, r0))return(0);
if(!BASM_OpArgRegP(i, 1, r1))return(0);
if(!BASM_OpArgRegP(i, 2, r2))return(0);
if(basm_opcat[i*16+3])return(0);
return(1);
}
int BASM_OpRegMemRegP(int i, int r0, int r1, int fl)
{
if(!BASM_OpArgRegP(i, 0, r0))return(0);
if(!BASM_OpArgMemP(i, 1, 0, fl))return(0);
if(!BASM_OpArgRegP(i, 2, r1))return(0);
if(basm_opcat[i*16+3])return(0);
return(1);
}
int BASM_OpMemRegRegP(int i, int r0, int r1, int fl)
{
if(!BASM_OpArgMemP(i, 0, 0, fl))return(0);
if(!BASM_OpArgRegP(i, 1, r0))return(0);
if(!BASM_OpArgRegP(i, 2, r1))return(0);
if(basm_opcat[i*16+3])return(0);
return(1);
}
BASM_API void BASM_OutOpSingle(BASM_Context *ctx, int op)
{
int i;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
if(!BASM_OpSingleP(i))
continue;
BASM_OutOpStr(ctx, basm_opdecl[i]);
return;
}
basm_error("ASM: Bad Opcode Args, %s\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpReg(BASM_Context *ctx, int op, int reg)
{
int i;
// if(!(ctx->fl&1) && (((reg>>4)==1) || ((reg>>4)==2)))
// {
// if(op==BASM_OP_INC)op=BASM_OP_INC_R;
// if(op==BASM_OP_DEC)op=BASM_OP_DEC_R;
// }
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
if(!BASM_OpRegP(i, reg))continue;
BASM_OutOpStrReg(ctx, basm_opdecl[i], reg);
return;
}
basm_error("ASM: Bad Opcode Args, %s reg\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpImm(BASM_Context *ctx, int op, int w,
long long imm, char *lbl)
{
int i;
if(lbl && !w)w=(ctx->fl&2)?16:32;
if(!w && (op==BASM_OP_X86_PUSH))w=(ctx->fl&2)?16:32;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
if(!BASM_OpImmP(i, w, imm))continue;
BASM_OutOpStrImm(ctx, basm_opdecl[i], imm, lbl);
return;
}
i=basm_opidx[op];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
if(!BASM_OpImmP(i, 0, imm))continue;
BASM_OutOpStrImm(ctx, basm_opdecl[i], imm, lbl);
return;
}
basm_error("ASM: Bad Opcode Args, %s imm\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpMem(BASM_Context *ctx, int op, int w,
char *lbl, int breg, int ireg, int sc, long long disp)
{
int i;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
if((w==0) && (basm_opnums[i+1]==op))
{
basm_warning("ASM: Warn, '%s mem', arg size needed\n",
basm_ops[op]);
w=(ctx->fl&BASM_FL_X86_64)?64:
((ctx->fl&BASM_FL_X86_16)?16:32);
}
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
if(!BASM_OpMemP(i, w))continue;
BASM_OutOpStrMem(ctx, basm_opdecl[i],
lbl, breg, ireg, sc, disp);
return;
}
basm_error("ASM: Bad Opcode Args, %s mem\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpRegReg(BASM_Context *ctx, int op, int r0, int r1)
{
int i, j;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
if(!BASM_OpRegRegP(i, r0, r1))continue;
if( (basm_opcat[i*16+0]!=OPCAT_REG8) &&
(basm_opcat[i*16+0]!=OPCAT_REG16) &&
(basm_opcat[i*16+0]!=OPCAT_REG32) &&
(basm_opcat[i*16+0]!=OPCAT_REG64) &&
(basm_opcat[i*16+0]!=OPCAT_FREG) &&
(basm_opcat[i*16+0]!=OPCAT_XREG))
{ j=r0; r0=r1; r1=j; }
BASM_OutOpStrRegReg(ctx, basm_opdecl[i], r0, r1);
return;
}
basm_error("ASM: Bad Opcode Args, %s reg reg\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpRegImm(BASM_Context *ctx, int op,
int reg, long long imm, char *lbl)
{
int i;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
if(!BASM_OpRegImmP(i, reg, lbl?0x7F7F7F7F7F7FLL:imm))continue;
// printf("OpRegImm: %s\n", basm_opdecl[i]);
BASM_OutOpStrRegImm(ctx, basm_opdecl[i], reg, imm, lbl);
return;
}
basm_error("ASM: Bad Opcode Args, %s reg, imm\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpRegMem(BASM_Context *ctx, int op, int reg,
char *lbl, int breg, int ireg, int sc, long long disp)
{
int i, j;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
j=0; if(breg!=BASM_Z)j|=1; if(ireg!=BASM_Z)j|=1;
if(sc && (sc!=1))j|=1;
if(!(ctx->fl&2) && lbl)j|=2;
if((disp<0) || (disp>=65536))j|=2;
if((disp<-2147483648LL) || (disp>2147483647LL))j|=4;
if(!BASM_OpRegMemP(i, reg, j))continue;
BASM_OutOpStrRegMem(ctx, basm_opdecl[i], reg,
lbl, breg, ireg, sc, disp);
return;
}
basm_error("ASM: Bad Opcode Args, %s reg, mem\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpMemReg(BASM_Context *ctx, int op, int reg,
char *lbl, int breg, int ireg, int sc, long long disp)
{
int i, j;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
j=0; if(breg!=BASM_Z)j|=1; if(ireg!=BASM_Z)j|=1;
if(sc && (sc!=1))j|=1;
if(!(ctx->fl&2) && lbl)j|=2;
if((disp<0) || (disp>=65536))j|=2;
if((disp<-2147483648LL) || (disp>2147483647LL))j|=4;
if(!BASM_OpMemRegP(i, reg, j))continue;
BASM_OutOpStrRegMem(ctx, basm_opdecl[i], reg,
lbl, breg, ireg, sc, disp);
return;
}
basm_error("ASM: Bad Opcode Args, %s mem, reg\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpMemImm(BASM_Context *ctx, int op, int w,
char *lbl, int breg, int ireg, int sc, long long disp,
long long imm, char *lbl2)
{
int i;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
if((w==0) && (basm_opnums[i+1]==op))
{
basm_warning("ASM: Warn, '%s mem, imm', arg size needed\n",
basm_ops[op]);
w=(ctx->fl&BASM_FL_X86_64)?64:
((ctx->fl&BASM_FL_X86_16)?16:32);
}
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
if(!BASM_OpMemImmP(i, w, lbl2?0x7F7F7F7F7F7FLL:imm))continue;
BASM_OutOpStrMemImm(ctx, basm_opdecl[i], w,
lbl, breg, ireg, sc, disp, imm, lbl2);
return;
}
basm_error("ASM: Bad Opcode Args, %s mem, imm\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpRegRegImm(BASM_Context *ctx,
int op, int r0, int r1,
long long imm, char *lbl2)
{
int i, j;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
if(!BASM_OpRegRegImmP(i, r0, r1, lbl2?0x7F7F7F7F7F7FLL:imm))
continue;
if( (basm_opcat[i*16+0]!=OPCAT_REG8) &&
(basm_opcat[i*16+0]!=OPCAT_REG16) &&
(basm_opcat[i*16+0]!=OPCAT_REG32) &&
(basm_opcat[i*16+0]!=OPCAT_REG64) &&
(basm_opcat[i*16+0]!=OPCAT_FREG) &&
(basm_opcat[i*16+0]!=OPCAT_XREG))
{ j=r0; r0=r1; r1=j; }
BASM_OutOpStrRegRegImm(ctx, basm_opdecl[i], r0, r1, imm, lbl2);
return;
}
basm_error("ASM: Bad Opcode Args, %s reg, reg, imm\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpRegMemImm(BASM_Context *ctx, int op, int reg,
char *lbl, int breg, int ireg, int sc, long long disp,
long long imm, char *lbl2)
{
int i, j;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
j=0; if(breg!=BASM_Z)j|=1; if(ireg!=BASM_Z)j|=1;
if(sc && (sc!=1))j|=1;
if(!(ctx->fl&2) && lbl)j|=2;
if((disp<0) || (disp>=65536))j|=2;
if((disp<-2147483648LL) || (disp>2147483647LL))j|=4;
if(!BASM_OpRegMemImmP(i, reg, j, lbl2?0x7F7F7F7F7F7FLL:imm))
continue;
BASM_OutOpStrRegMemImm(ctx, basm_opdecl[i], reg,
lbl, breg, ireg, sc, disp, imm, lbl2);
return;
}
basm_error("ASM: Bad Opcode Args, %s reg, mem\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpMemRegImm(BASM_Context *ctx, int op, int reg,
char *lbl, int breg, int ireg, int sc, long long disp,
long long imm, char *lbl2)
{
int i, j;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
j=0; if(breg!=BASM_Z)j|=1; if(ireg!=BASM_Z)j|=1;
if(sc && (sc!=1))j|=1;
if(!(ctx->fl&2) && lbl)j|=2;
if((disp<0) || (disp>=65536))j|=2;
if((disp<-2147483648LL) || (disp>2147483647LL))j|=4;
if(!BASM_OpMemRegImmP(i, reg, j, lbl2?0x7F7F7F7F7F7FLL:imm))
continue;
BASM_OutOpStrRegMemImm(ctx, basm_opdecl[i], reg,
lbl, breg, ireg, sc, disp, imm, lbl2);
return;
}
basm_error("ASM: Bad Opcode Args, %s mem, reg\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpRegRegReg(BASM_Context *ctx,
int op, int r0, int r1, int r2)
{
int i, j;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
if(!BASM_OpRegRegRegP(i, r0, r1, r2))
continue;
if( (basm_opcat[i*16+0]!=OPCAT_REG8) &&
(basm_opcat[i*16+0]!=OPCAT_REG16) &&
(basm_opcat[i*16+0]!=OPCAT_REG32) &&
(basm_opcat[i*16+0]!=OPCAT_REG64) &&
(basm_opcat[i*16+0]!=OPCAT_FREG) &&
(basm_opcat[i*16+0]!=OPCAT_XREG))
{ j=r0; r0=r1; r1=j; }
BASM_OutOpStrRegRegReg(ctx, basm_opdecl[i], r0, r1, r2);
return;
}
basm_error("ASM: Bad Opcode Args, %s reg, reg, reg\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpRegMemReg(BASM_Context *ctx, int op, int reg,
char *lbl, int breg, int ireg, int sc, long long disp,
int reg2)
{
int i, j;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
j=0; if(breg!=BASM_Z)j|=1; if(ireg!=BASM_Z)j|=1;
if(sc && (sc!=1))j|=1;
if(!(ctx->fl&2) && lbl)j|=2;
if((disp<0) || (disp>=65536))j|=2;
if((disp<-2147483648LL) || (disp>2147483647LL))j|=4;
if(!BASM_OpRegMemRegP(i, reg, reg2, j))
continue;
BASM_OutOpStrRegMemReg(ctx, basm_opdecl[i], reg,
lbl, breg, ireg, sc, disp, reg2);
return;
}
basm_error("ASM: Bad Opcode Args, %s reg, mem\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpMemRegReg(BASM_Context *ctx, int op, int reg,
char *lbl, int breg, int ireg, int sc, long long disp,
int reg2)
{
int i, j;
i=basm_opidx[op];
if(basm_opnums[i]!=op)
op=basm_opnums[i];
for(; basm_opnums[i]==op; i++)
{
if(!BASM_OpArchP(ctx, i))continue;
j=0; if(breg!=BASM_Z)j|=1; if(ireg!=BASM_Z)j|=1;
if(sc && (sc!=1))j|=1;
if(!(ctx->fl&2) && lbl)j|=2;
if((disp<0) || (disp>=65536))j|=2;
if((disp<-2147483648LL) || (disp>2147483647LL))j|=4;
if(!BASM_OpMemRegRegP(i, reg, reg2, j))
continue;
BASM_OutOpStrRegMemReg(ctx, basm_opdecl[i], reg,
lbl, breg, ireg, sc, disp,
reg2);
return;
}
basm_error("ASM: Bad Opcode Args, %s mem, reg\n", basm_ops[op]);
// *(int *)-1=-1;
}
BASM_API void BASM_OutOpGeneric1(BASM_Context *ctx, int op, int w,
char *lbl, int breg, int ireg, int sc, long long disp)
{
if(sc)
{
BASM_OutOpMem(ctx, op, w, lbl, breg, ireg, sc, disp);
}else if(breg!=BASM_Z)
{
BASM_OutOpReg(ctx, op, breg);
}else
{
BASM_OutOpImm(ctx, op, w, disp, lbl);
}
}
BASM_API void BASM_OutOpGeneric2(BASM_Context *ctx, int op, int w,
char *lbl0, int breg0, int ireg0, int sc0, long long disp0,
char *lbl1, int breg1, int ireg1, int sc1, long long disp1)
{
if(sc0)
{
if(sc1)
{
basm_warning("BASM_ParseOpcode: "
"Invalid opcode args G2-A, %s\n", basm_ops[op]);
return;
}
if(breg1!=BASM_Z)
{
BASM_OutOpMemReg(ctx, op, breg1,
lbl0, breg0, ireg0, sc0, disp0);
}else
{
BASM_OutOpMemImm(ctx, op, w,
lbl0, breg0, ireg0, sc0, disp0, disp1, lbl1);
}
}else if(breg0!=BASM_Z)
{
if(sc1)
{
if(ctx->fl&BASM_FL_ARM)
{
if(ireg1!=BASM_Z)
{
BASM_OutOpRegRegReg(ctx, op, breg0, breg1, ireg1);
return;
}
if(disp1 || lbl1)
{
BASM_OutOpRegRegImm(ctx, op, breg0, breg1, disp1, lbl1);
return;
}
BASM_OutOpRegReg(ctx, op, breg0, breg1);
return;
}
BASM_OutOpRegMem(ctx, op, breg0,
lbl1, breg1, ireg1, sc1, disp1);
}else if(breg1!=BASM_Z)
{
BASM_OutOpRegReg(ctx, op, breg0, breg1);
}else
{
BASM_OutOpRegImm(ctx, op, breg0, disp1, lbl1);
}
}else
{
basm_error("BASM_ParseOpcode: "
"Invalid opcode args G2-B, %s\n", basm_ops[op]);
return;
}
}
BASM_API void BASM_OutOpGeneric3(BASM_Context *ctx, int op, int w,
char *lbl0, int breg0, int ireg0, int sc0, long long disp0,
char *lbl1, int breg1, int ireg1, int sc1, long long disp1,
char *lbl2, int breg2, int ireg2, int sc2, long long disp2)
{
if(sc0)
{
if(sc1)
{
basm_error("BASM_ParseOpcode: "
"Invalid opcode args G3-A, %s\n", basm_ops[op]);
return;
}
if(breg1!=BASM_Z)
{
if(breg2!=BASM_Z)
{
BASM_OutOpMemRegReg(ctx, op, breg1,
lbl0, breg0, ireg0, sc0, disp0,
breg2);
return;
}
BASM_OutOpMemRegImm(ctx, op, breg1,
lbl0, breg0, ireg0, sc0, disp0, disp2, lbl2);
}else
{
basm_error("BASM_ParseOpcode: "
"Invalid opcode args %s\n", basm_ops[op]);
// BASM_OutOpMemImmImm(ctx, i, w,
// l0, br0, ir0, sc0, disp0, disp1, l1,
// disp2, l2);
}
}else if(breg0!=BASM_Z)
{
if(sc1)
{
if(breg2!=BASM_Z)
{
BASM_OutOpRegMemReg(ctx, op, breg0,
lbl1, breg1, ireg1, sc1, disp1,
breg2);
return;
}
BASM_OutOpRegMemImm(ctx, op, breg0,
lbl1, breg1, ireg1, sc1, disp1, disp2, lbl2);
}else if(breg1!=BASM_Z)
{
if(breg2!=BASM_Z)
{
BASM_OutOpRegRegReg(ctx, op,
breg0, breg1, breg2);
return;
}
BASM_OutOpRegRegImm(ctx, op, breg0, breg1,
disp2, lbl2);
}else
{
basm_error("BASM_ParseOpcode: "
"Invalid opcode args %s\n", basm_ops[op]);
// BASM_OutOpRegImmImm(ctx, op, breg0, disp1, lbl1,
// disp2, lbl2);
}
}else
{
basm_error("BASM_ParseOpcode: "
"Invalid opcode args %s, G3-B, \n", basm_ops[op]);
return;
}
}
BASM_API void BASM_EmitLabelPos(BASM_Context *ctx, char *name, int pos)
{
int i, j;
// printf("Emit Label %s @ %p\n", name, ctx->ip);
i=ctx->n_labels++;
if(i>=ctx->m_labels)
{
j=ctx->m_labels+(ctx->m_labels>>1);
ctx->label_name=(char **)
realloc(ctx->label_name, j*sizeof(char *));
ctx->label_pos=(int *)realloc(ctx->label_pos, j*sizeof(int));
ctx->llbl_name=(char **)
realloc(ctx->llbl_name, j*sizeof(char *));
ctx->llbl_pos=(int *)realloc(ctx->llbl_pos, j*sizeof(int));
ctx->m_labels=j;
}
ctx->label_name[i]=basm_strdup(name);
ctx->label_pos[i]=pos;
}
BASM_API void BASM_EmitGotoPos(BASM_Context *ctx,
char *name, int ty, int pos)
{
int i, j;
// printf("Emit Goto %s\n", name);
i=ctx->n_gotos++;
if(i>=ctx->m_gotos)
{
j=ctx->m_gotos+(ctx->m_gotos>>1);
ctx->goto_name=(char **)realloc(ctx->goto_name, j*sizeof(char *));
ctx->goto_pos=(int *)realloc(ctx->goto_pos, j*sizeof(int));
ctx->goto_type=(byte *)realloc(ctx->goto_type, j);
ctx->m_gotos=j;
}
ctx->goto_name[i]=name?basm_strdup(name):NULL;
ctx->goto_pos[i]=pos;
ctx->goto_type[i]=ty;
}
BASM_API void BASM_EmitLabel(BASM_Context *ctx, char *name)
{
int i;
if(!name)return;
if(ctx->fl&4)i=(2<<24)+(ctx->dp-ctx->data);
else i=(1<<24)+(ctx->ip-ctx->text);
BASM_EmitLabelPos(ctx, name, i);
}
BASM_API void BASM_EmitGoto(BASM_Context *ctx, char *name, int ty)
{
int i;
if(!name)return;
if(ctx->fl&4)i=(2<<24)+(ctx->dp-ctx->data);
else i=(1<<24)+(ctx->ip-ctx->text);
BASM_EmitGotoPos(ctx, name, ty, i);
}
BASM_API void BASM_EmitConst(BASM_Context *ctx, char *name, long long val)
{
int i, j;
if(!name)return;
i=ctx->n_const++;
if(i>=ctx->m_const)
{
j=ctx->m_const+(ctx->m_const>>1);
ctx->const_name=
(char **)realloc(ctx->const_name, j*sizeof(char *));
ctx->const_value=
(long long *)realloc(ctx->const_value,
j*sizeof(long long));
ctx->m_const=j;
}
ctx->const_name[i]=basm_strdup(name);
ctx->const_value[i]=val;
}
BASM_API int BASM_PredictPos(BASM_Context *ctx, char *name)
{
int i;
if(!name)return(-1);
for(i=0; i<ctx->n_labels; i++)
if(!strcmp(ctx->label_name[i], name))
return(ctx->label_pos[i]);
for(i=0; i<ctx->n_llbl; i++)
if(!strcmp(ctx->llbl_name[i], name))
return(ctx->llbl_pos[i]);
return(-1);
}
BASM_API int BASM_PredictDisp(BASM_Context *ctx, char *name)
{
int i, j;
if(!name)return(-1);
j=BASM_PredictPos(ctx, name);
if(j<0)return(0);
if(ctx->fl&4)
{
// i=(2<<24)+(ctx->dp-ctx->data);
if(((j>>24)&0x0F)!=2)return(0);
i=(j&0xFFFFFF)-(ctx->dp-ctx->data);
return(i);
}else
{
// i=(1<<24)+(ctx->ip-ctx->text);
if(((j>>24)&0x0F)!=1)return(0);
i=(j&0xFFFFFF)-(ctx->ip-ctx->text);
return(i);
}
}
| 2.09375 | 2 |
2024-11-18T20:50:29.295614+00:00 | 2018-10-26T03:19:03 | ae2678fb95819f4129eb8cd9ea6d7eb1f4ff4fa2 | {
"blob_id": "ae2678fb95819f4129eb8cd9ea6d7eb1f4ff4fa2",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-26T03:19:03",
"content_id": "3bde2a681f921d57a51a59026a990e4919c57af2",
"detected_licenses": [
"MIT"
],
"directory_id": "0e3c919dfcef7c6815e6709faabb474595723546",
"extension": "c",
"filename": "user.c",
"fork_events_count": 0,
"gha_created_at": "2018-10-26T03:18:05",
"gha_event_created_at": "2018-10-26T03:18:05",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 154771044,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2385,
"license": "MIT",
"license_type": "permissive",
"path": "/01 - Independent Study/UTAustinX_1201_RTOS/TM4C123Valvanoware/RTOS_4C123/user.c",
"provenance": "stackv2-0110.json.gz:215122",
"repo_name": "RyanTruran/EmbeddedSystems.Playground",
"revision_date": "2018-10-26T03:19:03",
"revision_id": "0374b601ce9138d730d15acd4071275315e316d7",
"snapshot_id": "4c00fff3cbb1cfe0cbefd0b1bd53e44f5d28f10a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RyanTruran/EmbeddedSystems.Playground/0374b601ce9138d730d15acd4071275315e316d7/01 - Independent Study/UTAustinX_1201_RTOS/TM4C123Valvanoware/RTOS_4C123/user.c",
"visit_date": "2021-09-25T21:56:03.070406"
} | stackv2 | //*****************************************************************************
// user.c
// Runs on LM4F120/TM4C123/MSP432
// An example user program that initializes the simple operating system
// Schedule three independent threads using preemptive round robin
// Each thread rapidly toggles a pin on profile pins and increments its counter
// THREADFREQ is the rate of the scheduler in Hz
// Daniel Valvano
// February 8, 2016
/* This example accompanies the book
"Embedded Systems: Real Time Interfacing to ARM Cortex M Microcontrollers",
ISBN: 978-1463590154, Jonathan Valvano, copyright (c) 2016
"Embedded Systems: Real-Time Operating Systems for ARM Cortex-M Microcontrollers",
ISBN: 978-1466468863, , Jonathan Valvano, copyright (c) 2016
Programs 4.4 through 4.12, section 4.2
Copyright 2016 by Jonathan W. Valvano, valvano@mail.utexas.edu
You may use, edit, run or distribute this file
as long as the above copyright notice remains
THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
VALVANO SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
For more information about my classes, my research, and my books, see
http://users.ece.utexas.edu/~valvano/
*/
#include <stdint.h>
#include "os.h"
#include "../inc/BSP.h"
#include "../inc/profile.h"
#define THREADFREQ 500 // frequency in Hz
// runs each thread 2 ms
uint32_t Count0; // number of times Task0 loops
uint32_t Count1; // number of times Task1 loops
uint32_t Count2; // number of times Task2 loops
void Task0(void){
Count0 = 0;
while(1){
Count0++;
Profile_Toggle0(); // toggle bit
}
}
void Task1(void){
Count1 = 0;
while(1){
Count1++;
Profile_Toggle1(); // toggle bit
}
}
void Task2(void){
Count2 = 0;
while(1){
Count2++;
Profile_Toggle2(); // toggle bit
}
}
int main(void){
OS_Init(); // initialize, disable interrupts
Profile_Init(); // enable digital I/O on profile pins
OS_AddThreads(&Task0, &Task1, &Task2);
OS_Launch(BSP_Clock_GetFreq()/THREADFREQ); // doesn't return, interrupts enabled in here
return 0; // this never executes
}
| 2.671875 | 3 |
2024-11-18T20:50:31.052700+00:00 | 2020-06-04T06:48:27 | ed614fba5d8c22d59cb3b12dc37e5aac9b01d007 | {
"blob_id": "ed614fba5d8c22d59cb3b12dc37e5aac9b01d007",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-04T06:48:27",
"content_id": "cf0a719f08a43659b44b8fb134853325928e0afe",
"detected_licenses": [
"MIT"
],
"directory_id": "1021c69e6f3eee99aca836fcfff3417f4a96590f",
"extension": "c",
"filename": "HeapSort.c",
"fork_events_count": 1,
"gha_created_at": "2019-06-22T14:39:04",
"gha_event_created_at": "2020-06-04T06:48:28",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 193244223,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1033,
"license": "MIT",
"license_type": "permissive",
"path": "/HeapSort.c",
"provenance": "stackv2-0110.json.gz:215515",
"repo_name": "adi0311/Data-Structures-and-Algorithms-in-C",
"revision_date": "2020-06-04T06:48:27",
"revision_id": "62a4cc42d9b2f24413d6c27cfe18d58003d83bc2",
"snapshot_id": "34b7512bad5eb84d5158ab94cfbc4a3f5fd1d8a1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/adi0311/Data-Structures-and-Algorithms-in-C/62a4cc42d9b2f24413d6c27cfe18d58003d83bc2/HeapSort.c",
"visit_date": "2020-06-08T14:28:18.674546"
} | stackv2 | #include<stdio.h>
#include<stdlib.h>
void Heapify(int*, int, int);
void HeapSort(int*, int);
void swap(int*, int*);
int main()
{
int size, i;
printf("Enter the size of the array.\n");
scanf("%d", &size);
int* arr = (int *)malloc(size * sizeof(int));
printf("Enter the elements of the heap one by one.\n");
for(i = 0; i < size; i++)
scanf("%d", &arr[i]);
HeapSort(arr, size);
printf("Sorted array:\n");
for(i = 0; i < size; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
void Heapify(int* arr, int size, int i)
{
int l = 2*i+1;
int r = 2*i+2;
int largest = i;
if(l < size && arr[l] > arr[largest])
largest = l;
if(r < size && arr[r] > arr[largest])
largest = r;
if(i != largest)
{
swap(&arr[i], &arr[largest]);
Heapify(arr, size, largest);
}
}
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void HeapSort(int* arr, int size)
{
int i;
for(i = size/2-1; i >= 0; i--)
Heapify(arr, size, i);
for(i = size-1; i >= 0; i--)
{
swap(&arr[0], &arr[i]);
Heapify(arr, i, 0);
}
}
| 3.8125 | 4 |
2024-11-18T20:50:31.182391+00:00 | 2020-06-03T06:46:40 | 753179e970a8d6a15b98fa1797f3600f8fa414bf | {
"blob_id": "753179e970a8d6a15b98fa1797f3600f8fa414bf",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-03T06:46:40",
"content_id": "4af43055a91bb094b507827569f71d3de95afb77",
"detected_licenses": [
"MIT"
],
"directory_id": "3e9072ed49bcf2e628417a63d729ea8d7033a051",
"extension": "c",
"filename": "IsoHardElastoplastic.C",
"fork_events_count": 3,
"gha_created_at": "2020-03-02T07:43:54",
"gha_event_created_at": "2020-03-23T16:28:47",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 244309925,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8955,
"license": "MIT",
"license_type": "permissive",
"path": "/Sources/Libraries/finiteElement/IsoHardElastoplastic.C",
"provenance": "stackv2-0110.json.gz:215644",
"repo_name": "pantale/ReDynELA",
"revision_date": "2020-06-03T06:46:40",
"revision_id": "273db43f7a32f956847ce88c2d0e0b7f432a2bb5",
"snapshot_id": "4e9f3ab0d0b2a1e806c310a0aba1ff292dd11338",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/pantale/ReDynELA/273db43f7a32f956847ce88c2d0e0b7f432a2bb5/Sources/Libraries/finiteElement/IsoHardElastoplastic.C",
"visit_date": "2021-07-20T11:03:27.103726"
} | stackv2 | /***************************************************************************
* *
* DynELA Project *
* *
* (c) Copyright 1997-2006 *
* *
* Equipe C.M.A.O *
* Laboratoire Genie de production *
* Ecole Nationale d'Ingenieurs de Tarbes *
* BP 1629 - 65016 TARBES cedex *
* *
* *
* Main Author: Olivier PANTALE *
* *
**************************************************************************/
// begin date :
/*
Class IsoHardElastoplastic definition
*/
/*!
\file IsoHardElastoplastic.C
\brief fichier .C de d�finition d'un mat�riau �lasto-plastique
\ingroup femLibrary
Ce fichier sert � la d�finition d'un mat�riau de type �lasto-plastique sur DynELA.
\author © Olivier PANTALE
\since DynELA 0.9.5
\date 1997-2004
*/
#include <IsoHardElastoplastic.h>
#include <IntegrationPoint.h>
#include <Element.h>
//-----------------------------------------------------------------------------
Indice
IsoHardElastoplastic::getType()
//-----------------------------------------------------------------------------
{
return ElastoPlastic;
}
//-----------------------------------------------------------------------------
IsoHardElastoplastic::IsoHardElastoplastic() : IsotropicHardening()
//-----------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
IsoHardElastoplastic::IsoHardElastoplastic(const IsoHardElastoplastic &mat) : IsotropicHardening(mat)
//-----------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
IsoHardElastoplastic::~IsoHardElastoplastic()
//-----------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
Real &IsoHardElastoplastic::Yield_Stress()
//-----------------------------------------------------------------------------
{
return A;
}
//-----------------------------------------------------------------------------
Real &IsoHardElastoplastic::Hard_Param()
//-----------------------------------------------------------------------------
{
return B;
}
//-----------------------------------------------------------------------------
Real &IsoHardElastoplastic::Hard_Exponent()
//-----------------------------------------------------------------------------
{
// is_Linear=No;
return n;
}
/*
* //-----------------------------------------------------------------------------
Real & IsoHardElastoplastic::Fail_Strain ()
//-----------------------------------------------------------------------------
{
return EpsM;
}
//-----------------------------------------------------------------------------
Real & IsoHardElastoplastic::Max_Stress ()
//-----------------------------------------------------------------------------
{
return SigM;
}
*/
//-----------------------------------------------------------------------------
Indice
IsoHardElastoplastic::getNumberOfConstitutiveParameters()
//-----------------------------------------------------------------------------
{
return 3;
}
//-----------------------------------------------------------------------------
const char *
IsoHardElastoplastic::getConstitutiveParameterName(Indice ind)
//-----------------------------------------------------------------------------
{
String retour;
switch (ind)
{
case 0:
return "A";
break;
case 1:
return "B";
break;
case 2:
return "n";
break;
default:
fatalError("IsoHardElastoplastic::geConstitutiveParameterName",
"called with ind = %d", ind);
}
return "";
}
//-----------------------------------------------------------------------------
Real &IsoHardElastoplastic::getConstitutiveParameter(Indice ind)
//-----------------------------------------------------------------------------
{
switch (ind)
{
case 0:
return A;
break;
case 1:
return B;
break;
case 2:
return n;
break;
default:
fatalError("IsoHardElastoplastic::geConstitutiveParameterName",
"called with ind = %d", ind);
}
// pour tromper le compilo, mais ca sert a rien car il ne passe jamais ici
return A;
}
//-----------------------------------------------------------------------------
void IsoHardElastoplastic::plot(FILE *pfile, Real epsMax)
//-----------------------------------------------------------------------------
{
for (Real evpl = 0; evpl < epsMax; evpl += (evpl / 5.0) + 1.0 / 1000.0)
{
Real val = (A + B * pow(evpl, n));
fprintf(pfile, "%lf, %lf\n", evpl, val);
}
}
//-----------------------------------------------------------------------------
Real IsoHardElastoplastic::getIsotropicYieldStress(Element *element, Real shift)
//-----------------------------------------------------------------------------
{
Real evp = element->ref->evp + Sqrt23 * shift;
return (A + B * pow(evp, n));
}
//-----------------------------------------------------------------------------
Real IsoHardElastoplastic::getIsotropicYieldHardening(Element *element, Real shift)
//-----------------------------------------------------------------------------
{
Real evp = element->ref->evp + Sqrt23 * shift;
return (n * B * pow(evp, (n - 1.)));
}
//-----------------------------------------------------------------------------
Real IsoHardElastoplastic::getYieldStress(IntegrationPoint *point)
//-----------------------------------------------------------------------------
{
return (A + B * pow(point->evp, n));
}
//-----------------------------------------------------------------------------
Real IsoHardElastoplastic::getDerYieldStress(IntegrationPoint *point)
//-----------------------------------------------------------------------------
{
return (n * B * pow(point->evp, (n - 1.)));
}
//-----------------------------------------------------------------------------
void IsoHardElastoplastic::print(ostream &os) const
//-----------------------------------------------------------------------------
{
os << "Elastic Plastic law\n";
// Material::print (os);
os << "A=" << A << endl;
os << "B=" << B << endl;
os << "n=" << n << endl;
// os << "EpsM=" << EpsM << endl;
// os << "SigM=" << SigM << endl;
}
//-----------------------------------------------------------------------------
ostream &operator<<(ostream &os, IsoHardElastoplastic &mat)
//-----------------------------------------------------------------------------
{
mat.print(os);
return os;
}
//-----------------------------------------------------------------------------
void IsoHardElastoplastic::toFile(FILE *pfile)
//-----------------------------------------------------------------------------
{
fprintf(pfile, " YIELD HARDENING HARDENING\n");
fprintf(pfile, " STRESS PARAMETER EXPONENT\n");
fprintf(pfile, " %8.5E %8.5E %8.5E\n", A, B, n);
fprintf(pfile, "\n");
}
//-----------------------------------------------------------------------------
void IsoHardElastoplastic::setYieldStress(Real val)
//-----------------------------------------------------------------------------
{
A = val;
}
//-----------------------------------------------------------------------------
void IsoHardElastoplastic::setHardParameter(Real val)
//-----------------------------------------------------------------------------
{
B = val;
}
//-----------------------------------------------------------------------------
void IsoHardElastoplastic::setHardExponent(Real val)
//-----------------------------------------------------------------------------
{
n = val;
}
//-----------------------------------------------------------------------------
String IsoHardElastoplastic::convertToDynELASourceFile(String name)
//-----------------------------------------------------------------------------
{
String str;
char sstr[1000];
str = "";
sprintf(sstr, "%s.setYieldStress(%12.7E);\n", name.chars(), A);
str += sstr;
sprintf(sstr, "%s.setHardParameter(%12.7E);\n", name.chars(), B);
str += sstr;
sprintf(sstr, "%s.setHardExponent(%12.7E);\n", name.chars(), n);
str += sstr;
return str;
}
| 2.3125 | 2 |
2024-11-18T20:50:31.576230+00:00 | 2023-05-26T06:18:10 | 9643eddf4faa1c2fd6b4d4e9d5f073246eee77f2 | {
"blob_id": "9643eddf4faa1c2fd6b4d4e9d5f073246eee77f2",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-26T06:18:10",
"content_id": "98c5da3f8ccf25ff4d3d51b0da9d07536d1486c2",
"detected_licenses": [
"MIT"
],
"directory_id": "8b13bf541ca06be4a179fabb11de1acd8eefe0c7",
"extension": "c",
"filename": "personalize.c",
"fork_events_count": 4,
"gha_created_at": "2014-10-25T07:06:45",
"gha_event_created_at": "2023-08-14T23:34:44",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 25723312,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9670,
"license": "MIT",
"license_type": "permissive",
"path": "/c/personalize.c",
"provenance": "stackv2-0110.json.gz:216033",
"repo_name": "rambo/nfc_lock",
"revision_date": "2023-05-26T06:18:10",
"revision_id": "c45bf485fc215185bde4931185f03d754b28c56e",
"snapshot_id": "666247db5486aed1c9682fc37f5bbbc1bb3d4b00",
"src_encoding": "UTF-8",
"star_events_count": 26,
"url": "https://raw.githubusercontent.com/rambo/nfc_lock/c45bf485fc215185bde4931185f03d754b28c56e/c/personalize.c",
"visit_date": "2023-08-25T12:17:41.121418"
} | stackv2 | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <err.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <string.h> // memcpy
#include <stdlib.h> //realloc
#include <pthread.h>
#include <nfc/nfc.h>
#include <freefare.h>
#include "pre-personalize_config.h"
#include "keydiversification.h"
#include "helpers.h"
// Catch SIGINT and SIGTERM so we can do a clean exit
static int s_interrupted = 0;
static void s_signal_handler(int signal_value)
{
s_interrupted = 1;
}
static void s_catch_signals (void)
{
struct sigaction action;
action.sa_handler = s_signal_handler;
action.sa_flags = 0;
sigemptyset (&action.sa_mask);
sigaction (SIGINT, &action, NULL);
sigaction (SIGTERM, &action, NULL);
}
int handle_tag(MifareTag tag, bool *tag_valid, uint32_t newacl, uint32_t newmid)
{
const uint8_t errlimit = 3;
int err = 0;
uint8_t errcnt = 0;
bool connected = false;
MifareDESFireKey key;
char *realuid_str = NULL;
MifareDESFireAID aid;
RETRY:
if (err != 0)
{
if (realuid_str)
{
free(realuid_str);
realuid_str = NULL;
}
// TODO: Retry only on RF-errors
++errcnt;
// TODO: resolve error string
if (errcnt > errlimit)
{
printf("failed (%s), retry-limit exceeded (%d/%d), skipping tag\n", freefare_strerror(tag), errcnt, errlimit);
goto FAIL;
}
printf("failed (%s), retrying (%d)\n", freefare_strerror(tag), errcnt);
}
if (connected)
{
mifare_desfire_disconnect(tag);
connected = false;
}
printf("Connecting, ");
err = mifare_desfire_connect(tag);
if (err < 0)
{
printf("Can't connect to Mifare DESFire target.");
goto RETRY;
}
printf("done\n");
connected = true;
printf("Selecting application, ");
aid = mifare_desfire_aid_new(nfclock_aid[0] | (nfclock_aid[1] << 8) | (nfclock_aid[2] << 16));
err = mifare_desfire_select_application(tag, aid);
if (err < 0)
{
free(aid);
aid = NULL;
goto RETRY;
}
printf("done\n");
free(aid);
aid = NULL;
printf("Re-Authenticating (AMK), ");
key = mifare_desfire_aes_key_new_with_version((uint8_t*)&nfclock_amk, 0x0);
err = mifare_desfire_authenticate(tag, 0, key);
if (err < 0)
{
free(key);
key = NULL;
goto RETRY;
}
free(key);
key = NULL;
printf("done\n");
printf("Getting real UID, ");
err = mifare_desfire_get_card_uid(tag, &realuid_str);
if (err < 0)
{
goto RETRY;
}
printf("%s\n", realuid_str);
printf("Writing ACL value (0x%lx), ", (unsigned long)newacl);
err = nfclock_write_uint32(tag, nfclock_acl_file_id, newacl);
if (err < 0)
{
goto RETRY;
}
printf("done\n");
printf("Writing member-id value (0x%lx), ", (unsigned long)newmid);
err = nfclock_write_uint32(tag, nfclock_mid_file_id, newmid);
if (err < 0)
{
goto RETRY;
}
printf("done\n");
printf("\n*** Write the following down ***\n");
printf(" UID: %s\n", realuid_str);
printf(" MID: 0x%lx\n", (unsigned long)newmid);
printf("*** Write the above down ***\n\n");
// All checks done seems good
if (realuid_str)
{
free(realuid_str);
realuid_str = NULL;
}
mifare_desfire_disconnect(tag);
*tag_valid = true;
return 0;
FAIL:
if (realuid_str)
{
free(realuid_str);
realuid_str = NULL;
}
if (connected)
{
mifare_desfire_disconnect(tag);
}
*tag_valid = false;
return err;
}
pthread_mutex_t tag_processing = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t tag_done = PTHREAD_COND_INITIALIZER;
struct thread_data {
MifareTag tag;
bool tag_valid;
int err;
uint32_t newacl;
uint32_t newmid;
};
void *handle_tag_pthread(void *threadarg)
{
/* allow the thread to be killed at any time */
int oldstate;
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate);
// Cast our data struct
struct thread_data *my_data;
my_data = (struct thread_data *) threadarg;
// Start processing
my_data->err = handle_tag(my_data->tag, &my_data->tag_valid, my_data->newacl, my_data->newmid);
// Signal done and return
pthread_cond_signal(&tag_done);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
int error = EXIT_SUCCESS;
nfc_context *nfc_ctx;
nfc_init (&nfc_ctx);
if (nfc_ctx == NULL)
{
errx(EXIT_FAILURE, "Unable to init libnfc (propbably malloc)");
}
// Connect to first by default, or to the connstring specified on CLI
nfc_connstring connstring;
nfc_device *device = NULL;
if (argc == 2)
{
strncpy(connstring, argv[1], NFC_BUFSIZE_CONNSTRING);
device = nfc_open (nfc_ctx, connstring);
if (!device)
{
errx(EXIT_FAILURE, "Unable to open device %s", argv[1]);
}
}
else
{
nfc_connstring devices[8];
size_t device_count;
// This will lose a few bytes of memory for some reason, the commented out frees below do not affect the result :(
device_count = nfc_list_devices(nfc_ctx, devices, 8);
if (device_count <= 0)
{
errx (EXIT_FAILURE, "No NFC device found.");
}
for (size_t d = 0; d < device_count; ++d)
{
device = nfc_open (nfc_ctx, devices[d]);
if (!device)
{
//free(devices[d]);
printf("nfc_open() failed for %s", devices[d]);
error = EXIT_FAILURE;
continue;
}
strncpy(connstring, devices[d], NFC_BUFSIZE_CONNSTRING);
//free(devices[d]);
break;
}
if (error != EXIT_SUCCESS)
{
errx(error, "Could not open any device");
}
}
printf("Using device %s\n", connstring);
s_catch_signals();
// Mainloop
MifareTag *tags = NULL;
while(!s_interrupted)
{
tags = freefare_get_tags(device);
if ( !tags // allocation failed
// The tag array ends with null element, if first one is null then array is empty
|| !tags[0])
{
if (tags)
{
// Free the empty array so we don't leak memory
freefare_free_tags(tags);
tags = NULL;
}
// Limit polling speed to 10Hz
usleep(100 * 1000);
//printf("Polling ...\n");
continue;
}
bool valid_found = false;
int err = 0;
for (int i = 0; (!error) && tags[i]; ++i)
{
char *tag_uid_str = freefare_get_tag_uid(tags[i]);
if (DESFIRE != freefare_get_tag_type(tags[i]))
{
// Skip non DESFire tags
printf("Skipping non DESFire tag %s\n", tag_uid_str);
free (tag_uid_str);
continue;
}
printf("Found DESFire tag %s\n", tag_uid_str);
free (tag_uid_str);
// Use this struct to pass data between thread and main
struct thread_data tagdata;
tagdata.tag = tags[i];
tagdata.newacl = 0;
tagdata.newmid = 0;
// Asking for mid (ACL is redundant, we can update it at smart node anyway)
char input_buffer[20];
fputs("enter mid (in hex format eg 0xdeadbeef): ", stdout);
fflush(stdout);
if ( fgets(input_buffer, sizeof input_buffer, stdin) != NULL )
{
tagdata.newmid = strtoul(input_buffer, NULL, 0);
}
// pthreads initialization stuff
struct timespec abs_time;
pthread_t tid;
pthread_mutex_lock(&tag_processing);
/* pthread cond_timedwait expects an absolute time to wait until */
clock_gettime(CLOCK_REALTIME, &abs_time);
abs_time.tv_sec += 2;
err = pthread_create(&tid, NULL, handle_tag_pthread, (void *)&tagdata);
if (err != 0)
{
printf("ERROR: pthread_create error %d\n", err);
continue;
}
err = pthread_cond_timedwait(&tag_done, &tag_processing, &abs_time);
if (err == ETIMEDOUT)
{
printf("TIMED OUT\n");
pthread_cancel(tid);
pthread_join(tid, NULL);
pthread_mutex_unlock(&tag_processing);
continue;
}
pthread_join(tid, NULL);
pthread_mutex_unlock(&tag_processing);
if (err)
{
printf("ERROR: pthread_cond_timedwait error %d\n", err);
continue;
}
if (tagdata.err != 0)
{
tagdata.tag_valid = false;
continue;
}
if (tagdata.tag_valid)
{
valid_found = true;
}
}
freefare_free_tags(tags);
tags = NULL;
if (valid_found)
{
printf("OK: tag personalized\n");
usleep(2500 * 1000);
}
else
{
printf("ERROR: problem personalizing\n");
usleep(500 * 1000);
}
}
nfc_close (device);
nfc_exit(nfc_ctx);
exit(EXIT_SUCCESS);
}
| 2.1875 | 2 |
2024-11-18T20:50:32.014665+00:00 | 2023-08-18T22:09:03 | b9ea9430604512900525cb60b8e8cfd0224c9c98 | {
"blob_id": "b9ea9430604512900525cb60b8e8cfd0224c9c98",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-18T22:09:03",
"content_id": "b9b9f7810bfd77905d92b74dd6781677799e35f3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7de358202da651f0d58a70bde7853e33782ace21",
"extension": "c",
"filename": "get_proj.c",
"fork_events_count": 2,
"gha_created_at": "2016-05-24T21:04:17",
"gha_event_created_at": "2023-01-09T22:50:37",
"gha_language": "Fortran",
"gha_license_id": null,
"github_id": 59608537,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7594,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/g2n/get_proj.c",
"provenance": "stackv2-0110.json.gz:216163",
"repo_name": "NCAR/GENPRO",
"revision_date": "2023-08-18T22:09:03",
"revision_id": "fbac242312b355441e3722a3bb0a0698f3ad5cba",
"snapshot_id": "fe22114c949a5b7fb4ff038deaa605aeba8937a4",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/NCAR/GENPRO/fbac242312b355441e3722a3bb0a0698f3ad5cba/g2n/get_proj.c",
"visit_date": "2023-08-30T23:33:10.316010"
} | stackv2 | /* void get_proj(char *line)
* Decode the PROJECT line */
/* COPYRIGHT: University Corporation for Atmospheric Research, 1994, 2004 */
/* How to do it:
* This may be an ongoing problem, since no real standard existed for how
* to format this line. In the most-recent NCAR GENPRO projects, the
* format was fixed, so it will be easier. A lot depends upon what
* information one wants to get from this line. For University of Wyoming
* headers, only a brief project description was saved here (e.g. WP4A is
* the entire project line for a WISP flight on 8 February 1994). */
/* For NCAR GENPRO files:
* netCDF wants a 3-digit project number. I can get that information
* for all the GENPRO-II examples I have. The line either begins
* with the project number or has a preceding P or minus sign.
* I suppose it would be good to skip white space, even though none
* of my examples has any before the information starts. */
/* In every example I have, the flight number immediately follows the
* project number separated from it with a minus sign. If only digits
* are desired, then one will have to skip the characters until a digit
* appears. (The characters can be R, RF, T, TF, F, FF, etc.) Save
* the flight type. (Default flight type to "R" if none appears.)
* The flight number may be followed by a segment letter. It may be
* important to have the segment information available, but I don't
* know whether that can be put into the netCDF header. For now,
* decode it and make it available. */
/* Following the flight number/segment is the project description. It
* would seem reasonable to just grab the rest of the string of text
* (until the second double quote) even though the last part of the
* description, in all the examples I have, includes the flight's date. */
/* For University of Wyoming GENPRO files:
* The tack to take for now is to read the first 40 characters of the
* line's text and use them as a project description. Use the default
* project number, flight number and segment; assume project type is
* research. */
# include <stdio.h>
# include <string.h>
# include "g2n.h"
void get_proj(char *line)
{
char *p; /* pointer into current line */
int j; /* pointer offset */
/*
* * * * * * * * * * * * * * *
* *
* Executable code starts here *
* *
* * * * * * * * * * * * * * *
*/
/* Skip past the keyword and its delimiter */
p = strtok(line,"=");
if (p != NULL)
{
/* Skip to project delimiter, if necessary */
j = 8;
while (*(p+j) != '\0') j++;
if (*(p+j+1) != '"') p = strtok(NULL,"\"");
/* Get project information string */
p = strtok(NULL,"\"");
if (p != NULL)
{
/* By now I should know the data format */
if (G_Format == Format_NCAR)
/* NCAR format */
{
/* Decode the project number, flight type, flight number and segment */
/* First format: Pppp-tFnn projname ddmmmyyyy (ppp = project number)
* and variants Pppp-tFnns projname ddmmmyyyy (t = project type)
* Pppp-tnn projname ddmmmyyyy (nn = flight number)
* Pppp-tnns projname ddmmmyyyy (s = flight segment)
* Pppp-nn projname ddmmmyyyy (projname = project name)
* Pppp-nns projname ddmmmyyyy (dd = day of month)
* Second format: ppp-tFnn projname ddmmmyyyy (mmm = month)
* and variants ppp-tFnns projname ddmmmyyyy (yyyy = year)
* ppp-tnn projname ddmmmyyyy
* ppp-tnns projname ddmmmyyyy
* ppp-nn projname ddmmmyyyy
* ppp-nns projname ddmmmyyyy
* Third format: f-ppp-tFnn projname ddmmmyyyy (f = fiscal year)
* and variants f-ppp-tFnns projname ddmmmyyyy
*/
/* Project number */
/* If the second character is a -, skip the fiscal year symbol */
if (*(p+1) == '-')
{
/* For some reason strtok fails in its normal operation (bug?)
* so I had to fudge it to work. It may fail on other machines.
* Instead, it may be that I don't understand how strtok works. */
projno = atoi(p+2);
/* For some reason this didn't work: p=strtok(NULL,"- "); */
if ((p=strtok(p,"- ")) == NULL) return;
if ((p=strtok(NULL,"-")) == NULL) return;
if ((p=strtok(NULL,"- ")) == NULL) return;
}
else
{
/* If the first character is a "P", skip it first. */
if (*(p) == 'P')
{
projno = atoi (p+1);
}
else
{
projno = atoi(p);
}
/* Flight number (including type and segment) */
/* For some reason this doesn't work: p=strtok(NULL,"- "); */
if ((p=strtok(p,"- ")) == NULL) return;
if ((p=strtok(NULL,"- ")) == NULL) return;
}
/* Aircraft tail number */
/* if (projno > 899) ; * Aircraft unknown *
else */ if (projno > 799) strcpy(aircraft,"N308D");
else if (projno > 699) strcpy(aircraft,"N307D");
else if (projno > 599) strcpy(aircraft,"N306D");
else if (projno > 499) strcpy(aircraft,"N595KR");
else if (projno > 399) strcpy(aircraft,"N304D");
else if (projno > 299) strcpy(aircraft,"N303D");
else if (projno > 199) strcpy(aircraft,"N312D");
else if (projno > 99) strcpy(aircraft,"N130AR");
/* Flight number */
if (isdigit(*p) == NO) ftype = *p++;
if (isdigit(*p) == NO) *p++;
fltno = atoi(p);
/* Skip up to a 3-digit flight number */
if (isdigit(*p) != NO) p++;
if (isdigit(*p) != NO) p++;
if (isdigit(*p) != NO) p++;
if (*p != ' ') segment = *p;
/* Project's name and possible date */
if ((p=strtok(NULL,"\"")) == NULL) return;
TrimTrailingBlanks(p);
strcpy(project,p);
/* ########### Diagnostic print */
printf ("get_proj: Format is %s\n","Format_NCAR");
printf ("get_proj: Aircraft = %s\n",aircraft);
}
else if ((G_Format == Format_UW) || (G_Format == Format_UW_IEEE))
/* University of Wyoming format */
{
/* For now, use the first 43 characters of the project text as a project
* description and use default values for project number, flight type,
* flight number and segment. */
*(p+43) = '\0';
TrimTrailingBlanks(p);
strcpy(project,p);
strcpy(aircraft,"N2UW");
projno = 1;
fltno = 1;
/* ########### Diagnostic print */
if (G_Format == Format_UW) printf ("get_proj: Format is %s\n","Format_UW");
if (G_Format == Format_UW_IEEE) printf ("get_proj: Format is %s\n","Format_UW_IEEE");
printf ("get_proj: Aircraft = %s\n",aircraft);
}
else if (G_Format == Format_N48RF)
/* NOAA Twin Otter format */
{
/* For now, use the first 43 characters of the project text as a project
* description and use default values for project number, flight type,
* flight number and segment. */
*(p+43) = '\0';
TrimTrailingBlanks(p);
strcpy(project,p);
strcpy(aircraft,"N48RF");
projno = 1;
fltno = 1;
/* ########### Diagnostic print */
printf ("get_proj: Format is %s\n","Format_N48RF");
printf ("get_proj: Aircraft = %s\n",aircraft);
}
/* else if ((G_Format == Format_HK))
* Add other formats here */
}
}
return;
}
| 2.484375 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.