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-18T20:57:43.569771+00:00
2018-12-15T04:28:00
34627a45cfebfce439041b4b800ad50c4fd342a2
{ "blob_id": "34627a45cfebfce439041b4b800ad50c4fd342a2", "branch_name": "refs/heads/master", "committer_date": "2018-12-15T04:28:00", "content_id": "bdd0aec4b48a500e0e7c8f6bd8b41f6594a289f6", "detected_licenses": [ "Unlicense" ], "directory_id": "3a6cd514adb0c89874575323775b42dcf9129d19", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 161861397, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 794, "license": "Unlicense", "license_type": "permissive", "path": "/test.c", "provenance": "stackv2-0064.json.gz:71392", "repo_name": "dylan-evans/jzen", "revision_date": "2018-12-15T04:28:00", "revision_id": "5e0cdbfd7409748074d25ffbb29045f2ad053999", "snapshot_id": "8b814d409f89086498483d6db87518efb5b5f867", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dylan-evans/jzen/5e0cdbfd7409748074d25ffbb29045f2ad053999/test.c", "visit_date": "2020-04-11T14:36:52.616044" }
stackv2
#include <stdio.h> #include "jzen.h" #define TEST_NULL(PTR) \ if (!PTR) { \ printf("Bad pointer : %s", #PTR); \ return; \ } void test_obj(); void test_string(); int main() { test_string(); test_obj(); return 0; } void test_string() { jzenString *str = jzenString_create(); TEST_NULL(str); wprintf(L"%d: %ls\n", str->length, str->value); jzenString_appendOne(str, L'F'); jzenString_appendOne(str, L'O'); jzenString_appendOne(str, L'o'); wprintf(L"%d: %ls\n", str->length, str->value); jzenString_append(str, L" bar"); wprintf(L"%d: %ls\n", str->length, str->value); jzenString_destroy(str); } void test_obj() { jzenObject *obj = jzenObject_create(); TEST_NULL(obj); jzenObject_destroy(obj); }
2.5
2
2024-11-18T20:57:43.646072+00:00
2018-06-21T16:04:49
4b8261eed82fe8f7c2cb71cea378f226dc7b4d67
{ "blob_id": "4b8261eed82fe8f7c2cb71cea378f226dc7b4d67", "branch_name": "refs/heads/master", "committer_date": "2018-06-21T16:04:49", "content_id": "57bd19601eb74e75bef691788c7cedbf314aaf7e", "detected_licenses": [ "MIT" ], "directory_id": "29fe0899c1d96556bad1615fe9104db824475b8c", "extension": "c", "filename": "leggi.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 136532094, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 904, "license": "MIT", "license_type": "permissive", "path": "/report/attachments/lab5_180529/leggi_scrivi/leggi.c", "provenance": "stackv2-0064.json.gz:71521", "repo_name": "lparolari/sys-prog-examples", "revision_date": "2018-06-21T16:04:49", "revision_id": "c7b776da4f8ce19d25b16bc7577708c90ac113eb", "snapshot_id": "413b5f63026bb94d074e7a49c25bdc6b67e905ad", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lparolari/sys-prog-examples/c7b776da4f8ce19d25b16bc7577708c90ac113eb/report/attachments/lab5_180529/leggi_scrivi/leggi.c", "visit_date": "2020-04-02T07:24:04.255516" }
stackv2
/*! \mainpage Esempio Leggi-Scrivi \section intro Introduzione Esempio system call per scrittura e lettura su file \date 29/05/2018 \version 0.1.0 \author Luca Parolari */ /*! * \file leggi.c * \brief Esempio lettura da file * \author Luca Parolari * \date 29/05/2018 */ #define _GNU_SOURCE #define BUF_SIZE 256 #include <unistd.h> #include <limits.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> int main() { int fd, count; char data[ BUF_SIZE ]; /* crea un file in sola scrittura */ fd = open( "data.txt", O_RDONLY); if( fd == - 1 ) { printf( "%s\n", strerror( errno ) ); exit( -1 ); } /* memorizza la stringa sul file */ count = read( fd, data, BUF_SIZE ); if( count == -1 ) { printf( "%s\n", strerror( errno ) ); exit( -1 ); } printf( "%s", data ); close( fd ); exit( 0 ); }
2.9375
3
2024-11-18T20:57:44.319568+00:00
2017-04-18T10:05:22
96d9f6290fbd2e415384b23d2f4af12db1b52dfa
{ "blob_id": "96d9f6290fbd2e415384b23d2f4af12db1b52dfa", "branch_name": "refs/heads/master", "committer_date": "2017-04-18T10:05:22", "content_id": "98ffdce0bc28b129e584b481d9d83b3af3fa6b95", "detected_licenses": [ "Apache-2.0" ], "directory_id": "2d8cab0a93def5bfe5253486e90dbcd3f8904b5b", "extension": "h", "filename": "steering.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 84055087, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3574, "license": "Apache-2.0", "license_type": "permissive", "path": "/lindukas/steering.h", "provenance": "stackv2-0064.json.gz:71905", "repo_name": "Technariumas/smalsiukas", "revision_date": "2017-04-18T10:05:22", "revision_id": "57e988ad460125b91edbf1e5edec164f901eb28c", "snapshot_id": "6c17a97a6cb8af482340b7210c4db35bff0fa0d9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Technariumas/smalsiukas/57e988ad460125b91edbf1e5edec164f901eb28c/lindukas/steering.h", "visit_date": "2021-01-17T12:04:11.120281" }
stackv2
#ifndef __STEERING_H #define __STEERING_H #include "pins.h" /* 90° prie 68 75/90 * 1024 */ #define STEPS_PER_DEGREE 773 uint16_t backlash = 175; uint8_t noFeedback = 0; uint16_t nextPosition = 0; uint8_t nextPositionScheduled = 0; #define STEERING_PIN_GREY_OFFSET (118 - 128) #define STEERING_PIN_YELLOW_OFFSET (138 - 128) #define STEERING_PIN_YELLOW_MAX_VALUE (200 + STEERING_PIN_YELLOW_OFFSET) #define STEERING_PIN_GREY_MAX_VALUE (200 + STEERING_PIN_GREY_OFFSET) #define STEERING_PIN_YELLOW_MIN_VALUE (20 - STEERING_PIN_YELLOW_OFFSET) #define STEERING_PIN_GREY_MIN_VALUE (20 - STEERING_PIN_GREY_OFFSET) #define TURN_PERIOD_MS 15 typedef enum{ Direction_CW, Direction_CCW } Direction_t; Direction_t direction = Direction_CW; //STEERING_PIN_GREY STEERING_PIN_YELLOW uint8_t center[] = {128 + STEERING_PIN_GREY_OFFSET, 128 + STEERING_PIN_YELLOW_OFFSET}; uint8_t curPos = 128; uint8_t isTurning = 0; uint8_t setPos = 128; uint32_t lastTurnTs = 0; uint8_t isTimeToTurnTheWheel() { return millis() - lastTurnTs >= TURN_PERIOD_MS; } void lindeSteerTo(uint16_t targetPosition) { if(targetPosition > STEERING_PIN_GREY_MAX_VALUE) { targetPosition = STEERING_PIN_GREY_MAX_VALUE; } if(targetPosition > STEERING_PIN_YELLOW_MAX_VALUE) { targetPosition = STEERING_PIN_YELLOW_MAX_VALUE; } if(targetPosition < STEERING_PIN_GREY_MIN_VALUE) { targetPosition = STEERING_PIN_GREY_MIN_VALUE; } if(targetPosition < STEERING_PIN_YELLOW_MIN_VALUE) { targetPosition = STEERING_PIN_YELLOW_MIN_VALUE; } if(targetPosition > curPos) { Serial.println("CW"); direction = Direction_CW; setPos = targetPosition; isTurning = 1; } else if(targetPosition < curPos) { Serial.println("CCW"); direction = Direction_CCW; setPos = targetPosition; isTurning = 1; } else { isTurning = 0; } Serial.print("go to: "); Serial.println(setPos); } void steeringToCenter() { analogWrite(STEERING_PIN_GREY, center[0]); analogWrite(STEERING_PIN_YELLOW, center[1]); } void steeringInit() { steeringToCenter(); delay(1);//kad PWM dac turetu laiko nusistoveti } /** * angle - degress/10 i.e. 90 degrees = 900 */ int16_t degreesToPosition(int16_t angle) { return (int16_t)128 + (((uint32_t)angle * STEPS_PER_DEGREE) / 1024); } void steeringSetAngle(int16_t angle) { lindeSteerTo(degreesToPosition(angle)); } uint8_t steeringIsMoveDone() { return !isTurning; } void steeringRun() { if(isTurning && isTimeToTurnTheWheel()){ if(Direction_CW == direction) { if(curPos + 1 <= setPos) { curPos++; analogWrite(STEERING_PIN_GREY, curPos + STEERING_PIN_GREY_OFFSET); analogWrite(STEERING_PIN_YELLOW, curPos + STEERING_PIN_YELLOW_OFFSET); // Serial.print(curPos + STEERING_PIN_GREY_OFFSET); // Serial.print(" "); // Serial.println(curPos + STEERING_PIN_YELLOW_OFFSET); } else { isTurning = 0; } } else { if(curPos - 1 >= setPos) { curPos--; analogWrite(STEERING_PIN_GREY, curPos + STEERING_PIN_GREY_OFFSET); analogWrite(STEERING_PIN_YELLOW, curPos + STEERING_PIN_YELLOW_OFFSET); // Serial.print(curPos + STEERING_PIN_GREY_OFFSET); // Serial.print(" "); // Serial.println(curPos + STEERING_PIN_YELLOW_OFFSET); } else { isTurning = 0; } } lastTurnTs = millis(); } } void steeringRunToPosition() { while(!steeringIsMoveDone()) { steeringRun(); } } #endif
2.875
3
2024-11-18T20:57:44.920199+00:00
2021-07-19T12:55:46
5e9fa07d5a0cacf2e9df9e862092e6175d5a019a
{ "blob_id": "5e9fa07d5a0cacf2e9df9e862092e6175d5a019a", "branch_name": "refs/heads/master", "committer_date": "2021-07-19T12:55:46", "content_id": "3914c33ab9fd1096d86162dd746cad7796577ea3", "detected_licenses": [ "MIT" ], "directory_id": "8fb9cd16c1cd769c25dadb246d8a2757a891f331", "extension": "c", "filename": "BlockMapping_FTLWrite -.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 223243138, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1595, "license": "MIT", "license_type": "permissive", "path": "/C/FTL/Static_Block_mapping/BlockMapping_FTLWrite -.c", "provenance": "stackv2-0064.json.gz:72419", "repo_name": "wook0605/wook0605.github.io", "revision_date": "2021-07-19T12:55:46", "revision_id": "85de61538a011a86e350cfee2d499fe319afd492", "snapshot_id": "1f1a138dcf1d224dca90b6b419734d79a800285a", "src_encoding": "UHC", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wook0605/wook0605.github.io/85de61538a011a86e350cfee2d499fe319afd492/C/FTL/Static_Block_mapping/BlockMapping_FTLWrite -.c", "visit_date": "2021-07-30T05:24:39.609631" }
stackv2
#include "BlockMapping_head.h" void FTL_write(FILE* Flash_memory, int LSN, int PBN, char* write_data, int owb, int owo) { int LBN = LSN / NOS; int file_end = 0; int write_sum = 0; char read_data[SS]; memset(temp.temp_blcok, NULL, sizeof(temp)); //임시블록 초기화 memset(read_data, NULL, SS); //읽어온 데이터 저장하는 배열 초기화 for (int i = 0; i < NOS; i++) //오프셋 증가 { fseek(Flash_memory, ((PBN*NOS)+i)*SS, SEEK_SET); // 해당 블록의 오프셋으로 파일 포인터 옮기기 if (owb == mtable.table[LBN] && owo == i) { fgets(read_data, SS, Flash_memory); strcpy(temp.temp_blcok[i], write_data); // 덮어쓰기가 일어난 지점의 데이터만 새로 써준다. } else { fgets(read_data, SS, Flash_memory); // 해당 블록의 해당 섹터 읽어오기 strcpy(temp.temp_blcok[i], read_data); // erase는 블록단위로 일어나기 때문에 해당 블록의 유효데이터 전부 복사 } } Flash_erase(Flash_memory, LBN); //해당 블록 삭제 rewind(Flash_memory); for (int i = 0; i < NOS; i++) //다시 블록에 적어줌 { fseek(Flash_memory, ((PBN*NOS)+i)*SS, SEEK_SET); //블록의 각 오프셋에 접근 fputs(temp.temp_blcok[i], Flash_memory); if (strlen(temp.temp_blcok[i]) == SS - 1 && strspn(temp.temp_blcok[i], " ") == SS - 1) //빈 공간은 쓰기카운트가 올라가지 않음 { } else { mtable.write_count[(PBN * NOS) + i]++; write_sum++; } } printf("쓰기 완료\n"); printf("write의 횟수 : %d\n", write_sum); }
2.765625
3
2024-11-18T20:57:45.063831+00:00
2021-03-02T13:17:42
9cc1a6d72e0fae0634a4aff4bbb3e987b013041f
{ "blob_id": "9cc1a6d72e0fae0634a4aff4bbb3e987b013041f", "branch_name": "refs/heads/master", "committer_date": "2021-03-02T13:17:42", "content_id": "fb87a19342d4e6c9511e18440f4941451de75b97", "detected_licenses": [ "MIT" ], "directory_id": "bc4d08a66c5c9649daf887998b26dd0f9d370141", "extension": "c", "filename": "q_6.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 343780952, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 654, "license": "MIT", "license_type": "permissive", "path": "/string01-09-2020/q_6.c", "provenance": "stackv2-0064.json.gz:72680", "repo_name": "suehtamCruz/FUP_2020", "revision_date": "2021-03-02T13:17:42", "revision_id": "450d2cd8f5c5f0fc2715c504a699403180f3a7b1", "snapshot_id": "23d6c89558af5054bef382b3e1d29ce8fb7542f3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/suehtamCruz/FUP_2020/450d2cd8f5c5f0fc2715c504a699403180f3a7b1/string01-09-2020/q_6.c", "visit_date": "2023-03-14T14:48:43.077168" }
stackv2
#include<stdio.h> #include<string.h> int maiorTam(char str1[] ,char str2[]){ int lengths[2]; lengths[0] = strlen(str1); lengths[1] = strlen(str2); int maior; if(lengths[0] == lengths[1]){ return 0; }else{ for(int i=0;i<2;i++){ if(i==0){ maior = lengths[i]; } if(lengths[i]>maior){ maior = lengths[i]; } } } return maior; } int main(void){ char string1[100]; char string2[100]; scanf("%[^\n] ",string1); scanf("%[^\n]",string2); int maiorLength = maiorTam(string1,string2); printf("%d\n",maiorLength); return 0; }
3.40625
3
2024-11-18T20:57:47.107179+00:00
2020-07-01T00:36:57
5e563fa25df52404b069f64d12009ee2a1a93cb0
{ "blob_id": "5e563fa25df52404b069f64d12009ee2a1a93cb0", "branch_name": "refs/heads/master", "committer_date": "2020-07-01T00:36:57", "content_id": "687255ca60620fc8b495dd0b521b42dc0a2fc11e", "detected_licenses": [ "MIT" ], "directory_id": "edfdd9ed56f984e834529934563c09f89afc0e69", "extension": "c", "filename": "1010.c", "fork_events_count": 0, "gha_created_at": "2020-08-27T18:29:51", "gha_event_created_at": "2020-08-27T18:29:52", "gha_language": null, "gha_license_id": "MIT", "github_id": 290852292, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 287, "license": "MIT", "license_type": "permissive", "path": "/URI/Iniciante/1010.c", "provenance": "stackv2-0064.json.gz:73195", "repo_name": "rpgchess/hello-world.c", "revision_date": "2020-07-01T00:36:57", "revision_id": "c989366311756a2594292d43cc95d6e7d420cd1b", "snapshot_id": "95536d99aff331ea7253453fa0b354ad211735b1", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/rpgchess/hello-world.c/c989366311756a2594292d43cc95d6e7d420cd1b/URI/Iniciante/1010.c", "visit_date": "2022-11-12T02:50:00.141861" }
stackv2
#include <stdio.h> int main () { int cod1, cod2, num1, num2; float valor1, valor2, valortotal; scanf ("%d %d %f",&cod1,&num1,&valor1); scanf ("%d %d %f",&cod2,&num2,&valor2); valortotal = ((num1*valor1) + (num2*valor2)); printf("VALOR A PAGAR: R$ %.2f\n",valortotal) ; return 0 ; }
2.703125
3
2024-11-18T20:57:47.430351+00:00
2013-03-10T21:47:49
d514ad544bbf53554aeacc3d4c1df87fdd75b5a5
{ "blob_id": "d514ad544bbf53554aeacc3d4c1df87fdd75b5a5", "branch_name": "refs/heads/master", "committer_date": "2013-03-10T21:47:49", "content_id": "e6d36bb824d5f99adb94e7f30f2bbfcc472b75a1", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "2f915ac72fafb36b962813663b8a9eee559f426a", "extension": "c", "filename": "main_view.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 48502, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 22994, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/ui/main_view.c", "provenance": "stackv2-0064.json.gz:73453", "repo_name": "jtt/tcpstat", "revision_date": "2013-03-10T21:47:49", "revision_id": "3d3393fdcbb9001c0e8badf94741df8110df0d70", "snapshot_id": "3673665f13238bb3c7e990d8d230f9c26207f99e", "src_encoding": "UTF-8", "star_events_count": 28, "url": "https://raw.githubusercontent.com/jtt/tcpstat/3d3393fdcbb9001c0e8badf94741df8110df0d70/src/ui/main_view.c", "visit_date": "2021-01-19T10:09:22.097878" }
stackv2
/** * @file main_view.c * @brief Module responsible for printing the information on main view. * * Copyright (c) 2006 - 2008, J. Taimisto * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @author Jukka Taimisto */ #include <stdio.h> #include <string.h> #include <inttypes.h> #include <ctype.h> #include <stdlib.h> #include <time.h> #include <stdarg.h> #include <ncurses.h> /* #include <arpa/inet.h> inet_ntop */ #define DBG_MODULE_NAME DBG_MODULE_VIEW #include "defs.h" #include "debug.h" #include "connection.h" #include "stat.h" #include "scouts.h" #include "printout_curses.h" /* * Symbols shown on UI for some connection situations. */ /** * Dead (lingering) connection */ #define SYMBOL_DEAD '#' /** * Connection state has changed */ #define SYMBOL_NEW_STATE '*' /** * New connection. */ #define SYMBOL_NEW '+' /** * Warning about the connection requested. */ #define SYMBOL_WARN '!' /* * default symbol shown */ #define SYMBOL_DEFAULT ' ' /** * Table holding the string representations of enum tcp_state. */ static char *tcp_stat_str[] = { "-", "ESTABLISHED", "SYN_SENT", "SYN_RECV", "FIN_WAIT1", "FIN_WAIT2", "TIME_WAIT", "CLOSE", "CLOSE_WAIT", "LAST_ACK", "LISTEN", "CLOSING" }; /** * Table holding the string representations of enum connection_dir. */ static char *dir_str[] = { "---", "-->", "<--" }; /** * Convert a given enum constant to corresponding direction. * @param dir The direction. * @return string representation of the enum constant. (local static buffer is * used, hence don't call multiple times e.g in prinf()). */ static char *dir_to_string( enum connection_dir dir ) { if ( dir > DIR_INBOUND ) { dir = DIR_UNKNOWN; } return dir_str[ dir ]; } /** * String representation of enum tcp_state. * @param state The enum constant to get string for. * @return String containing the string representation of the enum constant. */ static char *conn_state_to_str( enum tcp_state state ) { if ( state > TCP_CLOSING ) { state = 0; } return tcp_stat_str[ state ]; } #ifdef OPENBSD /* time_t, it seems, is not long */ #define EXACT_TIME_FMT "%ds" #define FUZZY_FMT "%d%c" #else /* OPENBSD */ #define EXACT_TIME_FMT "%lds" #define FUZZY_FMT "%ld%c" #endif /* OPENBSD */ /** * Struct holding information about how to print * fuzzy timestamps. */ struct timefmt { time_t div; char unit; }; /** * Table containing the fuzzy timestamp info */ struct timefmt fmts[] = { {60,'s'}, {60,'m'}, {24,'h'}, {7,'d'}, {0,'w'} }; /** * Number of different fuzzy timestamps */ #define FMTS_LEN 5 /** * @brief Get the number of seconds the connection has been active * * @param data_p Pointer to the metadata structure for the connection. * @param buf Pointer to the buffer that will receive the string containing the * number of seconds the connection has been active * @param buflen Length of the buffer. * * @return Pointer to the buffer @a buf. */ static char *get_live_time( struct conn_metadata *data_p, char *buf, int buflen ) { time_t now = time( NULL ); time_t diff = now - data_p->added; int i; if (!gui_is_enabled(UI_FUZZY_TIMESTAMPS)) { snprintf(buf,buflen,EXACT_TIME_FMT,diff); return buf; } for ( i = 0; i < FMTS_LEN; i++) { if (fmts[i].div == 0 || diff < fmts[i].div) { snprintf(buf,buflen,FUZZY_FMT,diff,fmts[i].unit); break; } diff = diff / fmts[i].div; } return buf; } /** * Format string used when printing address information to "wide" terminal. */ static const char conn_format_widest[] = "%40.40s"; static const char conn_format_wide[] = "%30.30s"; /** * Format string used when printing connection information to "narrow" * terminal. */ static const char conn_format_narrow[] = "%15.15s"; static const char conn_format_narrow_rt[] = "%11.11s"; static const char port_format[] = ":%-5hu"; static const char servname_format[] = ":%-5.5s"; #ifdef ENABLE_ROUTES static const char via_narrow_format[] = " %6.6s"; static const char via_wide_format[] = " %19.19s"; static const char via_wide_format_a[] = " via %15.15s"; #endif /* ENABLE_ROUTES */ /** * @brief Get the format string which is used to print the connection address information * * @return Format string. */ static const char *format_string_for_addr() { int cols; const char *fmt; cols = gui_get_columns(); if ( cols < GUI_COLUMN_WIDE_LIMIT ) { if (gui_is_enabled(UI_SHOW_ROUTE)) fmt = conn_format_narrow_rt; else fmt = conn_format_narrow; } else if ( cols < GUI_COLUMN_WIDEST_LIMIT ) { fmt = conn_format_wide; } else if ( cols >= GUI_COLUMN_WIDEST_LIMIT ) { fmt = conn_format_widest; } return fmt; } /** * @brief Print addresses of the connection on human readable form. * * The source and destination addresses of the connection are printed on either * "dotted decimal" (IPv4) or IPv6 form. If hostname resolution is requested in * the gui context, resolve names for numerical hosts (if not done yearlier) * and print the resolved names. * * The connection metadata caries most of the strings, the strings are printed * directly to the screen. * * @bug Formating for different size screens sucks. Port number/servname is not fixed width. * * @param conn_p Pointer to the connection whose addresses to print. * strings. */ static void print_connection_addrs( struct tcp_connection *conn_p ) { const char *fmt; if ( gui_is_enabled(UI_RESOLVE_NAMES) && ( ! ( conn_p->metadata.flags & METADATA_RESOLVED)) ) { connection_resolve( conn_p ); } fmt = format_string_for_addr(); /* Local address, is not resolved */ add_to_linebuf( fmt, conn_p->metadata.laddr_string ); add_to_linebuf( port_format, connection_get_port( conn_p, 1 )); if ( conn_p->state == TCP_LISTEN ) { /* Listening connection, there is no remote end. Just * fill to keep aligned with proper connections */ /* direction */ add_to_linebuf( " %.3s ", " " ); /* remote address */ add_to_linebuf( fmt, " " ); /* port */ add_to_linebuf( " %5s", " " ); return; } add_to_linebuf( " %.3s ", dir_to_string( conn_p->metadata.dir )); if ( gui_is_enabled(UI_RESOLVE_NAMES) && conn_p->metadata.rem_hostname[0] != '\0' ) { add_to_linebuf( fmt, conn_p->metadata.rem_hostname ); } else { add_to_linebuf( fmt, conn_p->metadata.raddr_string ); } if ( gui_is_enabled(UI_RESOLVE_NAMES) && conn_p->metadata.rem_servname[0] != '\0' ) { add_to_linebuf( servname_format, conn_p->metadata.rem_servname ); } else { add_to_linebuf( port_format, connection_get_port( conn_p, 0 )); } } /** * @brief Print the routing information of connection to the screen * * @param conn_p pointer to connection whose routing information should be * printed. */ #ifdef ENABLE_ROUTES static void print_rt_info( struct tcp_connection *conn_p ) { if ( conn_p->metadata.route == NULL ) { if ( gui_get_columns() < GUI_COLUMN_RT_WIDE_LIMIT ) add_to_linebuf( via_narrow_format, "-" ); else add_to_linebuf( via_wide_format, "-" ); return; } if ( gui_get_columns() < GUI_COLUMN_RT_WIDE_LIMIT ) { if ( rtinfo_is_on_local_net( conn_p->metadata.route ) ) add_to_linebuf( via_narrow_format, "on net" ); else add_to_linebuf( via_narrow_format, "via gw" ); } else { if ( rtinfo_is_on_local_net( conn_p->metadata.route ) ) add_to_linebuf( via_wide_format, "on local net" ); else add_to_linebuf( via_wide_format_a, conn_p->metadata.route->addr_str ); } } #endif /* ENABLE_ROUTES */ /** * Print a line containing the connection information. * @ingroup gui_c * @bug Layout of the line is messed up the address fields should change * dynamically according to the available row length. * @param conn_p Pointer to the connection which information should be printed. */ static void gui_print_connection( struct tcp_connection *conn_p ) { char update_symbol, live_time[10]; if ( conn_p->state == TCP_DEAD ) { /* lingering, already dead connection */ update_symbol = SYMBOL_DEAD; attron( A_DIM ); } else if ( metadata_is_state_changed( conn_p->metadata ) ){ update_symbol = SYMBOL_NEW_STATE; //attron( A_UNDERLINE ); } else if ( metadata_is_new( conn_p->metadata ) ) { update_symbol = SYMBOL_NEW; attron( A_STANDOUT ); } else if ( metadata_is_warn( conn_p->metadata)) { update_symbol = SYMBOL_WARN; } else { update_symbol = SYMBOL_DEFAULT; } add_to_linebuf( "%c %4s ",update_symbol, conn_p->metadata.ifname?conn_p->metadata.ifname:"N/A"); print_connection_addrs( conn_p ); #ifdef ENABLE_ROUTES if (gui_is_enabled(UI_SHOW_ROUTE)) print_rt_info( conn_p ); #endif /* ENABLE_ROUTES */ write_linebuf_partial(); add_to_linebuf( " %-12s", conn_state_to_str( conn_p->state )); if ( metadata_is_state_changed( conn_p->metadata ) ) write_linebuf_partial_attr(A_BOLD); add_to_linebuf( " %-9s", get_live_time( &(conn_p->metadata),live_time,10 ) ); write_linebuf(); attrset(A_NORMAL); } /** * Print the titlebar containing the column information for the printed connections */ static void print_titlebar() { const char *fmt = format_string_for_addr(); add_to_linebuf( " %4s ","Inf"); add_to_linebuf( fmt,"Local address"); add_to_linebuf( " %5s", "Port" ); add_to_linebuf( " %3s ", "Dir" ); add_to_linebuf( fmt, "Remote address"); add_to_linebuf( " %5s", "Port" ); #ifdef ENABLE_ROUTES if (gui_is_enabled(UI_SHOW_ROUTE)){ /* XXX : we really should not use numbers here */ if ( gui_get_columns() < GUI_COLUMN_RT_WIDE_LIMIT ) add_to_linebuf( via_narrow_format, "Route"); else add_to_linebuf( via_wide_format, "Route"); } #endif /* ENABLE_ROUTES */ add_to_linebuf( " %-12s", "State" ); add_to_linebuf( " %-9s", "Time" ); write_linebuf_partial_attr( A_REVERSE ); write_linebuf(); } /** * @brief Print information for a connection group. * A line containing information for each connection on the group is printed. * * @bug The printing of banner is really, really limited. And broken. * * @ingroup gui_c * * @param grp Pointer to the group that the info should be printed. * @param print_parent non-zero if information should be printed about the parent. * @param print_banner non-zero if a "banner" for the group should be printed. */ static void gui_print_group( struct group *grp, int print_parent, int print_banner ) { struct tcp_connection *conn_p; uint16_t policy = group_get_policy( grp ); if ( print_banner && (print_parent || group_get_size( grp ) > 0) ) { attron( A_UNDERLINE ); if ( policy & POLICY_IF ) { add_to_linebuf( "Connections in interface %s\n", grp->grp_filter->ifname ); } else if ( policy & POLICY_CLOUD ) { add_to_linebuf("Related ( %d connections)", group_get_size( grp )); } else if ( (policy & (POLICY_REMOTE | POLICY_LOCAL ) ) != 0 ) { conn_p = group_get_first_conn( grp ); if ( conn_p == NULL ) { /* Can happen. Especially with incoming * groups, try to use parent instead. */ conn_p = group_get_parent( grp ); } /* I know that conn_p be can be NULL here. I * just don't care, since it would mean that we * have group without connections and without * parent, we should not be printing that and * we deserve to die with segmentation fault on * that. */ add_to_linebuf( "Connections to " ); if ( policy & POLICY_ADDR ) { if ( policy & POLICY_LOCAL ) { add_to_linebuf( "%s ", conn_p->metadata.laddr_string ); } else { add_to_linebuf( "%s ", conn_p->metadata.raddr_string ); } } if ( policy & POLICY_PORT ) add_to_linebuf( " port %d ", connection_get_port( conn_p, policy & POLICY_LOCAL )); add_to_linebuf( " (%d connections)", group_get_size( grp) ); } else if ( policy & POLICY_STATE ) { add_to_linebuf( "Connections on state %s\n", conn_state_to_str( grp->grp_filter->state )); add_to_linebuf( " (%d connections)", group_get_size( grp) ); } else { add_to_linebuf( "+ Group: %d connections", group_get_size( grp )); } write_linebuf(); attroff( A_UNDERLINE); } conn_p = group_get_parent( grp ); if ( conn_p && print_parent ) gui_print_connection( conn_p ); conn_p = group_get_first_conn( grp ); while ( conn_p != NULL ) { gui_print_connection( conn_p ); conn_p = conn_p->next; } return; } /** * @defgroup mview Main view functions */ /** * @brief Handle user input when main view is active. * * This function is called when a user command is received and the command is * not any of the generic commands and main view is active. * * @ingroup mview * * @param ctx Pointer to the main context. * @param key The kay pressed. * * @return 1 if the key was main view command, 0 if not. */ int main_input( struct stat_context *ctx, int key ) { int rv = 1; switch( key ) { case 'l' : TRACE( "Toggling display of listen & In groups \n" ); OPERATION_TOGGLE(ctx, OP_SHOW_LISTEN); break; case 'L' : TRACE( "Setting lingering on" ); OPERATION_TOGGLE( ctx, OP_LINGER); break; case 'A' : TRACE( "Switching grouping to remote address" ); switch_grouping( ctx, POLICY_REMOTE | POLICY_ADDR ); break; case 'a' : TRACE( "Swithing the groupint to remote address and port" ); switch_grouping( ctx, POLICY_REMOTE | POLICY_ADDR | POLICY_PORT ); break; case 'P' : TRACE( "Switching grouping to remote port " ); switch_grouping( ctx, POLICY_REMOTE | POLICY_PORT ); break; case 'c' : TRACE("Swithcing to cloud (port) mode" ); switch_grouping( ctx, POLICY_CLOUD | POLICY_REMOTE | POLICY_PORT ); break; case 'S' : TRACE( "Switching grouping to state " ); switch_grouping( ctx, POLICY_STATE ); break; case 'T' : TRACE("Toggling fuzzy timestamps"); gui_toggle_operation(UI_FUZZY_TIMESTAMPS); break; #ifdef ENABLE_ROUTES case 'R' : TRACE("Toggling routing"); gui_toggle_operation(UI_SHOW_ROUTE); break; #endif /* ENABLE_ROUTES */ default : WARN( "Unkown key pressed %c (%d), ignoring\n",(char)key,key ); rv = 0; break; } return rv; } void main_print_help() { attron( A_UNDERLINE ); add_to_linebuf("\tMain view commands:"); write_linebuf(); attroff( A_UNDERLINE ); add_to_linebuf(" l "); write_linebuf_partial_attr( A_BOLD); add_to_linebuf(" Toggle display of listening \"connections\""); write_linebuf(); add_to_linebuf(" L "); write_linebuf_partial_attr( A_BOLD); add_to_linebuf(" Toggle lingering of closed connections"); write_linebuf(); add_to_linebuf(" T "); write_linebuf_partial_attr(A_BOLD); add_to_linebuf(" Toggle connection time format (fuzzy/exact)"); write_linebuf(); #ifdef ENABLE_ROUTES add_to_linebuf(" R "); write_linebuf_partial_attr( A_BOLD); add_to_linebuf(" Toggle displaying of routing information"); write_linebuf(); #endif /* ENABLE_ROUTES */ write_linebuf(); add_to_linebuf(" Commands for switching grouping of outgoing connections"); write_linebuf(); add_to_linebuf(" a"); write_linebuf_partial_attr( A_BOLD); add_to_linebuf(" group by remote address and port "); write_linebuf_partial(); add_to_linebuf("A"); write_linebuf_partial_attr( A_BOLD); add_to_linebuf(" group by remote address"); write_linebuf(); add_to_linebuf(" P"); write_linebuf_partial_attr( A_BOLD); add_to_linebuf(" group by remote port "); write_linebuf_partial(); add_to_linebuf("S"); write_linebuf_partial_attr( A_BOLD); add_to_linebuf(" group by connection state"); write_linebuf(); } /** * @brief Initialize the main view. * * This function should be called every time the main view is to be activated. * After this function has been called, the main_update() function can be * called to update the UI. * * @ingroup mview * * @param ctx Pointer to the global context. * * @return -1 on error, 0 on success. */ int init_main_view( _UNUSED struct stat_context *ctx ) { gui_set_current_view( MAIN_VIEW ); return 0; } /** * @brief Print information on follow pid -mode. * * For every PID we are following, all connections are printed. * @see do_print_stat() * * @param ctx Pointer to main context. */ #ifdef ENABLE_FOLLOW_PID static void do_print_stat_pids( struct stat_context *ctx ) { struct pidinfo *info_p; info_p = ctx->pinfo; while ( info_p != NULL ) { if ( group_get_size( info_p->grp ) > 0 ) { gui_print_pid_banner( info_p ); print_titlebar(); gui_print_group( info_p->grp, 0,0 ); } info_p = info_p->next; } } #endif /* ENABLE_FOLLOW_PID */ /** * @brief Print the information for all connections. * Call relevant gui functions for printing the information, this function does * not call gui_draw() to actually update the displayed GUI. * * @param ctx Pointer to main context. */ static void do_print_stat( struct stat_context *ctx ) { struct group *grp; if ( OPERATION_ENABLED( ctx, OP_SHOW_LISTEN) || glist_get_size_nonempty( ctx->listen_groups ) > 0 ) { gui_print_in_banner( ctx ); glist_foreach_group( ctx->listen_groups, grp ) { gui_print_group( grp, OPERATION_ENABLED(ctx, OP_SHOW_LISTEN),1 ); } } gui_print_out_banner( ctx ); print_titlebar(); glist_foreach_group( ctx->out_groups, grp ) { gui_print_group( grp,1,1 ); } } /** * @brief Update the UI with according to main view. * * This function updates the UI with latest information gathered by the scouts. * * @ingroup mview * * @param ctx Pointer to the global context. * * @return -1 on error, 0 on success. */ int main_update( struct stat_context *ctx ) { #ifdef ENABLE_FOLLOW_PID if ( OPERATION_ENABLED(ctx, OP_FOLLOW_PID) ) do_print_stat_pids( ctx ); else #endif /* ENABLE_FOLLOW_PID */ do_print_stat( ctx ); return 0; }
2.171875
2
2024-11-18T20:57:47.542669+00:00
2023-03-14T22:48:04
11be4f0a2941cd9ca3c9bdfd14443f52152fec07
{ "blob_id": "11be4f0a2941cd9ca3c9bdfd14443f52152fec07", "branch_name": "refs/heads/master", "committer_date": "2023-03-14T22:48:04", "content_id": "5d63e41e295b1b675d01fee7eb4805fe20385cc5", "detected_licenses": [ "MIT" ], "directory_id": "c86c2e7b71662bb1bbbdb1f20e4bd60ed9ba1398", "extension": "c", "filename": "pushtodev.c", "fork_events_count": 174, "gha_created_at": "2016-01-30T21:56:32", "gha_event_created_at": "2023-03-01T19:19:41", "gha_language": "C", "gha_license_id": "MIT", "github_id": 50746813, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5138, "license": "MIT", "license_type": "permissive", "path": "/web/pushtodev.c", "provenance": "stackv2-0064.json.gz:73582", "repo_name": "cnlohr/channel3", "revision_date": "2023-03-14T22:48:04", "revision_id": "cb678eaa6ff192fad00242b5adb035a7b17b7348", "snapshot_id": "84c146ead98a89c5e15add1dc81d7aeb48ddd516", "src_encoding": "UTF-8", "star_events_count": 1356, "url": "https://raw.githubusercontent.com/cnlohr/channel3/cb678eaa6ff192fad00242b5adb035a7b17b7348/web/pushtodev.c", "visit_date": "2023-04-07T15:51:52.335402" }
stackv2
//Unless what else is individually marked, all code in this file is //Copyright 2015 <>< Charles Lohr Under the MIT/x11 License, NewBSD License or // ColorChord License. You Choose. #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <sys/time.h> #include <sys/poll.h> #include <sys/types.h> #include <stdlib.h> #include <string.h> #define sector_SIZE 4096 int sockfd; char recvline[10000]; int PushMatch( const char * match ) { struct timeval tva, tvb; gettimeofday( &tva, 0 ); gettimeofday( &tvb, 0 ); int difftime = (tvb.tv_sec-tva.tv_sec)*1000000 + tvb.tv_usec - tva.tv_usec; while( difftime < 500000 ) //3 second timeout. { struct pollfd ufds; ufds.fd = sockfd; ufds.events = POLLIN; int rv = poll(&ufds, 1, 50); if( rv > 0 ) { // tbuf = recvline; int n=recvfrom(sockfd,recvline,10000,0,NULL,NULL); // printf( "!!%d ->%s\n", n,recvline ); // printf( "%s === %s\n", recvline, match ); if( strncmp( recvline, match, strlen( match ) ) == 0 ) { // printf( "Ok\n" ); fflush( stdout ); return 0; } } gettimeofday( &tvb, 0 ); difftime = (tvb.tv_sec-tva.tv_sec)*1000000 + tvb.tv_usec - tva.tv_usec; } return 1; } int main(int argc, char**argv) { int n; struct sockaddr_in servaddr,cliaddr; char sendline[1000]; // char recvline[1000]; if (argc != 4) { printf("usage: pushtodev [IP address] [address offset] [file]\n"); exit(-1); } int offset = atoi( argv[2] ); const char * file = argv[3]; if( offset <= 0 ) { fprintf( stderr, "Error: Cannot write to address 0 or before.\n" ); exit(-2); } FILE * f = fopen( file, "rb" ); if( !f || feof( f ) ) { fprintf( stderr, "Error: cannot open file.\n" ); exit(-3); } sockfd=socket(AF_INET,SOCK_DGRAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr=inet_addr(argv[1]); servaddr.sin_port=htons(7878); int devo = 0; int lastsector_block = -1; int resend_times = 0; int r; while( !feof( f ) ) { int tries; int thissuccess; char buffer[1024]; char bufferout[1600]; int reads = fread( buffer, 1, 1024, f ); int sendplace = offset + devo; int sendsize = reads; #ifdef SECTOR int sector = sendplace / sector_SIZE; if( sector != lastsector_block ) { char se[64]; int sel = sprintf( se, "FE%d\r\n", sector ); thissuccess = 0; for( tries = 0; tries < 10; tries++ ) { char match[75]; printf( "Erase: %d\n", sector ); sendto( sockfd, se, sel, MSG_NOSIGNAL, (struct sockaddr *)&servaddr,sizeof(servaddr)); sprintf( match, "FE%d", sector ); if( PushMatch(match) == 0 ) { thissuccess = 1; break; } printf( "Retry.\n" ); } if( !thissuccess ) { fprintf( stderr, "Error: Timeout in communications.\n" ); exit( -6 ); } lastsector_block = sector; } #else //block int block = sendplace / 65536; if( block != lastsector_block ) { char se[64]; int sel = sprintf( se, "FB%d\r\n", block ); thissuccess = 0; for( tries = 0; tries < 10; tries++ ) { char match[75]; printf( "Erase: %d\n", block ); sendto( sockfd, se, sel, MSG_NOSIGNAL, (struct sockaddr *)&servaddr,sizeof(servaddr)); sprintf( match, "FB%d", block ); if( PushMatch(match) == 0 ) { thissuccess = 1; break; } printf( "Retry.\n" ); } if( !thissuccess ) { fprintf( stderr, "Error: Timeout in communications.\n" ); exit( -6 ); } lastsector_block = block; } #endif resend_times = 0; resend: r = sprintf( bufferout, "FW%d\t%d\t", sendplace, sendsize ); printf( "bufferout: %d %d %s\n", sendplace, sendsize, bufferout ); memcpy( bufferout + r, buffer, sendsize ); thissuccess = 0; for( tries = 0; tries < 10; tries++ ) { char match[75]; sendto( sockfd, bufferout, reads + r, MSG_NOSIGNAL, (struct sockaddr *)&servaddr,sizeof(servaddr)); sprintf( match, "FW%d", sendplace ); if( PushMatch(match) == 0 ) { thissuccess = 1; break; } printf( "Retry.\n" ); } if( !thissuccess ) { fprintf( stderr, "Error: Timeout in communications.\n" ); exit( -6 ); } /* printf( "Verifying..." ); fflush( stdout ); int r = sprintf( bufferout, "FR%d:%d", sendplace, sendsize ); bufferout[r] = 0; thissuccess = 0; for( tries = 0; tries < 10; tries++ ) { char match[1600]; sendto( sockfd, bufferout, r, MSG_NOSIGNAL, (struct sockaddr *)&servaddr,sizeof(servaddr)); devo += reads; sprintf( match, "FR%08d", sendplace ); if( PushMatch(match) == 0 ) { //Check data... //printf( "RR:%s\n", recvline ); char * colon1 = strchr( recvline, ':' ); char * colon2 = (colon1)?strchr( colon1+1, ':' ):0; //printf( "::%p %p \"%s\"\n", colon1, colon2,recvline ); if( colon2 ) { if( memcmp( colon2+1, buffer, sendsize ) == 0 ) thissuccess = 1; } if( !thissuccess ) { if( resend_times > 2 ) { break; } resend_times++; goto resend; } break; } printf( "Retry.\n" ); } if( !thissuccess ) { fprintf( stderr, "Error: Fault verifying.\n" ); exit( -6 ); } */ devo += reads; } return 0; }
2.296875
2
2024-11-18T20:57:48.530018+00:00
2018-09-15T00:37:56
78d0597980db50e9aea1c70fc0e92208c768f081
{ "blob_id": "78d0597980db50e9aea1c70fc0e92208c768f081", "branch_name": "refs/heads/master", "committer_date": "2018-09-15T00:37:56", "content_id": "b5b02f671152d1bbff4ac85b250e6f5d26685c07", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cf28b477b007fde6e1d5e058113c1fe3f555b66e", "extension": "h", "filename": "config.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 146948289, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2018, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/config.h", "provenance": "stackv2-0064.json.gz:73968", "repo_name": "schmidtw/parodus2fs", "revision_date": "2018-09-15T00:37:56", "revision_id": "d39961344fc694883c1c4f5efc0b724517b632d6", "snapshot_id": "d8a1bbf77d98b0f5679b471353bfbfbb9900a0d1", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/schmidtw/parodus2fs/d39961344fc694883c1c4f5efc0b724517b632d6/src/config.h", "visit_date": "2020-03-27T18:50:57.658692" }
stackv2
/** * Copyright 2018 Weston Schmidt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __P2FS_CONFIG_H__ #define __P2FS_CONFIG_H__ #include <stdbool.h> #include <stdlib.h> /*----------------------------------------------------------------------------*/ /* Macros */ /*----------------------------------------------------------------------------*/ /* none */ /*----------------------------------------------------------------------------*/ /* Data Structures */ /*----------------------------------------------------------------------------*/ typedef struct { bool read_notify; long int max_transfer; int receive_timeout; } cfg_t; /*----------------------------------------------------------------------------*/ /* Function Prototypes */ /*----------------------------------------------------------------------------*/ /** * Reads the specified config file & builds the configuration to use. * * @note The configuration MUST be destroyed with config_free() or leaks * may happen. * * @param file the file to read/parse for configuration * * @return The configuration on success, NULL otherwise. */ cfg_t* config_get( const char *file ); /** * Frees the resources associated with cfg_t*. * * @param c the cfg_t to free */ void config_free( cfg_t *c ); #endif
2.09375
2
2024-11-18T20:57:48.906517+00:00
2016-07-05T16:13:37
808e8d957f5a342ff569295b08bd7cc1e0a339d2
{ "blob_id": "808e8d957f5a342ff569295b08bd7cc1e0a339d2", "branch_name": "refs/heads/master", "committer_date": "2016-07-05T16:13:37", "content_id": "b3a493f3d1ceae72162ec829721ef4fa56ac4aff", "detected_licenses": [ "MIT", "BSD-2-Clause" ], "directory_id": "c611a7cd3108e5d2dd78dbf5186113fd7471aa7f", "extension": "c", "filename": "_npymath_exports.c", "fork_events_count": 0, "gha_created_at": "2016-07-05T19:00:16", "gha_event_created_at": "2016-07-05T19:00:16", "gha_language": null, "gha_license_id": null, "github_id": 62661963, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2018, "license": "MIT,BSD-2-Clause", "license_type": "permissive", "path": "/numba/_npymath_exports.c", "provenance": "stackv2-0064.json.gz:74355", "repo_name": "jzwinck/numba", "revision_date": "2016-07-05T16:13:37", "revision_id": "fb92b43f2a2b8dd05c3f2ac4d646d36a82daa641", "snapshot_id": "110fb39b5d33b905465834ef7d83d4942ebd387f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jzwinck/numba/fb92b43f2a2b8dd05c3f2ac4d646d36a82daa641/numba/_npymath_exports.c", "visit_date": "2021-01-15T22:14:08.225672" }
stackv2
/* * This file contains exports of Numpy math functions needed by numba. */ #include "_pymodule.h" #include <numpy/npy_math.h> #include <math.h> /* * Map Numpy C function symbols to their addresses. */ struct npymath_entry { const char *name; void *func; }; #define NPYMATH_SYMBOL(name) \ { "npy_" #name, (void*) npy_##name } static struct npymath_entry npymath_exports[] = { /* double functions */ NPYMATH_SYMBOL(sin), NPYMATH_SYMBOL(cos), NPYMATH_SYMBOL(tan), NPYMATH_SYMBOL(asin), NPYMATH_SYMBOL(acos), NPYMATH_SYMBOL(atan), NPYMATH_SYMBOL(sinh), NPYMATH_SYMBOL(cosh), NPYMATH_SYMBOL(tanh), NPYMATH_SYMBOL(asinh), NPYMATH_SYMBOL(acosh), NPYMATH_SYMBOL(atanh), NPYMATH_SYMBOL(hypot), NPYMATH_SYMBOL(exp), NPYMATH_SYMBOL(exp2), NPYMATH_SYMBOL(expm1), NPYMATH_SYMBOL(log), NPYMATH_SYMBOL(log2), NPYMATH_SYMBOL(log10), NPYMATH_SYMBOL(log1p), NPYMATH_SYMBOL(pow), NPYMATH_SYMBOL(sqrt), NPYMATH_SYMBOL(atan2), NPYMATH_SYMBOL(logaddexp), NPYMATH_SYMBOL(logaddexp2), NPYMATH_SYMBOL(nextafter), NPYMATH_SYMBOL(spacing), NPYMATH_SYMBOL(modf), /* float functions */ NPYMATH_SYMBOL(sinf), NPYMATH_SYMBOL(cosf), NPYMATH_SYMBOL(tanf), NPYMATH_SYMBOL(asinf), NPYMATH_SYMBOL(acosf), NPYMATH_SYMBOL(atanf), NPYMATH_SYMBOL(sinhf), NPYMATH_SYMBOL(coshf), NPYMATH_SYMBOL(tanhf), NPYMATH_SYMBOL(asinhf), NPYMATH_SYMBOL(acoshf), NPYMATH_SYMBOL(atanhf), NPYMATH_SYMBOL(hypotf), NPYMATH_SYMBOL(expf), NPYMATH_SYMBOL(exp2f), NPYMATH_SYMBOL(expm1f), NPYMATH_SYMBOL(logf), NPYMATH_SYMBOL(log2f), NPYMATH_SYMBOL(log10f), NPYMATH_SYMBOL(log1pf), NPYMATH_SYMBOL(powf), NPYMATH_SYMBOL(sqrtf), NPYMATH_SYMBOL(atan2f), NPYMATH_SYMBOL(logaddexpf), NPYMATH_SYMBOL(logaddexp2f), NPYMATH_SYMBOL(nextafterf), NPYMATH_SYMBOL(spacingf), NPYMATH_SYMBOL(modff), }; #undef NPYMATH_SYMBOL
2.34375
2
2024-11-18T20:57:49.487883+00:00
2016-02-11T17:26:09
a2cb334c1fb7cc0fd2099d9c1d216c43b615bdca
{ "blob_id": "a2cb334c1fb7cc0fd2099d9c1d216c43b615bdca", "branch_name": "refs/heads/master", "committer_date": "2016-02-11T17:26:09", "content_id": "f1cc9c89efb2298929232ea93d1cb448cd04ed00", "detected_licenses": [ "MIT" ], "directory_id": "34edab51b4e6966c1b6666152926d505dfbd11a5", "extension": "c", "filename": "y4m.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 51531688, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5110, "license": "MIT", "license_type": "permissive", "path": "/src/demuxer/yuv4mpeg/y4m.c", "provenance": "stackv2-0064.json.gz:74484", "repo_name": "xaradevil/tcvp", "revision_date": "2016-02-11T17:26:09", "revision_id": "9d17022cb6470d546e11c65aafa41b940c888d5f", "snapshot_id": "8e5ce807f077fa4c0add31126de68ce7640e40d8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/xaradevil/tcvp/9d17022cb6470d546e11c65aafa41b940c888d5f/src/demuxer/yuv4mpeg/y4m.c", "visit_date": "2021-01-10T01:52:50.414533" }
stackv2
/** Copyright (C) 2003-2004 Michael Ahlberg, Måns Rullgård 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 <tcalloc.h> #include <tcmath.h> #include <yuv4mpeg_tc2.h> typedef struct yuv4mpeg { url_t *url; uint64_t pts, ptsd; int framesize; int offsets[3]; stream_t s; int used; } yuv4mpeg_t; typedef struct yuv4mpeg_packet { tcvp_data_packet_t pk; u_char *data[3]; int size[3]; } yuv4mpeg_packet_t; static int read_int(char *p) { int v; v = strtol(p, &p, 10); if(*p != ' ') v = -1; return v; } static int read_frac(char *p, tcfraction_t *f) { int n, d;; n = strtol(p, &p, 10); if(*p != ':') return -1; p++; d = strtol(p, &p, 10); if(*p != ' ' && *p != '\n') return -1; f->num = n; f->den = d; return 0; } static void y4m_free_pk(void *p) { yuv4mpeg_packet_t *yp = p; free(yp->data[0]); } extern tcvp_packet_t * y4m_packet(muxed_stream_t *ms, int s) { yuv4mpeg_t *y4m = ms->private; yuv4mpeg_packet_t *yp; char buf[256]; char *tag = buf; uint64_t pts = y4m->pts; if(!url_gets(buf, sizeof(buf), y4m->url)) return NULL; if(strncmp(buf, "FRAME", 5)) return NULL; while((tag = strchr(tag, ' '))){ if(!strncmp(++tag, "Xpts=", 5)){ pts = strtoull(tag + 5, &tag, 10); } } yp = tcallocdz(sizeof(*yp), NULL, y4m_free_pk); yp->data[0] = malloc(y4m->framesize); yp->data[1] = yp->data[0] + y4m->offsets[1]; yp->data[2] = yp->data[0] + y4m->offsets[2]; yp->size[0] = y4m->s.video.width; yp->size[1] = y4m->s.video.width / 2; yp->size[2] = yp->size[1]; y4m->url->read(yp->data[0], 1, y4m->framesize, y4m->url); yp->pk.data = yp->data; yp->pk.sizes = yp->size; yp->pk.flags = TCVP_PKT_FLAG_PTS | TCVP_PKT_FLAG_KEY; yp->pk.pts = pts; y4m->pts = pts + y4m->ptsd; return (tcvp_packet_t *) yp; } static void y4m_free(void *p) { muxed_stream_t *ms = p; yuv4mpeg_t *y4m = ms->private; tcfree(y4m->url); } extern muxed_stream_t * y4m_open(char *name, url_t *u, tcconf_section_t *conf, tcvp_timer_t *tm) { muxed_stream_t *ms; yuv4mpeg_t *y4m; int width = 0, height = 0; tcfraction_t rate = {0, 0}, aspect = {0, 0}; char buf[256]; char *p = buf; if(!url_gets(buf, sizeof(buf), u)) return NULL; if(strncmp(buf, "YUV4MPEG2 ", 10)){ tc2_print("YUV4MPEG", TC2_PRINT_ERROR, "bad signature\n"); return NULL; } while((p = strchr(p, ' '))){ switch(*++p){ case 'W': if((width = read_int(++p)) < 0) return NULL; break; case 'H': if((height = read_int(++p)) < 0) return NULL; break; case 'F': if(read_frac(++p, &rate)) return NULL; break; case 'A': if(read_frac(++p, &aspect)) return NULL; break; case 'I': break; case 'X': break; default: return NULL; } } y4m = calloc(1, sizeof(*y4m)); y4m->url = tcref(u); y4m->framesize = width * height * 3 / 2; y4m->offsets[1] = width * height; y4m->offsets[2] = y4m->offsets[1] + width * height / 4; y4m->s.stream_type = STREAM_TYPE_VIDEO; y4m->s.video.codec = "video/raw-i420"; y4m->s.video.bit_rate = y4m->framesize * 8 * rate.num / rate.den; y4m->s.video.frame_rate = rate; y4m->s.video.width = width; y4m->s.video.height = height; y4m->s.video.aspect.num = width * aspect.num; y4m->s.video.aspect.den = height * aspect.den; tcreduce(&y4m->s.video.aspect); y4m->ptsd = 27000000LL * rate.den / rate.num; ms = tcallocdz(sizeof(*ms), NULL, y4m_free); ms->n_streams = 1; ms->streams = &y4m->s; ms->used_streams = &y4m->used; ms->next_packet = y4m_packet; ms->private = y4m; return ms; }
2.140625
2
2024-11-18T20:57:50.348395+00:00
2015-01-11T22:12:55
44114318ddfa415851432b04e9318da708eca2bb
{ "blob_id": "44114318ddfa415851432b04e9318da708eca2bb", "branch_name": "refs/heads/master", "committer_date": "2015-01-11T22:12:55", "content_id": "7940282d384aae8e0377cfece7a55848145cb1fa", "detected_licenses": [ "MIT" ], "directory_id": "d42c67ea3cc11e10b2733de573ec899bf7c7e76a", "extension": "h", "filename": "stdarg.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 8643244, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 817, "license": "MIT", "license_type": "permissive", "path": "/kernel/stdarg.h", "provenance": "stackv2-0064.json.gz:74612", "repo_name": "jo-va/toutatis", "revision_date": "2015-01-11T22:12:55", "revision_id": "e42e84c8aef9d368a6836ee6d6e07ccd025ad437", "snapshot_id": "ae717335005cd7a2bf7621d94eabdeaac9b40572", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/jo-va/toutatis/e42e84c8aef9d368a6836ee6d6e07ccd025ad437/kernel/stdarg.h", "visit_date": "2016-09-05T12:31:08.858946" }
stackv2
#ifndef __KERNEL_VARGS_H__ #define __KERNEL_VARGS_H__ /* width of stack = 4 bytes */ #define STACKITEM int /* data type used for arguments */ #define va_list char * /* Amount of space required on the stack for an arg of type TYPE. TYPE may alternatively be an expression whose type is used. */ #define __va_rounded_size(TYPE) \ ((sizeof(TYPE) + sizeof(STACKITEM) - 1) & ~(sizeof(STACKITEM) - 1)) /* initialize AP so that it points to the first argument (right after LASTARG) */ #define va_start(AP, LASTARG) \ (AP = ((va_list) &(LASTARG) + __va_rounded_size(LASTARG))) /* do nothing */ #define va_end(AP) /* return the next argument in the argument list and increment AP */ #define va_arg(AP, TYPE) \ (AP += __va_rounded_size(TYPE), *((TYPE *)(AP - __va_rounded_size(TYPE)))) #endif
2.625
3
2024-11-18T20:57:50.403711+00:00
2015-02-03T21:04:41
8f505c468b775d4eef36bca973363f3d5231a28a
{ "blob_id": "8f505c468b775d4eef36bca973363f3d5231a28a", "branch_name": "refs/heads/master", "committer_date": "2015-02-03T21:04:41", "content_id": "7accc3717825b6de63c3291a39cef3d107d56ec1", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "1fc177184203fc9df8cb40a38ca7a2df1187472e", "extension": "c", "filename": "item.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 27124245, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 583, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/lab07/s201030_lab07/es01/adt_1_cat/item.c", "provenance": "stackv2-0064.json.gz:74740", "repo_name": "enbarberis/algoritmi", "revision_date": "2015-02-03T21:04:41", "revision_id": "d9928f6b6c68d7536edc3ef891e8fdb5ad556eed", "snapshot_id": "b062ca4825f30085a8fa978aca97cdc97540b358", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/enbarberis/algoritmi/d9928f6b6c68d7536edc3ef891e8fdb5ad556eed/lab07/s201030_lab07/es01/adt_1_cat/item.c", "visit_date": "2016-09-05T16:20:32.586411" }
stackv2
#include <stdio.h> #include "item.h" #include <stdlib.h> #include <string.h> struct item{ char *s; int n; }; Item item_scan() { char tmp[128]; Item i = malloc(sizeof(*i)); printf("\nString: "); scanf("%s", tmp); i->s = (char *) malloc((strlen(tmp)+1)*sizeof(char)); strcpy(i->s, tmp); printf("Number: "); scanf("%d", &i->n); return i; } Item item_new(char *s, int n) { Item i = malloc(sizeof(*i)); i->s = s; i->n = n; return i; } void item_print(Item i, FILE *fp) { fprintf(fp,"\n%s\n%d\n", i->s, i->n); } void item_free(Item i) { free(i->s); free(i); }
3.171875
3
2024-11-18T20:57:50.546030+00:00
2021-05-13T22:38:42
02c064d30e9633e87ed5eb28c2f75c75897c5c09
{ "blob_id": "02c064d30e9633e87ed5eb28c2f75c75897c5c09", "branch_name": "refs/heads/master", "committer_date": "2021-05-13T22:38:42", "content_id": "dcca41115821ddcba11094f2692deb2db443802a", "detected_licenses": [ "BSD-3-Clause", "SunPro" ], "directory_id": "74d8fd3c835507d6095a141f2bc7c3f5e59b14d3", "extension": "c", "filename": "unistd_fchown.c", "fork_events_count": 15, "gha_created_at": "2015-06-11T08:15:29", "gha_event_created_at": "2022-02-05T23:00:16", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 37248310, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5110, "license": "BSD-3-Clause,SunPro", "license_type": "permissive", "path": "/library/unistd_fchown.c", "provenance": "stackv2-0064.json.gz:74868", "repo_name": "adtools/clib2", "revision_date": "2021-05-13T22:38:42", "revision_id": "c02665938f32edcf3c4c921e2e9582ff45773475", "snapshot_id": "c2e993bdf2fe55be3fb50f5da44d535bdf620faa", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/adtools/clib2/c02665938f32edcf3c4c921e2e9582ff45773475/library/unistd_fchown.c", "visit_date": "2022-04-29T22:40:35.340096" }
stackv2
/* * $Id: unistd_fchown.c,v 1.15 2006-11-16 14:39:23 obarthel Exp $ * * :ts=4 * * Portable ISO 'C' (1994) runtime library for the Amiga computer * Copyright (c) 2002-2015 by Olaf Barthel <obarthel (at) gmx.net> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Neither the name of Olaf Barthel nor the names of contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _UNISTD_HEADERS_H #include "unistd_headers.h" #endif /* _UNISTD_HEADERS_H */ /****************************************************************************/ /* The following is not part of the ISO 'C' (1994) standard. */ /****************************************************************************/ int fchown(int file_descriptor, uid_t owner, gid_t group) { D_S(struct FileInfoBlock,fib); BPTR parent_dir = ZERO; BPTR old_current_dir = ZERO; BOOL current_dir_changed = FALSE; int result = ERROR; struct fd * fd = NULL; LONG success; ENTER(); SHOWVALUE(file_descriptor); SHOWVALUE(owner); SHOWVALUE(group); assert( file_descriptor >= 0 && file_descriptor < __num_fd ); assert( __fd[file_descriptor] != NULL ); assert( FLAG_IS_SET(__fd[file_descriptor]->fd_Flags,FDF_IN_USE) ); if(__check_abort_enabled) __check_abort(); __stdio_lock(); fd = __get_file_descriptor(file_descriptor); if(fd == NULL) { __set_errno(EBADF); goto out; } __fd_lock(fd); if(FLAG_IS_SET(fd->fd_Flags,FDF_IS_SOCKET)) { __set_errno(EINVAL); goto out; } if(FLAG_IS_SET(fd->fd_Flags,FDF_STDIO)) { __set_errno(EBADF); goto out; } PROFILE_OFF(); success = (__safe_examine_file_handle(fd->fd_File,fib) && (parent_dir = __safe_parent_of_file_handle(fd->fd_File)) != ZERO); PROFILE_ON(); if(NO success) { SHOWMSG("couldn't find parent directory"); __set_errno(__translate_io_error_to_errno(IoErr())); goto out; } old_current_dir = CurrentDir(parent_dir); current_dir_changed = TRUE; /* A value of -1 for either the owner or the group ID means that what's currently being used should not be changed. */ if(owner == (uid_t)-1) owner = fib->fib_OwnerUID; if(group == (gid_t)-1) group = fib->fib_OwnerGID; /* Check if the owner and group IDs are usable. This test follows the comparison against -1 above just so that we can be sure that we are not mistaking a -1 for a large unsigned number. */ if(owner > 65535 || group > 65535) { SHOWMSG("owner or group not OK"); SHOWVALUE(owner); SHOWVALUE(group); __set_errno(EINVAL); goto out; } /* Did anything change at all? */ if(group != fib->fib_OwnerUID || owner != fib->fib_OwnerUID) { PROFILE_OFF(); #if defined(__amigaos4__) { success = SetOwner(fib->fib_FileName,(LONG)((((ULONG)owner) << 16) | (ULONG)group)); } #else { if(((struct Library *)DOSBase)->lib_Version >= 39) { success = SetOwner(fib->fib_FileName,(LONG)((((ULONG)owner) << 16) | (ULONG)group)); } else { D_S(struct bcpl_name,new_name); struct DevProc * dvp; unsigned int len; SHOWMSG("have to do this manually..."); success = DOSFALSE; len = strlen(fib->fib_FileName); assert( len < sizeof(new_name->name) ); dvp = GetDeviceProc(fib->fib_FileName,NULL); if(dvp != NULL) { LONG error; new_name->name[0] = len; memmove(&new_name->name[1],fib->fib_FileName,len); success = DoPkt(dvp->dvp_Port,ACTION_SET_OWNER,0,dvp->dvp_Lock,MKBADDR(new_name),(LONG)((((ULONG)owner) << 16) | (ULONG)group),0); error = IoErr(); FreeDeviceProc(dvp); SetIoErr(error); } } } #endif /* __amigaos4__ */ PROFILE_ON(); if(NO success) { SHOWMSG("couldn't change owner/group"); __set_errno(__translate_io_error_to_errno(IoErr())); goto out; } } result = OK; out: __fd_unlock(fd); PROFILE_OFF(); UnLock(parent_dir); if(current_dir_changed) CurrentDir(old_current_dir); PROFILE_ON(); __stdio_unlock(); RETURN(result); return(result); }
2.03125
2
2024-11-18T20:57:50.752199+00:00
2015-02-01T21:10:16
b14a40859ab56f2ab287efb701e16d37f2861a8a
{ "blob_id": "b14a40859ab56f2ab287efb701e16d37f2861a8a", "branch_name": "refs/heads/master", "committer_date": "2015-02-01T21:10:16", "content_id": "fd2e67f81a8febdf0cbf97c95e6d46f645d6ef45", "detected_licenses": [ "Apache-2.0" ], "directory_id": "044d301039e78a35eeef7d5d63b12335d6a5102f", "extension": "c", "filename": "com_protocol.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": 6121, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/com_protocol.c", "provenance": "stackv2-0064.json.gz:75126", "repo_name": "smshen/libtee", "revision_date": "2015-02-01T21:10:16", "revision_id": "7a5d84de552b7f54e8a562a15535ebcda4a508e4", "snapshot_id": "8e0f50e4f5d5f331c94d090e8e8d0d4957f265d9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/smshen/libtee/7a5d84de552b7f54e8a562a15535ebcda4a508e4/src/com_protocol.c", "visit_date": "2021-01-17T08:21:38.067524" }
stackv2
/***************************************************************************** ** Copyright (C) 2014 Secure Systems Group. ** ** Copyright (C) 2014 Intel 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 <string.h> #include <sys/ioctl.h> #include <sys/select.h> #include <sys/uio.h> #include <zlib.h> #include "com_protocol.h" #include "tee_logging.h" static const uint32_t COM_MSG_START = 0xABCDEF12; #define TRY_READ_FD_COUNT 5 #define ELEMENTS_IN_MESSAGE 2 /* Transport information */ struct com_transport_info { uint64_t checksum; uint32_t start; uint32_t data_len; /* data_len: user message length */ } __attribute__((aligned)); static int read_iov_element(int fd, struct iovec *iov) { int read_bytes = 0; while (1) { read_bytes = readv(fd, iov, 1); if (read_bytes == -1) { if (errno == EINTR) continue; OT_LOG(LOG_ERR, "read error"); return -1; } else if (read_bytes == 0) { OT_LOG(LOG_ERR, "read error"); errno = EPIPE; return -1; } break; } return read_bytes; } static int wind_fd_next_start(int fd) { /* TODO: This function only emtying socket and due that message can be lost!! * * Use IOCTL call to find out data in socket, then peek and find next starting point */ static const int BUF_LEN = 256; char tmp[BUF_LEN]; int read_bytes; while (1) { read_bytes = read(fd, &tmp, BUF_LEN); if (read_bytes == -1) { if (errno == EINTR) continue; OT_LOG(LOG_ERR, "read error"); return -1; } else if (read_bytes == 0) { OT_LOG(LOG_ERR, "read error"); errno = EPIPE; return -1; } if (read_bytes == BUF_LEN) continue; else break; } return 1; /* This function should only call in com_recv_msg function */ } int com_recv_msg(int sockfd, void **msg, int *msg_len) { struct iovec iov[ELEMENTS_IN_MESSAGE]; int ret; struct com_transport_info com_recv_trans_info; if (!msg) { OT_LOG(LOG_ERR, "msg null") return 1; } /* Set NULL, because then can use ERR-goto and not refering unmalloced memory */ *msg = NULL; /*Transport capsule */ iov[0].iov_base = &com_recv_trans_info; iov[0].iov_len = sizeof(struct com_transport_info); /* Read transport capsule */ if (read_iov_element(sockfd, &iov[0]) == -1) { OT_LOG(LOG_ERR, "Problem with reading transport capsule"); ret = -1; goto err; } /* Transport information read. Verify bit sequence */ if (com_recv_trans_info.start != COM_MSG_START) { OT_LOG(LOG_ERR, "Read data is not beginning correctly"); ret = wind_fd_next_start(sockfd); goto err; } /* Malloc space for incomming message and read message */ *msg = calloc(1, com_recv_trans_info.data_len); if (!*msg) { OT_LOG(LOG_ERR, "Out of memory"); ret = 1; goto err; } iov[1].iov_base = *msg; iov[1].iov_len = com_recv_trans_info.data_len; if (read_iov_element(sockfd, &iov[1]) == -1) { OT_LOG(LOG_ERR, "Problem with reading msg"); ret = -1; goto err; } /* Calculate and verify checksum */ if (com_recv_trans_info.checksum != crc32(0, *msg, com_recv_trans_info.data_len)) { OT_LOG(LOG_ERR, "Message checksum is not matching, discard msg"); ret = 1; goto err; } if (msg_len) *msg_len = com_recv_trans_info.data_len; return 0; err: free(*msg); /* Discardin msg */ if (msg_len) *msg_len = 0; *msg = NULL; return ret; } int com_send_msg(int sockfd, void *msg, int msg_len) { struct iovec iov[ELEMENTS_IN_MESSAGE]; int bytes_write; struct com_transport_info com_trans_info; if (!msg) { OT_LOG(LOG_ERR, "message null"); return -1; } /* Fill and calculate transport information */ com_trans_info.start = COM_MSG_START; com_trans_info.data_len = msg_len; com_trans_info.checksum = crc32(0, msg, msg_len); iov[0].iov_base = &com_trans_info; iov[0].iov_len = sizeof(struct com_transport_info); iov[1].iov_base = msg; iov[1].iov_len = msg_len; /* Send message */ while (1) { bytes_write = writev(sockfd, iov, ELEMENTS_IN_MESSAGE); if (bytes_write == -1) { if (errno == EINTR) continue; OT_LOG(LOG_ERR, "send error: %s", strerror(errno)); return -1; } break; } return bytes_write - sizeof(struct com_transport_info); } int com_get_msg_name(void *msg, uint8_t *msg_name) { /* Not the most optimized operation, but I do not know a better way than * a "hardcoded" solution. */ struct com_msg_hdr msg_hdr; if (!msg || !msg_name) { OT_LOG(LOG_ERR, "message null"); return 1; } memcpy(&msg_hdr, msg, sizeof(struct com_msg_hdr)); *msg_name = msg_hdr.msg_name; return 0; } int com_get_msg_type(void *msg, uint8_t *msg_type) { struct com_msg_hdr msg_hdr; if (!msg || !msg_type) { OT_LOG(LOG_ERR, "message null"); return 1; } memcpy(&msg_hdr, msg, sizeof(struct com_msg_hdr)); *msg_type = msg_hdr.msg_type; return 0; } int com_get_msg_sess_id(void *msg, uint64_t *sess_id) { struct com_msg_hdr msg_hdr; if (!msg || !sess_id) { OT_LOG(LOG_ERR, "message null"); return 1; } memcpy(&msg_hdr, msg, sizeof(struct com_msg_hdr)); *sess_id = msg_hdr.sess_id; return 0; }
2.078125
2
2024-11-18T20:57:50.823777+00:00
2019-08-30T22:06:56
88f3f47266fdcff97fe10b14be6b0266d990a837
{ "blob_id": "88f3f47266fdcff97fe10b14be6b0266d990a837", "branch_name": "refs/heads/master", "committer_date": "2019-08-30T22:06:56", "content_id": "d09767b38f3e31055cf84d909465ba411fd093f5", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "990bc662498bb4a49d01f75a1f59ff645115e245", "extension": "c", "filename": "Timer2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 205408605, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7775, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/lab-5-jak3692_hs25796-master/lab-5-jak3692_hs25796-master/Timer2.c", "provenance": "stackv2-0064.json.gz:75255", "repo_name": "hydershad/Real-Time-Operating-Systems", "revision_date": "2019-08-30T22:06:56", "revision_id": "a54845faafb4204f79388bb0212f54f1c8ccea71", "snapshot_id": "fc6df7e031eda4257e25ae78cbc748fe7bc78fec", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hydershad/Real-Time-Operating-Systems/a54845faafb4204f79388bb0212f54f1c8ccea71/lab-5-jak3692_hs25796-master/lab-5-jak3692_hs25796-master/Timer2.c", "visit_date": "2020-07-14T21:38:16.760699" }
stackv2
// Timer2.c // Runs on LM4F120/TM4C123 // Use TIMER2 in 32-bit periodic mode to request interrupts at a periodic rate // Daniel Valvano // May 5, 2015 /* This example accompanies the book "Embedded Systems: Real Time Interfacing to Arm Cortex M Microcontrollers", ISBN: 978-1463590154, Jonathan Valvano, copyright (c) 2015 Program 7.5, example 7.6 Copyright 2015 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/ */ #define NUMTHREADS 8 #include <stdint.h> #include "tm4c123gh6pm.h" void (*PeriodicTask)(void) = 0; // user function void (*PeriodicTask2)(void); void (*PeriodicTask3)(void); void (*PeriodicTask4)(void) = 0; extern uint32_t OSTimerCount; int last = 0x11; int periodicity = 0; int first_Time, second_Time = 0; // ***************** Timer2_Init **************** // Activate Timer2 interrupts to run user task periodically // Inputs: task is a pointer to a user function // period in units (1/clockfreq) // Outputs: none void Timer2_Init(void(*task)(void), unsigned long period){ if(PeriodicTask == 0){ first_Time = (period/5000) + 1; SYSCTL_RCGCTIMER_R |= 0x04; // 0) activate timer2 PeriodicTask = task; // user function TIMER2_CTL_R = 0x00000000; // 1) disable timer2A during setup TIMER2_CFG_R = 0x00000000; // 2) configure for 32-bit mode TIMER2_TAMR_R = 0x00000002; // 3) configure for periodic mode, default down-count settings TIMER2_TAILR_R = period-1; // 4) reload value TIMER2_TAPR_R = 0; // 5) bus clock resolution TIMER2_ICR_R = 0x00000001; // 6) clear timer2A timeout flag TIMER2_IMR_R = 0x00000001; // 7) arm timeout interrupt NVIC_PRI5_R = (NVIC_PRI5_R&0x00FFFFFF)|0x40000000; // 8) priority 2 // interrupts enabled in the main program after all devices initialized // vector number 39, interrupt number 23 NVIC_EN0_R = 1<<23; // 9) enable IRQ 23 in NVIC TIMER2_CTL_R = 0x00000001; // 10) enable timer2A } else{ TIMER2_CTL_R = 0x00000000; TIMER2_TAILR_R = 500; // 4) reload value PeriodicTask4 = task; // user function TIMER2_CTL_R = 0x00000001; second_Time = (period / 5000) + 1; } } void Timer2A_Handler(void){ TIMER2_ICR_R = TIMER_ICR_TATOCINT; if(PeriodicTask4 != 0){ periodicity++; if(periodicity%first_Time == 0){ TIMER2_ICR_R = TIMER_ICR_TATOCINT;// acknowledge TIMER2A timeout (*PeriodicTask)(); } // execute user task if(periodicity%second_Time == 0){ (*PeriodicTask4)(); } if(periodicity == first_Time*second_Time){ periodicity = 0; } } else{ (*PeriodicTask)(); } } void Timer4_Handler(void){ TIMER4_ICR_R = TIMER_ICR_TATOCINT;// acknowledge TIMER4 timeout (*PeriodicTask4)(); // execute user task } void Timer3_Init(unsigned long period){ SYSCTL_RCGCTIMER_R |= 0x08; // 0) activate TIMER3 TIMER3_CTL_R = 0x00000000; // 1) disable TIMER3A during setup TIMER3_CFG_R = 0x00000000; // 2) configure for 32-bit mode TIMER3_TAMR_R = 0x00000002; // 3) configure for periodic mode, default down-count settings TIMER3_TAILR_R = period-1; // 4) reload value TIMER3_TAPR_R = 0; // 5) bus clock resolution TIMER3_ICR_R = 0x00000001; // 6) clear TIMER3A timeout flag TIMER3_IMR_R = 0x00000001; // 7) arm timeout interrupt NVIC_PRI8_R = (NVIC_PRI8_R&0x00FFFFFF)|0x80000000; // 8) priority 4 // interrupts enabled in the main program after all devices initialized // vector number 51, interrupt number 35 NVIC_EN1_R = 1<<(35-32); // 9) enable IRQ 35 in NVIC //TIMER3_CTL_R = 0x00000001; // 10) enable TIMER3A } static void GPIOArm(void){ GPIO_PORTF_ICR_R = 0x10; // (e) clear flag4 GPIO_PORTF_IM_R |= 0x10; // (f) arm interrupt on PF4 *** No IME bit as mentioned in Book *** NVIC_PRI7_R = (NVIC_PRI7_R&0xFF00FFFF)|0x00A00000; // (g) priority 5 NVIC_EN0_R = 0x40000000; // (h) enable interrupt 30 in NVIC } void Switch_Init(void(*task)(void)){ // **** general initialization **** SYSCTL_RCGCGPIO_R |= 0x00000020; // (a) activate clock for port F while((SYSCTL_PRGPIO_R & 0x00000020) == 0){}; PeriodicTask2 = task; GPIO_PORTF_DIR_R &= ~0x10; // (c) make PF4 in (built-in button) GPIO_PORTF_AFSEL_R &= ~0x10; // disable alt funct on PF4 GPIO_PORTF_DEN_R |= 0x10; // enable digital I/O on PF4 GPIO_PORTF_PCTL_R &= ~0x000F0000; // configure PF4 as GPIO GPIO_PORTF_AMSEL_R = 0; // disable analog functionality on PF GPIO_PORTF_PUR_R |= 0x10; // enable weak pull-up on PF4 GPIO_PORTF_IS_R &= ~0x10; // (d) PF4 is edge-sensitive GPIO_PORTF_IBE_R |= 0x10; // PF4 is both edges GPIOArm(); SYSCTL_RCGCTIMER_R |= 0x08; // 0) activate TIMER3 } static void GPIOArm2(void){ GPIO_PORTF_ICR_R = 0x1; // (e) clear flag4 GPIO_PORTF_IM_R |= 0x1; // (f) arm interrupt on PF0 *** No IME bit as mentioned in Book *** NVIC_PRI7_R = (NVIC_PRI7_R&0xFF00FFFF)|0x00A00000; // (g) priority 5 NVIC_EN0_R = 0x40000000; // (h) enable interrupt 30 in NVIC } void Switch_Init2(void(*task)(void)){ // **** general initialization **** SYSCTL_RCGCGPIO_R |= 0x00000020; // (a) activate clock for port F while((SYSCTL_PRGPIO_R & 0x00000020) == 0){}; PeriodicTask3 = task; GPIO_PORTF_LOCK_R = 0x4C4F434B; // unlock GPIO Port F GPIO_PORTF_CR_R = 0x11; GPIO_PORTF_DIR_R &= ~0x1; // (c) make PF0 in (built-in button) GPIO_PORTF_AFSEL_R &= ~0x1; // disable alt funct on PF0 GPIO_PORTF_DEN_R |= 0x1; // enable digital I/O on PF0 GPIO_PORTF_PCTL_R &= ~0x000F; // configure PF0 as GPIO GPIO_PORTF_AMSEL_R = 0; // disable analog functionality on PF GPIO_PORTF_PUR_R |= 0x1; // enable weak pull-up on PF0 GPIO_PORTF_IS_R &= ~0x1; // (d) PF0 is edge-sensitive GPIO_PORTF_IBE_R |= 0x1; // PF0 is both edges GPIOArm2(); SYSCTL_RCGCTIMER_R |= 0x08; // 0) activate TIMER3 } static void Timer3Arm(void){ TIMER3_CTL_R = 0x00000000; // 1) disable TIMER0A during setup TIMER3_CFG_R = 0x00000000; // 2) configure for 32-bit mode TIMER3_TAMR_R = 0x0000001; // 3) 1-SHOT mode TIMER3_TAILR_R = 160000; // 4) 10ms reload value TIMER3_TAPR_R = 0; // 5) bus clock resolution TIMER3_ICR_R = 0x00000001; // 6) clear TIMER0A timeout flag TIMER3_IMR_R = 0x00000001; // 7) arm timeout interrupt NVIC_PRI8_R = (NVIC_PRI8_R&0x00FFFFFF)|0x80000000; // 8) priority 4 // interrupts enabled in the main program after all devices initialized // vector number 35, interrupt number 19 NVIC_EN1_R = 1<<3; // 9) enable IRQ 19 in NVIC TIMER3_CTL_R = 0x00000001; // 10) enable TIMER0A } void Timer3A_Handler(void){ TIMER3_ICR_R = TIMER_ICR_TATOCINT;// acknowledge TIMER3A timeout //OS_DisableInterrupts(); int temp = GPIO_PORTF_DATA_R; if(((last & 0x10) != 0)&&((temp&0x10) == 0)){ (*PeriodicTask2)(); } if(((last & 0x1) != 0)&&((temp&0x1) == 0)){ (*PeriodicTask3)(); } last = temp; if((temp&0x11)== 0x11){ last = 0x11; } GPIOArm(); // start GPIO GPIOArm2(); //OS_EnableInterrupts(); } void GPIOPortF_Handler(void){ GPIO_PORTF_IM_R &= ~0x11; // disarm interrupt on PF4 and PF0 Timer3Arm(); // start one shot }
2.328125
2
2024-11-18T20:57:51.617247+00:00
2021-09-15T08:32:22
7de84403ab8aa7d45d0b89c772571864cf5f660d
{ "blob_id": "7de84403ab8aa7d45d0b89c772571864cf5f660d", "branch_name": "refs/heads/master", "committer_date": "2021-09-15T08:32:22", "content_id": "4eda724976daa4ea32b7922c39bfb24039f96388", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "fb12cbab0b88a6a8fa999b616b836490ba2f807b", "extension": "c", "filename": "compose-bmp.c", "fork_events_count": 8, "gha_created_at": "2018-07-18T10:35:43", "gha_event_created_at": "2023-09-07T07:50:21", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 141420359, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1574, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/05-data-encoding/bitmap/src/compose-bmp.c", "provenance": "stackv2-0064.json.gz:75513", "repo_name": "ComSys-OVGU/c-tasks", "revision_date": "2021-09-15T08:32:22", "revision_id": "a36cd544a3fa3235dafc5e278e7b6b231dafb93e", "snapshot_id": "5f988e3b2890f12714d872f2862f8d123e860eef", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/ComSys-OVGU/c-tasks/a36cd544a3fa3235dafc5e278e7b6b231dafb93e/05-data-encoding/bitmap/src/compose-bmp.c", "visit_date": "2022-05-04T12:21:30.146894" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #define UNUSED(x) (void)(x) #define FILENAME_RED "rawdata/img-5400x3600x8-r.bin" #define FILENAME_GREEN "rawdata/img-5400x3600x8-g.bin" #define FILENAME_BLUE "rawdata/img-5400x3600x8-b.bin" #define FILENAME_OUT "img.bmp" #define X_RESOLUTION 5400 #define Y_RESOLUTION 3600 void open_files(FILE** file_red, FILE** file_green, FILE** file_blue, FILE** file_out) { // open rgb raw data files if( (*file_red = fopen(FILENAME_RED, "rb")) == NULL) { fprintf(stderr, "Cannot open " FILENAME_RED); perror(" "); exit(1); } if( (*file_green = fopen(FILENAME_GREEN, "rb")) == NULL) { fprintf(stderr, "Cannot open " FILENAME_GREEN); perror(" "); exit(1); } if( (*file_blue = fopen(FILENAME_BLUE, "rb")) == NULL) { fprintf(stderr, "Cannot open " FILENAME_BLUE); perror(" "); exit(1); } // open output file if( (*file_out = fopen(FILENAME_OUT, "wb")) == NULL) { fprintf(stderr, "Cannot open " FILENAME_OUT); perror(" "); exit(1); } } void write_header(FILE* file_out) { // TODO: insert code here } void write_data(FILE* file_red, FILE* file_green, FILE* file_blue, FILE* file_out) { // TODO: insert code here } int main(int argc, char** argv) { UNUSED(argc); UNUSED(argv); FILE* file_red; FILE* file_green; FILE* file_blue; FILE* file_out; open_files(&file_red, &file_green, &file_blue, &file_out); write_header(file_out); write_data(file_red, file_green, file_blue, file_out); fclose(file_red); fclose(file_green); fclose(file_blue); fclose(file_out); }
2.515625
3
2024-11-18T20:57:52.215192+00:00
2016-10-12T05:54:05
8c20a6e4d4b36b483e315a1a3b2037a605c9929e
{ "blob_id": "8c20a6e4d4b36b483e315a1a3b2037a605c9929e", "branch_name": "refs/heads/master", "committer_date": "2016-10-12T05:54:05", "content_id": "a88a734568fda680c757a579c8d8722738ec7d95", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "10e0e8d855651f14645d36d7fab9e1dca7cc30f6", "extension": "c", "filename": "spice_rub.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": 7199, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/ext/spice_rub/spice_rub.c", "provenance": "stackv2-0064.json.gz:76157", "repo_name": "gtamba/spice_rub", "revision_date": "2016-10-12T05:54:05", "revision_id": "1147e34d48eae5a109c9bec0cec5fe41a9dda372", "snapshot_id": "cb769512e44bb8707be398153d5372d47ab016e5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gtamba/spice_rub/1147e34d48eae5a109c9bec0cec5fe41a9dda372/ext/spice_rub/spice_rub.c", "visit_date": "2021-06-07T08:35:15.956223" }
stackv2
#include "spice_rub.h" #include "spice_rub_utils.h" /* This is a thread safety mechanism. CSPICE uses various unix signals and it is prudent to block them while kernels are being loaded to ensure two threads do not interfere. This was inspired by similar blocks in place in the naif-spice gem : http://lunaserv.lroc.asu.edu/naif-spice.html Template usage : sigset_t old_mask = block_signals(); #DO THREAD UNSAFE C SPICE CALLS restore_signals(old_mask); #TODO : Elaborate explanation */ sigset_t block_signals() { sigset_t full_mask; sigset_t old_mask; //This UNIX routine sets all the mask bits to 1, effectively blocking every signal // indicated by the bitmask when sigprocmask is called sigfillset(&full_mask); //This UNIX routine utilizes the given mask to block the appropriate signals // The previous mask is stored in old_smask sigprocmask(SIG_BLOCK, &full_mask, &old_mask); return old_mask; } void restore_signals(sigset_t old_mask) { //Uses the parameter mask to restore signals to previous state sigprocmask(SIG_SETMASK, &old_mask, NULL); } bool spice_error(int error_detail) { SpiceInt buffer_size = 1024; char error_message[buffer_size]; if (failed_c()) { switch(error_detail) { case SPICE_ERROR_ALL : //TODO: Neat way to concat all error messages. reset_c(); break; case SPICE_ERROR_SHORT : getmsg_c("SHORT", buffer_size, error_message); reset_c(); rb_raise(rb_spice_error, "%s\n", error_message); break; case SPICE_ERROR_LONG : getmsg_c("LONG", buffer_size, error_message); reset_c(); rb_raise(rb_spice_error, "%s\n", error_message); break; case SPICE_ERROR_EXPLAIN : getmsg_c("EXPLAIN", buffer_size, error_message); reset_c(); rb_raise(rb_spice_error, "%s\n", error_message); break; default : reset_c(); break; } } return false; } void Init_spice_rub() { spicerub_top_module = rb_define_module("SpiceRub"); spicerub_nested_module = rb_define_module_under(spicerub_top_module, "Native"); //Attach Kernel Loading functions to module rb_define_module_function(spicerub_nested_module, "furnsh", sr_furnsh, 1); rb_define_module_function(spicerub_nested_module, "ktotal", sr_ktotal, -1); rb_define_module_function(spicerub_nested_module, "unload", sr_unload, 1); rb_define_module_function(spicerub_nested_module, "kclear", sr_kclear, 0); //Attach Geometry-Coordinate functions to module rb_define_module_function(spicerub_nested_module, "latrec", sr_latrec, 3); rb_define_module_function(spicerub_nested_module, "reclat", sr_reclat, 1); rb_define_module_function(spicerub_nested_module, "lspcn", sr_lspcn, -1); rb_define_module_function(spicerub_nested_module, "sincpt", sr_sincpt, 8); rb_define_module_function(spicerub_nested_module, "subpnt", sr_subpnt, 6); rb_define_module_function(spicerub_nested_module, "subslr", sr_subslr, 6); rb_define_module_function(spicerub_nested_module, "getfov", sr_getfov, 4); rb_define_module_function(spicerub_nested_module, "recsph", sr_recsph, 1); rb_define_module_function(spicerub_nested_module, "sphrec", sr_sphrec, 3); rb_define_module_function(spicerub_nested_module, "phaseq", sr_phaseq, 5); rb_define_module_function(spicerub_nested_module, "recrad", sr_recrad, 1); rb_define_module_function(spicerub_nested_module, "radrec", sr_radrec, 3); rb_define_module_function(spicerub_nested_module, "recgeo", sr_recgeo, 3); rb_define_module_function(spicerub_nested_module, "georec", sr_georec, 5); rb_define_module_function(spicerub_nested_module, "recpgr", sr_recpgr, 4); rb_define_module_function(spicerub_nested_module, "pgrrec", sr_pgrrec, 6); rb_define_module_function(spicerub_nested_module, "dpr", sr_dpr, 0); rb_define_module_function(spicerub_nested_module, "rpd", sr_rpd, 0); rb_define_module_function(spicerub_nested_module, "bodvrd", sr_bodvrd, 3); rb_define_module_function(spicerub_nested_module, "bodvcd", sr_bodvcd, 3); rb_define_module_function(spicerub_nested_module, "latsph", sr_latsph, 3); rb_define_module_function(spicerub_nested_module, "sphlat", sr_sphlat, 3); rb_define_module_function(spicerub_nested_module, "srfrec", sr_srfrec, 3); //Atttach Time and Time Conversion functions to module rb_define_module_function(spicerub_nested_module, "str2et", sr_str2et, 1); rb_define_module_function(spicerub_nested_module, "gfdist", sr_gfdist, 9); rb_define_module_function(spicerub_nested_module, "gfsntc", sr_gfsntc, 15); rb_define_module_function(spicerub_nested_module, "gfsep", sr_gfsep, 14); rb_define_module_function(spicerub_nested_module, "gftfov", sr_gftfov, 8); rb_define_module_function(spicerub_nested_module, "gfoclt", sr_gfoclt, 11); rb_define_module_function(spicerub_nested_module, "gfrfov", sr_gfrfov, 7); rb_define_module_function(spicerub_nested_module, "timout", sr_timout, 3); rb_define_module_function(spicerub_nested_module, "sce2c", sr_sce2c, 2); rb_define_module_function(spicerub_nested_module, "sctiks", sr_sctiks, 2); rb_define_module_function(spicerub_nested_module, "scencd", sr_scencd, 2); rb_define_module_function(spicerub_nested_module, "scs2e", sr_scs2e, 2); rb_define_module_function(spicerub_nested_module, "scdecd", sr_scdecd, 3); rb_define_module_function(spicerub_nested_module, "sct2e", sr_sct2e , 2); rb_define_module_function(spicerub_nested_module, "deltet", sr_deltet , 2); rb_define_module_function(spicerub_nested_module, "unitim", sr_unitim , 3); rb_define_module_function(spicerub_nested_module, "j1900", sr_j1900, 0); rb_define_module_function(spicerub_nested_module, "j1950", sr_j1950, 0); rb_define_module_function(spicerub_nested_module, "j2000", sr_j2000, 0); rb_define_module_function(spicerub_nested_module, "j2100", sr_j2100, 0); rb_define_module_function(spicerub_nested_module, "b1900", sr_b1900, 0); rb_define_module_function(spicerub_nested_module, "b1950", sr_b1950, 0); //Attach Ephemerides routines to module rb_define_module_function(spicerub_nested_module, "spkpos", sr_spkpos , 5); rb_define_module_function(spicerub_nested_module, "spkezr", sr_spkezr , 5); rb_define_module_function(spicerub_nested_module, "spkcpt", sr_spkcpt , 8); rb_define_module_function(spicerub_nested_module, "spkcvo", sr_spkcvo , 9); rb_define_module_function(spicerub_nested_module, "spkcvt", sr_spkcvt , 9); rb_define_module_function(spicerub_nested_module, "spkcpo", sr_spkcpo , 8); rb_define_module_function(spicerub_nested_module, "pxform", sr_pxform , 3); rb_define_module_function(spicerub_nested_module, "pxfrm2", sr_pxfrm2 , 4); rb_define_module_function(spicerub_nested_module, "sxform", sr_sxform , 3); rb_define_module_function(spicerub_nested_module, "pckfrm", sr_pckfrm , 1); rb_define_module_function(spicerub_nested_module, "spkobj", sr_spkobj , 1); rb_define_module_function(spicerub_nested_module, "bodc2n", sr_bodc2n, 1); rb_define_module_function(spicerub_nested_module, "bodn2c", sr_bodn2c, 1); rb_spice_error = rb_define_class("SpiceError", rb_eStandardError); }
2.140625
2
2024-11-18T20:58:01.330012+00:00
2013-11-18T12:20:37
9ff7731e94f63fe62bbb83bd3c53cf9f4cb6e03d
{ "blob_id": "9ff7731e94f63fe62bbb83bd3c53cf9f4cb6e03d", "branch_name": "refs/heads/master", "committer_date": "2013-11-18T12:20:37", "content_id": "f1ac54edf95f38677c4e4e4c45f191f0a0a6b724", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c955394e3f7810b7da90d04f2feb0987bd49ab34", "extension": "c", "filename": "priv.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 14491537, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3491, "license": "Apache-2.0", "license_type": "permissive", "path": "/libbase/lib/priv.c", "provenance": "stackv2-0064.json.gz:76286", "repo_name": "samitolvanen/ngim", "revision_date": "2013-11-18T12:20:37", "revision_id": "8e545ab88f87586ec2b6cd8c9590b6969e0880fb", "snapshot_id": "42142a421b37c56f218a13a60b78602fa4a5a942", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/samitolvanen/ngim/8e545ab88f87586ec2b6cd8c9590b6969e0880fb/libbase/lib/priv.c", "visit_date": "2020-05-18T02:24:21.375897" }
stackv2
/* * priv.c * * Copyright 2005, 2006 Sami Tolvanen <sami@ngim.org> */ #include "base.h" #include "common.h" #if HAVE_SYS_CAPABILITY_H static cap_value_t caps_netsrv[] = { /* This may be useful for allocating secure memory */ #ifdef CAP_IPC_LOCK CAP_IPC_LOCK, #endif /* This is needed to bind a socket to a privileged port */ #ifdef CAP_NET_BIND_SERVICE CAP_NET_BIND_SERVICE, #endif /* This is needed for dropping group privileges */ #ifdef CAP_SETGID CAP_SETGID, #endif /* This is needed for dropping user privileges */ #ifdef CAP_SETUID CAP_SETUID #endif }; static cap_value_t caps_srvctl[] = { /* This is needed for terminating children with different uids */ #ifdef CAP_KILL CAP_KILL #endif }; static inline int priv_cap_set_flag(cap_t ct, cap_flag_t cf, int level) { int rv = -1; switch (level) { case NGIM_PRIV_NONE: /* Set no flags */ return 0; case NGIM_PRIV_NETSRV: rv = cap_set_flag(ct, cf, NELEMS(caps_netsrv), caps_netsrv, CAP_SET); break; case NGIM_PRIV_SRVCTL: rv = cap_set_flag(ct, cf, NELEMS(caps_srvctl), caps_srvctl, CAP_SET); break; default: die_error1("invalid privilege level"); } return rv; } static int priv_setcaps(int level) { cap_t ct; if (level == NGIM_PRIV_CURRENT) { /* Do not change capabilities */ return 0; } #if HAVE_PRCTL && defined(PR_SET_KEEPCAPS) /* Make sure capabilities aren't preserved over uid change */ if (prctl(PR_SET_KEEPCAPS, 0) < 0) { return -1; } #endif /* Drop capabilities to a desired level */ if (ALLOC_FAIL(ct, cap_init())) { return -1; } if (priv_cap_set_flag(ct, CAP_PERMITTED, level) < 0 || priv_cap_set_flag(ct, CAP_EFFECTIVE, level) < 0) { cap_free(ct); return -1; } if (cap_set_proc(ct) < 0) { cap_free(ct); return -1; } cap_free(ct); return 0; } #endif /* HAVE_SYS_CAPABILITY_H */ static inline int priv_getuid(const char *name) { struct passwd *pw; die_assert(name); if (ALLOC_FAIL(pw, getpwnam(name))) { return -1; } return pw->pw_uid; } static inline int priv_getgid(const char *name) { struct group *gr; die_assert(name); if (ALLOC_FAIL(gr, getgrnam(name))) { return -1; } return gr->gr_gid; } static inline int priv_setuid(uid_t uid) { if (setuid(uid) < 0) { return -1; } /* Must not be able to regain root privileges */ if (uid > 0 && setuid(0) == 0) { die_error1("unable to drop privileges"); } return 0; } static inline int priv_setgid(gid_t gid) { #if HAVE_SETGROUPS if (setgroups(1, &gid) < 0) { return -1; } #endif if (setgid(gid) < 0) { return -1; } return 0; } int ngim_priv_drop(int level, const char *uname, const char *gname) { int uid; /* Set group id */ if (gname) { int gid = priv_getgid(gname); if (gid < 0) { warn_error2("unknown group ", gname); return -1; } if (priv_setgid(gid) < 0) { warn_syserror2("failed to change group to ", gname); return -1; } } /* Set user id */ if (uname) { uid = priv_getuid(uname); if (uid < 0) { warn_error2("unknown user ", uname); return -1; } if (priv_setuid(uid) < 0) { warn_syserror2("failed to change user to ", uname); return -1; } } else { uid = getuid(); } /* Drop unneeded privileges if still running as root */ if (uid == 0) { #if HAVE_SYS_CAPABILITY_H /* Set capabilities */ if (priv_setcaps(level) < 0) { warn_error1("failed to drop capabilities"); return -1; } #endif /* TODO: add platform-specific functionality here */ } return 0; }
2.59375
3
2024-11-18T20:58:01.439529+00:00
2022-02-03T03:59:41
66aa33f1a4eb34cb48de212f51ea2a908744f488
{ "blob_id": "66aa33f1a4eb34cb48de212f51ea2a908744f488", "branch_name": "refs/heads/main", "committer_date": "2022-02-03T03:59:41", "content_id": "c0c928df81da162e6b77d6d6464d820be165fecf", "detected_licenses": [ "MIT" ], "directory_id": "c6194c146264a314cddcf3ddfeaf9a9f4d06dfd5", "extension": "h", "filename": "AnalogAccumulator.h", "fork_events_count": 1, "gha_created_at": "2019-10-23T21:56:23", "gha_event_created_at": "2022-02-03T03:59:42", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 217160684, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4093, "license": "MIT", "license_type": "permissive", "path": "/frc/wpi/include/hal/AnalogAccumulator.h", "provenance": "stackv2-0064.json.gz:76545", "repo_name": "qhdwight/frc-go", "revision_date": "2022-02-03T03:59:41", "revision_id": "b3a59ac64b76d55c6ede586f8ca3a35bdfc3a4d3", "snapshot_id": "f911222c6d147ddeefa8a177d18dba0ea03c5b99", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/qhdwight/frc-go/b3a59ac64b76d55c6ede586f8ca3a35bdfc3a4d3/frc/wpi/include/hal/AnalogAccumulator.h", "visit_date": "2022-02-23T08:34:52.677930" }
stackv2
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #pragma once #include <stdint.h> #include "hal/Types.h" /** * @defgroup hal_analogaccumulator Analog Accumulator Functions * @ingroup hal_capi * @{ */ #ifdef __cplusplus extern "C" { #endif /** * Is the channel attached to an accumulator. * * @param[in] analogPortHandle Handle to the analog port. * @param[out] status Error status variable. 0 on success. * @return The analog channel is attached to an accumulator. */ HAL_Bool HAL_IsAccumulatorChannel(HAL_AnalogInputHandle analogPortHandle, int32_t* status); /** * Initialize the accumulator. * * @param[in] analogPortHandle Handle to the analog port. * @param[out] status Error status variable. 0 on success. */ void HAL_InitAccumulator(HAL_AnalogInputHandle analogPortHandle, int32_t* status); /** * Resets the accumulator to the initial value. * * @param[in] analogPortHandle Handle to the analog port. * @param[out] status Error status variable. 0 on success. */ void HAL_ResetAccumulator(HAL_AnalogInputHandle analogPortHandle, int32_t* status); /** * Set the center value of the accumulator. * * The center value is subtracted from each A/D value before it is added to the * accumulator. This is used for the center value of devices like gyros and * accelerometers to make integration work and to take the device offset into * account when integrating. * * This center value is based on the output of the oversampled and averaged * source from channel 1. Because of this, any non-zero oversample bits will * affect the size of the value for this field. * * @param[in] analogPortHandle Handle to the analog port. * @param[in] center The center value of the accumulator. * @param[out] status Error status variable. 0 on success. */ void HAL_SetAccumulatorCenter(HAL_AnalogInputHandle analogPortHandle, int32_t center, int32_t* status); /** * Set the accumulator's deadband. * * @param[in] analogPortHandle Handle to the analog port. * @param[in] deadband The deadband of the accumulator. * @param[out] status Error status variable. 0 on success. */ void HAL_SetAccumulatorDeadband(HAL_AnalogInputHandle analogPortHandle, int32_t deadband, int32_t* status); /** * Read the accumulated value. * * Read the value that has been accumulating on channel 1. * The accumulator is attached after the oversample and average engine. * * @param[in] analogPortHandle Handle to the analog port. * @param[out] status Error status variable. 0 on success. * @return The 64-bit value accumulated since the last Reset(). */ int64_t HAL_GetAccumulatorValue(HAL_AnalogInputHandle analogPortHandle, int32_t* status); /** * Read the number of accumulated values. * * Read the count of the accumulated values since the accumulator was last * Reset(). * * @param[in] analogPortHandle Handle to the analog port. * @param[out] status Error status variable. 0 on success. * @return The number of times samples from the channel were accumulated. */ int64_t HAL_GetAccumulatorCount(HAL_AnalogInputHandle analogPortHandle, int32_t* status); /** * Read the accumulated value and the number of accumulated values atomically. * * This function reads the value and count from the FPGA atomically. * This can be used for averaging. * * @param[in] analogPortHandle Handle to the analog port. * @param[in] value Pointer to the 64-bit accumulated output. * @param[in] count Pointer to the number of accumulation cycles. * @param[out] status Error status variable. 0 on success. */ void HAL_GetAccumulatorOutput(HAL_AnalogInputHandle analogPortHandle, int64_t* value, int64_t* count, int32_t* status); #ifdef __cplusplus } // extern "C" #endif /** @} */
2.359375
2
2024-11-18T20:58:01.541371+00:00
2017-11-26T01:24:23
e9a4e9cd1b3796d7a07eb6e03f8eec9dac734d3c
{ "blob_id": "e9a4e9cd1b3796d7a07eb6e03f8eec9dac734d3c", "branch_name": "refs/heads/master", "committer_date": "2017-11-26T01:24:23", "content_id": "5bb0eb6a934ef93e34c00757c8f155fca44c4203", "detected_licenses": [ "MIT" ], "directory_id": "f71756217c41930db2bdb142e3a458a9ef5ca536", "extension": "c", "filename": "video.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 112029960, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9311, "license": "MIT", "license_type": "permissive", "path": "/common/video.c", "provenance": "stackv2-0064.json.gz:76673", "repo_name": "derekdickinson/bisync-3780", "revision_date": "2017-11-26T01:24:23", "revision_id": "5cd5ed5b6d1bdc799132d90479458703f8414169", "snapshot_id": "eeb4ac31fc549c3f91f6b0e6cd4bfabbc22cff0b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/derekdickinson/bisync-3780/5cd5ed5b6d1bdc799132d90479458703f8414169/common/video.c", "visit_date": "2021-08-19T11:00:31.265523" }
stackv2
#include <bios.h> #include <conio.h> #include <dir.h> #include <dos.h> #include <string.h> #include <stdarg.h> #include <stdlib.h> #include "include\d3.h" #define DISPBYTE thevar->dispval->abyte #define DISPUINT thevar->dispval->auint #define DISPULNG thevar->dispval->aulng #define DISPASTR ((char *) thevar->dispval) #define MAXLEN thevar->maxlen #define LASTBYTE thevar->lastval.abyte #define LASTUINT thevar->lastval.auint #define LASTULNG thevar->lastval.aulng #define LASTASTR thevar->lastval.auint #define FORMSTR thevar->formstr #define STRS thevar->dispptr static void pascal shovar(DISPVAR *thevar) { if (thevar==NULL) return; if ( (thevar->statmask & themask) == 0) return; switch (thevar->varstat) { case 0: return; case BINDV: if (LASTBYTE==DISPBYTE) return; svform(FORMSTR,STRS[DISPBYTE]); LASTBYTE=DISPBYTE; return; case INTV: if (LASTUINT==DISPUINT) return; svform(FORMSTR,DISPUINT); LASTUINT=DISPUINT; return; case LONGV: if (LASTULNG==DISPULNG) return; svform(FORMSTR,DISPULNG); LASTULNG=DISPULNG; return; #if SYNC case SDEST: { byte ind; ind= (sndlist==NULL) ? prindest : sndlist->prindest ; if (LASTBYTE==ind) return; svform(FORMSTR,STRS[ind]); LASTBYTE=ind; } return; case SMODE: { byte ind; ind=(sndlist==NULL) ? buftype : sndlist->buftype; if (LASTBYTE==ind) return; svform(FORMSTR,STRS[ind]); LASTBYTE=ind; } return; #endif case STRV: { char *st; st=DISPASTR; if (chkcrc(st)==LASTASTR) return; LASTASTR=chkcrc(st); if (MAXLEN!=0 && strlen(st)>MAXLEN) st=&st[strlen(st)-MAXLEN]; svform(FORMSTR,st); } } } #define STRCHANG(str) (str->lastval.auint!=chkcrc((char *)str->dispval)) #define BYTECHANG(str) (str->lastval.abyte!=str->dispval->abyte) void pascal shoact(void) { #if SYNC byte i; DISPVAR *actname; static DISPVAR *actcnv; actname=NULL; if ( f_state>13 && f_state<21 ) { themask|=0x04; if (act==&ptr) { actname=&dv[PTRNAMEDV]; switch (rxtyp) { case STANTYPE: actcnv=&dv[PTRSTDDV]; break; case TRANTYPE: actcnv=&dv[PTRTRANDV]; break; } } else { actname=&dv[PUNNAMEDV]; switch (rxtyp) { case STANTYPE: actcnv=&dv[PUNSTDDV]; break; case TRANTYPE: actcnv=&dv[PUNTRANDV]; break; } } } else actcnv=NULL; if (f_state<9) { themask|=0x02; actname=&dv[SNDNAMEDV]; } for (i=0; i<3; i++) { if (*(namepos[i]->formstr)==0) continue; if (namepos[i]==actname) { if (actname->formstr[0]!=actat || STRCHANG(actname) ) { actname->lastval.auint=0xff; actname->formstr[0]=actat; shovar(actname); } } else { if (namepos[i]->formstr[0]!=dimat || STRCHANG(namepos[i])) { namepos[i]->lastval.auint=0xff; namepos[i]->formstr[0]=dimat; shovar(namepos[i]); } } } for (i=0; i<4; i++) { if (*(namepos[i]->formstr)==0) continue; if (cnvspos[i]==actcnv) { if ( actcnv->formstr[0]!=actat || BYTECHANG(actcnv) ) { actcnv->lastval.abyte=0xff; actcnv->formstr[0]=actat; shovar(actcnv); } } else { if (cnvspos[i]->formstr[0]!=dimat || BYTECHANG(cnvspos[i]) ) { cnvspos[i]->lastval.abyte=0xff; cnvspos[i]->formstr[0]=dimat; shovar(cnvspos[i]); } } } #endif } void pascal updatedisp(void) { static int oldsecond; static byte old_day; static byte oltop=1; static byte olbot=25; static byte oleft=1; static byte olrit=80; DISPVAR **curdisp; char dummybuf[20]; /* form("\2\1\1rx %.2d, tx %.2d, f %.2d ",rxstate,txstate,f_state); */ if (winbottom!=olbot || wintop!=oltop || winleft!=oleft || winright!=olrit) { WINDOW(wintop,winleft,winbottom,winright); if (!dosup) { myputs("\2\1\1\f\3"); /* Clear Screen place cursor. */ promp(); } olbot=winbottom; oltop=wintop; oleft=winleft; olrit=winright; } _AX=0x2c00; geninterrupt(0x21); hour=_CH; minute=_CL; second=_DH; if (second != oldsecond) { oldsecond=second; svform(dv[TIMEDV].formstr,( (hour+11) % 12 ) + 1,minute,second); } getdate(&thedate); if (redisplay || thedate.da_day!=old_day) { svform(dv[DATEDV].formstr,thedate.da_mon, thedate.da_day, (itoa(thedate.da_year,dummybuf,10)+2) ); old_day=thedate.da_day; } restat(); for (curdisp=updisps; *curdisp!=NULL; curdisp++) { if (redisplay) (*curdisp)->lastval.aulng=-1L; shovar(*curdisp); } redisplay=FALSE; shoact(); } void pascal putscrn(void) { dsrit(bscrn); redisplay=TRUE; updatedisp(); } int pascal wx(void) { if (hidecur) return 0x00FF & vx; return wherex(); } int pascal wy(void) { if (hidecur) return (0x00FF & vy); return wherey(); } void pascal gorocol(byte ro,byte col) { if (col > winright-winleft+1) /* Check for row out of window */ { ro+=( (col-1)/(winright-winleft+1) ); col=(col-1)%(winright-winleft+1)+1; } if (ro > winbottom-wintop+1) ro=winbottom-wintop+1; vx=col; vy=ro; if (hidecur) GOROCOL(26,1) else gotoxy(col,ro); } void pascal getrocol(byte *ro,byte *col) { if (hidecur) { *ro=vy; *col=vx; return; } GETROCOL(*ro,*col); } /* Use video mode to determine how and where to write direct video writes. */ void pascal getvidmode(void) { _AH=0x0f; geninterrupt(0x10); vidmode=_AL; video_base=0xb800; switch (vidmode) { case 7: video_base=0xb000; case 2: def_attr=grph_attr=cha_attr=key_attr=0x07; high_attr=0x0f; rev_attr=0x70; und_attr=(vidmode==2) ? 0x07 : 0x01; break; default: vidmode=0x03; _AX=0x0003; geninterrupt(0x10); case 3: key_attr=def_attr=0x0e; high_attr=0x0b; cha_attr=0x0f; grph_attr=0x0a; rev_attr=0x20; und_attr=0x0c; break; } } /* This is used for writing formatted output directly to the screen. The "dirite" function is a direct video write routine in scrnlib.asm. */ char * cdecl form(char *st, ...) { char dummyst[2500]; vsprintf(dummyst,st,...); rite(dummyst); /* Write resulting string to screen or buffer */ return &st[strlen(st)+1]; } void pascal promp(void) { if (wx()!=1) dputs("\r\n"); if (lfptr!=NULL) fprintf(lfptr,"%.3d ",cmdline); dputs(prompt); promplen=col; } void pascal cleanexit(int errorval) { byte i; if (lfptr!=NULL) { fprintf(lfptr, "\r\n%s ",packname); for(i=1;i<argcg;i++) fprintf(lfptr,"%s ",argvg[i]); fprintf(lfptr,"-- returned errorlevel %d",errorval); fclose(lfptr); } CLRBUF(); exit(errorval); }; void pascal myputs(char *st) { byte olatt; witop=wintop; wileft=winleft; wibot=winbottom; wiright=winright; olatt=def_attr; def_attr=win_attr; ro=wy(); col=wx(); rite(st); def_attr=olatt; gorocol(ro,col); witop=wileft=1; wibot=25; wiright=80; } void cdecl myprintf(char *st,...) { char dummyst[2500]; vsprintf(dummyst,st,...); myputs(dummyst); /* Write resulting string to screen or buffer */ } void cdecl dputs(char *st, ...) { va_list argptr; /* Argument list type. */ char dummyst[2500]; va_start(argptr,st); /* Initialize list. */ vsprintf(dummyst,st,argptr); /* Use as argument for vsprintf. */ va_end(argptr); /* Clean up result. */ if (dispstate!=CMDINT && lfptr!=NULL) { if (dummyst[0]==4) fputs(&dummyst[1],lfptr); /* Get rid of video control char */ else fputs(dummyst,lfptr); } if (dosup) return; put(dummyst); return; } void cdecl disp(char *st, ...) { va_list argptr; /* Argument list type. */ char dummyst[2500]; va_start(argptr,st); /* Initialize list. */ vsprintf(dummyst,st,argptr); /* Use as argument for vsprintf. */ va_end(argptr); /* Clean up result. */ if (dispstate==CMDINT) { switch (keystate) { case INCMD: prin("\r\n%s",dummyst); if (wx()==1) put(prompt); else put("\r\n"); edro=wy(); { byte dummy; dummy=edcur; edcur=0; edrite(); edcur=dummy; } gorocol(edro,edcur+edcol); return; case ATPROMPT: put("\r\n"); case DISPING: put(dummyst); #if SYNC if ( (f_state==START_R) && (!remwaiting) ) #endif #if ASYNC if (f_state==START_R) #endif { if (wx()==1) put(prompt); else prin("\r\n%s",prompt); keystate=ATPROMPT; } else keystate=DISPING; return; case INREMCMD: put(dummyst); return; } } if (dispstate!=CMDINT && lfptr!=NULL) fputs(dummyst,lfptr); if (dosup) return; put(dummyst); return; } void pascal cls(void) { myputs("\2\1\1\f\3"); }
2.09375
2
2024-11-18T20:58:01.946648+00:00
2019-03-29T13:17:02
e115ece26c19007c5beb8e25d3b14e2163f44843
{ "blob_id": "e115ece26c19007c5beb8e25d3b14e2163f44843", "branch_name": "refs/heads/master", "committer_date": "2019-03-29T13:17:02", "content_id": "50097a171cd5b15b3e57e3f987ab8c4256e5e289", "detected_licenses": [ "MIT" ], "directory_id": "d95baddc277f9c45f7542b4c4f30e2b40542013a", "extension": "c", "filename": "ProcessChecker.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 174514783, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1861, "license": "MIT", "license_type": "permissive", "path": "/ProcessChecker.c", "provenance": "stackv2-0064.json.gz:77057", "repo_name": "maxPrakken/AutomatedLogs", "revision_date": "2019-03-29T13:17:02", "revision_id": "97f44ac705185184be8466a6bc8afa87b8705070", "snapshot_id": "993e0a0e4c1cdea9838c26a9c17f32356fb63411", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/maxPrakken/AutomatedLogs/97f44ac705185184be8466a6bc8afa87b8705070/ProcessChecker.c", "visit_date": "2020-04-27T17:21:22.632465" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <windows.h> #include <string.h> int ProcessChecker() { while (1) { FILE *fp; char str[50]; // string off whitelisted programs char whitelist[200][50]; // where the strings are getting pushed into int lc = 0; // list counter for the whitelist char* filename = "whitelist.txt"; // whitelist file name fp = fopen(filename, "r"); // open file if (fp == NULL) { // check if null printf("Could not open file %s", filename); fflush(stdout); return 0; // return 0 if null } while (fgets(str, 20, fp) != NULL) { // if line is not empty/NULL strcpy(&whitelist[lc][0], str); // copy str in whitelist char* p = strchr(&whitelist[lc][0], '\n'); // remove newline from whitelist entry if (p) { // if newline is not null *p = '\0'; // set newline to null terminator } lc++; // +1 on list counter //Sleep(1000); } fclose(fp); // closes file HWND hWnd = GetForegroundWindow(); // contains path of foregroundwindow const int nMaxCount = 300; // max byte size of windowTile char windowTitle[nMaxCount]; // char array of the foregroundwindows name int i = GetWindowText( // gets foregroundwindows name and puts it into windowTile hWnd, windowTitle, sizeof(windowTitle) ); for (int x = 0; x < lc; x++) { char search[] = ""; // name of thing to search if (strstr(windowTitle, &whitelist[x][0]) != NULL) // substring is found { //printf("'%s' contains '%s'\n", windowTitle, whitelist[x][0]); printf(" yes"); } else // Substring not found { //printf("'%s' doesn't contain '%s'\n", windowTitle, whitelist[x][0]); printf(" no"); } fflush(stdout); Sleep(1000); // 1000 is one second wait time } } return 0; // end program }
3.046875
3
2024-11-18T20:58:02.059138+00:00
2016-03-24T15:06:47
4dff031ff56c51cfbab55b024d29dc226eec3eeb
{ "blob_id": "4dff031ff56c51cfbab55b024d29dc226eec3eeb", "branch_name": "refs/heads/master", "committer_date": "2016-03-24T15:06:47", "content_id": "adfd35278799218a562bebbfb325794eadee7136", "detected_licenses": [ "MIT" ], "directory_id": "9dc284aef72e5dc8f8b782269da595859f3a6788", "extension": "h", "filename": "dbg_log.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 54649935, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1702, "license": "MIT", "license_type": "permissive", "path": "/src/dbg_log.h", "provenance": "stackv2-0064.json.gz:77185", "repo_name": "siralexeyduke/dbg_log", "revision_date": "2016-03-24T15:06:47", "revision_id": "bf9cad72181d04cb68864ed54f77adeb0a874758", "snapshot_id": "cd09025cb5465eceec4f2496083bbc67ef67236a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/siralexeyduke/dbg_log/bf9cad72181d04cb68864ed54f77adeb0a874758/src/dbg_log.h", "visit_date": "2021-01-10T03:21:42.707426" }
stackv2
/** * @file dbg_log.h * @author Alexey Serdyuk * @version V0.0.1 * @date 23-March-2016 * @brief Debug log * * Lightweight implementation of debug logger for low scale embedded systems. * In this implementation standard streams are not used, since they are * not efficient or even not available for microcontroller based platforms. */ #ifndef _DBG_LOG_H_ #define _DBG_LOG_H_ #include <stdio.h> #include <string.h> #include <stdarg.h> /* Defines debug level of the logger: * 0 - no debug information * 1 - errors messages * 2 - warnings messages + level 1 * 3 - information messages + level 1 and 2 */ #define DEBUG_LEVEL 0 /* Defines printf variant with or without floats printing support. * Switching off this option may reduce code size. */ #define DEBUG_FLOAT_PRINT_SUPPORT /* The maximum length of the debug message */ #define DBG_STR_MAX 120 #if DEBUG_LEVEL >= 1 #define dbg_log_error( fmtstr, ... ) debug( "[ERROR] (%s:%d)" fmtstr "\n", __FILE__, __LINE__, ##__VA_ARGS__ ) #else #define dbg_log_error( fmtstr, ... ) #endif #if DEBUG_LEVEL >= 2 #define dbg_log_warning( fmtstr, ... ) debug( "[WARNING] (%s:%d)" fmtstr "\n", __FILE__, __LINE__, ##__VA_ARGS__ ) #else #define dbg_log_warning( fmtstr, ... ) #endif #if DEBUG_LEVEL >= 3 #define dbg_log_info( fmtstr, ... ) debug( "[INFO] (%s:%d)" fmtstr "\n", __FILE__, __LINE__, ##__VA_ARGS__ ) #else #define dbg_log_info( fmtstr, ... ) #endif /* This function is used as a base function for debug output. Should not be used directly by the applications. Macroses should be used instead. */ void debug( const char * fmtstr, ... ); #endif // _DGB_LOG_H_
2.3125
2
2024-11-18T21:09:16.128394+00:00
2019-03-12T11:51:34
5e0face82acdd17c0159dc32d28139b6253f5730
{ "blob_id": "5e0face82acdd17c0159dc32d28139b6253f5730", "branch_name": "refs/heads/master", "committer_date": "2019-03-12T11:51:34", "content_id": "2d553cdf1890240f4b19a1cbeda541af8b545382", "detected_licenses": [ "MIT" ], "directory_id": "f50271ce1a641e54564430ff69b401ab1d422445", "extension": "h", "filename": "io.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 175198891, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 824, "license": "MIT", "license_type": "permissive", "path": "/lib/kernel/io.h", "provenance": "stackv2-0065.json.gz:106", "repo_name": "Yu2erer/BearOS", "revision_date": "2019-03-12T11:51:34", "revision_id": "cb7ef91217e59de999ff1b4801fbe280a86b2662", "snapshot_id": "17d822380eb6bfcc569378cd52e96aac5da18d8a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Yu2erer/BearOS/cb7ef91217e59de999ff1b4801fbe280a86b2662/lib/kernel/io.h", "visit_date": "2020-04-28T10:21:44.246352" }
stackv2
#ifndef __LIB_IO_H #define __LIB_IO_H #include "stdint.h" // 向端口 写一个字节 static inline void outb(uint16_t port, uint8_t data) { // 机器模式 b 寄存器低8位al w寄存器2个字节ax q一个字节 N: 0~255立即数 asm volatile("outb %b0, %w1": : "a"(data), "Nd"(port)); } // 将addr的n个字 写入 port static inline void outsw(uint16_t port, const void* addr, uint32_t word_cnt) { asm volatile("cld; rep outsw": "+S"(addr), "+c"(word_cnt): "d"(port)); } // 读一个字节 static inline uint8_t inb(uint16_t port) { uint8_t data; asm volatile("inb %w1, %b0": "=a"(data): "Nd"(port)); return data; } static inline void insw(uint16_t port, const void* addr, uint32_t word_cnt) { asm volatile ("cld; rep insw" : "+D" (addr), "+c" (word_cnt): "d" (port) : "memory"); } #endif
2.359375
2
2024-11-18T21:09:16.196444+00:00
2023-05-23T01:50:34
3006f72e92fe17bc855a8f798da0f0e11e2b150a
{ "blob_id": "3006f72e92fe17bc855a8f798da0f0e11e2b150a", "branch_name": "refs/heads/master", "committer_date": "2023-05-23T01:50:34", "content_id": "27bc5fa0deca4b6b9a99613a4e429f85cfe2eedf", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8fceb4702c2e1f9521793e95e87a9621debd625d", "extension": "c", "filename": "riscv_cmplx_math.c", "fork_events_count": 14, "gha_created_at": "2019-12-27T02:22:55", "gha_event_created_at": "2021-06-07T01:11:49", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 230358080, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14046, "license": "Apache-2.0", "license_type": "permissive", "path": "/NMSIS/DSP/Test/ComplexMathFunctions/riscv_cmplx_math.c", "provenance": "stackv2-0065.json.gz:236", "repo_name": "Nuclei-Software/NMSIS", "revision_date": "2023-05-23T01:50:34", "revision_id": "3d9a71ab8e090fac01ea434b045d548671814e69", "snapshot_id": "763ba90a1aa7cfaa990872d8c42f931dd502838b", "src_encoding": "UTF-8", "star_events_count": 51, "url": "https://raw.githubusercontent.com/Nuclei-Software/NMSIS/3d9a71ab8e090fac01ea434b045d548671814e69/NMSIS/DSP/Test/ComplexMathFunctions/riscv_cmplx_math.c", "visit_date": "2023-05-25T11:08:41.502162" }
stackv2
// // Created by lujun on 19-6-28. // // This contains complx calculate in Conjugate, Dot Product, Magnitude, // Magnitude Squared, by-Complex Multiplication, by-Real Multiplication each one // has it's own function. All function can be found in main function. If you // don't want to use it, then comment it. contains following functions,eachone // includes q15,q31 and f32 versions #include "riscv_math.h" #include <stdint.h> #include "../common.h" #include "../HelperFunctions/math_helper.c" #include "../HelperFunctions/ref_helper.c" #include <stdio.h> #include <stdlib.h> #define ENABLE_ALL #ifdef ENABLE_ALL #define CMPLXMAG #define CMPLXDOTPRODUCT #define CONJ #define MAGSQUARED #define CMPLXMULT #define CMPLXMULTREAL #endif // Array for ComplxMathFunctions part1 #define ARRAY_SIZE 64 float32_t f32_pSrcA[ARRAY_SIZE * 2]; float32_t f32_pSrcB[ARRAY_SIZE * 2]; float32_t f32_pDst[ARRAY_SIZE * 2]; float32_t f32_pDst_ref[ARRAY_SIZE * 2]; q31_t q31_pSrcA[ARRAY_SIZE * 2]; q31_t q31_pSrcB[ARRAY_SIZE * 2]; q31_t q31_pDst[ARRAY_SIZE * 2]; q31_t q31_pDst_ref[ARRAY_SIZE * 2]; q15_t q15_pSrcA[ARRAY_SIZE * 2]; q15_t q15_pSrcB[ARRAY_SIZE * 2]; q15_t q15_pDst[ARRAY_SIZE * 2]; q15_t q15_pDst_ref[ARRAY_SIZE * 2]; int test_flag_error = 0; int8_t s, s1; BENCH_DECLARE_VAR(); /* ********************************************************************************************************* * DSP_MagSquared ********************************************************************************************************* */ static int DSP_MagSquared(void) { /***F32*******************************************************************************/ BENCH_START(riscv_cmplx_mag_squared_f32); riscv_cmplx_mag_squared_f32(f32_pSrcA, f32_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mag_squared_f32); ref_cmplx_mag_squared_f32(f32_pSrcA, f32_pDst_ref, ARRAY_SIZE); s = verify_results_f32(f32_pDst_ref, f32_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mag_squared_f32); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mag_squared_f32); /***Q31*******************************************************************************/ BENCH_START(riscv_cmplx_mag_squared_q31); riscv_cmplx_mag_squared_q31(q31_pSrcA, q31_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mag_squared_q31); ref_cmplx_mag_squared_q31(q31_pSrcA, q31_pDst_ref, ARRAY_SIZE); s = verify_results_q31(q31_pDst_ref, q31_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mag_squared_q31); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mag_squared_q31); /***Q15*******************************************************************************/ BENCH_START(riscv_cmplx_mag_squared_q15); riscv_cmplx_mag_squared_q15(q15_pSrcA, q15_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mag_squared_q15); ref_cmplx_mag_squared_q15(q15_pSrcA, q15_pDst_ref, ARRAY_SIZE); s = verify_results_q15(q15_pDst_ref, q15_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mag_squared_q15); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mag_squared_q15); } /* ********************************************************************************************************* * DSP_CmplxMult ********************************************************************************************************* */ static int DSP_CmplxMult(void) { /***F32*******************************************************************************/ BENCH_START(riscv_cmplx_mult_cmplx_f32); riscv_cmplx_mult_cmplx_f32(f32_pSrcA, f32_pSrcB, f32_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mult_cmplx_f32); ref_cmplx_mult_cmplx_f32(f32_pSrcA, f32_pSrcB, f32_pDst_ref, ARRAY_SIZE); s = verify_results_f32(f32_pDst_ref, f32_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mult_cmplx_f32); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mult_cmplx_f32); /***Q31*******************************************************************************/ BENCH_START(riscv_cmplx_mult_cmplx_q31); riscv_cmplx_mult_cmplx_q31(q31_pSrcA, q31_pSrcB, q31_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mult_cmplx_q31); ref_cmplx_mult_cmplx_q31(q31_pSrcA, q31_pSrcB, q31_pDst_ref, ARRAY_SIZE); s = verify_results_q31(q31_pDst_ref, q31_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mult_cmplx_q31); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mult_cmplx_q31); /***Q15*******************************************************************************/ BENCH_START(riscv_cmplx_mult_cmplx_q15); riscv_cmplx_mult_cmplx_q15(q15_pSrcA, q15_pSrcB, q15_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mult_cmplx_q15); ref_cmplx_mult_cmplx_q15(q15_pSrcA, q15_pSrcB, q15_pDst_ref, ARRAY_SIZE); s = verify_results_q15(q15_pDst_ref, q15_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mult_cmplx_q15); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mult_cmplx_q15); } /* ********************************************************************************************************* * DSP_CmplxMultReal ********************************************************************************************************* */ static int DSP_CmplxMultReal(void) { /***F32*******************************************************************************/ BENCH_START(riscv_cmplx_mult_real_f32); riscv_cmplx_mult_real_f32(f32_pSrcA, f32_pSrcB, f32_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mult_real_f32); ref_cmplx_mult_real_f32(f32_pSrcA, f32_pSrcB, f32_pDst_ref, ARRAY_SIZE); s = verify_results_f32(f32_pDst_ref, f32_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mult_real_f32); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mult_real_f32); /***Q31*******************************************************************************/ BENCH_START(riscv_cmplx_mult_real_q31); riscv_cmplx_mult_real_q31(q31_pSrcA, q31_pSrcB, q31_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mult_real_q31); ref_cmplx_mult_real_q31(q31_pSrcA, q31_pSrcB, q31_pDst_ref, ARRAY_SIZE); s = verify_results_q31(q31_pDst_ref, q31_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mult_real_q31); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mult_real_q31); /***Q15*******************************************************************************/ BENCH_START(riscv_cmplx_mult_real_q15); riscv_cmplx_mult_real_q15(q15_pSrcA, q15_pSrcB, q15_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mult_real_q15); ref_cmplx_mult_real_q15(q15_pSrcA, q15_pSrcB, q15_pDst_ref, ARRAY_SIZE); s = verify_results_q15(q15_pDst_ref, q15_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mult_real_q15); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mult_real_q15); } /* ********************************************************************************************************* * DSP_CONJ ********************************************************************************************************* */ static int DSP_CONJ(void) { /***F32*******************************************************************************/ BENCH_START(riscv_cmplx_conj_f32); riscv_cmplx_conj_f32(f32_pSrcA, f32_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_conj_f32); ref_cmplx_conj_f32(f32_pSrcA, f32_pDst_ref, ARRAY_SIZE); s = verify_results_f32(f32_pDst_ref, f32_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_conj_f32); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_conj_f32); /***Q31*******************************************************************************/ BENCH_START(riscv_cmplx_conj_q31); riscv_cmplx_conj_q31(q31_pSrcA, q31_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_conj_q31); ref_cmplx_conj_q31(q31_pSrcA, q31_pDst_ref, ARRAY_SIZE); s = verify_results_q31(q31_pDst_ref, q31_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_conj_q31); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_conj_q31); /***Q15*******************************************************************************/ BENCH_START(riscv_cmplx_conj_q15); riscv_cmplx_conj_q15(q15_pSrcA, q15_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_conj_q15); ref_cmplx_conj_q15(q15_pSrcA, q15_pDst_ref, ARRAY_SIZE); s = verify_results_q15(q15_pDst_ref, q15_pDst, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_conj_q15); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_conj_q15); } /* ********************************************************************************************************* * DSP_CmplxDotProduct ********************************************************************************************************* */ static int DSP_CmplxDotProduct(void) { float32_t f32_realResult; float32_t f32_imagResult; float32_t f32_realResult_ref; float32_t f32_imagResult_ref; q63_t q63_realResult; q63_t q63_imagResult; q63_t q63_realResult_ref; q63_t q63_imagResult_ref; q31_t q31_realResult; q31_t q31_imagResult; q31_t q31_realResult_ref; q31_t q31_imagResult_ref; /***F32*******************************************************************************/ BENCH_START(riscv_cmplx_dot_prod_f32); riscv_cmplx_dot_prod_f32(f32_pSrcA, f32_pSrcB, ARRAY_SIZE, &f32_realResult, &f32_imagResult); BENCH_END(riscv_cmplx_dot_prod_f32); ref_cmplx_dot_prod_f32(f32_pSrcA, f32_pSrcB, ARRAY_SIZE, &f32_realResult_ref, &f32_imagResult_ref); s = verify_results_f32(&f32_realResult, &f32_realResult_ref, 1); s1 = verify_results_f32(&f32_imagResult, &f32_imagResult_ref, 1); if (s != 0 || s1 != 0) { BENCH_ERROR(riscv_cmplx_dot_prod_f32); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_dot_prod_f32); /***Q31*******************************************************************************/ BENCH_START(riscv_cmplx_dot_prod_q31); riscv_cmplx_dot_prod_q31(q31_pSrcA, q31_pSrcB, ARRAY_SIZE, &q63_realResult, &q63_imagResult); BENCH_END(riscv_cmplx_dot_prod_q31); ref_cmplx_dot_prod_q31(q31_pSrcA, q31_pSrcB, ARRAY_SIZE, &q63_realResult_ref, &q63_imagResult_ref); s = verify_results_q63(&q63_realResult, &q63_realResult_ref, 1); s1 = verify_results_q63(&q63_imagResult, &q63_imagResult_ref, 1); if (s != 0 || s1 != 0) { BENCH_ERROR(riscv_cmplx_dot_prod_q31); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_dot_prod_q31); /***Q15*******************************************************************************/ BENCH_START(riscv_cmplx_dot_prod_q15); riscv_cmplx_dot_prod_q15(q15_pSrcA, q15_pSrcB, ARRAY_SIZE, &q31_realResult, &q31_imagResult); BENCH_END(riscv_cmplx_dot_prod_q15); ref_cmplx_dot_prod_q15(q15_pSrcA, q15_pSrcB, ARRAY_SIZE, &q31_realResult_ref, &q31_imagResult_ref); s = verify_results_q31(&q31_realResult, &q31_realResult_ref, 1); s1 = verify_results_q31(&q31_imagResult, &q31_imagResult_ref, 1); if (s != 0 || s1 != 0) { BENCH_ERROR(riscv_cmplx_dot_prod_q15); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_dot_prod_q15); } /* ********************************************************************************************************* * DSP_CmplxMag ********************************************************************************************************* */ static int DSP_CmplxMag(void) { /***F32*******************************************************************************/ BENCH_START(riscv_cmplx_mag_f32); riscv_cmplx_mag_f32(f32_pSrcA, f32_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mag_f32); ref_cmplx_mag_f32(f32_pSrcA, f32_pDst_ref, ARRAY_SIZE); s = verify_results_f32(f32_pDst, f32_pDst_ref, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mag_f32); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mag_f32); /***Q31*******************************************************************************/ BENCH_START(riscv_cmplx_mag_q31); riscv_cmplx_mag_q31(q31_pSrcA, q31_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mag_q31); ref_cmplx_mag_q31(q31_pSrcA, q31_pDst_ref, ARRAY_SIZE); s = verify_results_q31_low_precision(q31_pDst, q31_pDst_ref, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mag_q31); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mag_q31); /***Q15*******************************************************************************/ BENCH_START(riscv_cmplx_mag_q15); riscv_cmplx_mag_q15(q15_pSrcA, q15_pDst, ARRAY_SIZE); BENCH_END(riscv_cmplx_mag_q15); ref_cmplx_mag_q15(q15_pSrcA, q15_pDst_ref, ARRAY_SIZE); s = verify_results_q15_low_precision(q15_pDst, q15_pDst_ref, ARRAY_SIZE); if (s != 0) { BENCH_ERROR(riscv_cmplx_mag_q15); test_flag_error = 1; } BENCH_STATUS(riscv_cmplx_mag_q15); } int main(void) { BENCH_INIT(); generate_rand_q15(q15_pSrcA, ARRAY_SIZE * 2); generate_rand_q15(q15_pSrcB, ARRAY_SIZE * 2); generate_rand_q31(q31_pSrcA, ARRAY_SIZE * 2); generate_rand_q31(q31_pSrcB, ARRAY_SIZE * 2); generate_rand_f32(f32_pSrcA, ARRAY_SIZE * 2); generate_rand_f32(f32_pSrcB, ARRAY_SIZE * 2); #ifdef CMPLXMAG DSP_CmplxMag(); #endif #ifdef CMPLXDOTPRODUCT DSP_CmplxDotProduct(); #endif #ifdef CONJ DSP_CONJ(); #endif #ifdef MAGSQUARED DSP_MagSquared(); #endif #ifdef CMPLXMULT DSP_CmplxMult(); #endif #ifdef CMPLXMULTREAL DSP_CmplxMultReal(); #endif if (test_flag_error) { printf("test error apprears, please recheck.\n"); return 1; } else { printf("all test are passed. Well done!\n"); } return 0; }
2.328125
2
2024-11-18T21:09:16.355144+00:00
2019-02-27T21:37:37
ea8af641d7719c67dee087fa661e85f492b4146f
{ "blob_id": "ea8af641d7719c67dee087fa661e85f492b4146f", "branch_name": "refs/heads/onvm", "committer_date": "2019-02-27T21:37:37", "content_id": "7956719ce3d5b2f8641865efa2d40562858ca08b", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "269480ac5fba84ede20bd2286eb0630656282f6b", "extension": "c", "filename": "pktgen-seq.c", "fork_events_count": 2, "gha_created_at": "2017-02-01T23:39:16", "gha_event_created_at": "2019-02-27T21:37:38", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 80675987, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3895, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/app/pktgen-seq.c", "provenance": "stackv2-0065.json.gz:364", "repo_name": "sdnfv/onvm-pktgen", "revision_date": "2019-02-27T21:37:37", "revision_id": "48067fb9704b24de0124a4c10d89086b82265f51", "snapshot_id": "1248f02bc29129be249b4732a1fb9d153a243f5e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/sdnfv/onvm-pktgen/48067fb9704b24de0124a4c10d89086b82265f51/app/pktgen-seq.c", "visit_date": "2021-01-25T06:56:45.125448" }
stackv2
/*- * Copyright (c) <2010-2019>, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ /* Created 2010 by Keith Wiles @ intel.com */ #include <rte_lua.h> #include "pktgen-display.h" #include "pktgen.h" void pktgen_send_seq_pkt(port_info_t *info, uint32_t seq_idx) { (void)info; (void)seq_idx; } /**************************************************************************//** * * pktgen_page_seq - Display the sequence port data on the screen. * * DESCRIPTION * For a given port display the sequence packet data. * * RETURNS: N/A * * SEE ALSO: */ void pktgen_page_seq(uint32_t pid) { uint32_t i, row, col, sav; port_info_t *info; pkt_seq_t *pkt; char buff[128]; pktgen_display_set_color("top.page"); display_topline("<Sequence Page>"); info = &pktgen.info[pid]; pktgen_display_set_color("top.ports"); row = PORT_STATE_ROW; col = 1; scrn_printf(row, col, "Port: %2d, Sequence Count: %2d of %2d ", pid, info->seqCnt, NUM_SEQ_PKTS); pktgen_display_set_color("stats.stat.label"); scrn_printf(row++, col + 97, "GTP-u"); scrn_printf(row++, col, "%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s", 3, "Seq", 15, "Dst MAC", 15, "Src MAC", 16, "Dst IP", 18, "Src IP", 12, "Port S/D", 16, "Protocol:VLAN", 8, "CoS/ToS", 5, "TEID", 17, "Flag/Group/vxlan", 6, "Size"); pktgen_display_set_color("stats.stat.values"); scrn_fgcolor(SCRN_DEFAULT_FG, SCRN_NO_ATTR); sav = row; for (i = 0; i <= NUM_SEQ_PKTS; i++) { if (i >= info->seqCnt) scrn_eol_pos(row++, col); } row = sav; for (i = 0; i < info->seqCnt; i++) { pkt = &info->seq_pkt[i]; col = 1; scrn_printf(row, col, "%2d:", i); col += 3; snprintf(buff, sizeof(buff), "%02x%02x:%02x%02x:%02x%02x", pkt->eth_dst_addr.addr_bytes[0], pkt->eth_dst_addr.addr_bytes[1], pkt->eth_dst_addr.addr_bytes[2], pkt->eth_dst_addr.addr_bytes[3], pkt->eth_dst_addr.addr_bytes[4], pkt->eth_dst_addr.addr_bytes[5]); scrn_printf(row, col, "%*s", 15, buff); col += 15; snprintf(buff, sizeof(buff), "%02x%02x:%02x%02x:%02x%02x", pkt->eth_src_addr.addr_bytes[0], pkt->eth_src_addr.addr_bytes[1], pkt->eth_src_addr.addr_bytes[2], pkt->eth_src_addr.addr_bytes[3], pkt->eth_src_addr.addr_bytes[4], pkt->eth_src_addr.addr_bytes[5]); scrn_printf(row, col, "%*s", 15, buff); col += 15; scrn_printf(row, col, "%*s", 16, inet_ntop4(buff, sizeof(buff), htonl(pkt->ip_dst_addr.addr.ipv4.s_addr), 0xFFFFFFFF)); col += 16; scrn_printf(row, col, "%*s", 16 + 2, inet_ntop4(buff, sizeof(buff), htonl(pkt->ip_src_addr.addr.ipv4.s_addr), pkt->ip_mask)); col += 18; snprintf(buff, sizeof(buff), "%d/%d", pkt->sport, pkt->dport); scrn_printf(row, col, "%*s", 12, buff); col += 12; snprintf(buff, sizeof(buff), "%s/%s:%04x", (pkt->ethType == ETHER_TYPE_IPv4) ? "IPv4" : (pkt->ethType == ETHER_TYPE_IPv6) ? "IPv6" : "Other", (pkt->ipProto == PG_IPPROTO_TCP) ? "TCP" : (pkt->ipProto == PG_IPPROTO_ICMP) ? "ICMP" : "UDP", pkt->vlanid); scrn_printf(row, col, "%*s", 16, buff); col += 16; snprintf(buff, sizeof(buff), "%3d/%3d", pkt->cos, pkt->tos); scrn_printf(row, col, "%*s", 8, buff); col += 8; scrn_printf(row, col, "%5d", pkt->gtpu_teid); col += 6; snprintf(buff, sizeof(buff), "%04x/%5d/%5d", pkt->vni_flags, pkt->group_id, pkt->vxlan_id); scrn_printf(row, col, "%*s", 16, buff); col += 16; scrn_printf(row, col, "%6d", pkt->pktSize + ETHER_CRC_LEN); row++; } display_dashline(row + 2); pktgen_display_set_color(NULL); }
2.21875
2
2024-11-18T21:09:16.576131+00:00
2017-10-01T09:15:59
5f8179afbfaa2f9e8e23c39c5f66cb39d4e4a5a7
{ "blob_id": "5f8179afbfaa2f9e8e23c39c5f66cb39d4e4a5a7", "branch_name": "refs/heads/master", "committer_date": "2017-10-01T09:15:59", "content_id": "e4da5c363038a6f5ffb913885adfde896e69d4f4", "detected_licenses": [ "Artistic-2.0" ], "directory_id": "7f65f4ae925f3dfec96d6d51c4f3e1ac4df80970", "extension": "h", "filename": "config.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 30803313, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1157, "license": "Artistic-2.0", "license_type": "permissive", "path": "/config.h", "provenance": "stackv2-0065.json.gz:620", "repo_name": "srcx/shttpd", "revision_date": "2017-10-01T09:15:59", "revision_id": "96ebd218b143afcf6c9df5aebf65941f1781a56c", "snapshot_id": "e000ec1c957258b74ab4b8dedff853df93f20cb4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/srcx/shttpd/96ebd218b143afcf6c9df5aebf65941f1781a56c/config.h", "visit_date": "2021-01-25T05:34:27.297968" }
stackv2
/* shttpd (c)1999,2000 Stepan Roh * see license.txt for copying */ /* config.h * zpracovani konfiguracnich souboru */ #ifndef SHTTPD_CONFIG_H #define SHTTPD_CONFIG_H #include "global.h" #include "utils.h" typedef struct { int min_threads; /* min. pocet bezicich vlaken */ int max_threads; /* max. pocet bezicich vlaken */ int port; /* port pro cekani na spojeni */ char *access_log; /* jmeno access_log souboru */ char *error_log; /* jmeno error_log souboru */ int log_level; /* min. log level pro error_log */ int error_log_stderr; /* kopirovat error log na stderr ? */ char *doc_root; /* koren dokumentu */ int remote_names; /* zda-li se maji prekladat IP adresy na jmena */ sarray_item_t *status_page; /* pole odpovedi pri chybovych stavech */ char *index_file; /* jmeno defaultniho index souboru */ char *media_type; /* defaultni media (MIME) typ */ char *media_config; /* soubor s konfiguraci media typu */ } server_config_t; extern server_config_t server_config; /* nacteni konfigurace */ int load_config (char *fname); /* zruseni konfigurace */ void done_config (void); #endif
2.015625
2
2024-11-18T21:09:16.642165+00:00
2020-10-01T14:09:55
a0e22df28558d6acca9394f0d00762ec6def6770
{ "blob_id": "a0e22df28558d6acca9394f0d00762ec6def6770", "branch_name": "refs/heads/master", "committer_date": "2020-10-01T14:09:55", "content_id": "a8f11ed10b8fdf9973b2f677055b091546c7ff84", "detected_licenses": [ "MIT" ], "directory_id": "4f83056c14b2bb57bba7af464771d51f20e89783", "extension": "c", "filename": "read_words.c", "fork_events_count": 0, "gha_created_at": "2020-10-01T13:58:51", "gha_event_created_at": "2020-10-01T13:58:52", "gha_language": null, "gha_license_id": "MIT", "github_id": 300299011, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 459, "license": "MIT", "license_type": "permissive", "path": "/read_words/read_words.c", "provenance": "stackv2-0065.json.gz:748", "repo_name": "rishikasoni67/100DaysOfCode", "revision_date": "2020-10-01T14:09:55", "revision_id": "532ee760da2ae19cee7be57e5fd1f18f05972fbe", "snapshot_id": "8d3dcc6b67402f0700348c53a6c81e04a1dd9c91", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rishikasoni67/100DaysOfCode/532ee760da2ae19cee7be57e5fd1f18f05972fbe/read_words/read_words.c", "visit_date": "2022-12-25T19:58:36.816894" }
stackv2
#include <stdio.h> #include <string.h> #include <stdlib.h> #define str_size 100 void main() { char str[str_size]; int i, wrd; printf("Input the string : "); fgets(str, sizeof str, stdin); i = 0; wrd = 1; while(str[i]!='\0') { if(str[i]==' ' || str[i]=='\n' || str[i]=='\t') { wrd++; } i++; } printf("Total number of words in the string is : %d\n", wrd-1); }
3.1875
3
2024-11-18T21:09:16.963736+00:00
2019-12-19T11:02:44
dfd6b82eede7f732716c1ff17b6b7173c457d92f
{ "blob_id": "dfd6b82eede7f732716c1ff17b6b7173c457d92f", "branch_name": "refs/heads/timing", "committer_date": "2019-12-19T11:03:15", "content_id": "1284d7714d342088ff66b795af457691cd203c27", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "a05a902689118666b27844938ca8a3463abbcef8", "extension": "c", "filename": "btb_spy.c", "fork_events_count": 2, "gha_created_at": "2019-12-19T02:59:44", "gha_event_created_at": "2020-05-13T10:36:55", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 228963312, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2227, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/apps/side-bench/src/mastik/btb_spy.c", "provenance": "stackv2-0065.json.gz:1261", "repo_name": "SEL4PROJ/channel-bench", "revision_date": "2019-12-19T11:02:44", "revision_id": "4fbaaa644ca9f1dc8faa1e17c2c557579afd13a0", "snapshot_id": "ee73e979393829568f025c78d9c19ffa4467e78f", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/SEL4PROJ/channel-bench/4fbaaa644ca9f1dc8faa1e17c2c557579afd13a0/apps/side-bench/src/mastik/btb_spy.c", "visit_date": "2023-04-29T18:57:18.666135" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <sel4/sel4.h> #include "../mastik_common/low.h" #include <channel-bench/bench_common.h> #include <channel-bench/bench_types.h> #define JMP_ALIGN 16 #define BTB_ENTRIES (4096*2) extern void btb_probe(void); static void btb_jmp(uint32_t s) { /*calculate the jump entry based on the secret*/ unsigned long entry = (unsigned long)btb_probe + (BTB_ENTRIES - s) * JMP_ALIGN; #ifdef CONFIG_ARCH_X86_64 asm volatile ("callq %0" : : "r" (entry): ); #else asm volatile ("call %0" : : "r" (entry): ); #endif } int btb_trojan(bench_env_t *env) { uint32_t total_sec = 128 + 1, secret; seL4_MessageInfo_t info; bench_args_t *args = env->args; /*receive the shared address to record the secret*/ volatile uint32_t *share_vaddr = (uint32_t *)args->shared_vaddr; info = seL4_MessageInfo_new(seL4_Fault_NullFault, 0, 0, 1); seL4_SetMR(0, 0); seL4_Send(args->r_ep, info); /*ready to do the test*/ seL4_Send(args->ep, info); for (int i = 0; i < CONFIG_BENCH_DATA_POINTS; i++) { /*waiting for a system tick*/ newTimeSlice(); /*trojan: 3584 - 3712*/ secret = (random() % total_sec ) + 3584; /*do the probe*/ btb_jmp(secret); /*update the secret read by low*/ *share_vaddr = secret; } while (1); return 0; } int btb_spy(bench_env_t *env) { seL4_Word badge; seL4_MessageInfo_t info; uint32_t start; bench_args_t *args = env->args; /*the record address*/ struct bench_l1 *r_addr = (struct bench_l1 *)args->record_vaddr; /*the shared address*/ volatile uint32_t *secret = (uint32_t*)args->shared_vaddr; /*syn with trojan*/ info = seL4_Recv(args->ep, &badge); assert(seL4_MessageInfo_get_label(info) == seL4_Fault_NullFault); for (int i = 0; i < CONFIG_BENCH_DATA_POINTS; i++) { newTimeSlice(); start = rdtscp(); btb_jmp(4096); r_addr->result[i] = rdtscp() - start; r_addr->sec[i] = *secret; } /*send result to manager, spy is done*/ info = seL4_MessageInfo_new(seL4_Fault_NullFault, 0, 0, 1); seL4_SetMR(0, 0); seL4_Send(args->r_ep, info); while (1); return 0; }
2.25
2
2024-11-18T21:09:18.534782+00:00
2016-07-07T22:53:20
722256dfccc1c6a7486f3bf97957ebd588c3426b
{ "blob_id": "722256dfccc1c6a7486f3bf97957ebd588c3426b", "branch_name": "refs/heads/master", "committer_date": "2016-07-07T22:53:20", "content_id": "aab5e35ead56fcd47cfe1812b845d682cd9d0841", "detected_licenses": [ "MIT" ], "directory_id": "e873307e708756d709b4f8e180756ef1453de96a", "extension": "c", "filename": "wiring_pulse.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": 967, "license": "MIT", "license_type": "permissive", "path": "/libPropelleruino/wiring_pulse.c", "provenance": "stackv2-0065.json.gz:2162", "repo_name": "bas051969/libArduino", "revision_date": "2016-07-07T22:53:20", "revision_id": "6141a44075d8df994012c6bf20a2e11da4eebb6d", "snapshot_id": "e82ddeba3170fbaf022d3bb5fef3949ccfbf4574", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bas051969/libArduino/6141a44075d8df994012c6bf20a2e11da4eebb6d/libPropelleruino/wiring_pulse.c", "visit_date": "2021-01-10T23:36:22.291039" }
stackv2
/** * @file wiring_pulse.c * @brief Provides Arduino types and functions on the Propeller * * Copyright (c) 2013 by Martin Heermance * MIT Licensed */ #include <Arduino.h> static const int Us = 1000000; static int32_t Pulsin_clk(int32_t Pin, int32_t State) { int32_t Duration = 0; DIRA &= ~(1<<Pin); CTRA = 0; if (State == 1) { CTRA = (0x68800000 | Pin); } else { CTRA = (0x54800000 | Pin); } FRQA = 1; waitpne((State << Pin), ((1<<Pin))); PHSA = 0; waitpeq((State << Pin), ((1<<Pin))); waitpne((State << Pin), ((1<<Pin))); Duration = PHSA; CTRA = 0; return Duration; } unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout) { int32_t Duration = 0; Duration = (((Pulsin_clk(pin, state) / Us) / 2) + 1); return Duration; } void pulseOut(uint8_t pin, unsigned long duration) { digitalWrite(pin, HIGH); duration = max(duration - 20, 1); delayMicroseconds(duration); digitalWrite(pin, LOW); }
2.59375
3
2024-11-18T21:09:18.754050+00:00
2020-04-15T07:24:19
d9a6c15db38c284555b17d4993c501c9bdac728f
{ "blob_id": "d9a6c15db38c284555b17d4993c501c9bdac728f", "branch_name": "refs/heads/master", "committer_date": "2020-04-15T07:24:19", "content_id": "55d2bee415aff7b27ebe395dd370c2bc02553869", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "f3f3c677fd6fd6d399661d5b1d4fe01b062314e1", "extension": "c", "filename": "curses_erase.c", "fork_events_count": 4, "gha_created_at": "2015-08-02T02:56:43", "gha_event_created_at": "2016-06-29T10:10:52", "gha_language": "C", "gha_license_id": null, "github_id": 40067024, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 498, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/curses/curses_erase.c", "provenance": "stackv2-0065.json.gz:2418", "repo_name": "Zirias/clang-libdos", "revision_date": "2020-04-15T07:24:19", "revision_id": "63e20a4cd75efe56a8133ad484c7c066cff965cc", "snapshot_id": "3eb2afdb3c05b29c3c19fae412216cc03769dea5", "src_encoding": "UTF-8", "star_events_count": 49, "url": "https://raw.githubusercontent.com/Zirias/clang-libdos/63e20a4cd75efe56a8133ad484c7c066cff965cc/src/curses/curses_erase.c", "visit_date": "2021-01-17T14:42:27.302352" }
stackv2
#include <curses.h> int werase(WINDOW *win) { chtype ech = (win->bkgd & 0xff00) | 0x20; if (win->parent) { for (int r = win->row - win->parent->row; r < win->row - win->parent->row + win->rows; ++r) { for (int c = win->col - win->parent->col; c < win->col - win->parent->col + win->cols; ++c) { win->parent->data[r*win->parent->cols + c] = ech; } } return OK; } for (int i = 0; i < win->rows * win->cols; ++i) win->data[i] = ech; return OK; }
2.328125
2
2024-11-18T21:09:20.044257+00:00
2018-12-29T14:03:10
2e0ae7c41c28dddca9f85e068dd6f5405789359b
{ "blob_id": "2e0ae7c41c28dddca9f85e068dd6f5405789359b", "branch_name": "refs/heads/master", "committer_date": "2018-12-29T14:03:10", "content_id": "a9f54f2d49dadca42af3ba471f82e9eab39efe88", "detected_licenses": [ "Unlicense" ], "directory_id": "fe60e562ca86a0cf28dfac5535ebf339c0ada44d", "extension": "c", "filename": "system_init.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": 1390, "license": "Unlicense", "license_type": "permissive", "path": "/src/x86_64/kernel/system/system_init.c", "provenance": "stackv2-0065.json.gz:2933", "repo_name": "jdonszelmann/osdev", "revision_date": "2018-12-29T14:03:10", "revision_id": "83803c72e50dba308979e985e54709dba412dcfc", "snapshot_id": "06522c2bb59da26ca082f0f959fa2ccf2ada877d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jdonszelmann/osdev/83803c72e50dba308979e985e54709dba412dcfc/src/x86_64/kernel/system/system_init.c", "visit_date": "2023-06-21T05:03:52.696676" }
stackv2
#include <stdio.h> #include <serial.h> #include <stdio.h> #include <vga.h> #include <interrupts.h> #include <gdt.h> #include <util.h> #include <debug.h> #include <memory.h> #include <paging.h> #include <drivers.h> #include <timer.h> #include <keyboard.h> #include <rtc.h> #define INIT_SYSTEM(name, func, args...) \ vga_setfgcolor(Green); \ printf("initializing %s...\n", name); \ vga_setfgcolor(Yellow); \ if(MACROCAT(func)(args)) { \ vga_setfgcolor(Green); \ printf("%s initialized succesfully\n", name); \ } else { \ PANIC("initializing " name " failed (func: " #func ")"); \ } void system_init() { // allways first, else printing will triple fault kernel_set_printer(vga_putc); vga_cls(); INIT_SYSTEM("serial", init_serial); INIT_SYSTEM("gdt & tss", init_gdt); add_driver_loader("timer",init_timer); add_driver_loader("keyboard",init_keyboard); add_driver_loader("rtc", rtc_init); INIT_SYSTEM("idt", init_idt); INIT_SYSTEM("memory", init_memory, 1024*1024*1024); //1GB for now. TODO: read memory map INIT_SYSTEM("paging", init_paging); INIT_SYSTEM("heap", init_kheap); //vga_cls(); vga_resetcolors(); }
2.109375
2
2024-11-18T21:09:20.126553+00:00
2020-11-16T23:33:50
a8334f2df8fee8106643dfd362c783503b090ea8
{ "blob_id": "a8334f2df8fee8106643dfd362c783503b090ea8", "branch_name": "refs/heads/master", "committer_date": "2020-11-16T23:33:50", "content_id": "2455def0ccbe9fa72bab04416b5b4f99f7e0af2a", "detected_licenses": [ "MIT" ], "directory_id": "daa1e20975fc9cfaf692945667b60a7f1a02a06e", "extension": "c", "filename": "ps.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": 1180, "license": "MIT", "license_type": "permissive", "path": "/src/ps.c", "provenance": "stackv2-0065.json.gz:3061", "repo_name": "Sawndip/hb-cairo", "revision_date": "2020-11-16T23:33:50", "revision_id": "5c4b8ff68c84922049c8416d449a3e355cfff1e3", "snapshot_id": "a0ae49f1dfb94d02d1852d762a6c0e7daa9bdd6e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Sawndip/hb-cairo/5c4b8ff68c84922049c8416d449a3e355cfff1e3/src/ps.c", "visit_date": "2023-01-09T23:46:39.963465" }
stackv2
/* * Cairo library: ps * * Copyright 2011 Mindaugas Kavaliauskas <dbtopas at dbtopas.lt> * */ #include "hbcairo.h" HB_FUNC( CAIRO_PS_SURFACE_CREATE ) { #ifdef CAIRO_HAS_PS_SURFACE hb_cairo_surface_ret( cairo_ps_surface_create( hb_parc( 1 ), hb_parnd( 2 ), hb_parnd( 3 ) ) ); #else hb_retptr( NULL ); #endif } HB_FUNC( CAIRO_PS_SURFACE_SET_SIZE ) { #ifdef CAIRO_HAS_PS_SURFACE cairo_surface_t * pSurface = hb_cairo_surface_param( 1 ); if( pSurface ) cairo_ps_surface_set_size( pSurface, hb_parnd( 2 ), hb_parnd( 3 ) ); #else /* Parameter validation */ hb_cairo_surface_param( 1 ); #endif } HB_FUNC( CAIRO_PS_SURFACE_SET_EPS ) { #ifdef CAIRO_HAS_PS_SURFACE cairo_surface_t * pSurface = hb_cairo_surface_param( 1 ); if( pSurface ) cairo_ps_surface_set_eps( pSurface, hb_parl( 2 ) ); #else /* Parameter validation */ hb_cairo_surface_param( 1 ); #endif } HB_FUNC( CAIRO_PS_SURFACE_GET_EPS ) { #ifdef CAIRO_HAS_PS_SURFACE cairo_surface_t * pSurface = hb_cairo_surface_param( 1 ); if( pSurface ) hb_retl( cairo_ps_surface_get_eps( pSurface ) ); #else /* Parameter validation */ hb_cairo_surface_param( 1 ); #endif }
2.046875
2
2024-11-18T21:09:20.192099+00:00
2020-12-12T13:11:36
010060a83650489973b5538bde6ffb2c1e3d425f
{ "blob_id": "010060a83650489973b5538bde6ffb2c1e3d425f", "branch_name": "refs/heads/master", "committer_date": "2020-12-12T13:11:36", "content_id": "f7948c3a86ce12c7169464f08683a523ffcd89e8", "detected_licenses": [ "MIT" ], "directory_id": "161c1c93850003bf8328d75defd56d1182f1b067", "extension": "c", "filename": "prioqueue.c", "fork_events_count": 3, "gha_created_at": "2018-09-28T13:32:10", "gha_event_created_at": "2019-04-11T16:55:13", "gha_language": "C", "gha_license_id": "MIT", "github_id": 150745229, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2271, "license": "MIT", "license_type": "permissive", "path": "/Algo-2018/TP-05-06/bakery/prioqueue.c", "provenance": "stackv2-0065.json.gz:3190", "repo_name": "Caucorico/ESIPE", "revision_date": "2020-12-12T13:11:36", "revision_id": "473a40b5ac5751c5bfaddeabb81d6e7568589fa7", "snapshot_id": "30aca7c675632611fde8b31b42d7cd2b920d49a8", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Caucorico/ESIPE/473a40b5ac5751c5bfaddeabb81d6e7568589fa7/Algo-2018/TP-05-06/bakery/prioqueue.c", "visit_date": "2021-06-23T17:25:45.956747" }
stackv2
#include <stdlib.h> #include <stdio.h> #include "event.h" typedef struct _link { event* e; struct _link* next; } link; typedef struct _prioqueue { link* first; int size; } prioqueue; prioqueue *create_pq() { prioqueue* new_pq = (prioqueue*)malloc(sizeof(prioqueue)); if ( new_pq == NULL ) return NULL; new_pq->first = NULL; new_pq->size = 0; return new_pq; } void free_pq(prioqueue *q) { link* buff; link* last_buff; if ( q != NULL ) { buff = q->first; while ( buff != NULL ) { last_buff = buff; buff = buff->next; if ( last_buff->e != NULL ) { if ( last_buff->e->c != NULL ) { free_customer( last_buff->e->c ); } free_event( last_buff->e ); } free(last_buff); } free(q); } } int size_pq(prioqueue *q) { if ( q != NULL ) return q->size; else return -1; } void insert_pq(prioqueue *q, event *e) { link* buff; link* new_link = (link*)malloc(sizeof(link)); if ( new_link != NULL ) { new_link->e = e; if ( q->first == NULL ) { new_link->next = NULL; q->first = new_link; q->size++; } else { buff = q->first; if ( buff->e->etime >= e->etime ) { new_link->next = buff; q->first = new_link; q->size++; } else { while ( buff->next != NULL && buff->next->e->etime < e->etime ) buff = buff->next; new_link->next = buff->next; buff->next = new_link; q->size++; } } } } void display_pq(prioqueue *pq) { link* buff = pq->first; while ( buff != NULL ) { printf("%d~", buff->e->etime); buff = buff->next; } putchar('\n'); } event* remove_min_pq(prioqueue *q) { link* buff = q->first; event* ev; if ( buff == NULL ) return NULL; q->first = buff->next; q->size--; ev = buff->e; free(buff); return ev; }
3.09375
3
2024-11-18T21:09:20.418238+00:00
2016-05-18T14:23:57
294f024b84010ea68b66582d74c5ef735358337b
{ "blob_id": "294f024b84010ea68b66582d74c5ef735358337b", "branch_name": "refs/heads/master", "committer_date": "2016-05-18T14:23:57", "content_id": "50a00cf01731effb4b8eaf5e31740b61247d6e1e", "detected_licenses": [ "MIT" ], "directory_id": "6ced3392371eb12d134be4dbe66244c0251402c3", "extension": "c", "filename": "xclass.c", "fork_events_count": 1, "gha_created_at": "2015-02-19T16:11:30", "gha_event_created_at": "2019-11-19T20:01:47", "gha_language": "D", "gha_license_id": "MIT", "github_id": 31023723, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1831, "license": "MIT", "license_type": "permissive", "path": "/examples/misc/operator/xclass.c", "provenance": "stackv2-0065.json.gz:3446", "repo_name": "John-Colvin/pyd", "revision_date": "2016-05-18T14:23:57", "revision_id": "ff27d4ec4ac2e3fcb716b1f272598b3db4e2302c", "snapshot_id": "20abf4eabb0671c2216fabe82ccf1783ee2f0cad", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/John-Colvin/pyd/ff27d4ec4ac2e3fcb716b1f272598b3db4e2302c/examples/misc/operator/xclass.c", "visit_date": "2020-04-05T13:42:44.917927" }
stackv2
#include <Python.h> #include <stdio.h> typedef struct { } x_XObject; static PyTypeObject x_XType = { PyObject_HEAD_INIT(NULL) 0,/*ob_size*/ "x.X", /*tp_name*/ sizeof(x_XObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "X objects", /* tp_doc */ }; static PyMethodDef x_methods[] = { {NULL} /*sentinal*/ }; PyObject *x_add(PyObject * arg1, PyObject * arg2) { return Py_BuildValue("OO", arg1, arg2); } #ifndef PyMODINIT_FUNC #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC initx(void) { PyObject* m; x_XType.tp_new = PyType_GenericNew; x_XType.tp_as_number = (PyNumberMethods *) malloc(sizeof(PyNumberMethods)); memset(x_XType.tp_as_number, 0, sizeof(PyNumberMethods)); x_XType.tp_as_number->nb_add = &x_add; // this is important! x_XType.tp_flags |= Py_TPFLAGS_CHECKTYPES; if(PyType_Ready(&x_XType) < 0) return; m = Py_InitModule3("x", x_methods, "Hi ho, pipsissiwa is slow"); Py_INCREF(&x_XType); PyModule_AddObject(m, "X", (PyObject *)&x_XType); }
2.09375
2
2024-11-18T21:09:21.318793+00:00
2019-09-28T15:10:20
5ef54407743db63f52b9fdc4d9ea82d3877f5ee4
{ "blob_id": "5ef54407743db63f52b9fdc4d9ea82d3877f5ee4", "branch_name": "refs/heads/master", "committer_date": "2019-09-28T15:10:20", "content_id": "fe7009c0502372eaecb0b5b64a865b89294dd9d5", "detected_licenses": [ "MIT" ], "directory_id": "afaeecbfd1d1a4cc9a7cdd7a0b637ffbac7f8ece", "extension": "c", "filename": "parser.c", "fork_events_count": 0, "gha_created_at": "2019-05-24T17:09:06", "gha_event_created_at": "2022-12-08T05:46:35", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 188460098, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11410, "license": "MIT", "license_type": "permissive", "path": "/Runner/lib/parser.c", "provenance": "stackv2-0065.json.gz:3704", "repo_name": "Coestaris/Zomboid3D.Nevermind", "revision_date": "2019-09-28T15:10:20", "revision_id": "dd6ff91cc95c2b51eb2ab879255b1c1d162b1fa4", "snapshot_id": "58f80ca271f1ae2b9a2ebd0dd501897288f1bb65", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/Coestaris/Zomboid3D.Nevermind/dd6ff91cc95c2b51eb2ab879255b1c1d162b1fa4/Runner/lib/parser.c", "visit_date": "2022-12-18T14:01:50.672122" }
stackv2
// // Created by maxim on 6/21/19. // #include "parser.h" uint16_t getChunkType(const uint8_t array[2]) { return array[1] << 8 | array[0]; } nmProgram_t* nmParserLoad(FILE* file) { uint8_t buffer[sizeof(nmbSignature)]; if(fread(buffer, sizeof(nmbSignature), 1, file) != 1) { nmPushError("Unable to read file signature"); return NULL; } for(size_t i = 0; i < sizeof(nmbSignature); i++) if(buffer[i] != nmbSignature[i]) { nmPushError("Wrong file signature"); return NULL; } nmProgram_t* program = malloc(sizeof(nmProgram_t)); program->sourceFilename = NULL; uint16_t chunkCount; if(fread(&chunkCount, sizeof(chunkCount), 1 ,file) != 1) { nmPushError("Unable to read chunk count"); free(program); return NULL; } for(size_t i = 0; i < chunkCount; i++) { uint32_t len; uint32_t crc; uint16_t type; uint8_t* dataBuffer; if(fread(&len, sizeof(len), 1 ,file) != 1) { nmPushError("Unable to read chunk length from file"); free(program); return NULL; } if(fread(&crc, sizeof(crc), 1, file) != 1) { nmPushError("Unable to read chunk crc from file"); free(program); return NULL; } if(fread(&type, sizeof(type), 1, file) != 1) { nmPushError("Unable to read chunk type from file"); free(program); return NULL; } dataBuffer = malloc(sizeof(uint8_t) * len); if(fread(dataBuffer, sizeof(uint8_t) * len, 1, file) != 1) { nmPushError("Unable to read data from file"); free(program); free(dataBuffer); return NULL; } uint32_t dataCrc = crc32(dataBuffer, len); if(dataCrc != crc) { nmPushErrorf("CRCs doesnt match. Calculated %X but expected %X", dataCrc, crc); free(program); free(dataBuffer); return NULL; } chunkHanlder_t* handler = NULL; for(size_t i = 0; i < chunkHanldersCount; i++) if(getChunkType(chunkHanlders[i].chunktype) == type) { handler = (chunkHanlder_t*)(&chunkHanlders[i]); break; } if(handler == NULL) { nmPushErrorf("Unknown chunk type: %c%c", type & 0xFF, (type >> 8) & 0xFF); free(program); free(dataBuffer); return NULL; } printf("[%li/%i]: Found chunk %c%c\n", i + 1, chunkCount, type & 0xFF, (type >> 8) & 0xFF); FILE* memStream = fmemopen(dataBuffer, len, "r"); if(!memStream) { nmPushError("Unable to open memstream"); free(program); free(dataBuffer); return NULL; } if(!handler->hanlder(program, memStream)) { nmPushError("Unable to parse chunk"); free(program); fclose(memStream); free(dataBuffer); return NULL; } fclose(memStream); free(dataBuffer); } return program; } nmProgram_t* nmParserFromFile(const char* filename) { FILE* file = fopen(filename, "rb"); if(!file) { nmPushErrorf("Unable to open file %s", filename); return NULL; } nmProgram_t* program = nmParserLoad(file); if(fclose(file) == EOF) { nmPushErrorf("Unable to close file %s", filename); return NULL; } return program; } #define readStr(ptr, lenType) { \ lenType len; \ if(fread(&len, sizeof(lenType), 1, file) != 1) return 0; \ ptr = malloc(sizeof(uint8_t) * len + 1); \ if(fread(ptr, sizeof(uint8_t) * len, 1, file) != 1) return 0; \ ptr[len] = '\0'; \ } #define readValue(ptr) if(fread(&ptr, sizeof(ptr), 1, file) != 1) return 0; uint8_t chunkhandler_header(nmProgram_t* program, FILE* file) { readValue(program->nmVersion); if(fread(program->sourceHash, sizeof(uint8_t) * 16, 1, file) != 1) return 0; readValue(program->importCount); readValue(program->funcCount); readValue(program->entryPointFuncIndex); program->imports = malloc(sizeof(nmImport_t*) * program->importCount); program->functions = malloc(sizeof(nmFunction_t*) * program->funcCount); program->globalsCount = 0; for(size_t i = 0; i < program->importCount; i++) { program->imports[i] = malloc(sizeof(nmImport_t)); readValue(program->imports[i]->isLib); readStr(program->imports[i]->moduleName, uint32_t); } return 1; } uint8_t chunkhandler_metadata(nmProgram_t* program, FILE* file) { program->metadata = malloc(sizeof(nmMetadata_t)); //Date readValue(program->metadata->compileDateTime.second); readValue(program->metadata->compileDateTime.minute); readValue(program->metadata->compileDateTime.hour); readValue(program->metadata->compileDateTime.day); readValue(program->metadata->compileDateTime.month); readValue(program->metadata->compileDateTime.year); readStr(program->metadata->binaryName, uint16_t); readStr(program->metadata->binaryDescription, uint16_t); readStr(program->metadata->binaryAuthor, uint16_t); readValue(program->metadata->minorVersion); readValue(program->metadata->majorVersion); return 1; } uint8_t chunkhandler_types(nmProgram_t* program, FILE* file) { uint32_t count; readValue(count); program->usedTypesCount = count; program->usedTypes = malloc(sizeof(nmType_t*) * count); for(size_t i = 0; i < count; i++) { program->usedTypes[i] = malloc(sizeof(nmType_t)); uint16_t signature; readValue(signature); program->usedTypes[i]->typeSignature = signature; readValue(program->usedTypes[i]->dim); readValue(program->usedTypes[i]->typeBase); program->usedTypes[i]->typeIndex = i; if(signature != tArray) program->usedTypes[i]->typeBase /= 8; } return 1; } uint8_t chunkhandler_constants(nmProgram_t* program, FILE* file) { uint32_t count; readValue(count); program->constantCount = count; program->constants = malloc(sizeof(nmConstant_t*) * count); for(size_t i = 0; i < count; i++) { program->constants[i] = malloc(sizeof(nmConstant_t)); readValue(program->constants[i]->typeIndex); readValue(program->constants[i]->len); program->constants[i]->typePtr = program->usedTypes[program->constants[i]->typeIndex]; size_t valueLen = program->constants[i]->typePtr->typeBase * program->constants[i]->len; program->constants[i]->value = malloc(valueLen); if(fread(program->constants[i]->value, valueLen, 1, file) != 1) return 0; } return 1; } uint8_t chunkhandler_functions(nmProgram_t* program, FILE* file) { uint32_t funcIndex; readValue(funcIndex); program->functions[funcIndex] = malloc(sizeof(nmFunction_t)); program->functions[funcIndex]->index = funcIndex; readValue(program->functions[funcIndex]->instructionsCount); readValue(program->functions[funcIndex]->localsCount); program->functions[funcIndex]->variableNames = NULL; program->functions[funcIndex]->variableSourceCharIndices = NULL; program->functions[funcIndex]->variableSourceLineIndices = NULL; program->functions[funcIndex]->name = NULL; program->functions[funcIndex]->localTypes = malloc( sizeof(uint32_t) * program->functions[funcIndex]->localsCount); for(size_t i = 0; i < program->functions[funcIndex]->localsCount; i++) readValue(program->functions[funcIndex]->localTypes[i]); readValue(program->functions[funcIndex]->regCount); program->functions[funcIndex]->regTypes = malloc( sizeof(uint32_t) * program->functions[funcIndex]->regCount); for(size_t i = 0; i < program->functions[funcIndex]->regCount; i++) readValue(program->functions[funcIndex]->regTypes[i]); program->functions[funcIndex]->instructions = malloc( sizeof(nmInstruction_t*) * program->functions[funcIndex]->instructionsCount); for(size_t i = 0; i < program->functions[funcIndex]->instructionsCount; i++) { program->functions[funcIndex]->instructions[i] = malloc(sizeof(nmInstruction_t)); uint16_t index; readValue(index); program->functions[funcIndex]->instructions[i]->dataPtr = getInstructionData(index); if(!program->functions[funcIndex]->instructions[i]->dataPtr) { printf("Unknown instruction 0x%X\n", index); return 0; } size_t count = getOperandsCount(program->functions[funcIndex]->instructions[i]->dataPtr); program->functions[funcIndex]->instructions[i]->parameters = malloc(sizeof(uint64_t) * count); for(size_t j = 0; j < count; j++) { program->functions[funcIndex]->instructions[i]->parameters[j] = 0; if(fread(&program->functions[funcIndex]->instructions[i]->parameters[j], getOperandSize(program->functions[funcIndex]->instructions[i]->dataPtr->parameterTypes[j]), 1, file) != 1) return 0; } } return 1; } uint8_t chunkhandler_debug(nmProgram_t* program, FILE* file) { readStr(program->sourceFilename, uint32_t); program->globalsNames = malloc(sizeof(char*) * program->globalsCount); program->globalsSourceLineIndices = malloc(sizeof(uint32_t) * program->globalsCount); program->globalsSourceCharIndices = malloc(sizeof(uint32_t) * program->globalsCount); for(size_t i = 0; i < program->globalsCount; i++) { readStr (program->globalsNames[i], uint32_t); readValue(program->globalsSourceLineIndices[i]); readValue(program->globalsSourceCharIndices[i]); } for(size_t i = 0; i < program->funcCount; i++) { readStr(program->functions[i]->name, uint32_t); readValue(program->functions[i]->sourceLineIndex); readValue(program->functions[i]->sourceCharIndex); program->functions[i]->variableNames = malloc(sizeof(char*) * program->functions[i]->localsCount); program->functions[i]->variableSourceLineIndices = malloc(sizeof(uint32_t) * program->functions[i]->localsCount); program->functions[i]->variableSourceCharIndices = malloc(sizeof(uint32_t) * program->functions[i]->localsCount); for(size_t j = 0; j < program->functions[i]->localsCount; j++) { readStr(program->functions[i]->variableNames[j], uint32_t); readValue(program->functions[i]->variableSourceLineIndices[j]); readValue(program->functions[i]->variableSourceCharIndices[j]); } } return 1; } uint8_t chunkhandler_globals(nmProgram_t* program, FILE* file) { readValue(program->globalsCount); program->globalsTypes = malloc(sizeof(uint32_t) * program->globalsCount); for(size_t i = 0; i < program->globalsCount; i++) { readValue(program->globalsTypes[i]); } }
2.671875
3
2024-11-18T21:09:22.653597+00:00
2023-06-18T14:24:56
c766ea92bb1387cb7289091596da002826462a3c
{ "blob_id": "c766ea92bb1387cb7289091596da002826462a3c", "branch_name": "refs/heads/master", "committer_date": "2023-06-18T14:24:56", "content_id": "fb13d3e3677f6a40e1abcc1d384c19cafdac7b3e", "detected_licenses": [ "MIT" ], "directory_id": "0abb8c8ec971028b35b8adf7310b6564becd3bbf", "extension": "c", "filename": "wx_scan.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 177630090, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5089, "license": "MIT", "license_type": "permissive", "path": "/track-executables/wx_scan.c", "provenance": "stackv2-0065.json.gz:3833", "repo_name": "lukasjenks/unixutilities", "revision_date": "2023-06-18T14:24:56", "revision_id": "56d33623a14263cbf88baca67bc1acb1483791ac", "snapshot_id": "8fb951a82fe6e0024baa508d9ef2aaabefa1dfbe", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lukasjenks/unixutilities/56d33623a14263cbf88baca67bc1acb1483791ac/track-executables/wx_scan.c", "visit_date": "2023-07-04T15:11:20.360332" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <ctype.h> // File entry filter function for use in scandir in main() that takes // a pointer to a dirent struct and determines if entry->d_name is // a string of digits, which represents a pid, and if so, returns 1, // and returns 0 in all other cases. int isdigit_filter(const struct dirent *entry) { // Check if string entry->d_name is a string of digits int index = 0; int isdigit = 1; while (index < strlen(entry->d_name)) { // If this if statement is ever entered, // entry->d_name is not a string of digits if (!isdigit(entry->d_name[index])) isdigit = 0; index = index + 1; } // Return 1 if string of digits if (isdigit == 1) { return 1; // Return 0 if not } else if (isdigit == 0) { return 0; } return 0; } // This function checks if the maps file at the location "path" // contains any memory with the "wx" permissions set by scanning // the file for one of the appropriate strings that represent this. // returns 1 if wx permissions are found, 0 in all other cases. int string_search(char *path) { FILE *mapsfile = fopen(path, "r"); // Allocate memory for where we'll store a read line from the maps file char *line = (char *)malloc(300 * sizeof(char)); // Make a copy pointer to do operations on so that we can free(line) // properly at the end of this function char *linecopy = line; linecopy[0] = '\0'; // fopen will have returned null if it was unable to read the mapsfile if (mapsfile == NULL) { free(line); return 0; } while (fgets(linecopy, 35, mapsfile)) { if ((strstr(linecopy, " rwxp ") != NULL) || (strstr(linecopy, " rwx- ") != NULL) || (strstr(linecopy, " -wxp ") != NULL) || (strstr(linecopy, " -wx- ") != NULL)) { fclose(mapsfile); free(line); return 1; } } fclose(mapsfile); free(line); return 0; } // Checks if a directory entry for a directory in /proc/ that represents // a pid contains "wx" permissions in its maps file by calling string_search // and returns 1 if the "wx" permission is found, 0 otherwise. int wx_filter(const struct dirent *entry) { // Check if "rwxp","rwx-" "-wxp" or "-wx-" is to be found in the file // "/proc/[entry->d_name]/maps" char *path = calloc(30, sizeof(char)); char *pathcopy = path; strcpy(pathcopy, "/proc/"); strcat(pathcopy, entry->d_name); strcat(pathcopy, "/maps"); // pathcopy now = "/proc/[pid]/maps" int has_wx_perms = string_search(pathcopy); if (has_wx_perms == 1) { free(path); return 1; } free(path); return 0; } int main(int argc, char **argv) { // PARSE COMMAND LINE ARGUMENTS, IF ANY: int kflag = 0; if (argc > 2) { fprintf(stderr, "Error; too many arguments given to wx_scan\n"); exit(-1); } else if (argc == 2) { if (strcmp("-k", argv[1]) == 0) { kflag = 1; } else { fprintf(stderr, "Error; invalid flag passed to wx_scan\n"); } } //GET RELEVANT INFO FROM PROC struct dirent **entryarray; int numentries; int has_wx_perms; pid_t pid; numentries = scandir("/proc/", &entryarray, isdigit_filter, alphasort); if (numentries < 0) { fprintf(stderr, "ERROR CALLING SCANDIR\n"); exit(-1); } else { // Subtract 1 to account for null terminator from numentries // to get the number of elements within entryarray, so that we // can iterate through the elements within entryarray numentries = numentries - 1; // Print newline at the beginning of output to match // the output on the assignment spec printf("\n"); while (numentries >= 0) { has_wx_perms = wx_filter(entryarray[numentries]); if (has_wx_perms == 1) { // Build a string which is the path to the // status file, so we can extract the executable // name from it char *statusfilepath = calloc(1024, sizeof(char)); char *line = calloc(1024, sizeof(char)); char *linecopy = line; strcpy(statusfilepath, "/proc/"); strcat(statusfilepath, entryarray[numentries]->d_name); strcat(statusfilepath, "/status"); // Open status file and extract the executable // name from the first line FILE *statusfile = fopen(statusfilepath, "r"); fgets(linecopy, 1000, statusfile); linecopy = strtok(linecopy, ":"); linecopy = strtok(NULL, "\t"); // (Now linecopy is executable name) fclose(statusfile); free(statusfilepath); // Regular mode (non-kill mode) if (kflag == 0) { printf("%s %s\n", entryarray[numentries]->d_name, linecopy); free(line); // Kill mode (k flag passed) } else if (kflag == 1) { printf("%s %s", entryarray[numentries]->d_name, linecopy); printf("Killing %s\n", entryarray[numentries]->d_name); pid = atoi(entryarray [numentries]->d_name); // kill process kill(pid, SIGKILL); free(line); } } free(entryarray[numentries]); numentries = numentries - 1; } free(entryarray); } return 0; }
3.03125
3
2024-11-18T21:09:22.726590+00:00
2020-11-14T15:23:19
170f8dfd4cc1e5821da7e27e9730aa07eb4b240c
{ "blob_id": "170f8dfd4cc1e5821da7e27e9730aa07eb4b240c", "branch_name": "refs/heads/main", "committer_date": "2020-11-14T15:23:19", "content_id": "bef1d0782b9ddabbce0673ddccd42745a76548d8", "detected_licenses": [ "MIT" ], "directory_id": "2d0235ef124eb8d4247acd149e86ac9123bd4c3c", "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": 312547366, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5237, "license": "MIT", "license_type": "permissive", "path": "/System_Programming/report5/kadai-bcde/main.c", "provenance": "stackv2-0065.json.gz:3961", "repo_name": "yoshi-ki/BACHELOR", "revision_date": "2020-11-14T15:23:19", "revision_id": "65d01c62ab2ea4a6d2616a6b6c535bd4f1645630", "snapshot_id": "0ece5db48a9b7efef7f1a4cdd0368e70ff1d72df", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yoshi-ki/BACHELOR/65d01c62ab2ea4a6d2616a6b6c535bd4f1645630/System_Programming/report5/kadai-bcde/main.c", "visit_date": "2023-01-08T14:02:42.800315" }
stackv2
#include <unistd.h> #include <stdio.h> #include <sys/wait.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <dirent.h> #include "parse.h" void print_job_list(job*); //環境変数を見る関数 char* lookpath(char* pr){ int flag = 0; struct dirent *dirst1; DIR *dp1 = opendir("/usr/local/bin/"); while((dirst1 = readdir(dp1)) != NULL) { if(strcmp(dirst1->d_name, pr) == 0){ flag = 1; break; } } closedir(dp1); struct dirent *dirst2; DIR *dp2 = opendir("/usr/sbin/"); while((dirst2 = readdir(dp2)) != NULL) { if(strcmp(dirst2->d_name, pr) == 0){ flag = 2; break; } } closedir(dp2); struct dirent *dirst3; DIR *dp3 = opendir("/usr/bin/"); while((dirst3 = readdir(dp3)) != NULL) { if(strcmp(dirst3->d_name, pr) == 0){ flag = 3; break; } } closedir(dp3); struct dirent *dirst4; DIR *dp4 = opendir("/sbin/"); while((dirst4 = readdir(dp4)) != NULL) { if(strcmp(dirst4->d_name, pr) == 0){ flag = 4; break; } } closedir(dp4); struct dirent *dirst5; DIR *dp5 = opendir("/bin/"); while((dirst5 = readdir(dp5)) != NULL) { if(strcmp(dirst5->d_name, pr) == 0){ flag = 5; break; } } closedir(dp5); if(flag == 1) {char temp[512] = "/usr/local/bin/";return strcat(temp, pr);} else if(flag == 2) {char temp[512] = "/usr/sbin/";return strcat(temp,pr);} else if(flag == 3) {char temp[512] = "/usr/bin"; return strcat(temp, pr);} else if(flag == 4) {char temp[512] = "/sbin/";return strcat(temp, pr);} else if(flag == 5) {char temp[512] = "/bin/";return strcat(temp, pr);} else {return "";} } void do_child (int i, int cmd_n, job * curr_job, char* argv[], char* envp[]){ pid_t ret; int pp[2] = {}; if(i == cmd_n - 1){ //最後に実行する部分(さいしょにforkする部分) process* pr = (curr_job->process_list); for(int c = 0; c < cmd_n - i - 1; c++){ pr = pr->next; } //環境変数を見るコード int x = 1; for (int i = 0 ; i < sizeof(pr->program_name); i++){ if((pr->program_name)[i] == '/') x = 0; } char pr_name[512]; if(x) { //環境変数をみる strcpy(pr_name, lookpath(pr->program_name)); }else{ strcpy(pr_name , pr->program_name); } if((pr->input_redirection)!=NULL){ int file_in; file_in = open((pr->input_redirection),O_RDONLY); close(0); dup2(file_in,0); close(file_in); } if((pr->output_redirection) != NULL){ int file_out; (pr->output_option) == TRUNC ? (file_out = open((pr->output_redirection),O_WRONLY|O_CREAT|O_EXCL,0666)) : (file_out = open((pr->output_redirection),O_WRONLY|O_APPEND|O_EXCL,0666)); close(1); dup2(file_out,1); close(file_out); } execve(pr_name,pr->argument_list,envp); return ; } else{ if (pipe(pp) == -1) perror("pipe error"); ret = fork(); if(ret < 0) perror("fork error"); if(ret == 0){ close(pp[0]); dup2(pp[1],1); close(pp[1]); do_child(i+1,cmd_n,curr_job,argv,envp); } else{ //親プロセス、stdinとつなげて、i番目を実行 close(pp[1]); dup2(pp[0],0); close(pp[0]); process* pr = (curr_job->process_list); for(int c = 0; c < cmd_n - i -1; c++){ pr = pr->next; } //ここから環境変数をみるコード int x = 1; for (int i = 0 ; i < sizeof(pr->program_name); i++){ if((pr->program_name)[i] == '/') x = 0; } char pr_name[512]; if(x) { //環境変数をみる strcpy(pr_name, lookpath(pr->program_name)); }else{ strcpy(pr_name , pr->program_name); } //ここまで if((pr->input_redirection)!=NULL){ int file_in; file_in = open((pr->input_redirection),O_RDONLY); close(0); dup2(file_in,0); close(file_in); } if((pr->output_redirection) != NULL){ int file_out; (pr->output_option) == TRUNC ? (file_out = open((pr->output_redirection),O_WRONLY|O_CREAT|O_EXCL,0666)) : (file_out = open((pr->output_redirection),O_WRONLY|O_APPEND|O_EXCL,0666)); close(1); dup2(file_out,1); close(file_out); } execve(pr_name,pr->argument_list,envp); } } } int main(int argc, char *argv[], char *envp[]) { char s[LINELEN]; job *curr_job; while(get_line(s, LINELEN)) { if(!strcmp(s, "exit\n")) break; pid_t pid; int status; pid = fork(); if(pid == 0){ curr_job = parse_line(s); //pipeでつながっているprocessの数を調べる int cmd_n = 1; process* hoge = (curr_job->process_list); while(1){ hoge = hoge->next; if(hoge == NULL) break; cmd_n++; } //ここから実行 do_child (0,cmd_n,curr_job,argv,envp); free_job(curr_job); exit(1); } else if(pid < 0) {perror("fork error"); exit(1);} else{ pid_t r = waitpid (-1, &status, WUNTRACED); if (r < 0){ perror("wait error"); } } } return 0; }
2.453125
2
2024-11-18T21:09:23.508889+00:00
2021-05-16T21:46:26
012fe1f372085ee0fcfb814bbd71696dca77fe64
{ "blob_id": "012fe1f372085ee0fcfb814bbd71696dca77fe64", "branch_name": "refs/heads/master", "committer_date": "2021-05-16T21:46:26", "content_id": "91356337b5165e6956023d4db8ef161c09f78f45", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0853c4c87ccdbda20ad3facc7702baf187ebc8dc", "extension": "h", "filename": "mdv_evt_trlog.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": 3348, "license": "Apache-2.0", "license_type": "permissive", "path": "/mdv_core/event/mdv_evt_trlog.h", "provenance": "stackv2-0065.json.gz:4348", "repo_name": "bellyfat/MedvedDB", "revision_date": "2021-05-16T21:46:26", "revision_id": "2c4b999871decd77ed12a8a9d0ec2f4a73215354", "snapshot_id": "0f4d0508a5234565b68a07153423d135435b457c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bellyfat/MedvedDB/2c4b999871decd77ed12a8a9d0ec2f4a73215354/mdv_core/event/mdv_evt_trlog.h", "visit_date": "2023-04-29T07:06:39.099296" }
stackv2
/** * @file mdv_evt_trlog.h * @author Vladislav Volkov (wwwvladislav@gmail.com) * @brief Transaction logs events definitions * @version 0.1 * @date 2019-11-12 * * @copyright Copyright (c) 2019, Vladislav Volkov * */ #pragma once #include <mdv_ebus.h> #include <mdv_uuid.h> #include "../storage/mdv_trlog.h" typedef struct { mdv_event base; mdv_uuid uuid; ///< Transaction log UUID (in) mdv_trlog *trlog; ///< Transaction log (out) bool create; ///< Flag indicates that new TR log should be created if TR log isn't exist. } mdv_evt_trlog; mdv_evt_trlog * mdv_evt_trlog_create(mdv_uuid const *uuid, bool create); mdv_evt_trlog * mdv_evt_trlog_retain(mdv_evt_trlog *evt); uint32_t mdv_evt_trlog_release(mdv_evt_trlog *evt); typedef struct { mdv_event base; mdv_uuid trlog; ///< Transaction log UUID } mdv_evt_trlog_changed; mdv_evt_trlog_changed * mdv_evt_trlog_changed_create(mdv_uuid const *trlog); mdv_evt_trlog_changed * mdv_evt_trlog_changed_retain(mdv_evt_trlog_changed *evt); uint32_t mdv_evt_trlog_changed_release(mdv_evt_trlog_changed *evt); typedef struct { mdv_event base; mdv_uuid trlog; ///< Transaction log UUID } mdv_evt_trlog_apply; mdv_evt_trlog_apply * mdv_evt_trlog_apply_create(mdv_uuid const *trlog); mdv_evt_trlog_apply * mdv_evt_trlog_apply_retain(mdv_evt_trlog_apply *evt); uint32_t mdv_evt_trlog_apply_release(mdv_evt_trlog_apply *evt); typedef struct { mdv_event base; mdv_uuid from; ///< Source peer UUID mdv_uuid to; ///< Destination peer UUID for synchronization mdv_uuid trlog; ///< Transaction log UUID } mdv_evt_trlog_sync; mdv_evt_trlog_sync * mdv_evt_trlog_sync_create(mdv_uuid const *trlog, mdv_uuid const *from, mdv_uuid const *to); mdv_evt_trlog_sync * mdv_evt_trlog_sync_retain(mdv_evt_trlog_sync *evt); uint32_t mdv_evt_trlog_sync_release(mdv_evt_trlog_sync *evt); typedef struct { mdv_event base; mdv_uuid from; ///< Source peer UUID mdv_uuid to; ///< Destination peer UUID for synchronization mdv_uuid trlog; ///< Transaction log UUID uint64_t top; ///< Transaction log last record identifier } mdv_evt_trlog_state; mdv_evt_trlog_state * mdv_evt_trlog_state_create(mdv_uuid const *trlog, mdv_uuid const *from, mdv_uuid const *to, uint64_t top); mdv_evt_trlog_state * mdv_evt_trlog_state_retain(mdv_evt_trlog_state *evt); uint32_t mdv_evt_trlog_state_release(mdv_evt_trlog_state *evt); typedef struct { mdv_event base; mdv_uuid from; ///< Source peer UUID mdv_uuid to; ///< Destination peer UUID for synchronization mdv_uuid trlog; ///< Transaction log UUID uint32_t count; ///< log records count mdv_list rows; ///< transaction log data (list<mdv_trlog_data>) } mdv_evt_trlog_data; mdv_evt_trlog_data * mdv_evt_trlog_data_create(mdv_uuid const *trlog, mdv_uuid const *from, mdv_uuid const *to, mdv_list *rows, uint32_t count); mdv_evt_trlog_data * mdv_evt_trlog_data_retain(mdv_evt_trlog_data *evt); uint32_t mdv_evt_trlog_data_release(mdv_evt_trlog_data *evt);
2.109375
2
2024-11-18T21:09:23.594865+00:00
2021-09-17T08:26:12
1e413dbb34512404c42467049b5aabb607982050
{ "blob_id": "1e413dbb34512404c42467049b5aabb607982050", "branch_name": "refs/heads/main", "committer_date": "2021-09-17T08:26:12", "content_id": "b214e845f543b36f41941b1f8e0ae124482e1029", "detected_licenses": [ "MIT" ], "directory_id": "30b563a46fa3aeff3e2365ad67a053752482e560", "extension": "c", "filename": "LA-5.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": 1127, "license": "MIT", "license_type": "permissive", "path": "/DSA LAB/Week-5/LA/LA-5.c", "provenance": "stackv2-0065.json.gz:4479", "repo_name": "Rohan-2107/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-lelo", "revision_date": "2021-09-17T08:26:12", "revision_id": "4f001bd24ebd32761a74b64585bbd227db1e3930", "snapshot_id": "2aae82f72b4209a6e5cce5c96b4900ce3784b94c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Rohan-2107/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-lelo/4f001bd24ebd32761a74b64585bbd227db1e3930/DSA LAB/Week-5/LA/LA-5.c", "visit_date": "2023-08-15T02:14:02.896874" }
stackv2
// Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or { ) occurs to the left of a closing bracket // (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). // A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. // WAP to determine whether the input sequence of brackets is balanced or not. If a string is balanced, // it print YES on a new line; otherwise, print NO on a new line. // Example: Input: {[()]} and Output: YES // Input: {[(])} and Output: NO #include<stdio.h> char stack[100]; int top = -1; void isValid(char* e){ while(*e != '\0'){ if(*e=='(' || *e=='{' || *e=='[')stack[++top] = *e; else if((stack[top]=='('&&*e==')') || (stack[top]=='{'&&*e=='}') || (stack[top]=='['&&*e==']'))top--; else {printf("NO\n");return;} if(top==-1){printf("YES\n");return;} else e++; } } int main(){ char input[100],*e; printf("Enter the bracket expression: "); scanf("%s",input); e=input; isValid(e); return 0; }
3.484375
3
2024-11-18T21:09:23.679088+00:00
2020-04-08T23:01:52
77207dd7f6ea87fc5e6c96136d0c4ec0527f2aa8
{ "blob_id": "77207dd7f6ea87fc5e6c96136d0c4ec0527f2aa8", "branch_name": "refs/heads/master", "committer_date": "2020-04-08T23:01:52", "content_id": "a70c5b4c9869d0af61ac040eb5ea549977ffc299", "detected_licenses": [ "MIT" ], "directory_id": "3da33ec54ea52bd8ea43784a5fe97c88add8b78b", "extension": "h", "filename": "sll.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 244518889, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2524, "license": "MIT", "license_type": "permissive", "path": "/src/include/sll.h", "provenance": "stackv2-0065.json.gz:4607", "repo_name": "openlunar/fc-bootloader", "revision_date": "2020-04-08T23:01:52", "revision_id": "793e42ea0095a5d1d767c1eca7e1d3a27b7f5599", "snapshot_id": "3bd09a1629ce629cbfb67b2c65bcc8b3b4f37e0d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/openlunar/fc-bootloader/793e42ea0095a5d1d767c1eca7e1d3a27b7f5599/src/include/sll.h", "visit_date": "2022-04-14T03:43:28.618135" }
stackv2
/** * @brief Stand-in Link Layer * * TODO: (10) [doc] Notes on nocopy implementation * * @author Logan Smith <logan@openlunar.org */ #ifdef __cplusplus extern "C" { #endif #ifndef SLL_H #define SLL_H #include <stdint.h> #define SLL_MAX_PAYLOD_LEN 128 #define SLL_OVERHEAD_LEN 5 #define SLL_MAX_MSG_LEN (SLL_MAX_PAYLOD_LEN + SLL_OVERHEAD_LEN) // 5 = 2 sync bytes, 1 length byte, 2 crc bytes // TODO: (10) [robustness] Assert (macro error) that SLL_MAX_MSG_LEN is lte to UINT8_T_MAX #define SLL_SYNC_SEQ_1 0x5A #define SLL_SYNC_SEQ_2 0x7E typedef enum { SLL_DECODE_SYNC1 = 0, // 0 SLL_DECODE_SYNC2, // 1 SLL_DECODE_LEN, // 2 SLL_DECODE_DATA, // 3 SLL_DECODE_CRC1, // 4 SLL_DECODE_CRC2, // 5 SLL_DECODE_N_STATES } sll_decode_state_t; // TODO: (0) [refactor] I'm going to try and make this entire structure "internal state" so // that the user shouldn't ever need to use it; It's still going to be declared // externally so that instances of it can be declared statically (without its // prototype the compiler can't allocate the correct amount of memory). // // TODO: (0) [refactor] Rename to sll_state_t // TODO: (0) [refactor] Remove _ctx sub-struct and reorganize fields typedef struct { uint32_t length; // Payload length // uint8_t data[SLL_MAX_PAYLOD_LEN]; uint8_t * data_buffer; uint8_t * frame_buffer; // -- Internal State -- // struct { // uint8_t * buffer; // Buffer used by codec sll_decode_state_t state; uint32_t idx; uint16_t crc; } _ctx; } sll_decode_frame_t; /** * @brief Initialize a SLL frame structure * * @param frame The frame * @param buffer The buffer * @param[in] buffer_len The buffer length * * @return { description_of_the_return_value } */ int sll_init( sll_decode_frame_t * const frame, uint8_t * buffer, const uint8_t buffer_len ); uint8_t * sll_get_data_buffer( sll_decode_frame_t * const frame ); // Only valid after sll_decode() returns 1 uint32_t sll_get_decoded_len( sll_decode_frame_t * const frame ); /** * @brief Execute the SLL decode FSM with the character 'c' * * @param frame The frame * @param[in] c { parameter_description } * * @return { description_of_the_return_value } */ int sll_decode( sll_decode_frame_t * frame, uint8_t c ); // no-copy prototype; the frame has the buffer references int sll_encode( sll_decode_frame_t * const frame, uint32_t data_len ); // int sll_encode( uint8_t * out_buffer, uint8_t * data, uint8_t len ); #endif // SLL_H
2.390625
2
2024-11-18T21:09:24.181649+00:00
2016-10-21T13:29:01
ba341da235f1de37f79c7a89f7fb486d4ddb59d6
{ "blob_id": "ba341da235f1de37f79c7a89f7fb486d4ddb59d6", "branch_name": "refs/heads/master", "committer_date": "2016-10-21T13:29:01", "content_id": "0f8657217abe2283490f12c742979d482d29b7a3", "detected_licenses": [ "MIT" ], "directory_id": "7725f7cc593c82b5403bb03e5668ee8f1662bc6c", "extension": "c", "filename": "generator.c", "fork_events_count": 0, "gha_created_at": "2016-10-21T06:15:43", "gha_event_created_at": "2016-10-21T06:15:43", "gha_language": null, "gha_license_id": null, "github_id": 71535515, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4257, "license": "MIT", "license_type": "permissive", "path": "/src/generator.c", "provenance": "stackv2-0065.json.gz:4736", "repo_name": "hmfrank/pwdgen", "revision_date": "2016-10-21T13:29:01", "revision_id": "932f7b496e42a36feac4f81a0a37ef282475f522", "snapshot_id": "5a3f1324d2f02a4e0228368ae84970766ee279b3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hmfrank/pwdgen/932f7b496e42a36feac4f81a0a37ef282475f522/src/generator.c", "visit_date": "2021-01-12T17:16:16.625438" }
stackv2
/* libscrypt requires size_t */ #include <stddef.h> #include <assert.h> #include <libscrypt.h> #include <math.h> #include <openssl/sha.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <generator.h> #include <globals.h> #include <hashTools.h> #include <interpreter.h> static void bundleInput(char *output, size_t outputLen); static int validatePwd(char *password); /** * Combines the global input parameters and stores the result in output. * Shape: account.len(account)@domain.len(domain):version * * @param output combination will be stored here * @param outputLen length of output */ static void bundleInput(char *output, size_t outputLen) { /* Sanity check */ assert(output != NULL && outputLen >= MAX_INPUT_LEN); strncpy(output, account, 256); snprintf(output + strlen(output), 6, ".%u@", (unsigned) strlen(account)); strncat(output, domain, 256); snprintf(output + strlen(output), 6, ".%u:", (unsigned) strlen(domain)); strncat(output, version, 16); } /** * Checks if a password is valid or not. * * @param password points to the to-be-checked password * @return 1 when password is valid, 0 otherwise */ static int validatePwd(char *password) { /* Sanity check */ assert(password != NULL); size_t length = strlen(password); int containsUpperCase = 0; int containsLowerCase = 0; for (size_t i = 0; i < length; i++) { if (65 <= password[i] && password[i] <= 90) { containsUpperCase = 1; } if (97 <= password[i] && password[i] <= 122) { containsLowerCase = 1; } } return containsUpperCase && containsLowerCase; } /** * Generates a costly scrypt digest from the master password and stores it * globally in `cache'. The generation should take ~1-2 minutes. * * @return taken time in seconds */ int generateCache() { uint8_t hashedMPwd[32] = {0}; clock_t begin = clock(); hashSHA256((uint8_t *) masterPwd, strlen(masterPwd), hashedMPwd, 32); for (int i = 0; i < 12; i++) { libscrypt_scrypt(hashedMPwd, 32, NULL, 0, pow(2, 21), 8, 1, cache, 32); /* TODO: Handle scrypt errors */ hashSHA256(cache, 32, hashedMPwd, 32); } memset(hashedMPwd, 0, 32); return (int) (clock() - begin) / CLOCKS_PER_SEC; } /** * Generates a password from the input parameters and the master password * and stores it in the global variable `password'. */ /* TODO: Add more detailed description */ void generatePwd() { uint8_t hashedMPwd[32] = {0}; uint8_t hashedInput[32] = {0}; uint8_t digest[194] = {0}; char buffer[MAX_INPUT_LEN + 32] = {0}; /* Program will end up in infinite loop otherwise */ /* If this occurs, some terrible mistake has happend */ assert(pwdLen >= 4); hashSHA256((uint8_t *) masterPwd, strlen(masterPwd), hashedMPwd, 32); bundleInput(buffer, MAX_INPUT_LEN); size_t inputLen = strlen(buffer); for (int i = 0; i < 32; i++) { buffer[inputLen++] = cache[i]; } hashSHA256((uint8_t *) buffer, inputLen, hashedInput, 32); if (debug) { printf("\nInput: `%.*s\' + Cache\n", (int) inputLen - 32, buffer); } do { /* password, len, salt, len, cost, block size, parallelisation, digest, len */ libscrypt_scrypt(hashedMPwd, 32, hashedInput, 32, pow(2, 17), 8, 1, digest, 194); /* TODO: Handle scrypt errors */ encodeBase64(digest, 192, buffer, 192 / 3 * 4 + 1); strncpy(password, buffer, pwdLen - 2); if (validatePwd(password)) { if (debug) { printf("Scrypt: `%s\' <Okay>\n", password); } break; } else { if (debug) { printf("Scrypt: `%s\' <Bad password>\n", password); } hashSHA256(hashedInput, 32, digest, 194); continue; } } while (1); interpretLastBits(digest); /* Erase confidential data */ memset(hashedMPwd, 0, 32); memset(hashedInput, 0, 32); memset(digest, 0, 194); memset(buffer, 0, MAX_INPUT_LEN + 32); }
2.625
3
2024-11-18T21:09:25.639203+00:00
2012-03-23T03:07:26
356133defb81ff9280975fd0dbde622b9cb3bac1
{ "blob_id": "356133defb81ff9280975fd0dbde622b9cb3bac1", "branch_name": "refs/heads/master", "committer_date": "2012-03-23T03:07:26", "content_id": "8b99b9b9d49f6268b353b8f2af392ddb69e37412", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "c72cfd5592a51876459e9cf5047a07ac89502ba4", "extension": "c", "filename": "th_tcl.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 3804829, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11523, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/th_tcl.c", "provenance": "stackv2-0065.json.gz:4993", "repo_name": "oopos/fossil", "revision_date": "2012-03-23T03:07:26", "revision_id": "a213b3e819ed0ce47b6a5a06270f44ae5d2bb6d0", "snapshot_id": "665eb05fb877a7094f9302f486b88bf952b004e9", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/oopos/fossil/a213b3e819ed0ce47b6a5a06270f44ae5d2bb6d0/src/th_tcl.c", "visit_date": "2021-01-01T16:05:25.150627" }
stackv2
/* ** This program is free software; you can redistribute it and/or ** modify it under the terms of the Simplified BSD License (also ** known as the "2-Clause License" or "FreeBSD License".) ** ** This program is distributed in the hope that it will be useful, ** but without any warranty; without even the implied warranty of ** merchantability or fitness for a particular purpose. ** ******************************************************************************* ** This file contains code used to bridge the TH1 and Tcl scripting languages. */ #include "config.h" #ifdef FOSSIL_ENABLE_TCL #include "th.h" #include "tcl.h" /* ** Are we being compiled against Tcl 8.6 or higher? */ #if (TCL_MAJOR_VERSION > 8) || \ ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 6)) /* ** Workaround NRE-specific issue in Tcl_EvalObjCmd (SF bug #3399564) by using ** Tcl_EvalObjv instead of invoking the objProc directly. */ #define USE_TCL_EVALOBJV 1 #endif /* ** These macros are designed to reduce the redundant code required to marshal ** arguments from TH1 to Tcl. */ #define USE_ARGV_TO_OBJV() \ int objc; \ Tcl_Obj **objv; \ int i; #define COPY_ARGV_TO_OBJV() \ objc = argc-1; \ objv = (Tcl_Obj **)ckalloc((unsigned)(objc * sizeof(Tcl_Obj *))); \ for(i=1; i<argc; i++){ \ objv[i-1] = Tcl_NewStringObj(argv[i], argl[i]); \ Tcl_IncrRefCount(objv[i-1]); \ } #define FREE_ARGV_TO_OBJV() \ for(i=1; i<argc; i++){ \ Tcl_DecrRefCount(objv[i-1]); \ } \ ckfree((char *)objv); /* ** Fetch the Tcl interpreter from the specified void pointer, cast to a Tcl ** context. */ #define GET_CTX_TCL_INTERP(ctx) \ ((struct TclContext *)(ctx))->interp /* ** Creates and initializes a Tcl interpreter for use with the specified TH1 ** interpreter. Stores the created Tcl interpreter in the Tcl context supplied ** by the caller. This must be declared here because quite a few functions in ** this file need to use it before it can be defined. */ static int createTclInterp(Th_Interp *interp, void *pContext); /* ** Returns the Tcl interpreter result as a string with the associated length. ** If the Tcl interpreter or the Tcl result are NULL, the length will be 0. ** If the length pointer is NULL, the length will not be stored. */ static char *getTclResult( Tcl_Interp *pInterp, int *pN ){ Tcl_Obj *resultPtr; if( !pInterp ){ /* This should not happen. */ if( pN ) *pN = 0; return 0; } resultPtr = Tcl_GetObjResult(pInterp); if( !resultPtr ){ /* This should not happen either? */ if( pN ) *pN = 0; return 0; } return Tcl_GetStringFromObj(resultPtr, pN); } /* ** Tcl context information used by TH1. This structure definition has been ** copied from and should be kept in sync with the one in "main.c". */ struct TclContext { int argc; char **argv; Tcl_Interp *interp; }; /* ** Syntax: ** ** tclEval arg ?arg ...? */ static int tclEval_command( Th_Interp *interp, void *ctx, int argc, const char **argv, int *argl ){ Tcl_Interp *tclInterp; Tcl_Obj *objPtr; int rc; int nResult; const char *zResult; if ( createTclInterp(interp, ctx)!=TH_OK ){ return TH_ERROR; } if( argc<2 ){ return Th_WrongNumArgs(interp, "tclEval arg ?arg ...?"); } tclInterp = GET_CTX_TCL_INTERP(ctx); if( !tclInterp || Tcl_InterpDeleted(tclInterp) ){ Th_ErrorMessage(interp, "invalid Tcl interpreter", (const char *)"", 0); return TH_ERROR; } Tcl_Preserve((ClientData)tclInterp); if( argc==2 ){ objPtr = Tcl_NewStringObj(argv[1], argl[1]); Tcl_IncrRefCount(objPtr); rc = Tcl_EvalObjEx(tclInterp, objPtr, 0); Tcl_DecrRefCount(objPtr); }else{ USE_ARGV_TO_OBJV(); COPY_ARGV_TO_OBJV(); objPtr = Tcl_ConcatObj(objc, objv); Tcl_IncrRefCount(objPtr); rc = Tcl_EvalObjEx(tclInterp, objPtr, 0); Tcl_DecrRefCount(objPtr); FREE_ARGV_TO_OBJV(); } zResult = getTclResult(tclInterp, &nResult); Th_SetResult(interp, zResult, nResult); Tcl_Release((ClientData)tclInterp); return rc; } /* ** Syntax: ** ** tclExpr arg ?arg ...? */ static int tclExpr_command( Th_Interp *interp, void *ctx, int argc, const char **argv, int *argl ){ Tcl_Interp *tclInterp; Tcl_Obj *objPtr; Tcl_Obj *resultObjPtr; int rc; int nResult; const char *zResult; if ( createTclInterp(interp, ctx)!=TH_OK ){ return TH_ERROR; } if( argc<2 ){ return Th_WrongNumArgs(interp, "tclExpr arg ?arg ...?"); } tclInterp = GET_CTX_TCL_INTERP(ctx); if( !tclInterp || Tcl_InterpDeleted(tclInterp) ){ Th_ErrorMessage(interp, "invalid Tcl interpreter", (const char *)"", 0); return TH_ERROR; } Tcl_Preserve((ClientData)tclInterp); if( argc==2 ){ objPtr = Tcl_NewStringObj(argv[1], argl[1]); Tcl_IncrRefCount(objPtr); rc = Tcl_ExprObj(tclInterp, objPtr, &resultObjPtr); Tcl_DecrRefCount(objPtr); }else{ USE_ARGV_TO_OBJV(); COPY_ARGV_TO_OBJV(); objPtr = Tcl_ConcatObj(objc, objv); Tcl_IncrRefCount(objPtr); rc = Tcl_ExprObj(tclInterp, objPtr, &resultObjPtr); Tcl_DecrRefCount(objPtr); FREE_ARGV_TO_OBJV(); } if( rc==TCL_OK ){ zResult = Tcl_GetStringFromObj(resultObjPtr, &nResult); }else{ zResult = getTclResult(tclInterp, &nResult); } Th_SetResult(interp, zResult, nResult); if( rc==TCL_OK ) Tcl_DecrRefCount(resultObjPtr); Tcl_Release((ClientData)tclInterp); return rc; } /* ** Syntax: ** ** tclInvoke command ?arg ...? */ static int tclInvoke_command( Th_Interp *interp, void *ctx, int argc, const char **argv, int *argl ){ Tcl_Interp *tclInterp; #ifndef USE_TCL_EVALOBJV Tcl_Command command; Tcl_CmdInfo cmdInfo; #endif int rc; int nResult; const char *zResult; #ifndef USE_TCL_EVALOBJV Tcl_Obj *objPtr; #endif USE_ARGV_TO_OBJV(); if ( createTclInterp(interp, ctx)!=TH_OK ){ return TH_ERROR; } if( argc<2 ){ return Th_WrongNumArgs(interp, "tclInvoke command ?arg ...?"); } tclInterp = GET_CTX_TCL_INTERP(ctx); if( !tclInterp || Tcl_InterpDeleted(tclInterp) ){ Th_ErrorMessage(interp, "invalid Tcl interpreter", (const char *)"", 0); return TH_ERROR; } Tcl_Preserve((ClientData)tclInterp); #ifndef USE_TCL_EVALOBJV objPtr = Tcl_NewStringObj(argv[1], argl[1]); Tcl_IncrRefCount(objPtr); command = Tcl_GetCommandFromObj(tclInterp, objPtr); if( !command || Tcl_GetCommandInfoFromToken(command,&cmdInfo)==0 ){ Th_ErrorMessage(interp, "Tcl command not found:", argv[1], argl[1]); Tcl_DecrRefCount(objPtr); Tcl_Release((ClientData)tclInterp); return TH_ERROR; } if( !cmdInfo.objProc ){ Th_ErrorMessage(interp, "Cannot invoke Tcl command:", argv[1], argl[1]); Tcl_DecrRefCount(objPtr); Tcl_Release((ClientData)tclInterp); return TH_ERROR; } Tcl_DecrRefCount(objPtr); #endif COPY_ARGV_TO_OBJV(); #ifdef USE_TCL_EVALOBJV rc = Tcl_EvalObjv(tclInterp, objc, objv, 0); #else Tcl_ResetResult(tclInterp); rc = cmdInfo.objProc(cmdInfo.objClientData, tclInterp, objc, objv); #endif FREE_ARGV_TO_OBJV(); zResult = getTclResult(tclInterp, &nResult); Th_SetResult(interp, zResult, nResult); Tcl_Release((ClientData)tclInterp); return rc; } /* ** Syntax: ** ** th1Eval arg */ static int Th1EvalObjCmd( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ Th_Interp *th1Interp; int nArg; const char *arg; int rc; if( objc!=2 ){ Tcl_WrongNumArgs(interp, 1, objv, "arg"); return TCL_ERROR; } th1Interp = (Th_Interp *)clientData; if( !th1Interp ){ Tcl_AppendResult(interp, "invalid TH1 interpreter", NULL); return TCL_ERROR; } arg = Tcl_GetStringFromObj(objv[1], &nArg); rc = Th_Eval(th1Interp, 0, arg, nArg); arg = Th_GetResult(th1Interp, &nArg); Tcl_SetObjResult(interp, Tcl_NewStringObj(arg, nArg)); return rc; } /* ** Syntax: ** ** th1Expr arg */ static int Th1ExprObjCmd( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ Th_Interp *th1Interp; int nArg; const char *arg; int rc; if( objc!=2 ){ Tcl_WrongNumArgs(interp, 1, objv, "arg"); return TCL_ERROR; } th1Interp = (Th_Interp *)clientData; if( !th1Interp ){ Tcl_AppendResult(interp, "invalid TH1 interpreter", NULL); return TCL_ERROR; } arg = Tcl_GetStringFromObj(objv[1], &nArg); rc = Th_Expr(th1Interp, arg, nArg); arg = Th_GetResult(th1Interp, &nArg); Tcl_SetObjResult(interp, Tcl_NewStringObj(arg, nArg)); return rc; } /* ** Array of Tcl integration commands. Used when adding or removing the Tcl ** integration commands from TH1. */ static struct _Command { const char *zName; Th_CommandProc xProc; void *pContext; } aCommand[] = { {"tclEval", tclEval_command, 0}, {"tclExpr", tclExpr_command, 0}, {"tclInvoke", tclInvoke_command, 0}, {0, 0, 0} }; /* ** Called if the Tcl interpreter is deleted. Removes the Tcl integration ** commands from the TH1 interpreter. */ static void Th1DeleteProc( ClientData clientData, Tcl_Interp *interp ){ int i; Th_Interp *th1Interp = (Th_Interp *)clientData; if( !th1Interp ) return; /* Remove the Tcl integration commands. */ for(i=0; i<(sizeof(aCommand)/sizeof(aCommand[0])); i++){ Th_RenameCommand(th1Interp, aCommand[i].zName, -1, NULL, 0); } } /* ** Creates and initializes a Tcl interpreter for use with the specified TH1 ** interpreter. Stores the created Tcl interpreter in the Tcl context supplied ** by the caller. */ static int createTclInterp( Th_Interp *interp, void *pContext ){ struct TclContext *tclContext = (struct TclContext *)pContext; Tcl_Interp *tclInterp; if ( !tclContext ){ Th_ErrorMessage(interp, "Invalid Tcl context", (const char *)"", 0); return TH_ERROR; } if ( tclContext->interp ){ return TH_OK; } if ( tclContext->argc>0 && tclContext->argv ) { Tcl_FindExecutable(tclContext->argv[0]); } tclInterp = tclContext->interp = Tcl_CreateInterp(); if( !tclInterp || Tcl_InterpDeleted(tclInterp) ){ Th_ErrorMessage(interp, "Could not create Tcl interpreter", (const char *)"", 0); return TH_ERROR; } if( Tcl_Init(tclInterp)!=TCL_OK ){ Th_ErrorMessage(interp, "Tcl initialization error:", Tcl_GetStringResult(tclInterp), -1); Tcl_DeleteInterp(tclInterp); tclContext->interp = tclInterp = 0; return TH_ERROR; } /* Add the TH1 integration commands to Tcl. */ Tcl_CallWhenDeleted(tclInterp, Th1DeleteProc, interp); Tcl_CreateObjCommand(tclInterp, "th1Eval", Th1EvalObjCmd, interp, NULL); Tcl_CreateObjCommand(tclInterp, "th1Expr", Th1ExprObjCmd, interp, NULL); return TH_OK; } /* ** Register the Tcl language commands with interpreter interp. ** Usually this is called soon after interpreter creation. */ int th_register_tcl( Th_Interp *interp, void *pContext ){ int i; /* Add the Tcl integration commands to TH1. */ for(i=0; i<(sizeof(aCommand)/sizeof(aCommand[0])); i++){ void *ctx; if ( !aCommand[i].zName || !aCommand[i].xProc ) continue; ctx = aCommand[i].pContext; /* Use Tcl interpreter for context? */ if( !ctx ) ctx = pContext; Th_CreateCommand(interp, aCommand[i].zName, aCommand[i].xProc, ctx, 0); } return TH_OK; } #endif /* FOSSIL_ENABLE_TCL */
2.296875
2
2024-11-18T21:09:26.061595+00:00
2023-08-20T06:13:11
8226a72c4f314f105bf39a1041d75753ba15777f
{ "blob_id": "8226a72c4f314f105bf39a1041d75753ba15777f", "branch_name": "refs/heads/master", "committer_date": "2023-08-20T06:13:11", "content_id": "a4396134d098428de1a453bc388bee83c15584b5", "detected_licenses": [ "MIT" ], "directory_id": "309e1045a872514f82e7b3987f97b38c28b03e41", "extension": "c", "filename": "cfftpack.c", "fork_events_count": 9, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 19373094, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8118, "license": "MIT", "license_type": "permissive", "path": "/rouziclib/libraries/cfftpack.c", "provenance": "stackv2-0065.json.gz:5380", "repo_name": "Photosounder/rouziclib", "revision_date": "2023-08-20T06:13:11", "revision_id": "fdc965964b13edf8c110fb1258d422856b5180dc", "snapshot_id": "ca51421f59389ed153cbd9598b7045772fdeed9b", "src_encoding": "UTF-8", "star_events_count": 43, "url": "https://raw.githubusercontent.com/Photosounder/rouziclib/fdc965964b13edf8c110fb1258d422856b5180dc/rouziclib/libraries/cfftpack.c", "visit_date": "2023-08-24T23:51:23.023879" }
stackv2
#ifndef RL_EXCL_CFFTPACK #include "orig/fftpack_float.c" #include "orig/fftpack_double.c" void cfft_plan_free(cfft_plan_t *plan) { if (plan==NULL) return ; free(plan->workf); free(plan->workd); free(plan->savef); free(plan->saved); memset(plan, 0, sizeof(cfft_plan_t)); } cfft_plan_t cfft_1D_create_plan(int n, const size_t elemsize) { cfft_plan_t plan={0}; int ret = 0; if (n == 0) return plan; plan.lensav = n*2 + (int) log2((double) n) + 8; plan.lenwork = 2 * n; plan.dim = xyi(n, 1); plan.elemsize = elemsize; if (elemsize == sizeof(float)) { plan.savef = calloc(plan.lensav, sizeof(float)); plan.workf = calloc(plan.lenwork, sizeof(float)); cfft1i_f(&n, plan.savef, &plan.lensav, &ret); } else { plan.saved = calloc(plan.lensav, sizeof(double)); plan.workd = calloc(plan.lenwork, sizeof(double)); cfft1i_d(&n, plan.saved, &plan.lensav, &ret); } if (ret) { fprintf_rl(stderr, "cfft1i_() returned %d in cfft_1D_create_plan()\n", ret); cfft_plan_free(&plan); } return plan; } cfft_plan_t cfft_2D_create_plan(xyi_t dim, const size_t elemsize) { cfft_plan_t plan={0}; int ret = 0; if (is0_xyi(dim)) return plan; plan.lensav = dim.x*2 + (int) log2((double) dim.x) + dim.y*2 + (int) log2((double) dim.y) + 8; plan.lenwork = 2 * dim.x * dim.y; plan.dim = dim; plan.elemsize = elemsize; if (elemsize == sizeof(float)) { plan.savef = calloc(plan.lensav, sizeof(float)); plan.workf = calloc(plan.lenwork, sizeof(float)); cfft2i_f(&dim.x, &dim.y, plan.savef, &plan.lensav, &ret); } else { plan.saved = calloc(plan.lensav, sizeof(double)); plan.workd = calloc(plan.lenwork, sizeof(double)); cfft2i_d(&dim.x, &dim.y, plan.saved, &plan.lensav, &ret); } if (ret) { fprintf_rl(stderr, "cfft2i_() returned %d in cfft_2D_create_plan()\n", ret); cfft_plan_free(&plan); } return plan; } int cfft_1D(cfft_plan_t *plan, void *data, const int way) { int ret = 0, inc=1; if (plan==NULL || data==NULL) return -1; if (plan->elemsize == sizeof(float)) { if (way==0) cfft1f_f(&plan->dim.x, &inc, (fft_complexf_t *) data, &plan->dim.x, plan->savef, &plan->lensav, plan->workf, &plan->lenwork, &ret); else cfft1b_f(&plan->dim.x, &inc, (fft_complexf_t *) data, &plan->dim.x, plan->savef, &plan->lensav, plan->workf, &plan->lenwork, &ret); } else { if (way==0) cfft1f_d(&plan->dim.x, &inc, (fft_complexd_t *) data, &plan->dim.x, plan->saved, &plan->lensav, plan->workd, &plan->lenwork, &ret); else cfft1b_d(&plan->dim.x, &inc, (fft_complexd_t *) data, &plan->dim.x, plan->saved, &plan->lensav, plan->workd, &plan->lenwork, &ret); } return ret; } int cfft_2D(cfft_plan_t *plan, void *data, const int way) { int ret = 0; if (plan==NULL || data==NULL) return -1; if (plan->elemsize == sizeof(float)) { if (way==0) cfft2f_f(&plan->dim.x, &plan->dim.x, &plan->dim.y, (fft_complexf_t *) data, plan->savef, &plan->lensav, plan->workf, &plan->lenwork, &ret); else cfft2b_f(&plan->dim.x, &plan->dim.x, &plan->dim.y, (fft_complexf_t *) data, plan->savef, &plan->lensav, plan->workf, &plan->lenwork, &ret); } else { if (way==0) cfft2f_d(&plan->dim.x, &plan->dim.x, &plan->dim.y, (fft_complexd_t *) data, plan->saved, &plan->lensav, plan->workd, &plan->lenwork, &ret); else cfft2b_d(&plan->dim.x, &plan->dim.x, &plan->dim.y, (fft_complexd_t *) data, plan->saved, &plan->lensav, plan->workd, &plan->lenwork, &ret); } return ret; } // Processing fft_complexf_t cfft_complex_mul_f(fft_complexf_t a, fft_complexf_t b) { fft_complexf_t r={0}; r.r = a.r*b.r - a.i*b.i; r.i = a.r*b.i + a.i*b.r; return r; } fft_complexd_t cfft_complex_mul_d(fft_complexd_t a, fft_complexd_t b) { fft_complexd_t r={0}; r.r = a.r*b.r - a.i*b.i; r.i = a.r*b.i + a.i*b.r; return r; } void cfft_complex_mul_2D_f(void *va, void *vb, void *vr, xyi_t dim) { int i, count; fft_complexf_t *a = va, *b = vb, *r = vr; count = mul_x_by_y_xyi(dim); for (i=0; i < count; i++) r[i] = cfft_complex_mul_f(a[i], b[i]); } void cfft_complex_mul_2D_d(void *va, void *vb, void *vr, xyi_t dim) { int i, count; fft_complexd_t *a = va, *b = vb, *r = vr; count = mul_x_by_y_xyi(dim); for (i=0; i < count; i++) r[i] = cfft_complex_mul_d(a[i], b[i]); } void cfft_copy_r2c_pad(void *in, const size_t in_elemsize, void **pout, const size_t out_elemsize, size_t *out_as, xyi_t in_dim, xyi_t out_dim) // makes a 0-padded complex copy { xyi_t ip; float *inf; double *ind; fft_complexf_t *outf; fft_complexd_t *outd; alloc_enough(pout, mul_x_by_y_xyi(out_dim), out_as, out_elemsize*2, 1.); memset(*pout, 0, mul_x_by_y_xyi(out_dim) * out_elemsize*2); outf = *pout; outd = *pout; inf = in; ind = in; if (out_elemsize == sizeof(float)) { if (in_elemsize == sizeof(float)) for (ip.y=0; ip.y < in_dim.y; ip.y++) for (ip.x=0; ip.x < in_dim.x; ip.x++) outf[ip.y*out_dim.x + ip.x].r = inf[ip.y*in_dim.x + ip.x]; else for (ip.y=0; ip.y < in_dim.y; ip.y++) for (ip.x=0; ip.x < in_dim.x; ip.x++) outf[ip.y*out_dim.x + ip.x].r = ind[ip.y*in_dim.x + ip.x]; } else { if (in_elemsize == sizeof(float)) for (ip.y=0; ip.y < in_dim.y; ip.y++) for (ip.x=0; ip.x < in_dim.x; ip.x++) outd[ip.y*out_dim.x + ip.x].r = inf[ip.y*in_dim.x + ip.x]; else for (ip.y=0; ip.y < in_dim.y; ip.y++) for (ip.x=0; ip.x < in_dim.x; ip.x++) outd[ip.y*out_dim.x + ip.x].r = ind[ip.y*in_dim.x + ip.x]; } } void cfft_copy_c2r(void *in, const size_t in_elemsize, void *out, const size_t out_elemsize, xyi_t dim) { int i, count = mul_x_by_y_xyi(dim); fft_complexf_t *inf = in; fft_complexd_t *ind = in; float *outf = out; double *outd = out; if (out_elemsize == sizeof(float)) { if (in_elemsize == sizeof(float)) for (i=0; i < count; i++) outf[i] = inf[i].r; else for (i=0; i < count; i++) outf[i] = ind[i].r; } else { if (in_elemsize == sizeof(float)) for (i=0; i < count; i++) outd[i] = inf[i].r; else for (i=0; i < count; i++) outd[i] = ind[i].r; } } void cfft_1D_c2c_fft(cfft_plan_t *plan, void *array, const size_t elemsize, int n) // when the input is already alloced, padded and complex { if (equal_xyi(plan->dim, xyi(n, 1))==0) // if we must recreate the plan { cfft_plan_free(plan); *plan = cfft_1D_create_plan(n, elemsize); } cfft_1D(plan, array, 0); } void cfft_1D_r2c_padded_fft(cfft_plan_t *plan, void *in, size_t in_elemsize, void **pout, const size_t out_elemsize, size_t *out_as, int in_n, int out_n) // every arg besides in and *_n can be uninitialised { cfft_copy_r2c_pad(in, in_elemsize, pout, out_elemsize, out_as, xyi(in_n, 1), xyi(out_n, 1)); // 1D real -> 1D complex and padded cfft_1D_c2c_fft(plan, *pout, out_elemsize, out_n); } void cfft_2D_r2c_padded_fft(cfft_plan_t *plan, void *in, const size_t in_elemsize, void **pout, const size_t out_elemsize, size_t *out_as, xyi_t in_dim, xyi_t out_dim) // every arg besides in and *_dim can be uninitialised { cfft_copy_r2c_pad(in, in_elemsize, pout, out_elemsize, out_as, in_dim, out_dim); // 2D real -> 2D complex and padded if (equal_xyi(plan->dim, out_dim)==0) // if we must recreate the plan { cfft_plan_free(plan); *plan = cfft_2D_create_plan(out_dim, out_elemsize); } cfft_2D(plan, *pout, 0); } void cfft_1D_c2r_full_ifft(cfft_plan_t *plan, void *in, const size_t in_elemsize, void *out, const size_t out_elemsize, int n) // the IFFT is still in-place for in { xyi_t dim = xyi(n, 1); if (equal_xyi(plan->dim, dim)==0) // if we must recreate the plan { cfft_plan_free(plan); *plan = cfft_1D_create_plan(n, out_elemsize); } cfft_1D(plan, in, 1); cfft_copy_c2r(in, in_elemsize, out, out_elemsize, dim); } void cfft_2D_c2r_full_ifft(cfft_plan_t *plan, void *in, const size_t in_elemsize, void *out, const size_t out_elemsize, xyi_t dim) // the IFFT is still in-place for in { if (equal_xyi(plan->dim, dim)==0) // if we must recreate the plan { cfft_plan_free(plan); *plan = cfft_2D_create_plan(dim, out_elemsize); } cfft_2D(plan, in, 1); cfft_copy_c2r(in, in_elemsize, out, out_elemsize, dim); } #endif
2.21875
2
2024-11-18T21:09:26.437718+00:00
2016-04-19T03:31:47
13b7b866b421a86b1545edcad378deb3ce4562c9
{ "blob_id": "13b7b866b421a86b1545edcad378deb3ce4562c9", "branch_name": "refs/heads/master", "committer_date": "2016-04-19T03:31:47", "content_id": "35504bcc02eaab8f1595bc238ab2611d7d67e928", "detected_licenses": [ "Unlicense" ], "directory_id": "746ce13305c233ff604f3530815e29c8f6f515a3", "extension": "h", "filename": "VFS.H", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 40918074, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1723, "license": "Unlicense", "license_type": "permissive", "path": "/0.0.1/SRC/SYSTEM/FS/VFS.H", "provenance": "stackv2-0065.json.gz:5764", "repo_name": "basicfreak/BOS", "revision_date": "2016-04-19T03:31:47", "revision_id": "6587ed9c12e7f5a62d25be13109f80a011e5b90a", "snapshot_id": "73097a13c0786c1eca3bca539e23d6e8d4214a9f", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/basicfreak/BOS/6587ed9c12e7f5a62d25be13109f80a011e5b90a/0.0.1/SRC/SYSTEM/FS/VFS.H", "visit_date": "2021-01-17T08:12:20.621305" }
stackv2
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * SYSTEM/FS/VFS.H * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef VFS_H_INCLUDED #define VFS_H_INCLUDED #define FS_FILE 0 #define FS_DIRECTORY 1 #define FS_INVALID 2 #define FS_DISK 3 #include <FORMATTING.H> typedef struct _FILE { char name[35]; uint32_t flags; uint32_t fileLength; uint32_t id; uint32_t eof; uint32_t position; uint32_t currentCluster; uint16_t DiskID; uint8_t FSysID; } FILE, *PFILE; typedef struct _VFSDIR { FILE File[65536]; } VFSDIR, *PVFSDIR; typedef struct Disk_Properties { uint8_t SectorsPerCluster; uint64_t OffsetDataStart; uint32_t ROOTOFFSET; uint16_t RootCount; //0 = cluster based / else = number of entries uint32_t FATOffset; uint16_t PartID; uint8_t FSysID; } DISK, *PDISK; typedef struct _FILE_SYSTEM { char Name[8]; void (*DIR) (uint16_t DiskID, PVFSDIR DIR, const char* Path); FILE (*Open) (uint16_t DiskID, const char* Path); void (*Close) (PFILE File); void (*Read) (PFILE File, void *Buffer, uint32_t Length); void (*Write) (PFILE File, void *Buffer, uint32_t Length); error (*MOUNT) (PDISK Disk); } FILESYSTEM, *PFILESYSTEM; void _VFS_DIR(const char* Path); void _VFS_init(void); void Install_FS(FILESYSTEM FSys, uint8_t FSysID); void Mount_Disk(uint16_t PartID); uint64_t Get_OffsetDataStart(uint16_t DiskID); uint8_t Get_SectorsPerCluster(uint16_t DiskID); uint32_t Get_OffsetFatStart(uint16_t DiskID); uint16_t Get_PartID(uint16_t DiskID); uint8_t Get_FSysID(uint16_t DiskID); uint32_t Get_ROOTOFFSET(uint16_t DiskID); uint16_t Get_RootCount(uint16_t DiskID); #endif
2.171875
2
2024-11-18T21:09:26.600916+00:00
2017-02-27T08:29:35
d1a0e274a6a4691c0d3ee18445100f3ba755dad9
{ "blob_id": "d1a0e274a6a4691c0d3ee18445100f3ba755dad9", "branch_name": "refs/heads/master", "committer_date": "2017-02-27T08:29:35", "content_id": "be271948b9ac02597c1fa4a6b5226f8710070519", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c595b995f0467871d07eb70dd5fa8b19d4b2b7d5", "extension": "c", "filename": "logging.c", "fork_events_count": 0, "gha_created_at": "2017-02-27T06:50:06", "gha_event_created_at": "2017-02-27T06:50:06", "gha_language": null, "gha_license_id": null, "github_id": 83277923, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8937, "license": "Apache-2.0", "license_type": "permissive", "path": "/lib/logging.c", "provenance": "stackv2-0065.json.gz:6021", "repo_name": "Camisa/openstack-guest-agents-unix", "revision_date": "2017-02-27T08:29:35", "revision_id": "f0d75d0260dd02619c49c54f2b2e81742c28c0d6", "snapshot_id": "e79dd857031a5416bc58b66142519e6e9575153a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Camisa/openstack-guest-agents-unix/f0d75d0260dd02619c49c54f2b2e81742c28c0d6/lib/logging.c", "visit_date": "2021-01-21T06:46:27.211249" }
stackv2
/* * vim: tabstop=4 shiftwidth=4 softtabstop=4 * * Copyright (c) 2011 Openstack, LLC. * 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 "libagent_int.h" #include <sys/stat.h> static PyObject *logging = NULL; #define VSMPRINTF(p, fmt) \ va_list ap; \ int n, size = 100; \ p = malloc(size); \ if (!p) \ { \ fprintf(stderr, "couldn't allocate %d bytes for buffer\n", size); \ return; \ } \ while (1) \ { \ va_start(ap, fmt); \ n = vsnprintf(p, size, fmt, ap); \ va_end(ap); \ if (n > -1 && n < size) \ break; \ if (n > -1) \ size = n + 1; \ else \ size *= 2; \ char *np = realloc(p, size); \ if (!np) \ { \ free(p); \ fprintf(stderr, "couldn't allocate %d bytes for buffer\n", size); \ return; \ } \ p = np; \ } static int basic_config(char *filename, char *level) { PyObject *args = PyTuple_New(0); if (!args) goto err_args; PyObject *kwargs = PyDict_New(); if (!args) goto err_kwargs; /* * "-" means stdout, so don't set filename in the dictionary * in this case */ int haveRealFile = filename && strcmp(filename, "-"); if (haveRealFile) { PyObject *value = PyString_FromString(filename); if (!value) goto err_value; int ret = PyDict_SetItemString(kwargs, "filename", value); Py_DECREF(value); if (ret < 0) goto err_value; } if (level) { char *buf = strdup(level); if (!buf) { PyErr_NoMemory(); goto err_value; } char *p; for (p = buf; *p; p++) *p = toupper(*p); PyObject *value = PyObject_GetAttrString(logging, buf); free(buf); if (!value) goto err_value; if (!PyInt_Check(value)) { Py_DECREF(value); PyErr_Format(PyExc_ValueError, "logging level must resolve to integer"); goto err_value; } int ret = PyDict_SetItemString(kwargs, "level", value); Py_DECREF(value); if (ret < 0) goto err_value; } PyObject *value = PyString_FromString("%(asctime)s [%(levelname)s] %(message)s"); PyDict_SetItemString(kwargs, "format", value); Py_DECREF(value); PyObject *logging_basicConfig = PyObject_GetAttrString(logging, "basicConfig"); if (!logging_basicConfig) goto err_callable; PyObject *ret = PyObject_Call(logging_basicConfig, args, kwargs); Py_DECREF(logging_basicConfig); Py_DECREF(args); Py_DECREF(kwargs); int retcode = -1; if (ret) { retcode = 0; Py_DECREF(ret); } // If we just created the file, make sure it's not world readable if (haveRealFile) chmod(filename, S_IRUSR|S_IWUSR); return retcode; err_callable: err_value: Py_DECREF(kwargs); err_kwargs: Py_DECREF(args); err_args: return -1; } static void _log(char *level, char *p) { PyObject *ret = NULL; if (logging) { PyGILState_STATE gstate = PyGILState_Ensure(); ret = PyObject_CallMethod(logging, level, "s", p); Py_XDECREF(ret); if (!ret) { PyErr_Print(); PyErr_Clear(); } PyGILState_Release(gstate); } if (!ret) fprintf(stderr, "%s\n", p); } int LIBAGENT_PUBLIC_API agent_open_log(char *filename, char *level) { PyGILState_STATE gstate = PyGILState_Ensure(); logging = PyImport_ImportModule("logging"); if (!logging) { fprintf(stderr, "unable to import logging module\n"); goto err; } if (filename || level) { int ret = basic_config(filename, level); if (ret < 0) { fprintf(stderr, "could not setup basic config\n"); goto err; } } PyGILState_Release(gstate); return 0; err: Py_CLEAR(logging); PyErr_Print(); PyErr_Clear(); PyGILState_Release(gstate); return -1; } /* * The logging calls below should be exported to modules */ int LIBAGENT_PUBLIC_API agent_log_python_error(char *log_prefix) { PyObject *ptype; PyObject *pvalue; PyObject *ptraceback; /* Acquire GIL */ PyGILState_STATE gstate = PyGILState_Ensure(); PyErr_Fetch(&ptype, &pvalue, &ptraceback); if (ptype == NULL) { agent_error("%s: No python error available", log_prefix); /* Just in case */ Py_XDECREF(pvalue); Py_XDECREF(ptraceback); /* Release GIL */ PyGILState_Release(gstate); return -1; } if (ptraceback == NULL) { PyObject *obj; agent_error("%s: A python exception has occurred:", log_prefix); if (pvalue != NULL) { obj = PyObject_Str(pvalue); } else { obj = PyObject_Str(ptype); } agent_error("[EXC] %s", PyString_AsString(obj)); Py_DECREF(obj); Py_DECREF(ptype); Py_XDECREF(pvalue); /* Release GIL */ PyGILState_Release(gstate); return 0; } PyObject *tb_mod = PyImport_AddModule("traceback"); if (tb_mod == NULL) { PyErr_Clear(); Py_DECREF(ptype); Py_XDECREF(pvalue); Py_XDECREF(ptraceback); agent_error("%s: [Couldn't find traceback module " "to print the error]", log_prefix); /* Release GIL */ PyGILState_Release(gstate); return -1; } /* * Call traceback.format_exception(ptype, pvalue, ptraceback) */ PyObject *pobj_list = PyObject_CallMethod(tb_mod, "format_exception", "OOO", ptype, pvalue, ptraceback); if (pobj_list == NULL) { PyErr_Clear(); Py_DECREF(ptype); Py_XDECREF(pvalue); Py_XDECREF(ptraceback); agent_error("%s: [Couldn't format traceback]", log_prefix); /* Release GIL */ PyGILState_Release(gstate); return -1; } Py_DECREF(ptype); Py_XDECREF(pvalue); Py_XDECREF(ptraceback); /* * Now we have a list of 'lines'. Each 'line' might actually be * multiple lines, however ('line' might contain '\n's). So, we * need to go through every list entry and log each real line * (looking for \n separator) */ agent_error("%s: A python exception has occurred:", log_prefix); Py_ssize_t list_sz = PyList_Size(pobj_list); PyObject *pobj_str; Py_ssize_t i; for(i = 0;i < list_sz;i++) { pobj_str = PyList_GetItem(pobj_list, i); char *obj_str = strdup(PyString_AsString(pobj_str)); Py_DECREF(pobj_str); if (obj_str == NULL) { agent_error("Out of memory"); Py_DECREF(pobj_list); /* Release GIL */ PyGILState_Release(gstate); return 0; } char *ptr = strchr(obj_str, '\n'); if (ptr == NULL) { /* No \n... just log this element and go to the next */ agent_error("[EXC] %s", obj_str); free(obj_str); continue; } char *start = obj_str; *(ptr++) = '\0'; agent_error("[EXC] %s", start); while((ptr != NULL) && (*ptr != '\0')) { start = ptr; ptr = strchr(start, '\n'); if (ptr != NULL) { *ptr++ = '\0'; } agent_error("[EXC] %s", start); } free(obj_str); } /* Release GIL */ PyGILState_Release(gstate); return 0; } void LIBAGENT_PUBLIC_API agent_debug(char *fmt, ...) { char *p; VSMPRINTF(p, fmt); _log("debug", p); free(p); } void LIBAGENT_PUBLIC_API agent_error(char *fmt, ...) { char *p; VSMPRINTF(p, fmt); _log("error", p); free(p); } void LIBAGENT_PUBLIC_API agent_info(char *fmt, ...) { char *p; VSMPRINTF(p, fmt); _log("info", p); free(p); } void LIBAGENT_PUBLIC_API agent_warn(char *fmt, ...) { char *p; VSMPRINTF(p, fmt); _log("warn", p); free(p); }
2.234375
2
2024-11-18T21:09:26.685269+00:00
2020-11-29T18:44:38
b4ee1b0c62e7fad3c7c08895e9cabd956f2f78fb
{ "blob_id": "b4ee1b0c62e7fad3c7c08895e9cabd956f2f78fb", "branch_name": "refs/heads/master", "committer_date": "2020-11-29T18:44:38", "content_id": "93ad7ce42805281c7b357a1ea99adaa88960acfc", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e93a80168efe321e3586118ee7097f5192a284ec", "extension": "h", "filename": "cuda_GpuMat.h", "fork_events_count": 0, "gha_created_at": "2019-11-16T17:26:54", "gha_event_created_at": "2019-11-16T17:26:55", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 222134723, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6572, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/OpenCvSharpExtern/cuda_GpuMat.h", "provenance": "stackv2-0065.json.gz:6149", "repo_name": "TWhidden/opencvsharp", "revision_date": "2020-11-29T18:44:38", "revision_id": "b88305b021c88775a0da8ada237778f4ed90dc41", "snapshot_id": "bc2d5120bb53ca393493bcaf4dcf31e0a493fc71", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/TWhidden/opencvsharp/b88305b021c88775a0da8ada237778f4ed90dc41/src/OpenCvSharpExtern/cuda_GpuMat.h", "visit_date": "2021-07-11T05:06:32.867687" }
stackv2
#ifndef _CPP_GPU_GPUMAT_H_ #define _CPP_GPU_GPUMAT_H_ #ifdef ENABLED_CUDA #include "include_opencv.h" #pragma region Init and Disposal CVAPI(void) cuda_GpuMat_delete(GpuMat *obj) { delete obj; } CVAPI(GpuMat*) cuda_GpuMat_new1() { return new GpuMat(); } CVAPI(GpuMat*) cuda_GpuMat_new2(int rows, int cols, int type) { return new GpuMat(rows, cols, type); } CVAPI(GpuMat*) cuda_GpuMat_new3(int rows, int cols, int type, void* data, uint64 step) { return new GpuMat(rows, cols, type, data, static_cast<size_t>(step)); } CVAPI(GpuMat*) cuda_GpuMat_new4(cv::Mat *mat) { return new GpuMat(*mat); } CVAPI(GpuMat*) cuda_GpuMat_new5(GpuMat *gpumat) { return new GpuMat(*gpumat); } CVAPI(GpuMat*) cuda_GpuMat_new6(CvSize size, int type) { return new GpuMat((cv::Size)size, type); } CVAPI(GpuMat*) cuda_GpuMat_new7(CvSize size, int type, void* data, uint64 step) { return new GpuMat((cv::Size)size, type, data, static_cast<size_t>(step)); } CVAPI(GpuMat*) cuda_GpuMat_new8(int rows, int cols, int type, CvScalar s) { return new GpuMat(rows, cols, type, s); } CVAPI(GpuMat*) cuda_GpuMat_new9(GpuMat *m, CvSlice rowRange, CvSlice colRange) { return new GpuMat(*m, (cv::Range)rowRange, (cv::Range)colRange); } CVAPI(GpuMat*) cuda_GpuMat_new10(GpuMat *m, CvRect roi) { return new GpuMat(*m, (cv::Rect)roi); } CVAPI(GpuMat*) cuda_GpuMat_new11(CvSize size, int type, CvScalar s) { return new GpuMat((cv::Size)size, type, s); } #pragma endregion #pragma region Fields CVAPI(int) cuda_GpuMat_flags(GpuMat *obj) { return obj->flags; } CVAPI(int) cuda_GpuMat_rows(GpuMat *obj) { return obj->rows; } CVAPI(int) cuda_GpuMat_cols(GpuMat *obj) { return obj->cols; } CVAPI(uint64) cuda_GpuMat_step(GpuMat *obj) { return static_cast<uint64>(obj->step); } CVAPI(uchar*) cuda_GpuMat_data(GpuMat *obj) { return obj->data; } CVAPI(int*) cuda_GpuMat_refcount(GpuMat *obj) { return obj->refcount; } CVAPI(uchar*) cuda_GpuMat_datastart(GpuMat *obj) { return obj->datastart; } CVAPI(const uchar*) cuda_GpuMat_dataend(GpuMat *obj) { return obj->dataend; } #pragma endregion #pragma region Operators CVAPI(void) cuda_GpuMat_opAssign(GpuMat *left, GpuMat *right) { *left = *right; } CVAPI(GpuMat*) cuda_GpuMat_opRange1(GpuMat *src, CvRect roi) { GpuMat gm = (*src)(roi); return new GpuMat(gm); } CVAPI(GpuMat*) cuda_GpuMat_opRange2(GpuMat *src, CvSlice rowRange, CvSlice colRange) { GpuMat gm = (*src)(rowRange, colRange); return new GpuMat(gm); } CVAPI(cv::Mat*) cuda_GpuMat_opToMat(GpuMat *src) { cv::Mat m = (cv::Mat)(*src); return new cv::Mat(m); } CVAPI(GpuMat*) cuda_GpuMat_opToGpuMat(cv::Mat *src) { GpuMat gm = (GpuMat)(*src); return new GpuMat(gm); } #pragma endregion #pragma region Methods CVAPI(void) cuda_GpuMat_upload(GpuMat *obj, cv::Mat *m) { obj->upload(*m); } CVAPI(void) cuda_GpuMat_download(GpuMat *obj, cv::Mat *m) { obj->download(*m); } CVAPI(GpuMat*) cuda_GpuMat_row(GpuMat *obj, int y) { GpuMat ret = obj->row(y); return new GpuMat(ret); } CVAPI(GpuMat*) cuda_GpuMat_col(GpuMat *obj, int x) { GpuMat ret = obj->col(x); return new GpuMat(ret); } CVAPI(GpuMat*) cuda_GpuMat_rowRange(GpuMat *obj, int startrow, int endrow) { GpuMat ret = obj->rowRange(startrow, endrow); return new GpuMat(ret); } CVAPI(GpuMat*) cuda_GpuMat_colRange(GpuMat *obj, int startcol, int endcol) { GpuMat ret = obj->colRange(startcol, endcol); return new GpuMat(ret); } CVAPI(GpuMat*) cuda_GpuMat_clone(GpuMat *obj) { GpuMat ret = obj->clone(); return new GpuMat(ret); } CVAPI(void) cuda_GpuMat_copyTo1(GpuMat *obj, GpuMat *m) { obj->copyTo(*m); } CVAPI(void) cuda_GpuMat_copyTo2(GpuMat *obj, GpuMat *m, GpuMat *mask) { obj->copyTo(*m, *mask); } CVAPI(void) cuda_GpuMat_convertTo(GpuMat *obj, GpuMat *m, int rtype, double alpha, double beta) { obj->convertTo(*m, rtype, alpha, beta); } CVAPI(void) cuda_GpuMat_assignTo(GpuMat *obj, GpuMat *m, int type) { obj->assignTo(*m, type); } CVAPI(GpuMat*) cuda_GpuMat_setTo(GpuMat *obj, CvScalar s, GpuMat *mask) { GpuMat gm = obj->setTo(s, entity(mask)); return new GpuMat(gm); } CVAPI(GpuMat*) cuda_GpuMat_reshape(GpuMat *obj, int cn, int rows) { GpuMat gm = obj->reshape(cn, rows); return new GpuMat(gm); } CVAPI(void) cuda_GpuMat_create1(GpuMat *obj, int rows, int cols, int type) { obj->create(rows, cols, type); } CVAPI(void) cuda_GpuMat_create2(GpuMat *obj, CvSize size, int type) { obj->create((cv::Size)size, type); } CVAPI(void) cuda_GpuMat_release(GpuMat *obj) { obj->release(); } CVAPI(void) cuda_GpuMat_swap(GpuMat *obj, GpuMat *mat) { obj->swap(*mat); } CVAPI(void) cuda_GpuMat_locateROI(GpuMat *obj, CvSize *wholeSize, CvPoint *ofs) { cv::Size _wholeSize; cv::Point _ofs; obj->locateROI(_wholeSize, _ofs); *wholeSize = (CvSize)_wholeSize; *ofs = (CvPoint)_ofs; } CVAPI(GpuMat*) cuda_GpuMat_adjustROI(GpuMat *obj, int dtop, int dbottom, int dleft, int dright) { GpuMat gm = obj->adjustROI(dtop, dbottom, dleft, dright); return new GpuMat(gm); } CVAPI(int) cuda_GpuMat_isContinuous(GpuMat *obj) { return obj->isContinuous() ? 1 : 0; } CVAPI(uint64) cuda_GpuMat_elemSize(GpuMat *obj) { return static_cast<uint64>(obj->elemSize()); } CVAPI(uint64) cuda_GpuMat_elemSize1(GpuMat *obj) { return static_cast<uint64>(obj->elemSize1()); } CVAPI(int) cuda_GpuMat_type(GpuMat *obj) { return obj->type(); } CVAPI(int) cuda_GpuMat_depth(GpuMat *obj) { return obj->depth(); } CVAPI(int) cuda_GpuMat_channels(GpuMat *obj) { return obj->channels(); } CVAPI(uint64) cuda_GpuMat_step1(GpuMat *obj) { return static_cast<uint64>(obj->step1()); } CVAPI(MyCvSize) cuda_GpuMat_size(GpuMat *obj) { return c(obj->size()); } CVAPI(int) cuda_GpuMat_empty(GpuMat *obj) { return obj->empty() ? 1 : 0; } CVAPI(const uchar*) cuda_GpuMat_ptr(const GpuMat *obj, int y) { return obj->ptr(y); } #pragma endregion //! Creates continuous GPU matrix CVAPI(void) cuda_createContinuous1(int rows, int cols, int type, GpuMat *gm) { createContinuous(rows, cols, type, *gm); } CVAPI(GpuMat*) cuda_createContinuous2(int rows, int cols, int type) { GpuMat gm = createContinuous(rows, cols, type); return new GpuMat(gm); } //! Ensures that size of the given matrix is not less than (rows, cols) size //! and matrix type is match specified one too CVAPI(void) cuda_ensureSizeIsEnough(int rows, int cols, int type, GpuMat *m) { ensureSizeIsEnough(rows, cols, type, *m); } #endif #endif
2.21875
2
2024-11-18T21:09:27.364150+00:00
2021-09-11T23:48:25
54de6cf5cbbccef7c0a0e7f8611a297caade299b
{ "blob_id": "54de6cf5cbbccef7c0a0e7f8611a297caade299b", "branch_name": "refs/heads/main", "committer_date": "2021-09-11T23:48:25", "content_id": "52bf55c43577054cc90ee51ae8025afe81c4fc90", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "193ae9f73e4c093eae3a63e367dfd3e84dc7503c", "extension": "c", "filename": "gdt.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 397747436, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1947, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/kernel/sys/GDT/gdt.c", "provenance": "stackv2-0065.json.gz:6405", "repo_name": "EmeraldMastaMC/myOS", "revision_date": "2021-09-11T23:48:25", "revision_id": "7c172883206738635e501203a8c2f42208946159", "snapshot_id": "fd8661dbf107b4186d02bec9d2fa7eca8514919e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/EmeraldMastaMC/myOS/7c172883206738635e501203a8c2f42208946159/kernel/sys/GDT/gdt.c", "visit_date": "2023-08-06T21:42:13.064887" }
stackv2
#include "../../include/stdint.h" #include "../../include/sys/GDT.h" GDT_entry_t GDT[5]; GDT_descriptor_t GDTDescriptor; void GDTSetEntry(uint16_t index, uint32_t base, uint32_t limit, uint8_t accessByte, uint8_t flags) { // Base GDT[index].base_low = (base & 0x0000FFFF) >> 0; GDT[index].base_mid = (base & 0x00FF0000) >> 16; GDT[index].base_high = (base & 0xFF000000) >> 24; // Limit GDT[index].limit_low = (limit & 0x0FFFF) >> 0; GDT[index].limit_high = (limit & 0xF0000) >> 16; // Access Byte GDT[index].Pr = (accessByte & 0b10000000) >> 7; GDT[index].Privl = (accessByte & 0b01100000) >> 5; GDT[index].S = (accessByte & 0b00010000) >> 4; GDT[index].Ex = (accessByte & 0b00001000) >> 3; GDT[index].DC = (accessByte & 0b00000100) >> 2; GDT[index].RW = (accessByte & 0b00000010) >> 1; GDT[index].Ac = (accessByte & 0b00000001) >> 0; // Flags GDT[index].null = (flags & 0b00000001) >> 0; GDT[index].L = (flags & 0b00000010) >> 1; GDT[index].Sz = (flags & 0b00000100) >> 2; GDT[index].Gr = (flags & 0b00001000) >> 3; } void init_GDT() { GDTSetEntry(0, 0x00000000, 0x00000, 0b00000000, 0b00000000); GDTSetEntry(1, 0x00000000, 0xFFFFF, GDT_VALID_ENTRY | GDT_RING_0 | GDT_CODE_DATA_ENTRY | GDT_EXECUTABLE_ENTRY | GDT_READ_WRITE, GDT_PAGE_GRANULARITY | GDT_64_BIT); GDTSetEntry(2, 0x00000000, 0xFFFFF, GDT_VALID_ENTRY | GDT_RING_0 | GDT_CODE_DATA_ENTRY | GDT_READ_WRITE, GDT_PAGE_GRANULARITY | GDT_64_BIT); GDTSetEntry(3, 0x00000000, 0xFFFFF, GDT_VALID_ENTRY | GDT_RING_3 | GDT_CODE_DATA_ENTRY | GDT_EXECUTABLE_ENTRY | GDT_READ_WRITE, GDT_PAGE_GRANULARITY | GDT_64_BIT); GDTSetEntry(4, 0x00000000, 0xFFFFF, GDT_VALID_ENTRY | GDT_RING_3 | GDT_CODE_DATA_ENTRY | GDT_READ_WRITE, GDT_PAGE_GRANULARITY | GDT_64_BIT); GDTDescriptor.size = sizeof(GDT) - 1; GDTDescriptor.offset = (uint64_t)GDT; load_GDT((uint64_t)&GDTDescriptor, 0x08, 0x10); }
2.125
2
2024-11-18T21:09:27.653288+00:00
2022-11-04T11:58:48
c8764dd961607f1400e78f88bf77e6e8edb4eaf8
{ "blob_id": "c8764dd961607f1400e78f88bf77e6e8edb4eaf8", "branch_name": "refs/heads/develop", "committer_date": "2022-11-04T11:59:26", "content_id": "b713d6c6db98a0b22a675f117f30278187fe15ee", "detected_licenses": [ "MIT" ], "directory_id": "f2bdddf5db40ac4b4e606f4e884a5a77a223e94d", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2019-08-18T18:09:24", "gha_event_created_at": "2023-07-04T22:03:48", "gha_language": "C", "gha_license_id": "MIT", "github_id": 203039910, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1734, "license": "MIT", "license_type": "permissive", "path": "/buildTools/linux-x64/gbdk/examples/cross-platform/rle_map/src/main.c", "provenance": "stackv2-0065.json.gz:6533", "repo_name": "pau-tomas/gb-studio", "revision_date": "2022-11-04T11:58:48", "revision_id": "1f995a976bd3aa5579ed86678912f59ed3a42ddb", "snapshot_id": "ce31e09dd4784b9648598b8a049d66d8f4985d91", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/pau-tomas/gb-studio/1f995a976bd3aa5579ed86678912f59ed3a42ddb/buildTools/linux-x64/gbdk/examples/cross-platform/rle_map/src/main.c", "visit_date": "2023-07-10T09:52:12.584616" }
stackv2
#include <gbdk/platform.h> #include <gbdk/incbin.h> #include <gbdk/rledecompress.h> INCBIN(level1_tiles, "res/level1_tiles.bin") INCBIN_EXTERN(level1_tiles) INCBIN(level1_map, "res/level1_map.rle") INCBIN_EXTERN(level1_map) extern uint8_t sample_rle_data[]; #define DATA_HEIGHT 16 uint8_t data[32][DATA_HEIGHT]; // collision map buffer uint8_t scrollpos = 0; // scroll position in pixels uint8_t datapos = 0; // x position in tiles inside the collision map void main() { SHOW_BKG; set_bkg_data(0, INCBIN_SIZE(level1_tiles) >> 4, level1_tiles); rle_init(level1_map); // initialize decompressor // decompress and display whole screen uint8_t * data_ptr = &data[0][0]; for (uint8_t i = 0; (rle_decompress(data_ptr, DATA_HEIGHT)) && (i != DEVICE_SCREEN_WIDTH); i++) { // pre-process column here // ... // display column set_bkg_tiles(i, 2, 1, DATA_HEIGHT, data_ptr); } // main game loop datapos = scrollpos = 0; while(TRUE) { if ((scrollpos & 7) == 0) { datapos = (scrollpos >> 3); uint8_t x_pos = (datapos + DEVICE_SCREEN_WIDTH) & 31; // decompress and display column data_ptr = &data[x_pos][0]; if (rle_decompress(data_ptr, DATA_HEIGHT)) { // pre-process column here // ... // display column set_bkg_tiles(x_pos, 2, 1, DATA_HEIGHT, data_ptr); scrollpos++; move_bkg(scrollpos, 0); } } else { scrollpos++; move_bkg(scrollpos, 0); } wait_vbl_done(); } }
2.171875
2
2024-11-18T21:09:28.484429+00:00
2021-04-09T21:29:14
c042b0eacc07aeeb41ba97cea14a6d7d0eb902a7
{ "blob_id": "c042b0eacc07aeeb41ba97cea14a6d7d0eb902a7", "branch_name": "refs/heads/master", "committer_date": "2021-04-09T21:29:14", "content_id": "6cae3d1e3066b3e359d9915bc83852aceea70bed", "detected_licenses": [ "MIT" ], "directory_id": "10d181a539df671170a8268f43acab0829edb51c", "extension": "c", "filename": "write.c", "fork_events_count": 0, "gha_created_at": "2019-03-07T08:58:50", "gha_event_created_at": "2019-03-07T08:58:51", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 174308305, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3291, "license": "MIT", "license_type": "permissive", "path": "/src/storage/write.c", "provenance": "stackv2-0065.json.gz:7046", "repo_name": "fluca1978/pgbackrest", "revision_date": "2021-04-09T21:29:14", "revision_id": "3b9bed95186118a3fbf47e3e0900e74f4ad01217", "snapshot_id": "fe356cad81bbc3ed2f1fc5fbbf80d9a3c787c8d2", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/fluca1978/pgbackrest/3b9bed95186118a3fbf47e3e0900e74f4ad01217/src/storage/write.c", "visit_date": "2021-06-14T20:43:13.507725" }
stackv2
/*********************************************************************************************************************************** Storage Write Interface ***********************************************************************************************************************************/ #include "build.auto.h" #include "common/debug.h" #include "common/log.h" #include "common/memContext.h" #include "storage/write.h" /*********************************************************************************************************************************** Object type ***********************************************************************************************************************************/ struct StorageWrite { StorageWritePub pub; // Publicly accessible variables void *driver; }; /*********************************************************************************************************************************** Macros for function logging ***********************************************************************************************************************************/ #define FUNCTION_LOG_STORAGE_WRITE_INTERFACE_TYPE \ StorageWriteInterface #define FUNCTION_LOG_STORAGE_WRITE_INTERFACE_FORMAT(value, buffer, bufferSize) \ objToLog(&value, "StorageWriteInterface", buffer, bufferSize) /*********************************************************************************************************************************** This object expects its context to be created in advance. This is so the calling function can add whatever data it wants without required multiple functions and contexts to make it safe. ***********************************************************************************************************************************/ StorageWrite * storageWriteNew(void *driver, const StorageWriteInterface *interface) { FUNCTION_LOG_BEGIN(logLevelTrace); FUNCTION_LOG_PARAM_P(VOID, driver); FUNCTION_LOG_PARAM_P(STORAGE_WRITE_INTERFACE, interface); FUNCTION_LOG_END(); ASSERT(driver != NULL); ASSERT(interface != NULL); StorageWrite *this = memNew(sizeof(StorageWrite)); *this = (StorageWrite) { .pub = { .memContext = memContextCurrent(), .interface = interface, .io = ioWriteNew(driver, interface->ioInterface), }, .driver = driver, }; FUNCTION_LOG_RETURN(STORAGE_WRITE, this); } /**********************************************************************************************************************************/ String * storageWriteToLog(const StorageWrite *this) { return strNewFmt( "{type: %s, name: %s, modeFile: %04o, modePath: %04o, createPath: %s, syncFile: %s, syncPath: %s, atomic: %s}", strZ(storageWriteType(this)), strZ(strToLog(storageWriteName(this))), storageWriteModeFile(this), storageWriteModePath(this), cvtBoolToConstZ(storageWriteCreatePath(this)), cvtBoolToConstZ(storageWriteSyncFile(this)), cvtBoolToConstZ(storageWriteSyncPath(this)), cvtBoolToConstZ(storageWriteAtomic(this))); }
2.15625
2
2024-11-18T21:09:28.574847+00:00
2018-07-16T16:02:22
ed31faf95515e0410b80a7a046810c8a1b8ae630
{ "blob_id": "ed31faf95515e0410b80a7a046810c8a1b8ae630", "branch_name": "refs/heads/master", "committer_date": "2018-07-16T16:02:22", "content_id": "4430df7dca08cb570dd7b8a563514eda859aed75", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "716c0bbb26b894d84f0725bf9c797439844da9e1", "extension": "c", "filename": "posix.c", "fork_events_count": 0, "gha_created_at": "2018-05-25T11:40:28", "gha_event_created_at": "2018-05-25T11:40:28", "gha_language": null, "gha_license_id": null, "github_id": 134848506, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 25001, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/src/posix/posix.c", "provenance": "stackv2-0065.json.gz:7174", "repo_name": "kaman/phoenix-rtos-kernel", "revision_date": "2018-07-16T16:02:22", "revision_id": "ba8bfe23c3eca6458a371e1ea4676c44a5af6c7a", "snapshot_id": "ab9f4b88a8a53b471933d8f9bc462a329af0f9ff", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kaman/phoenix-rtos-kernel/ba8bfe23c3eca6458a371e1ea4676c44a5af6c7a/src/posix/posix.c", "visit_date": "2020-03-18T14:26:48.770510" }
stackv2
/* * Phoenix-RTOS * * Operating system kernel * * POSIX-compatibility module * * Copyright 2018 Phoenix Systems * Author: Jan Sikorski, Michal Miroslaw * * This file is part of Phoenix-RTOS. * * %LICENSE% */ #include HAL #include "../../include/errno.h" #include "../proc/proc.h" #include "posix.h" #define MAX_FD_COUNT 32 #define set_errno(x) (((x) < 0) ? -1 : x) //#define TRACE(str, ...) lib_printf("posix %x: " str "\n", proc_current()->process->id, ##__VA_ARGS__) #define TRACE(str, ...) /* NOTE: temporarily disable locking, need to be tested */ #define proc_lockSet(x) (void)0 #define proc_lockClear(x) (void)0 enum { ftRegular, ftPipe, ftFifo, ftInetSocket, ftUnixSocket, ftTty }; enum { pxBufferedPipe, pxPipe, pxPTY }; typedef struct { oid_t oid; unsigned refs; off_t offset; unsigned status; lock_t lock; char type; } open_file_t; typedef struct { open_file_t *file; unsigned flags; } fildes_t; typedef struct { rbnode_t linkage; process_t *process; lock_t lock; int maxfd; fildes_t *fds; } process_info_t; struct { rbtree_t pid; lock_t lock; id_t fresh; } posix_common; static char *strrchr(const char *s, int c) { const char *p = NULL; do { if (*s == c) p = s; } while (*(s++)); return (char *)p; } static void splitname(char *path, char **base, char **dir) { char *slash; slash = strrchr(path, '/'); if (slash == NULL) { *dir = "."; *base = path; } else if (slash == path) { *base = path + 1; *dir = "/"; } else { *dir = path; *base = slash + 1; *slash = 0; } } static void posix_fileDeref(open_file_t *f) { proc_lockSet(&f->lock); if (!--f->refs) { proc_close(f->oid, f->status); proc_lockDone(&f->lock); vm_kfree(f); } else { proc_lockClear(&f->lock); } } static int posix_newFile(process_info_t *p, int fd) { open_file_t *f; while (p->fds[fd].file != NULL && fd++ < p->maxfd); if (fd > p->maxfd) return -ENFILE; if ((f = p->fds[fd].file = vm_kmalloc(sizeof(open_file_t))) == NULL) return -ENOMEM; proc_lockInit(&f->lock); f->refs = 1; f->offset = 0; return fd; } static int pinfo_cmp(rbnode_t *n1, rbnode_t *n2) { process_info_t *p1 = lib_treeof(process_info_t, linkage, n1); process_info_t *p2 = lib_treeof(process_info_t, linkage, n2); if (p1->process->id < p2->process->id) return -1; else if (p1->process->id > p2->process->id) return 1; return 0; } process_info_t *pinfo_find(unsigned int pid) { process_t p; process_info_t pi, *r; p.id = pid; pi.process = &p; proc_lockSet(&posix_common.lock); r = lib_treeof(process_info_t, linkage, lib_rbFind(&posix_common.pid, &pi.linkage)); proc_lockClear(&posix_common.lock); return r; } int posix_clone(int ppid) { TRACE("clone(%x)", ppid); process_info_t *p, *pp; process_t *proc; int i; oid_t console; open_file_t *f; proc = proc_current()->process; if ((p = vm_kmalloc(sizeof(process_info_t))) == NULL) return -ENOMEM; hal_memset(&console, 0, sizeof(oid_t)); proc_lockInit(&p->lock); if ((pp = pinfo_find(ppid)) != NULL) { TRACE("clone: got parent"); proc_lockSet(&pp->lock); p->maxfd = pp->maxfd; } else { p->maxfd = MAX_FD_COUNT - 1; } p->process = proc; if ((p->fds = vm_kmalloc((p->maxfd + 1) * sizeof(fildes_t))) == NULL) { vm_kfree(p); return -ENOMEM; } if (pp != NULL) { hal_memcpy(p->fds, pp->fds, (pp->maxfd + 1) * sizeof(fildes_t)); for (i = 0; i <= p->maxfd; ++i) { if ((f = p->fds[i].file) != NULL) { proc_lockSet(&f->lock); ++f->refs; proc_lockClear(&f->lock); } } proc_lockClear(&pp->lock); } else { hal_memset(p->fds, 0, (p->maxfd + 1) * sizeof(fildes_t)); for (i = 0; i < 3; ++i) { if ((f = p->fds[i].file = vm_kmalloc(sizeof(open_file_t))) == NULL) return -ENOMEM; proc_lockInit(&f->lock); f->refs = 1; f->offset = 0; f->type = ftTty; p->fds[i].flags = 0; hal_memcpy(&f->oid, &console, sizeof(oid_t)); } p->fds[0].file->status = O_RDONLY; p->fds[1].file->status = O_WRONLY; p->fds[2].file->status = O_WRONLY; } proc_lockSet(&posix_common.lock); lib_rbInsert(&posix_common.pid, &p->linkage); proc_lockClear(&posix_common.lock); return EOK; } int posix_fork() { int pid; if (!(pid = proc_vfork())) { proc_copyexec(); /* Not reached */ } return pid; } int posix_exec(void) { TRACE("exec"); process_info_t *p; open_file_t *f; int fd; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; proc_lockSet(&p->lock); for (fd = 0; fd <= p->maxfd; ++fd) { if ((f = p->fds[fd].file) != NULL && p->fds[fd].flags & FD_CLOEXEC) { posix_fileDeref(f); p->fds[fd].file = NULL; } } proc_lockClear(&p->lock); return 0; } int posix_exit(process_t *process) { TRACE("exit(%x)", process->id); process_info_t *p; open_file_t *f; int fd; if ((p = pinfo_find(process->id)) == NULL) return -1; proc_lockSet(&p->lock); for (fd = 0; fd <= p->maxfd; ++fd) { if ((f = p->fds[fd].file) != NULL) posix_fileDeref(f); } proc_lockSet(&posix_common.lock); lib_rbRemove(&posix_common.pid, &p->linkage); proc_lockClear(&posix_common.lock); vm_kfree(p->fds); proc_lockDone(&p->lock); vm_kfree(p); return 0; } static int posix_create(const char *filename, int type, mode_t mode, oid_t dev, oid_t *oid) { TRACE("posix_create(%s, %d)", filename, mode); int err; oid_t dir; char *name, *basename, *dirname; int namelen; namelen = hal_strlen(filename); name = vm_kmalloc(namelen + 1); hal_memcpy(name, filename, namelen + 1); splitname(name, &basename, &dirname); do { if ((err = proc_lookup(dirname, &dir)) < 0) break; if ((err = proc_create(dir.port, type, mode, dev, dir, basename, oid)) < 0) break; return EOK; } while (0); vm_kfree(name); return err; } /* TODO: handle O_CREAT and O_EXCL */ int posix_open(const char *filename, int oflag, char *ustack) { TRACE("open(%s, %d, %d)", filename, oflag); oid_t oid, dev, pipesrv; int fd = 0, err; process_info_t *p; open_file_t *f; mode_t mode; if ((proc_lookup("/dev/posix/pipes", &pipesrv)) < 0) ; /* that's fine */ if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; hal_memset(&dev, 0, sizeof(oid_t)); hal_memset(&pipesrv, -1, sizeof(oid_t)); proc_lockSet(&p->lock); do { while (p->fds[fd].file != NULL && fd++ < p->maxfd); if (fd > p->maxfd) break; if ((f = p->fds[fd].file = vm_kmalloc(sizeof(open_file_t))) == NULL) break; proc_lockInit(&f->lock); proc_lockClear(&p->lock); do { if (proc_lookup(filename, &oid) == EOK) { /* pass */ } else if (oflag & O_CREAT) { GETFROMSTACK(ustack, mode_t, mode, 2); if (posix_create(filename, 1 /* otFile */, mode, dev, &oid) < 0) break; } else { break; } if ((err = proc_open(oid, oflag)) < 0) break; /* TODO: truncate, append */ proc_lockSet(&p->lock); p->fds[fd].flags = oflag & O_CLOEXEC ? FD_CLOEXEC : 0; proc_lockClear(&p->lock); if (!err) { hal_memcpy(&f->oid, &oid, sizeof(oid)); } else { f->oid.port = oid.port; f->oid.id = err; } f->refs = 1; f->offset = 0; /* TODO: check for other types */ f->type = oid.port == pipesrv.port ? ftPipe : ftRegular; f->status = oflag & ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC | O_CLOEXEC); return fd; } while (0); proc_lockSet(&p->lock); p->fds[fd].file = NULL; proc_lockDone(&f->lock); vm_kfree(f); } while (0); proc_lockClear(&p->lock); return -1; } int posix_close(int fildes) { TRACE("close(%d)", fildes); open_file_t *f; process_info_t *p; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; proc_lockSet(&p->lock); do { if (fildes < 0 || fildes > p->maxfd) break; if ((f = p->fds[fildes].file) == NULL) break; p->fds[fildes].file = NULL; proc_lockClear(&p->lock); posix_fileDeref(f); return 0; } while (0); proc_lockClear(&p->lock); return -1; } int posix_read(int fildes, void *buf, size_t nbyte) { TRACE("read(%d, %p, %u)", fildes, buf, nbyte); open_file_t *f; process_info_t *p; int rcnt; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; proc_lockSet(&p->lock); do { if (fildes < 0 || fildes > p->maxfd) break; if ((f = p->fds[fildes].file) == NULL) break; proc_lockClear(&p->lock); if ((rcnt = proc_read(f->oid, f->offset, buf, nbyte, f->status)) < 0) return set_errno(-EIO); proc_lockSet(&f->lock); f->offset += rcnt; proc_lockClear(&f->lock); return rcnt; } while (0); proc_lockClear(&p->lock); return -1; } int posix_write(int fildes, void *buf, size_t nbyte) { TRACE("write(%d, %p, %u)", fildes, buf, nbyte); open_file_t *f; process_info_t *p; int rcnt; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; proc_lockSet(&p->lock); do { if (fildes < 0 || fildes > p->maxfd) break; if ((f = p->fds[fildes].file) == NULL) break; proc_lockClear(&p->lock); if ((rcnt = proc_write(f->oid, f->offset, buf, nbyte, f->status)) < 0) return set_errno(-EIO); proc_lockSet(&f->lock); f->offset += rcnt; proc_lockClear(&f->lock); return rcnt; } while (0); proc_lockClear(&p->lock); return -1; } int posix_dup(int fildes) { TRACE("dup(%d)", fildes); process_info_t *p; int newfd = 0; open_file_t *f; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; proc_lockSet(&p->lock); do { if (fildes < 0 || fildes > p->maxfd) break; if ((f = p->fds[fildes].file) == NULL) break; while (p->fds[newfd].file != NULL && newfd++ < p->maxfd); if (newfd > p->maxfd) break; p->fds[newfd].file = f; p->fds[newfd].flags = 0; proc_lockSet(&f->lock); f->refs++; proc_lockClear(&f->lock); proc_lockClear(&p->lock); return newfd; } while (0); proc_lockClear(&p->lock); return -1; } /* FIXME: handle fildes == fildes2 */ int _posix_dup2(process_info_t *p, int fildes, int fildes2) { open_file_t *f, *f2; if (fildes < 0 || fildes > p->maxfd) return -1; if (fildes2 < 0 || fildes2 > p->maxfd) return -1; if ((f = p->fds[fildes].file) == NULL) return -1; if ((f2 = p->fds[fildes2].file) != NULL) { p->fds[fildes2].file = NULL; posix_fileDeref(f2); } p->fds[fildes2].file = f; p->fds[fildes2].flags = 0; proc_lockSet(&f->lock); f->refs++; proc_lockClear(&f->lock); return fildes2; } int posix_dup2(int fildes, int fildes2) { TRACE("dup2(%d, %d)", fildes, fildes2); process_info_t *p; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; proc_lockSet(&p->lock); fildes2 = _posix_dup2(p, fildes, fildes2); proc_lockClear(&p->lock); return fildes2; } int posix_pipe(int fildes[2]) { TRACE("pipe(%p)", fildes); process_info_t *p; open_file_t *fi, *fo; oid_t oid; oid_t pipesrv; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; hal_memset(&oid, 0, sizeof(oid)); if ((proc_lookup("/dev/posix/pipes", &pipesrv)) < 0) return set_errno(-ENOSYS); if (proc_create(pipesrv.port, pxBufferedPipe, O_RDONLY | O_WRONLY, oid, pipesrv, NULL, &oid) < 0) return set_errno(-EIO); proc_lockSet(&p->lock); do { fildes[0] = 0; while (p->fds[fildes[0]].file != NULL && fildes[0]++ < p->maxfd); fildes[1] = fildes[0] + 1; while (p->fds[fildes[1]].file != NULL && fildes[1]++ < p->maxfd); if (fildes[0] > p->maxfd || fildes[1] > p->maxfd) break; p->fds[fildes[0]].flags = p->fds[fildes[1]].flags = 0; if ((fo = p->fds[fildes[0]].file = vm_kmalloc(sizeof(open_file_t))) == NULL) { /* FIXME: destroy pipe */ break; } proc_lockInit(&fo->lock); hal_memcpy(&fo->oid, &oid, sizeof(oid)); fo->refs = 1; fo->offset = 0; fo->type = ftPipe; fo->status = O_RDONLY; if ((fi = p->fds[fildes[1]].file = vm_kmalloc(sizeof(open_file_t))) == NULL) { p->fds[fildes[0]].file = NULL; proc_lockDone(&fo->lock); vm_kfree(fo); /* FIXME: destroy pipe */ break; } proc_lockInit(&fi->lock); hal_memcpy(&fi->oid, &oid, sizeof(oid)); fi->refs = 1; fi->offset = 0; fi->type = ftPipe; fi->status = O_WRONLY; proc_lockClear(&p->lock); return 0; } while (0); proc_lockClear(&p->lock); return -1; } int posix_mkfifo(const char *pathname, mode_t mode) { TRACE("mkfifo(%s, %x)", pathname, mode); process_info_t *p; oid_t oid, file; oid_t pipesrv; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; hal_memset(&oid, 0, sizeof(oid)); if ((proc_lookup("/dev/posix/pipes", &pipesrv)) < 0) return set_errno(-ENOSYS); if (proc_create(pipesrv.port, pxPipe, 0, oid, pipesrv, NULL, &oid) < 0) return set_errno(-EIO); /* link pipe in posix server */ if (proc_link(oid, oid, pathname) < 0) return set_errno(-EIO); /* create pipe in filesystem */ if (posix_create(pathname, 2 /* otDev */, mode, oid, &file) < 0) return set_errno(-EIO); proc_lockClear(&p->lock); return 0; } int posix_link(const char *path1, const char *path2) { process_info_t *p; oid_t oid, dir; int err; char *name, *basename, *dirname; int namelen; namelen = hal_strlen(path2); name = vm_kmalloc(namelen + 1); hal_memcpy(name, path2, namelen + 1); splitname(name, &basename, &dirname); do { if ((p = pinfo_find(proc_current()->process->id)) == NULL) { err = -ENOSYS; break; } if ((err = proc_lookup(dirname, &dir)) < 0) break; if ((err = proc_lookup(path1, &oid)) < 0) break; if ((err = proc_link(dir, oid, basename)) < 0) break; if (dir.port != oid.port) { /* Signal link to device */ /* FIXME: refcount here? */ if ((err = proc_link(oid, oid, path2)) < 0) break; } err = EOK; } while (0); vm_kfree(name); return set_errno(err); } int posix_unlink(const char *pathname) { process_info_t *p; oid_t oid, dir; int err; char *name, *basename, *dirname; int namelen; namelen = hal_strlen(pathname); name = vm_kmalloc(namelen + 1); hal_memcpy(name, pathname, namelen + 1); splitname(name, &basename, &dirname); do { if ((p = pinfo_find(proc_current()->process->id)) == NULL) { err = -ENOSYS; break; } if ((err = proc_lookup(dirname, &dir)) < 0) break; if ((err = proc_lookup(pathname, &oid)) < 0) break; if ((err = proc_unlink(dir, oid, basename)) < 0) break; if (dir.port != oid.port) { /* Signal unlink to device */ /* FIXME: refcount here? */ if ((err = proc_unlink(oid, oid, pathname)) < 0) break; } err = EOK; } while (0); vm_kfree(name); return set_errno(err); } off_t posix_lseek(int fildes, off_t offset, int whence) { return -1; } int posix_ftruncate(int fildes, off_t length) { return -1; } int posix_fstat(int fd, struct stat *buf) { open_file_t *f; process_info_t *p; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; if (fd < 0 || fd > p->maxfd || (f = p->fds[fd].file) == NULL) return set_errno(-EBADF); switch (f->type) { case ftRegular: buf->st_mode = S_IFREG; break; case ftPipe: case ftFifo: buf->st_mode = S_IFIFO; break; case ftInetSocket: case ftUnixSocket: buf->st_mode = S_IFSOCK; break; case ftTty: buf->st_mode = S_IFCHR; break; default: buf->st_mode = 0; break; } buf->st_uid = 0; buf->st_gid = 0; buf->st_size = proc_size(f->oid); buf->st_dev = f->oid.port; buf->st_ino = (int)f->oid.id; /* FIXME */ return 0; } static int socksrvcall(msg_t *msg) { oid_t oid; int err; if ((err = proc_lookup(PATH_SOCKSRV, &oid)) < 0) return set_errno(err); if ((err = proc_send(oid.port, msg)) < 0) return set_errno(err); return 0; } static ssize_t sockcall(int socket, msg_t *msg) { process_info_t *p; open_file_t *f; sockport_resp_t *smo = (void *)msg->o.raw; int err; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; if ((f = p->fds[socket].file) == NULL) return set_errno(-EBADF); if (f->type != ftInetSocket) return set_errno(-ENOTSOCK); if ((err = proc_send(f->oid.port, msg)) < 0) return set_errno(err); err = smo->ret; return set_errno(err); } static ssize_t socknamecall(int socket, msg_t *msg, struct sockaddr *address, socklen_t *address_len) { sockport_resp_t *smo = (void *)msg->o.raw; ssize_t err; if ((err = sockcall(socket, msg)) < 0) return err; if (smo->sockname.addrlen > *address_len) smo->sockname.addrlen = *address_len; hal_memcpy(address, smo->sockname.addr, smo->sockname.addrlen); *address_len = smo->sockname.addrlen; return err; } static ssize_t sockdestcall(int socket, msg_t *msg, const struct sockaddr *address, socklen_t address_len) { sockport_msg_t *smi = (void *)msg->i.raw; if (address_len > sizeof(smi->send.addr)) return set_errno(-EINVAL); smi->send.addrlen = address_len; hal_memcpy(smi->send.addr, address, address_len); return sockcall(socket, msg); } int posix_accept(int socket, struct sockaddr *address, socklen_t *address_len) { process_info_t *p; ssize_t err; msg_t msg; oid_t oid; sockport_msg_t *smi = (void *)msg.i.raw; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; hal_memset(&oid, 0, sizeof(oid)); hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmAccept; smi->send.flags = 0; if ((err = socknamecall(socket, &msg, address, address_len)) < 0) return set_errno(err); oid.port = err; if ((err = posix_newFile(p, 0)) < 0) { msg.type = mtClose; proc_send(oid.port, &msg); return set_errno(err); } p->fds[err].file->type = ftInetSocket; hal_memcpy(&p->fds[err].file->oid, &oid, sizeof(oid)); return err; } int posix_bind(int socket, const struct sockaddr *address, socklen_t address_len) { msg_t msg; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmBind; return sockdestcall(socket, &msg, address, address_len); } int posix_connect(int socket, const struct sockaddr *address, socklen_t address_len) { msg_t msg; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmConnect; return sockdestcall(socket, &msg, address, address_len); } int posix_getpeername(int socket, struct sockaddr *address, socklen_t *address_len) { msg_t msg; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmGetPeerName; return socknamecall(socket, &msg, address, address_len); } int posix_getsockname(int socket, struct sockaddr *address, socklen_t *address_len) { msg_t msg; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmGetSockName; return socknamecall(socket, &msg, address, address_len); } int posix_getsockopt(int socket, int level, int optname, void *optval, socklen_t *optlen) { msg_t msg; sockport_msg_t *smi = (void *)msg.i.raw; ssize_t ret; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmGetOpt; smi->opt.level = level; smi->opt.optname = optname; msg.o.data = optval; msg.o.size = *optlen; ret = sockcall(socket, &msg); if (ret < 0) return ret; *optlen = ret; return 0; } int posix_listen(int socket, int backlog) { msg_t msg; sockport_msg_t *smi = (void *)msg.i.raw; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmListen; smi->listen.backlog = backlog; return sockcall(socket, &msg); } ssize_t posix_recvfrom(int socket, void *message, size_t length, int flags, struct sockaddr *src_addr, socklen_t *src_len) { msg_t msg; sockport_msg_t *smi = (void *)msg.i.raw; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmRecv; smi->send.flags = flags; msg.o.data = message; msg.o.size = length; return socknamecall(socket, &msg, src_addr, src_len); } ssize_t posix_sendto(int socket, const void *message, size_t length, int flags, const struct sockaddr *dest_addr, socklen_t dest_len) { msg_t msg; sockport_msg_t *smi = (void *)msg.i.raw; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmSend; smi->send.flags = flags; msg.i.data = (void *)message; msg.i.size = length; return sockdestcall(socket, &msg, dest_addr, dest_len); } int posix_socket(int domain, int type, int protocol) { process_info_t *p; msg_t msg; sockport_msg_t *smi = (void *)msg.i.raw; int err; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmSocket; smi->socket.domain = domain; smi->socket.type = type; smi->socket.protocol = protocol; if ((err = socksrvcall(&msg)) < 0) return err; if (msg.o.lookup.err < 0) return set_errno(msg.o.lookup.err); if ((err = posix_newFile(p, 0)) < 0) return set_errno(err); p->fds[err].file->type = ftInetSocket; hal_memcpy(&p->fds[err].file->oid, &msg.o.lookup.res, sizeof(oid_t)); return err; } int posix_shutdown(int socket, int how) { msg_t msg; sockport_msg_t *smi = (void *)msg.i.raw; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmShutdown; smi->send.flags = how; return sockcall(socket, &msg); } int posix_setsockopt(int socket, int level, int optname, const void *optval, socklen_t optlen) { msg_t msg; sockport_msg_t *smi = (void *)msg.i.raw; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmSetOpt; smi->opt.level = level; smi->opt.optname = optname; msg.i.data = (void *)optval; msg.i.size = optlen; return sockcall(socket, &msg); } static int posix_fcntlDup(int fd, int fd2, int cloexec) { process_info_t *p; int err; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -1; proc_lockSet(&p->lock); while (p->fds[fd2].file != NULL && fd2++ < p->maxfd); if ((err = _posix_dup2(p, fd, fd2)) == fd2 && cloexec) p->fds[fd2].flags = FD_CLOEXEC; proc_lockClear(&p->lock); return err; } static int posix_fcntlSetFd(int fd, unsigned flags) { process_info_t *p; int err = EOK; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -ENOSYS; proc_lockSet(&p->lock); if (p->fds[fd].file != NULL) p->fds[fd].flags = flags; else err = -EBADF; proc_lockClear(&p->lock); return err; } static int posix_fcntlGetFd(int fd) { process_info_t *p; int err; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -ENOSYS; proc_lockSet(&p->lock); if (p->fds[fd].file != NULL) err = p->fds[fd].flags; else err = -EBADF; proc_lockClear(&p->lock); return err; } static int _sock_getfl(open_file_t *f) { msg_t msg; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmGetFl; return proc_send(f->oid.port, &msg); } static int _sock_setfl(open_file_t *f, int val) { msg_t msg; sockport_msg_t *smi = (void *)msg.i.raw; hal_memset(&msg, 0, sizeof(msg)); msg.type = sockmSetFl; smi->send.flags = val; return proc_send(f->oid.port, &msg); } static int posix_fcntlSetFl(int fd, int val) { process_info_t *p; open_file_t *f; int err = EOK; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -ENOSYS; proc_lockSet(&p->lock); if ((f = p->fds[fd].file) != NULL) { if (f->type == ftInetSocket) { proc_lockClear(&p->lock); return _sock_setfl(f, val); } else { f->status = val; } } else { err = -EBADF; } proc_lockClear(&p->lock); return err; } static int posix_fcntlGetFl(int fd) { process_info_t *p; open_file_t *f; int err = EOK; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return -ENOSYS; proc_lockSet(&p->lock); if ((f = p->fds[fd].file) != NULL) { if (f->type == ftInetSocket) { proc_lockClear(&p->lock); return _sock_getfl(f); } else { err = f->status; } } else { err = -EBADF; } proc_lockClear(&p->lock); return err; } int posix_fcntl(int fd, unsigned int cmd, char *ustack) { TRACE("fcntl(%d, %u)", fd, cmd); int err = -EINVAL, fd2; unsigned long arg; int cloexec = 0; switch (cmd) { case F_DUPFD_CLOEXEC: cloexec = 1; case F_DUPFD: GETFROMSTACK(ustack, int, fd2, 2); err = posix_fcntlDup(fd, fd2, cloexec); break; case F_GETFD: err = posix_fcntlGetFd(fd); break; case F_SETFD: GETFROMSTACK(ustack, unsigned long, arg, 2); err = posix_fcntlSetFd(fd, arg); break; case F_GETFL: err = posix_fcntlGetFl(fd); break; case F_SETFL: GETFROMSTACK(ustack, unsigned int, arg, 2); err = posix_fcntlSetFl(fd, arg); break; case F_GETLK: case F_SETLK: case F_SETLKW: case F_GETOWN: case F_SETOWN: default: break; } return set_errno(err); } int posix_ioctl(int fildes, int request, char *ustack) { process_info_t *p; open_file_t *f; int err; msg_t msg; if ((p = pinfo_find(proc_current()->process->id)) == NULL) return set_errno(-ENOSYS); proc_lockSet(&p->lock); if ((f = p->fds[fildes].file) == NULL) { proc_lockClear(&p->lock); return set_errno(-EBADF); } proc_lockClear(&p->lock); switch (request) { /* TODO: handle POSIX defined requests */ default: hal_memset(&msg, 0, sizeof(msg)); msg.type = mtDevCtl; GETFROMSTACK(ustack, void *, msg.i.data, 2); GETFROMSTACK(ustack, size_t, msg.i.size, 3); GETFROMSTACK(ustack, void *, msg.o.data, 4); GETFROMSTACK(ustack, size_t, msg.o.size, 5); err = proc_send(f->oid.port, &msg); } return err; } void posix_init(void) { proc_lockInit(&posix_common.lock); lib_rbInit(&posix_common.pid, pinfo_cmp, NULL); posix_common.fresh = 0; }
2.265625
2
2024-11-18T21:09:28.680692+00:00
2018-02-03T18:01:00
68b9b8e1b7ed07cbefb290f5fc79e47679523260
{ "blob_id": "68b9b8e1b7ed07cbefb290f5fc79e47679523260", "branch_name": "refs/heads/master", "committer_date": "2018-02-03T18:01:00", "content_id": "af2f67d34ad79ed0904429b4d0f53637145109ef", "detected_licenses": [ "MIT" ], "directory_id": "bc4818dde50bca6455541cae4813128d15662207", "extension": "c", "filename": "template.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 120115017, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1150, "license": "MIT", "license_type": "permissive", "path": "/template.c", "provenance": "stackv2-0065.json.gz:7303", "repo_name": "SuperOxigen/cs-games-2018-os-challenge", "revision_date": "2018-02-03T18:01:00", "revision_id": "5320873029ac31e334ac1edd041e0f4495c382a3", "snapshot_id": "51f40fc5d87504136e722baa38887eb040e01307", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/SuperOxigen/cs-games-2018-os-challenge/5320873029ac31e334ac1edd041e0f4495c382a3/template.c", "visit_date": "2021-05-08T15:27:45.637249" }
stackv2
/* * CS Games 2018 - Operating System Challenge */ #include <arpa/inet.h> #include <netinet/in.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> void write_uint16_to_packet(char * packet_buffer, int offset, uint16_t value) { if (!packet_buffer) return; /* Convert the integer byte representation to network order */ value = htons(value); memcpy(&packet_buffer[offset], &value, 2); } uint16_t read_uint16_from_packet(char * packet_buffer, int offset) { uint16_t value; if (!packet_buffer) return 0; memcpy(&value, &packet_buffer[offset], 2); return ntohs(value); } int main(int argc, char ** argv) { int port; /* Add your variables here. */ if (argc < 2 || sscanf(argv[1], "%d", &port) != 1) { fprintf(stderr, "Program requires a port number as the first argument\n"); exit(EXIT_FAILURE); } if (port <= 1023 || port > 65535) { fprintf(stderr, "Port number must be greater than or equal to 1024 " "and less than or equal to 65535\n"); } }
3.0625
3
2024-11-18T21:09:29.942784+00:00
2020-07-02T05:16:29
ccaf112844e8c619b675fef2120c6708a86053af
{ "blob_id": "ccaf112844e8c619b675fef2120c6708a86053af", "branch_name": "refs/heads/master", "committer_date": "2020-07-02T05:16:29", "content_id": "0754ac0a441efc95d733b60ad09d2634fe129bd0", "detected_licenses": [ "MIT" ], "directory_id": "6d79377ae1876a7771bcc2dc6cd3e1e9a96d7f94", "extension": "c", "filename": "boundingBox_test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 271184485, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 994, "license": "MIT", "license_type": "permissive", "path": "/src/graphics/pictures/boundingBox/boundingBox_test.c", "provenance": "stackv2-0065.json.gz:7689", "repo_name": "AngheloAlf/GenIAlgos", "revision_date": "2020-07-02T05:16:29", "revision_id": "8354895a0a085e71a87ff27ec32317882d98e89b", "snapshot_id": "30a546fba7ea6c7bb8cedfaabc1cf6cab93c1e7e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AngheloAlf/GenIAlgos/8354895a0a085e71a87ff27ec32317882d98e89b/src/graphics/pictures/boundingBox/boundingBox_test.c", "visit_date": "2022-11-16T01:51:44.683955" }
stackv2
#include "boundingBox.h" #include "utils/io/io.h" #include "utils/text/text.h" #include <stdio.h> #include <stdlib.h> #define BYTES_PER_TILE 8 #define WIDTH_IN_TILES 7 #define HEIGHT_IN_TILES 7 #define BUFF_SIZE WIDTH_IN_TILES*HEIGHT_IN_TILES*BYTES_PER_TILE void check_arguments(int argc, char **argv){ if(argc < 2){ printf("Usage: %s %s\n", argv[0], UNDERLINE("sprite_file")); exit(-1); } } int main(int argc, char **argv){ check_arguments(argc, argv); const char *filename = argv[1]; uint8_t full_buffer[3*BUFF_SIZE]; uint8_t *buffer0 = &full_buffer[0*BUFF_SIZE]; uint8_t *buffer1 = &full_buffer[1*BUFF_SIZE]; uint8_t *buffer2 = &full_buffer[2*BUFF_SIZE]; readFile(&full_buffer[1*BUFF_SIZE], 2*BUFF_SIZE, filename, 0); addBoundingBox(BUFF_SIZE, buffer0, buffer1, buffer2, 0x55, WIDTH_IN_TILES, HEIGHT_IN_TILES, BYTES_PER_TILE); writeFile(&full_buffer[1*BUFF_SIZE], 2*BUFF_SIZE, "bb_out.bin", 0); return 0; }
2.234375
2
2024-11-18T21:09:30.608120+00:00
2019-04-23T15:56:47
dae7c78308ee3fc3b9fcbe424921331770fc3efa
{ "blob_id": "dae7c78308ee3fc3b9fcbe424921331770fc3efa", "branch_name": "refs/heads/master", "committer_date": "2019-04-23T15:56:47", "content_id": "9b13a1235bb8e61f57cf0353e139d52ddd6e3106", "detected_licenses": [ "MIT" ], "directory_id": "17e6d110a6a685cdc63a186963c921cb91450d15", "extension": "c", "filename": "subsample.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 159146747, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 390, "license": "MIT", "license_type": "permissive", "path": "/vivado/proj/HDMI.sdk/QLight_1/src/subsample.c", "provenance": "stackv2-0065.json.gz:8203", "repo_name": "Q-Mart/QLight", "revision_date": "2019-04-23T15:56:47", "revision_id": "18c1d2b6dd8a2a262230596e9cf20cdc36e7052f", "snapshot_id": "e0ea175e1115df9b66c42c3139ce1d4ad7e82003", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Q-Mart/QLight/18c1d2b6dd8a2a262230596e9cf20cdc36e7052f/vivado/proj/HDMI.sdk/QLight_1/src/subsample.c", "visit_date": "2020-04-08T07:39:34.542093" }
stackv2
#include "subsample.h" u32 getNewSubsampleDelay(u8 numberofDifferencesDetected, u32 currentDelay) { if (numberofDifferencesDetected < 4) { if ((currentDelay + INCREASE_STEP) > MAX_DELAY) { return MAX_DELAY; } else { return currentDelay + INCREASE_STEP; } } else { if (currentDelay < DECREASE_STEP) { return 0; } else { return currentDelay / DECREASE_STEP; } } }
2
2
2024-11-18T21:09:31.142845+00:00
2017-02-18T17:48:49
6e7ac383ab2e2f627620851d2f0e3acf48d7b24d
{ "blob_id": "6e7ac383ab2e2f627620851d2f0e3acf48d7b24d", "branch_name": "refs/heads/master", "committer_date": "2017-02-18T17:48:49", "content_id": "5be79fafcfa0b7db9cf27912719fb710f042027f", "detected_licenses": [ "Apache-2.0", "MIT" ], "directory_id": "dd80a584130ef1a0333429ba76c1cee0eb40df73", "extension": "c", "filename": "CommandLine.c", "fork_events_count": 2, "gha_created_at": "2017-02-13T16:47:00", "gha_event_created_at": "2020-03-09T00:02:12", "gha_language": null, "gha_license_id": "MIT", "github_id": 81847777, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2635, "license": "Apache-2.0,MIT", "license_type": "permissive", "path": "/external/srec/shared/src/CommandLine.c", "provenance": "stackv2-0065.json.gz:8716", "repo_name": "karunmatharu/Android-4.4-Pay-by-Data", "revision_date": "2017-02-18T17:48:49", "revision_id": "fcb778e92d4aad525ef7a995660580f948d40bc9", "snapshot_id": "466f4e169ede13c5835424c78e8c30ce58f885c1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/karunmatharu/Android-4.4-Pay-by-Data/fcb778e92d4aad525ef7a995660580f948d40bc9/external/srec/shared/src/CommandLine.c", "visit_date": "2021-03-24T13:33:01.721868" }
stackv2
/*---------------------------------------------------------------------------* * CommandLine.c * * * * Copyright 2007, 2008 Nuance Communciations, Inc. * * * * Licensed under the Apache License, Version 2.0 (the 'License'); * * you may not use this file except in compliance with the License. * * * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an 'AS IS' BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * *---------------------------------------------------------------------------*/ #include "ESR_CommandLine.h" ESR_ReturnCode ESR_CommandLineGetValue(int argc, const LCHAR * argv[], LCHAR* key, LCHAR* value, size_t* len) { const LCHAR* lastKeyFound = NULL; while (--argc > 0 && **++argv) { if (**argv != '-') { /* got value */ if (key == NULL) { /* but we don't have any key to associate it with */ continue; } else { if (lastKeyFound != NULL && LSTRCMP(lastKeyFound, key) == 0) { if (LSTRLEN(*argv) + 1 > *len) { *len = LSTRLEN(*argv) + 1; return ESR_BUFFER_OVERFLOW; } *len = LSTRLEN(*argv) + 1; LSTRCPY(value, *argv); return ESR_SUCCESS; } } } else { /* got key */ if (lastKeyFound != NULL && LSTRCMP(lastKeyFound, key) == 0) { *len = 1; LSTRCPY(value, L("")); return ESR_SUCCESS; } lastKeyFound = *argv + 1; } } /* Handle case where last argument is a key with no value */ if (lastKeyFound != NULL && LSTRCMP(lastKeyFound, key) == 0) { *len = 1; LSTRCPY(value, L("")); return ESR_SUCCESS; } return ESR_NO_MATCH_ERROR; }
2.1875
2
2024-11-18T21:09:31.279725+00:00
2020-10-18T16:33:47
1c429aa0d9b9ac45380cb92526b548718df44e20
{ "blob_id": "1c429aa0d9b9ac45380cb92526b548718df44e20", "branch_name": "refs/heads/master", "committer_date": "2020-10-18T16:33:47", "content_id": "fd78fd4ada1f7464658cdaea05383662d06d8b45", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "11a64eb4c73a0fceb38372b09b6aa8a3d367d9b3", "extension": "c", "filename": "Ex11.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 125666040, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 605, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/2sem/LP/Lista2/Ex11.c", "provenance": "stackv2-0065.json.gz:8974", "repo_name": "Mateusmsouza/Fatec", "revision_date": "2020-10-18T16:33:47", "revision_id": "ae783ef85e4f3d125b0fe80c2fe32f66846eee9c", "snapshot_id": "368959d9a1736c9735e12e8f1e5abb6a936228f2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Mateusmsouza/Fatec/ae783ef85e4f3d125b0fe80c2fe32f66846eee9c/2sem/LP/Lista2/Ex11.c", "visit_date": "2021-04-09T15:49:02.886147" }
stackv2
//Escreva um programa que leia um número inteiro maior do que zero e devolva, na tela, a //soma de todos os seus algarismos. Por exemplo, ao número 251 corresponderá o valor //8 (2 + 5 + 1). Se o número lido não for maior do que zero, o programa terminará com a //mensagem “Número inválido”. #include <stdio.h> int main(){ int numero, acumulador=0; scanf("%d", &numero); if (numero>0){ while (numero >0 ){ acumulador += numero%10; numero /= 10; } printf("Sominha: %d\n", acumulador); return 0; } printf("NÚMERO INVÁLIDO.\n"); return 0; }
3.65625
4
2024-11-18T21:09:31.357227+00:00
2018-05-07T15:08:27
d6a4b570790165aef5f18e23e6067b578d2a5864
{ "blob_id": "d6a4b570790165aef5f18e23e6067b578d2a5864", "branch_name": "refs/heads/master", "committer_date": "2018-05-07T15:08:27", "content_id": "4ff7d36eb526822015fbdcb573683a08cbc1111f", "detected_licenses": [ "MIT" ], "directory_id": "37b18b613ad7931d32ada824427f4648390eb728", "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": 113346862, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 731, "license": "MIT", "license_type": "permissive", "path": "/src/release/main.c", "provenance": "stackv2-0065.json.gz:9102", "repo_name": "ZaoLahma/Emu", "revision_date": "2018-05-07T15:08:27", "revision_id": "c0472d395ac8f3b6a8369faf1e21d9702f44872c", "snapshot_id": "025ec803ef20a8b10c2b46f74f67057db5e6b334", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ZaoLahma/Emu/c0472d395ac8f3b6a8369faf1e21d9702f44872c/src/release/main.c", "visit_date": "2021-09-14T02:28:05.291693" }
stackv2
#include "emu_debug.h" #include "emu.h" #include <stdio.h> #include <string.h> #include <stdbool.h> #define MIN_EXPECTED_NUM_ARGUMENTS (2) #define DEBUGGER_ACTIVATED_FLAG "dbg" int main(int argc, char** argv) { EMU_DEBUG_ASSERT_COND(argc >= MIN_EXPECTED_NUM_ARGUMENTS); if(argc < MIN_EXPECTED_NUM_ARGUMENTS) { (void) printf("Launch failed. Usage: \"gameboy path_to_rom\" with an optional third flag dbg\n"); } else { char* romPath = argv[1u]; bool debuggerActive = false; if(argc == 3u) { if(0u == memcmp(argv[2u], DEBUGGER_ACTIVATED_FLAG, strlen(DEBUGGER_ACTIVATED_FLAG))) { debuggerActive = true; } } EMU_init(romPath, debuggerActive); EMU_run(); } }
2.53125
3
2024-11-18T21:09:32.717364+00:00
2014-11-12T16:43:36
46c2a8a209d79243d76aa1ab1da982a1e8cd5f27
{ "blob_id": "46c2a8a209d79243d76aa1ab1da982a1e8cd5f27", "branch_name": "refs/heads/master", "committer_date": "2014-11-12T16:43:36", "content_id": "1315e6b95b592c8fa6dc9ecd0bfc2d12d5f0349b", "detected_licenses": [ "MIT" ], "directory_id": "e24d2b446c40eed76506c7a0bee2ef81b55943bd", "extension": "h", "filename": "gtkfieldcard.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": 1259, "license": "MIT", "license_type": "permissive", "path": "/src/gtkfieldcard.h", "provenance": "stackv2-0065.json.gz:9360", "repo_name": "Pyr0x1/gPlead", "revision_date": "2014-11-12T16:43:36", "revision_id": "8df96ae38a43fc9c509d09a398d72565947b82b5", "snapshot_id": "e0f2a2d86eee07e73de95e7e7daae6ba1f90df03", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Pyr0x1/gPlead/8df96ae38a43fc9c509d09a398d72565947b82b5/src/gtkfieldcard.h", "visit_date": "2016-08-06T21:11:28.083812" }
stackv2
/* "Extends" GtkCard to have coordinates for cards in field only */ /* To use functions belonging to GtkCard, use them passing gtk_field_card_get_gtk_card (gfcard) */ #ifndef GTKFIELDCARD_H #define GTKFIELDCARD_H #include <gtk/gtk.h> #include "gtkcard.h" typedef struct gtkfieldcard { guint row; guint col; GtkCard* gcard; guint elements[4]; // top, left, right, bottom } GtkFieldCard; GtkFieldCard* gtk_field_card_new_empty (GtkToggleButton* button, guint row, guint col); GtkFieldCard* gtk_field_card_new_with_values (GtkToggleButton* button, guint top, guint down, guint left, guint right, guint element, gboolean show, guint row, guint col); GtkFieldCard* gtk_field_card_new_random (GtkToggleButton* button, guint max, gboolean show, guint row, guint col); GtkCard* gtk_field_card_get_gtk_card (GtkFieldCard* gfcard); gint gtk_field_card_get_row (GtkFieldCard* gfcard); gint gtk_field_card_get_col (GtkFieldCard* gfcard); gint gtk_field_card_clear (GtkFieldCard* gfcard); gint gtk_field_card_augment_values_from_runes (GtkFieldCard* gfcard, GtkCard* player_card); gint gtk_field_card_get_expected_augmentation (GtkFieldCard* gfcard, GtkCard* gcard, guint position); void gtk_field_card_free (GtkFieldCard* gfcard); #endif /* GTKFIELDCARD_H */
2.0625
2
2024-11-18T21:09:33.361791+00:00
2020-09-04T16:54:47
2d3ea048796cc2555bce16ee9a4af5dc7c1fd0b0
{ "blob_id": "2d3ea048796cc2555bce16ee9a4af5dc7c1fd0b0", "branch_name": "refs/heads/master", "committer_date": "2020-09-04T16:54:47", "content_id": "792d4ccab8b1f95a1939a369fcbb7a3e3c611b66", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "2a01d8d0b5715216cb77d08b973676fe8295bb6a", "extension": "c", "filename": "upnp-search.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 261803121, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2204, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/cpp/hanser_c_und_linux/Quelltexte/Kapitel7/upnp-search.c", "provenance": "stackv2-0065.json.gz:9745", "repo_name": "maximilianharr/code_snippets", "revision_date": "2020-09-04T16:54:47", "revision_id": "8b271e6fa9174e24200e88be59e417abd5f2f59a", "snapshot_id": "78cb72de2f5765f8578ee46b381bb8abf25918bc", "src_encoding": "ISO-8859-1", "star_events_count": 0, "url": "https://raw.githubusercontent.com/maximilianharr/code_snippets/8b271e6fa9174e24200e88be59e417abd5f2f59a/cpp/hanser_c_und_linux/Quelltexte/Kapitel7/upnp-search.c", "visit_date": "2022-12-12T23:13:12.184496" }
stackv2
/* upnp-search.c - UPnP-Dienste abfragen */ # include <stdio.h> # include <unistd.h> # include <string.h> # include <sys/poll.h> # include <sys/types.h> # include <sys/socket.h> # include <sys/time.h> # include <netinet/in.h> # include <arpa/inet.h> # define BUF_SIZE 20000 # define TIMEOUT 3000 /* Millisekunden */ # define UPNP_ADDR "239.255.255.250" # define UPNP_PORT 1900 int main() { int sock_fd, length, i, err; struct sockaddr_in server_addr, from_addr; socklen_t addr_size; struct pollfd pollfd; static char buffer[BUF_SIZE]; /*--- Socket öffnen ---*/ sock_fd = socket(PF_INET, SOCK_DGRAM, 0); if (sock_fd == -1) { perror("upnp-search: Can't create new socket"); return(1); } /*--- Zieladresse ---*/ server_addr.sin_family = AF_INET; server_addr.sin_port = htons(UPNP_PORT); inet_aton(UPNP_ADDR, &(server_addr.sin_addr)); /*--- Anfrage senden ---*/ strcpy(buffer, "M-SEARCH * HTTP/1.1\r\n" "HOST: 239.255.255.250:1900\r\n" "MAN: \"ssdp:discover\"\r\n" "MX: 2\r\n" "ST: ssdp:all\r\n" "\r\n"); length = sendto(sock_fd, buffer, strlen(buffer), 0, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)); if (length != strlen(buffer)) { perror("upnp-search: sendto() failed"); return(1); } /*--- auf Antwort warten ---*/ pollfd.fd = sock_fd; /* Polling vorbereiten */ pollfd.events = POLLIN | POLLPRI; i = 0; while (1) { err = poll(&pollfd, 1, TIMEOUT); if (err < 0) { perror("upnp-search: poll() failed"); break; } else if (err == 0) /* Timeout erreicht */ { if (i == 0) printf("<No response received.>\n"); break; } else { addr_size = sizeof(struct sockaddr_in); length = recvfrom(sock_fd, buffer, BUF_SIZE-1, 0, (struct sockaddr *)&from_addr, &addr_size); if (length == -1) perror("upnp-search: recvfrom() failed"); else { buffer[length] = '\0'; printf("\33[1m---- Response from %s:\33[0m\n%s\n", inet_ntoa(from_addr.sin_addr), buffer); } i = 1; } } close(sock_fd); return(0); }
2.75
3
2024-11-18T21:09:34.289533+00:00
2023-07-17T21:01:17
87aff021801a9bc1cfab097a13b5d6ba08a80974
{ "blob_id": "87aff021801a9bc1cfab097a13b5d6ba08a80974", "branch_name": "refs/heads/main", "committer_date": "2023-07-21T00:07:03", "content_id": "0ecad62cea632d4d713cd8cae6e1d40d009b011d", "detected_licenses": [ "MIT", "BSD-2-Clause" ], "directory_id": "9f33f09e5398d9b6104e09d54264c89e0a1e0e86", "extension": "c", "filename": "str_token.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": 2711, "license": "MIT,BSD-2-Clause", "license_type": "permissive", "path": "/src/str_token.c", "provenance": "stackv2-0065.json.gz:10387", "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/str_token.c", "visit_date": "2023-08-28T11:53:53.650125" }
stackv2
#include "str_token.h" #include <errno.h> #include <string.h> #include "alloc.h" #include "log.h" /** * Does not assume that @string is NULL-terminated. */ static char * string_clone(void const *string, size_t size) { char *result; result = pmalloc(size + 1); memcpy(result, string, size); result[size] = '\0'; return result; } int ia5s2string(ASN1_IA5STRING *ia5, char **result) { if (ia5->flags & ASN1_STRING_FLAG_BITS_LEFT) return pr_val_err("CRL URI IA5String has unused bits."); *result = string_clone(ia5->data, ia5->length); return 0; } int BN2string(BIGNUM *bn, char **_result) { BIO *bio; uint64_t written; char *result; /* Callers can call free() whether this function fails or not. */ *_result = NULL; bio = BIO_new(BIO_s_mem()); if (bio == NULL) enomem_panic(); if (BN_print(bio, bn) == 0) { BIO_free(bio); return val_crypto_err("Unable to print the BIGNUM into a BIO"); } written = BIO_number_written(bio); result = pmalloc(written + 1); BIO_read(bio, result, written); result[written] = '\0'; BIO_free(bio); *_result = result; return 0; } void string_tokenizer_init(struct string_tokenizer *tokenizer, char const *str, size_t str_len, unsigned char separator) { tokenizer->str = str; tokenizer->str_len = str_len; tokenizer->separator = separator; tokenizer->start = 0; tokenizer->end = 0; } /** * Returns whether a new token was found. */ bool string_tokenizer_next(struct string_tokenizer *tokenizer) { size_t end = tokenizer->end; if (end == tokenizer->str_len) return false; /* Ignore "empty" tokens */ while (tokenizer->str[end] == tokenizer->separator) { end++; if (end == tokenizer->str_len) { tokenizer->start = end; tokenizer->end = end; return false; } } tokenizer->start = end; for (; end < tokenizer->str_len; end++) if (tokenizer->str[end] == tokenizer->separator) break; tokenizer->end = end; return true; } /** * Returns whether the tokens described by @t1 and @t2 are identical. */ bool token_equals(struct string_tokenizer *t1, struct string_tokenizer *t2) { size_t t1len = t1->end - t1->start; size_t t2len = t2->end - t2->start; return (t1len == t2len) ? (memcmp(t1->str + t1->start, t2->str + t2->start, t1len) == 0) : false; } char * token_read(struct string_tokenizer *tokenizer) { return string_clone(tokenizer->str + tokenizer->start, tokenizer->end - tokenizer->start); } size_t token_count(struct string_tokenizer *tokenizer) { struct string_tokenizer copy; size_t count; string_tokenizer_init(&copy, tokenizer->str, tokenizer->str_len, tokenizer->separator); count = 0; while (string_tokenizer_next(&copy)) count++; return count; }
2.875
3
2024-11-18T21:09:34.538731+00:00
2021-02-02T06:38:28
8a6dab276badbcf890502ed9c131e3b0838ed9ba
{ "blob_id": "8a6dab276badbcf890502ed9c131e3b0838ed9ba", "branch_name": "refs/heads/master", "committer_date": "2021-02-02T06:38:28", "content_id": "8cc3df2ad535820932bdb3e74fc07f8286062bec", "detected_licenses": [ "MIT" ], "directory_id": "93f23682eec53944d1ed9107ab914820ab5dba1c", "extension": "c", "filename": "ast.c", "fork_events_count": 13, "gha_created_at": "2019-10-15T08:53:56", "gha_event_created_at": "2022-04-25T15:32:19", "gha_language": "C", "gha_license_id": "MIT", "github_id": 215252215, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 22120, "license": "MIT", "license_type": "permissive", "path": "/ami/lib/ast.c", "provenance": "stackv2-0065.json.gz:10643", "repo_name": "DevoInc/pCraft", "revision_date": "2021-02-02T06:38:28", "revision_id": "089bac6eb0d5963c52dc5465378213ef1ece5c10", "snapshot_id": "48f43c4fd4d25009363baf3c97b3a6e79dd37809", "src_encoding": "UTF-8", "star_events_count": 91, "url": "https://raw.githubusercontent.com/DevoInc/pCraft/089bac6eb0d5963c52dc5465378213ef1ece5c10/ami/lib/ast.c", "visit_date": "2022-05-30T03:31:42.779117" }
stackv2
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <libgen.h> #include <ami/kvec.h> #include <ami/ami.h> #include <ami/action.h> #include <ami/tree.h> #include <ami/ast.h> #include <ami/csvread.h> #include <ami/base64.h> #include <ami/rc4.h> #include <ami/strutil.h> #include <uuid/uuid.h> #include <md5.h> #include <sha1.h> #include <sha256.h> static char *_replace_strval_from_variables(ami_t *ami, char *strval) { char *replaced_buf = NULL; char *found; khint_t k; replaced_buf = strdup(strval); if (ami->variables) { for (k = 0; k < kh_end(ami->variables); ++k) { if (kh_exist(ami->variables, k)) { char *key = (char *)kh_key(ami->variables, k); ami_variable_t *value = (ami_variable_t *)kh_value(ami->variables, k); if (!value->type == AMI_VAR_STR) { fprintf(stderr, "Error: Can only get value from a string variable!\n"); return replaced_buf; } char *replacevar = ami_strutil_make_replacevar(key); found = strstr(replaced_buf, replacevar); if (found) { char *new_replaced_buf = ami_strutil_replace_all_substrings(replaced_buf, replacevar, value->strval); free(replaced_buf); replaced_buf = new_replaced_buf; } free(replacevar); } } } return replaced_buf; } static void walk_node(ami_t *ami, ami_node_t *node, int repeat_index, int right) { ami_node_t *n; ami_action_t *action; int index; char *stack_str = NULL; // Keeping the last value int stack_int = 0; char *tmp_str; /* static char *csv_args[4] = { NULL, NULL, NULL, NULL }; // For now, we only have the CSV function */ kvec_t(char *) values_stack; static int varpos = 0; ami_field_action_t *field_action; char *replaced_var = NULL; int repeat_n = 0; size_t array_values_len = 0; int array_get_index = 0; ami_variable_t *globalvar; ami_variable_t *localvar; ami_variable_t *tmp_var = NULL; for (n = node; n; n = right ? n->right : n->next) { if ((n->strval) && (!n->is_verbatim)) { if (n->type == AMI_NT_VARVALSTR) { replaced_var = _replace_strval_from_variables(ami, n->strval); } } switch(n->type) { case AMI_NT_REFERENCE: kv_push(char *, ami->references, n->strval); break; case AMI_NT_TAG: kv_push(char *, ami->tags, n->strval); break; case AMI_NT_ACTION: ami->in_action = 1; action = ami_action_new(); if (!action) { fprintf(stderr, "Error creating the action!\n"); } action->name = n->strval; break; case AMI_NT_EXEC: action->exec = n->strval; break; case AMI_NT_ACTIONCLOSE: ami->in_action = 0; /* ami_field_action_debug(action); */ if (right) { action->repeat_index = repeat_index; } action->sleep_cursor = ami->sleep_cursor; /* action = ami_action_copy_variables(ami, action); */ if (ami->action_cb) { ami->action_cb(action, ami->action_cb_userdata1, ami->action_cb_userdata2); } else { fprintf(stderr,"*** Warning: No Action Callback Set!\n"); } ami_action_close(action); /* ami_erase_local_variables(ami); */ break; case AMI_NT_REPEAT: { char *lastval = kv_A(ami->values_stack, kv_size(ami->values_stack)-1); /* ami_variable_t *repeat = ami_get_variable(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); */ repeat_n = (int)strtod(lastval, NULL); free(lastval); } ami->in_repeat = 1; tmp_var = ami_variable_new(); for (index = 1; index <= repeat_n; index++) { ami_variable_set_int(tmp_var, index); ami_set_variable(ami, n->strval, tmp_var); walk_node(ami, n->right, index, 1); } /* ami_erase_repeat_variables(ami); */ ami->in_repeat = 0; index = 0; break; case AMI_NT_MESSAGE: printf("%s\n", n->strval); break; case AMI_NT_VARVALSTR: if (replaced_var) { kv_push(char *, ami->values_stack, strdup(replaced_var)); free(replaced_var); } else { kv_push(char *, ami->values_stack, strdup(n->strval)); } break; case AMI_NT_VARVALINT: asprintf(&tmp_str, "%d", n->intval); kv_push(char *, ami->values_stack, strdup(tmp_str)); free(tmp_str); /* kv_a(char *, ami->values_stack, strdup(n->strval)); */ break; case AMI_NT_VARVAR: kv_push(char *, ami->values_stack, strdup(n->strval)); break; case AMI_NT_VARNAME: if (array_get_index > 0) { char *lastval = kv_A(ami->values_stack, kv_size(ami->values_stack)-1); ami_variable_t *arrayfrom = ami_get_variable(ami, lastval); if (arrayfrom) { ami_variable_t *var = ami_variable_array_get_at_index(arrayfrom, array_get_index); ami_set_variable(ami, n->strval, ami_variable_copy(var)); } else { fprintf(stderr, "Could not fetch our array to the global variable!\n"); } free(lastval); } else { globalvar = ami_get_variable(ami, n->strval); tmp_str = kv_A(ami->values_stack, kv_size(ami->values_stack)-1); if (!tmp_str) { fprintf(stderr, "Error: no such value for '%s'\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); exit(1); } if (!globalvar) { globalvar = ami_variable_new_string(tmp_str); } else { ami_variable_set_string(globalvar, tmp_str); } ami_set_variable(ami, n->strval, globalvar); free(tmp_str); } array_get_index = 0; break; case AMI_NT_LOCALVARNAME: if (array_get_index > 0) { char *lastval = kv_A(ami->values_stack, kv_size(ami->values_stack)-1); ami_variable_t *arrayfrom = ami_action_get_variable(action, lastval); if (arrayfrom) { ami_variable_t *var = ami_variable_array_get_at_index(arrayfrom, array_get_index); ami_action_set_variable(action, n->strval, ami_variable_copy(var)); } else { fprintf(stderr, "Could not fetch our array to the local variable!\n"); } free(lastval); } else { localvar = ami_action_get_variable(action, n->strval); tmp_str = kv_A(ami->values_stack, kv_size(ami->values_stack)-1); if (!tmp_str) { fprintf(stderr, "Error: no such value for '%s'\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); exit(1); } if (!localvar) { localvar = ami_variable_new_string(tmp_str); } ami_action_set_variable(action, n->strval, localvar); free(tmp_str); } array_get_index = 0; break; case AMI_NT_FIELDFUNC: /* printf("Fieldfunc :%s\n", n->strval); // ip */ if (!strcmp("replace", kv_A(ami->values_stack, kv_size(ami->values_stack)-1))) { size_t stacklen = kv_size(ami->values_stack); /* printf("the stacklen when we replace:%ld\n", stacklen); */ /* for (size_t i = 0; i < stacklen; i++) { */ /* printf("i:%d;val:%s\n", i, kv_A(ami->values_stack, i)); */ /* } */ for (int i = 1; i <= ami->replace_count; i++) { int pos_from = (i*-1)-i; int pos_to = (i*-1)-(i+1); char *to = kv_A(ami->values_stack, stacklen+pos_to); char *from = kv_A(ami->values_stack, stacklen+pos_from); field_action = ami_field_action_new(); field_action->field = n->strval; field_action->action = "replace"; field_action->left = ami_get_nested_variable_as_str(ami, from); field_action->right = ami_get_nested_variable_as_str(ami, to); action->field_actions = ami_field_action_append(action->field_actions, field_action); } ami->replace_count = 0; } else { fprintf(stderr, "Unknown function call on field %s: %s\n", n->strval, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); exit(1); } break; case AMI_NT_FIELDVAR: /* printf("Fieldvar :%s\n", n->strval); // FullFilePath */ field_action = ami_field_action_new(); field_action->field = n->strval; field_action->action = "set"; char *vstr = kv_A(ami->values_stack, kv_size(ami->values_stack)-1); char *value = ami_get_nested_variable_as_str(ami, vstr); if (!value) { fprintf(stderr, "Error getting value for field %s\n", n->strval); exit(1); } field_action->right = value; if (!action) { fprintf(stderr, "No Action created!\n"); } else { action->field_actions = ami_field_action_append(action->field_actions, field_action); } break; case AMI_NT_REPLACE: { /* ami_print_all_variables(ami); */ /* char *replace_with = ami_get_variable(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); */ /* printf("replace:%s with:%s\n", n->strval, replace_with); */ kv_push(char *, ami->values_stack, strdup(n->strval)); ami->replace_count++; } break; case AMI_NT_FUNCTION: if (!strcmp("base64.encode", n->strval)) { char *data = kv_A(ami->values_stack, kv_size(ami->values_stack)-1); char *b64 = base64_enc_malloc(data, strlen(data)); kv_push(char *, ami->values_stack, b64); } else if (!strcmp("base64url.encode", n->strval)) { char *data = kv_A(ami->values_stack, kv_size(ami->values_stack)-1); char *b64 = base64url_enc_malloc(data, strlen(data)); kv_push(char *, ami->values_stack, b64); } else if (!strcmp("ip.gethostbyname", n->strval)) { struct hostent *he; const char *hostname = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); char ipstr[INET6_ADDRSTRLEN]; he = gethostbyname(hostname); if (!he) { fprintf(stderr, "Could not resolve '%s'\n", hostname); exit(1); } if (inet_ntop(AF_INET, (const void *)he->h_addr_list[0], ipstr, sizeof(ipstr)) == NULL) { fprintf(stderr, "Cannot convert IP address %s: %s\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-1), strerror(errno)); exit(1); } kv_push(char *, ami->values_stack, ipstr); } else if (!strcmp("ip.cidr",n->strval)) { static const uint32_t cidr_table[] = { 0x00000000, 0x00000080, 0x000000c0, 0x000000e0, 0x000000f0, 0x000000f8, 0x000000fc, 0x000000fe, 0x000000ff, 0x000080ff, 0x0000c0ff, 0x0000e0ff, 0x0000f0ff, 0x0000f8ff, 0x0000fcff, 0x0000feff, 0x0000ffff, 0x0080ffff, 0x00c0ffff, 0x00e0ffff, 0x000fffff, 0x00f8ffff, 0x00fcffff, 0x00feffff, 0x00ffffff, 0x80ffffff, 0xc0ffffff, 0xe0ffffff, 0xf0ffffff, 0xf8ffffff, 0xfcffffff, 0xfeffffff, 0xffffffff}; char *ipaddr = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-2)); char *ipnumber = kv_A(ami->values_stack, kv_size(ami->values_stack)-1); int ipn = ami_get_nested_variable_as_int(ami, ipnumber); /* char *ipnumber = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); */ /* int ipn = (int)strtod(ipnumber, NULL); */ int ret; struct in_addr addr4; struct in_addr out_network; struct in_addr out_broadcast; struct in_addr addr_iter; char ret_network[INET6_ADDRSTRLEN]; const char ret_broadcast[INET6_ADDRSTRLEN]; char *ip, *mask; int mask_int; int counter; if (!ipaddr) { fprintf(stderr, "No such IP Address from %s\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-2)); exit(1); } ip = strtok(ipaddr, "/"); if (!ip) { fprintf(stderr, "Could not get ip from %s\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-2)); exit(1); } mask = strtok(NULL, "\0"); if (!mask) { fprintf(stderr, "Could not get mask from %s\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-2)); exit(1); } mask_int = (int)strtod(mask, NULL); if ((mask_int > 32) || (mask_int < 0)) { fprintf(stderr, "Invalid mask: %d\n", mask_int); exit(1); } ret = inet_pton(AF_INET, ip, &addr4); switch(ret) { case 1: // Success break; case 0: fprintf(stderr, "Invalid network address: %s\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); exit(1); break; case -1: fprintf(stderr, "IP Conversion Error: %s\n", strerror(errno)); exit(1); break; } out_network.s_addr = ntohl(addr4.s_addr & cidr_table[mask_int]); out_broadcast.s_addr = ntohl(addr4.s_addr | ~cidr_table[mask_int]); counter = 0; for (addr_iter.s_addr = out_network.s_addr; addr_iter.s_addr <= out_broadcast.s_addr; addr_iter.s_addr++) { struct in_addr out; out.s_addr = ntohl(addr_iter.s_addr); if (inet_ntop(AF_INET, (const void *)&out, ret_network, sizeof(ret_network)) == NULL) { fprintf(stderr, "Cannot convert IP address %s: %s\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-2), strerror(errno)); exit(1); } if (counter == ipn) { break; } counter++; } /* if (inet_ntop(AF_INET, (const void *)&out_network, ret_network, sizeof(ret_network)) == NULL) { */ /* fprintf(stderr, "Cannot convert IP address %s: %s\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-2), strerror(errno)); */ /* exit(1); */ /* } */ /* if (inet_ntop(AF_INET, (const void *)&out_broadcast, ret_broadcast, sizeof(ret_broadcast)) == NULL) { */ /* fprintf(stderr, "Cannot convert IP address %s: %s\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-2), strerror(errno)); */ /* exit(1); */ /* } */ /* printf("Network return:%s, broadcast:%s\n", ret_network, ret_broadcast); */ kv_push(char *, ami->values_stack, strdup(ret_network)); } else if (!strcmp("crypto.md5", n->strval)) { const char *strbuf = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); MD5_CTX ctx; unsigned char buf[16]; md5_init(&ctx); md5_update(&ctx, strbuf, strlen(strbuf)); md5_final(&ctx, buf); char *hex = ami_rc4_to_hex(buf, 16); kv_push(char *, ami->values_stack, hex); } else if (!strcmp("crypto.sha1", n->strval)) { const char *strbuf = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); SHA1_CTX ctx; unsigned char buf[SHA1_BLOCK_SIZE]; sha1_init(&ctx); sha1_update(&ctx, strbuf, strlen(strbuf)); sha1_final(&ctx, buf); char *hex = ami_rc4_to_hex(buf, SHA1_BLOCK_SIZE); kv_push(char *, ami->values_stack, hex); } else if (!strcmp("crypto.sha256", n->strval)) { const char *strbuf = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); SHA256_CTX ctx; unsigned char buf[SHA256_BLOCK_SIZE]; sha256_init(&ctx); sha256_update(&ctx, strbuf, strlen(strbuf)); sha256_final(&ctx, buf); char *hex = ami_rc4_to_hex(buf, SHA256_BLOCK_SIZE); kv_push(char *, ami->values_stack, hex); } else if (!strcmp("string.upper", n->strval)) { const char *str_origin = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); char *s = (char *)str_origin; char c; int i = 0; char *out; out = malloc(strlen(str_origin)+1); while (c = *s++) { if ((c >= 'a') && (c <= 'z')) { out[i] = c-32; } else { out[i] = c; } i++; } out[i] = '\0'; kv_push(char *, ami->values_stack, out); } else if (!strcmp("string.lower", n->strval)) { const char *str_origin = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); char *s = (char *)str_origin; char c; int i = 0; char *out; out = malloc(strlen(str_origin)+1); while (c = *s++) { if ((c >= 'A') && (c <= 'Z')) { out[i] = c+32; } else { out[i] = c; } i++; } out[i] = '\0'; kv_push(char *, ami->values_stack, out); } else if (!strcmp("hostname_generator", n->strval)) { const char *ipaddr = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); char vowels[] = {'a','e','i','o','u','y','a','e','i','o'}; char consonants[] = {'p','b','c','z','m','f','d','s','t','r'}; in_addr_t ipint; char *ia; size_t ia_len; size_t i; char retstr[11]; // size of max int len + 1 if (!ipaddr) { fprintf(stderr, "No such IP Address from %s\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); exit(1); } ipint = inet_addr(ipaddr); asprintf(&ia, "%d", ipint); ia_len = strlen(ia); for (i = 0; i < ia_len; i++) { char pos = ia[i] - '0'; if (i%2) { retstr[i] = vowels[pos]; } else { retstr[i] = consonants[pos]; } } retstr[i] = '\0'; free(ia); kv_push(char *, ami->values_stack, retstr); } else if (!strcmp("file.amidir", n->strval)) { const char *filename = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); char *result; char *dname, *da; da = strdup(ami->file); dname = dirname(da); asprintf(&result,"%s/%s", dname, filename); free(da); kv_push(char *, ami->values_stack, result); } else if (!strcmp("file.readall", n->strval)) { const char *filename = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); struct stat st; FILE *fp; off_t filesize; fp = fopen(filename, "rb"); if (!fp) { fprintf(stderr, "file.readall: Could not read file %s\n", filename); return; } if (stat(filename, &st) == 0) { filesize = st.st_size; } else { fprintf(stderr, "file.readall: Error reading file %s\n", filename); return; } unsigned char *file_content = malloc(filesize + 1); fread(file_content, 1, filesize, fp); file_content[filesize] = '\0'; fclose(fp); char *b64 = base64url_enc_malloc(file_content, filesize); kv_push(char *, ami->values_stack, b64); } else if (!strcmp("uuid.v4", n->strval)) { // random uuid_t uuid; char retstr[37]; uuid_generate_random(uuid); uuid_unparse_lower(uuid, retstr); kv_push(char *, ami->values_stack, strdup((char *)retstr)); } else if (!strcmp("uuid.v5", n->strval)) { // form string uuid_t uuid; const uuid_t *uuid_template; const char *data = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); size_t data_len = strlen(data); char retstr[37]; uuid_template = uuid_get_template("dns"); uuid_generate_sha1(uuid, *uuid_template, (const char *)data, data_len); uuid_unparse_lower(uuid, retstr); kv_push(char *, ami->values_stack, strdup((char *)retstr)); } else if (!strcmp("crypto.rc4", n->strval)) { ami_rc4_t rc4; char *value = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-1)); size_t value_len = strlen(value); char *key = ami_get_nested_variable_as_str(ami, kv_A(ami->values_stack, kv_size(ami->values_stack)-2)); unsigned char *res = ami_rc4_do(&rc4, (unsigned char*)key, strlen(key), (unsigned char *)value, value_len); /* for (int count = 0; count < value_len; count++) { */ /* printf("res[]:%c\n", res[count]); */ /* } */ char *rc4hex = ami_rc4_to_hex(res, value_len); kv_push(char *, ami->values_stack, rc4hex); free(res); } else if (!strcmp("random.int", n->strval)) { char *randstr; int to = (int)strtod(kv_A(ami->values_stack, kv_size(ami->values_stack)-1), NULL); int from = (int)strtod(kv_A(ami->values_stack, kv_size(ami->values_stack)-2), NULL); int rout = (rand() % (to - from + 1)) + from; asprintf(&randstr, "%d", rout); kv_push(char *, ami->values_stack, randstr); } else if (!strcmp("csv", n->strval)) { /* size_t stacklen = kv_size(ami->values_stack); */ /* for (size_t i = 0; i < stacklen; i++) { */ /* printf("i:%d;val:%s\n", i, kv_A(ami->values_stack, i)); */ /* } */ int has_header = (int)strtod(kv_A(ami->values_stack, kv_size(ami->values_stack)-1), NULL); char *field = kv_A(ami->values_stack, kv_size(ami->values_stack)-2); /* char *field = ami_get_variable(ami, field_val_stack); */ char *line_val_stack = kv_A(ami->values_stack, kv_size(ami->values_stack)-3); /* printf("line val:%s\n", line_val_stack); */ ami_variable_t *line_val = ami_get_variable(ami, line_val_stack); if (!line_val) { fprintf(stderr, "Cannot get the variable value from %s\n", kv_A(ami->values_stack, kv_size(ami->values_stack)-3)); exit(1); } int line_in_csv = line_val->ival; char *file = kv_A(ami->values_stack, kv_size(ami->values_stack)-4); /* char *file_stack = kv_A(ami->values_stack, kv_size(ami->values_stack)-4); */ /* printf("file stack:%s\n", file_stack); */ /* char *file = ami_get_variable(ami, file_stack); */ /* printf("file:%s;line_in_csv:%d;field:%s;has_header:%d\n", file, line_in_csv, field, has_header); */ char *result = ami_csvread_get_field_at_line(file, line_in_csv, field, has_header); if (!result) { fprintf(stderr, "Error reading CSV file %s, field:%s, line:%d\n", file, field, line_in_csv); exit(1); } else { kv_push(char *, ami->values_stack, strdup(result)); } } else if (!strcmp("replace", n->strval)) { kv_push(char *, ami->values_stack, "replace");// So we know we have a replace to perform /* printf("We are going to REPLACE!\n"); */ } else { fprintf(stderr, "Unhandled function:[%s]\n", n->strval); kv_push(char *, ami->values_stack, n->strval); } varpos = 0; break; case AMI_NT_SLEEP: ami->sleep_cursor += n->intval; ami->sleep_cursor += n->fval; break; case AMI_NT_ARRAYVAR: /* printf("We set the values for our array. We have %d values\n", n->intval); */ array_values_len = n->intval; localvar = ami_variable_new(); for (size_t i = array_values_len; i > 0; i--) { ami_variable_t *var = ami_variable_new(); ami_variable_set_string(var, kv_A(ami->values_stack, kv_size(ami->values_stack)-i)); ami_variable_array_append(localvar, var); } ami_action_set_variable(action, n->strval, ami_variable_copy(localvar)); /* tmp_var = ami_action_get_newvariable(action, n->strval); */ /* ami_variable_debug(localvar); */ break; case AMI_NT_ARRAYGET: array_get_index = n->intval; kv_push(char *, ami->values_stack, n->strval); break; } } } int ami_ast_walk_actions(ami_t *ami) { time_t t; srand((unsigned) time(&t)); if (!ami) { fprintf(stderr, "Ami is empty, cannot run %s!\n", __FUNCTION__); return -1; } if (!ami->root_node) { fprintf(stderr, "Ami root node is empty, cannot run %s!\n", __FUNCTION__); return -1; } walk_node(ami, ami->root_node, 0, 0); return 0; }
2.140625
2
2024-11-18T21:09:34.743655+00:00
2021-05-20T09:31:53
343173f47af4855bfb4f49423988ac426ffac911
{ "blob_id": "343173f47af4855bfb4f49423988ac426ffac911", "branch_name": "refs/heads/master", "committer_date": "2021-05-20T09:31:53", "content_id": "5c407b8ec92985436c20b339a5eee737cfcc7952", "detected_licenses": [ "Apache-2.0" ], "directory_id": "09a1776449e54060270ff6090d740e361d44fa02", "extension": "c", "filename": "hwtimer_test.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": 4278, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/test/hwtimer_test.c", "provenance": "stackv2-0065.json.gz:10771", "repo_name": "CocoRoboLabs/K210-Micropython-OpenMV", "revision_date": "2021-05-20T09:31:53", "revision_id": "6eb42fd94c7f1281b582387845b5645774cb6da6", "snapshot_id": "e11ca4e5c7589e0a7df4d5ada8083e1cb4fad060", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/CocoRoboLabs/K210-Micropython-OpenMV/6eb42fd94c7f1281b582387845b5645774cb6da6/src/test/hwtimer_test.c", "visit_date": "2023-04-26T05:11:10.895804" }
stackv2
#include <rtthread.h> #include <rtdevice.h> #include <finsh.h> #ifdef RT_USING_HWTIMER static rt_err_t timer_oneshot_cb(rt_device_t dev, rt_size_t size) { rt_kprintf("enter oneshot@Tick(%d)\n", rt_tick_get()); return 0; } static rt_err_t timer_period_cb(rt_device_t dev, rt_size_t size) { rt_kprintf("enter period@Tick(%d)\n", rt_tick_get()); return 0; } static int period_test(rt_device_t dev) { rt_err_t err; rt_hwtimer_mode_t mode; rt_hwtimerval_t val; /* 设置超时回调函数 */ rt_device_set_rx_indicate(dev, timer_period_cb); /* 单次模式 */ mode = HWTIMER_MODE_PERIOD; err = rt_device_control(dev, HWTIMER_CTRL_MODE_SET, &mode); /* 设置定时器超时值并启动定时器 */ val.sec = 1; val.usec = 0; rt_kprintf("Start period callback: Sec %d, Usec %d@Tick(%d)\n", val.sec, val.usec, rt_tick_get()); if (rt_device_write(dev, 0, &val, sizeof(val)) != sizeof(val)) { rt_kprintf("SetTime Fail\n"); return -1; } /* 等待回调函数执行 */ rt_kprintf("sleep 5s\n"); rt_thread_mdelay(5100); /* 停止定时器 */ rt_device_control(dev, HWTIMER_CTRL_STOP, RT_NULL); rt_kprintf("Timer Stoped\n"); return 0; } static int oneshot_test(rt_device_t dev) { rt_err_t err; rt_hwtimer_mode_t mode; rt_hwtimerval_t val; /* 设置超时回调函数 */ rt_device_set_rx_indicate(dev, timer_oneshot_cb); /* 单次模式 */ mode = HWTIMER_MODE_ONESHOT; err = rt_device_control(dev, HWTIMER_CTRL_MODE_SET, &mode); /* 设置定时器超时值并启动定时器 */ val.sec = 1; val.usec = 0; rt_kprintf("Start oneshot callback: Sec %d, Usec %d@Tick(%d)\n", val.sec, val.usec, rt_tick_get()); if (rt_device_write(dev, 0, &val, sizeof(val)) != sizeof(val)) { rt_kprintf("SetTime Fail\n"); return -1; } /* 等待回调函数执行 */ rt_thread_mdelay(1100); return 0; } static int timemeasure_test(rt_device_t dev) { rt_err_t err; rt_hwtimerval_t val; rt_hwtimer_mode_t mode; mode = HWTIMER_MODE_PERIOD; if (rt_device_control(dev, HWTIMER_CTRL_MODE_SET, &mode) != 0) return -1; rt_kprintf("Start time measure@Tick(%d)\n", rt_tick_get()); /* 设置定时器超时值并启动定时器 */ val.sec = 1; val.usec = 0; if (rt_device_write(dev, 0, &val, sizeof(val)) != sizeof(val)) { rt_kprintf("SetTime Fail\n"); return -1; } /* 读取计数 */ rt_kprintf("Sleep %d sec\n", val.sec); rt_thread_mdelay(val.sec * 1000); rt_device_read(dev, 0, &val, sizeof(val)); rt_kprintf("Read@Tick(%d): Sec = %d, Usec = %d\n", rt_tick_get(), val.sec, val.usec); rt_kprintf("Sleep %d sec with timer running\n", val.sec); rt_thread_mdelay(val.sec * 1000); rt_device_read(dev, 0, &val, sizeof(val)); rt_kprintf("Read@Tick(%d): Sec = %d, Usec = %d\n", rt_tick_get(), val.sec, val.usec); /* 停止定时器 */ err = rt_device_control(dev, HWTIMER_CTRL_STOP, RT_NULL); rt_kprintf("Timer Stoped\n"); return 0; } static void show_info(rt_device_t dev) { struct rt_hwtimer_info info; rt_memset(&info, 0, sizeof(info)); rt_device_control(dev, HWTIMER_CTRL_INFO_GET, &info); rt_kprintf("TimerInfo: maxfreq %d, minfreq %d\n", info.maxfreq, info.minfreq); } int hwtimer(int argc, char **argv) { rt_device_t dev = RT_NULL; char *devname = "timer10"; if (argc == 2) { devname = argv[1]; } if ((dev = rt_device_find(devname)) == RT_NULL) { rt_kprintf("No Device: %s\n", devname); return -1; } if (rt_device_open(dev, RT_DEVICE_OFLAG_RDWR) != RT_EOK) { rt_kprintf("Open %s Fail\n", devname); return -1; } show_info(dev); /**** 时间测量 */ if (timemeasure_test(dev) != 0) goto EXIT; /**** 定时执行回调函数 -- 单次模式 */ if (oneshot_test(dev) != 0) goto EXIT; /**** 定时执行回调函数 -- 周期模式 */ period_test(dev); EXIT: rt_device_close(dev); rt_kprintf("Close %s\n", devname); return 0; } MSH_CMD_EXPORT(hwtimer, "hwtimer NAME"); #endif /* RT_USING_HWTIMER */
2.6875
3
2024-11-18T21:09:35.026162+00:00
2014-06-01T13:43:58
a0c0654ecf2ead49451823956f9f31f94e6f2c07
{ "blob_id": "a0c0654ecf2ead49451823956f9f31f94e6f2c07", "branch_name": "refs/heads/master", "committer_date": "2014-06-01T13:50:19", "content_id": "5163ca18643fa7703bb48f4739594410f7933764", "detected_licenses": [ "MIT" ], "directory_id": "7976266422dee8b6561e01d8b7671497f4a51754", "extension": "h", "filename": "multiboot.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 19082428, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1519, "license": "MIT", "license_type": "permissive", "path": "/src/multiboot.h", "provenance": "stackv2-0065.json.gz:11286", "repo_name": "kapec94/DemOS", "revision_date": "2014-06-01T13:43:58", "revision_id": "664d65bd35688eb44eacff69b930c25be9b0c58a", "snapshot_id": "d8eef5ef03214dfe61ce7901843bb2d78d22b018", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kapec94/DemOS/664d65bd35688eb44eacff69b930c25be9b0c58a/src/multiboot.h", "visit_date": "2021-01-25T07:18:42.071894" }
stackv2
/* * multiboot.h * * Created on: 20 kwi 2014 * Author: Mateusz */ #ifndef MULTIBOOT_H_ #define MULTIBOOT_H_ #include <stddef.h> #include <mbdef.h> #ifndef __ASSEMBLER__ /* Multiboot structure contains various information about the boot environment. * Some of them available only when explicitly asked for, other available when * possible. * http://www.gnu.org/software/grub/manual/multiboot/multiboot.html#boot-information-format */ struct multiboot_info_t { u32 flags; u32 mem_lower; u32 mem_upper; u32 boot_device; const char* cmdline; u32 mods_count; struct mod_info_t* mods_addr; u8 syms[16]; u32 mmap_length; struct mmap_entry_t* mmap_addr; u32 drives_length; void* drives_addr; void* config_table; const char* boot_loader_name; void* apm_table; void* vbe_control_info; void* vbe_mode_info; u16 vbe_mode; u16 vbe_interface_seg; u16 vbe_interface_off; u16 vbe_interface_len; } __attribute__((packed)); struct boot_device_t { u8 disk; u8 part1; u8 part2; u8 part3; }; struct mod_info_t { void* start; void* end; const char* string; u32 reserved; }; struct syms_aout_t { u32 tabsize; u32 strsize; void* addr; u32 reserved; }; struct syms_elf_t { u32 num; u32 size; void* addr; void* shndx; }; struct mmap_entry_t { u32 size; u64 base_addr; u64 length; u32 type; } __attribute__((packed)); #endif /* __ASSEMBLER__ */ #endif /* MULTIBOOT_H_ */
2.109375
2
2024-11-18T21:09:35.306694+00:00
2019-07-20T11:40:57
dcf2223ab11bc8ba4dd89a21c11ee7a60b95189d
{ "blob_id": "dcf2223ab11bc8ba4dd89a21c11ee7a60b95189d", "branch_name": "refs/heads/master", "committer_date": "2019-07-20T11:49:11", "content_id": "f1d26b4944a66219d305a22df8b1d42eab0f79a1", "detected_licenses": [ "Artistic-2.0" ], "directory_id": "c6c142f46daba7ab31f7a9a233fefbf56f5e1473", "extension": "c", "filename": "exception.c", "fork_events_count": 0, "gha_created_at": "2019-07-21T12:08:58", "gha_event_created_at": "2019-07-21T12:08:59", "gha_language": null, "gha_license_id": null, "github_id": 198051701, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 751, "license": "Artistic-2.0", "license_type": "permissive", "path": "/a1200/std/exception.c", "provenance": "stackv2-0065.json.gz:11542", "repo_name": "fluffyfreak/demoscene", "revision_date": "2019-07-20T11:40:57", "revision_id": "af5c06ab2b8ebf42994a4903c8c3c05cc288b4b7", "snapshot_id": "c111c5de615f57db69b32c7706dcb930caecaaa8", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/fluffyfreak/demoscene/af5c06ab2b8ebf42994a4903c8c3c05cc288b4b7/a1200/std/exception.c", "visit_date": "2022-02-03T23:50:27.515797" }
stackv2
#include "std/exception.h" #include "std/memory.h" ContextT *_last_ctx = NULL; /* * Creates new exception context. */ void ExceptionInit() { ContextT *new_ctx = NewRecord(ContextT); new_ctx->prev = _last_ctx; new_ctx->active = true; _last_ctx = new_ctx; } /* * Removes exception context if marked as inactive. */ bool ExceptionClear() { if (!_last_ctx->active) { ContextT *prev_ctx = _last_ctx->prev; MemUnref(_last_ctx); _last_ctx = prev_ctx; return false; } return true; } /* * Marks exception context as inactive. */ void ExceptionFinish() { _last_ctx->active = false; } /* * Used to raise an exception. */ void ExceptionRaise() { if (!_last_ctx) abort(); longjmp(_last_ctx->state, 1); }
2.578125
3
2024-11-18T21:09:35.369021+00:00
2020-01-31T09:27:01
ea05628473d5218f7f392edeb2f928c5a8303ba3
{ "blob_id": "ea05628473d5218f7f392edeb2f928c5a8303ba3", "branch_name": "refs/heads/master", "committer_date": "2020-01-31T09:27:01", "content_id": "477c9551f7312df1280e3d5682f0d6e40c7ed8f7", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "e764040792e5364cba77525986a635236df59025", "extension": "c", "filename": "zf_number.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 176800768, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3524, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/zenny_foundation/zf_number.c", "provenance": "stackv2-0065.json.gz:11671", "repo_name": "zenny-chen/Zenny-Foundation-Library", "revision_date": "2020-01-31T09:27:01", "revision_id": "0fab45bc8ecaddb9b4d1791347a40ac5a35ed52f", "snapshot_id": "d1f2149c85501c7532603caffeecd0c16dd8ccfc", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/zenny-chen/Zenny-Foundation-Library/0fab45bc8ecaddb9b4d1791347a40ac5a35ed52f/zenny_foundation/zf_number.c", "visit_date": "2020-04-30T11:24:42.045836" }
stackv2
// // zf_number.c // FoundationBasedAlgorithms // // Created by Zenny Chen on 2018/11/21. // Copyright © 2018 CodeLearning Studio. All rights reserved. // #include "zf_number.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void ZFConvertNumberToUTF8String(const struct ZFNumber *numObj, char dstBuffer[64]) { if(numObj == NULL || numObj->obj.identifier != ZENNY_NUMBER_IDENTIFIER) { dstBuffer[0] = '\0'; return; } const union ZFNumberValueType value = numObj->value; switch(numObj->encoding) { case ZF_NUMBER_ENCODING_BOOL: if(value.b) { dstBuffer[0] = 't'; dstBuffer[1] = 'r'; dstBuffer[2] = 'u'; dstBuffer[3] = 'e'; dstBuffer[4] = '\0'; } else { dstBuffer[0] = 'f'; dstBuffer[1] = 'a'; dstBuffer[2] = 'l'; dstBuffer[3] = 's'; dstBuffer[3] = 'e'; dstBuffer[5] = '\0'; } break; case ZF_NUMBER_ENCODING_CHAR: dstBuffer[0] = value.c; dstBuffer[1] = '\0'; break; case ZF_NUMBER_ENCODING_CHAR16: zf_char16_to_chars(value.u, dstBuffer); break; case ZF_NUMBER_ENCODING_BYTE: sprintf(dstBuffer, "%d", value.a); break; case ZF_NUMBER_ENCODING_UBYTE: sprintf(dstBuffer, "%u", value.A); break; case ZF_NUMBER_ENCODING_SHORT: sprintf(dstBuffer, "%d", value.s); break; case ZF_NUMBER_ENCODING_USHORT: sprintf(dstBuffer, "%u", value.S); break; case ZF_NUMBER_ENCODING_INT: sprintf(dstBuffer, "%d", value.n); break; case ZF_NUMBER_ENCODING_UINT: sprintf(dstBuffer, "%u", value.N); break; case ZF_NUMBER_ENCODING_LONG: sprintf(dstBuffer, "%lld", (long long)value.l); break; case ZF_NUMBER_ENCODING_ULONG: sprintf(dstBuffer, "%llu", (unsigned long long)value.L); break; case ZF_NUMBER_ENCODING_PTRDIFF: // including case ZF_NUMBER_ENCODING_SSIZE: sprintf(dstBuffer, "%td", value.t); break; case ZF_NUMBER_ENCODING_SSIZE: sprintf(dstBuffer, "%zd", value.z); break; case ZF_NUMBER_ENCODING_SIZE: sprintf(dstBuffer, "%zu", value.Z); break; case ZF_NUMBER_ENCODING_INTPTR: sprintf(dstBuffer, "%td", value.p); break; case ZF_NUMBER_ENCODING_UINTPTR: sprintf(dstBuffer, "%tu", value.P); break; case ZF_NUMBER_ENCODING_INTMAX: sprintf(dstBuffer, "%td", value.x); break; case ZF_NUMBER_ENCODING_UINTMAX: sprintf(dstBuffer, "%tu", value.X); break; case ZF_NUMBER_ENCODING_FLOAT: sprintf(dstBuffer, "%f", value.f); break; case ZF_NUMBER_ENCODING_DOUBLE: sprintf(dstBuffer, "%f", value.d); break; default: dstBuffer[0] = '\0'; break; } }
2.90625
3
2024-11-18T21:09:35.811762+00:00
2015-08-01T16:29:13
6247c833c853a656bf69b14480062ae023e0f0fc
{ "blob_id": "6247c833c853a656bf69b14480062ae023e0f0fc", "branch_name": "refs/heads/master", "committer_date": "2015-08-01T16:29:13", "content_id": "aa30815f77ee4396ddeaa08558fa6263d5702a26", "detected_licenses": [ "MIT" ], "directory_id": "9df87cf106bcc88028a007c979c19a8e54f9a14d", "extension": "c", "filename": "dgcave_guards2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 40052469, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2052, "license": "MIT", "license_type": "permissive", "path": "/Areas/Bird/Oakdale/o/Forest/Room/dgcave_guards2.c", "provenance": "stackv2-0065.json.gz:12058", "repo_name": "yodakingdoms/kingdoms", "revision_date": "2015-08-01T16:29:13", "revision_id": "831b74ba4a086de69cce213ad2398f646c3efb39", "snapshot_id": "b00751ec6a838c23d916a311ba101cf8d3e4b19d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yodakingdoms/kingdoms/831b74ba4a086de69cce213ad2398f646c3efb39/Areas/Bird/Oakdale/o/Forest/Room/dgcave_guards2.c", "visit_date": "2020-05-20T16:04:32.008700" }
stackv2
#include "../def.h" #pragma strict_types inherit MASTER_ROOM; void create_object(void); void reset(int arg); void init(void); int do_listen(string str); void create_object(void) { set_short("A small, damp cave"); set_long("A small, damp cave dimly lit by a flickering torch hanging " + "on a wall. A narrow tunnel goes east from here and to the " + "southeast there seems to be another, larger cave. There is " + "a wooden table and two stools here. Strange shadows dance " + "on the walls and the dampness in the air seeps into your " + "clothes, making you feel sluggish. You hear voices coming " + "from some other room, but the echoes created in the caves " + "makes it hard to determine exactly which direction they " + "come from.\n"); set_new_light(10); add_property("indoors"); add_item("cave","A small cave, apparently a guardroom"); add_item("torch","A flickering wooden torch hanging on a wall"); add_item("wall|walls","Smooth stone"); add_item("tunnel","You can't see where it leads from here"); add_item("table","A wooden table"); add_item("stools","Two small wooden stools"); add_item("stool","A small wooden stool"); add_exit(ROOM + "dgcave_throne","southeast"); add_exit(ROOM + "dgcave_beds","southwest"); add_exit(ROOM + "dgcave_tunnel","east"); reset(0); } void reset(int arg) { add_monster(MONSTER + "DGguard",2); } void init(void) { add_action("do_listen","listen"); } int do_listen(string str) { if(TP->query_skill("perception") > (30+random(20))) { W("You think the voices are coming from the larger cave to the " + "southeast, but you can't be entirely sure.\n"); S(TP->QN + " listens carefully.\n"); return 1; } W("You can't discern where the sounds come from... Listening to them " + "only confuses you.\n"); S(TP->QN + " listens carefully and seems a bit confused.\n"); return 1; }
2.171875
2
2024-11-18T21:09:37.760709+00:00
2021-07-28T15:28:26
bb8ab867bda45532687514086112b4945666fe46
{ "blob_id": "bb8ab867bda45532687514086112b4945666fe46", "branch_name": "refs/heads/master", "committer_date": "2021-07-28T15:28:26", "content_id": "5b0f7ace0f6b0d827abae55d8ca9356937539d1e", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "63baa72eacddc957d9d7ba9c7fd91e94079351f8", "extension": "c", "filename": "bistro_x86_64.c", "fork_events_count": 2, "gha_created_at": "2020-02-26T10:04:52", "gha_event_created_at": "2023-06-06T09:37:12", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 243230556, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7606, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/ucm/bistro/bistro_x86_64.c", "provenance": "stackv2-0065.json.gz:13216", "repo_name": "Mellanox/ucx", "revision_date": "2021-07-28T15:28:26", "revision_id": "2ddc9db49026b688cab741f5d2bc9756b7b11662", "snapshot_id": "e9e8c6d0d94199cfa349c7b237aed372c294dd91", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Mellanox/ucx/2ddc9db49026b688cab741f5d2bc9756b7b11662/src/ucm/bistro/bistro_x86_64.c", "visit_date": "2023-08-18T01:29:57.312670" }
stackv2
/** * Copyright (C) Mellanox Technologies Ltd. 2018. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* ******************************************************* * x86 processors family * * ***************************************************** */ #if defined(__x86_64__) #include <sys/mman.h> #include <string.h> #include <stdlib.h> #include <ucm/bistro/bistro.h> #include <ucm/bistro/bistro_int.h> #include <ucm/util/sys.h> #include <ucs/sys/math.h> typedef struct { void *jmp_addr; char code[]; } ucm_bistro_orig_func_t; typedef struct { uint8_t opcode; /* 0xff */ uint8_t modrm; /* 0x25 */ int32_t displ; } UCS_S_PACKED ucm_bistro_jmp_indirect_t; /* REX prefix */ #define UCM_BISTRO_X86_REX_MASK 0xF0 /* Mask */ #define UCM_BISTRO_X86_REX 0x40 /* Value */ #define UCM_BISTRO_X86_REX_W 0x48 /* REX.W value */ #define UCM_BISTRO_X86_REX_B 0x41 /* REX.B value */ /* PUSH general register * "push $reg" */ #define UCM_BISTRO_X86_PUSH_R_MASK 0xF0 /* Mask */ #define UCM_BISTRO_X86_PUSH_R 0x50 /* Value */ /* Immediate Grp 1(1A), Ev, Iz */ #define UCM_BISTRO_X86_IMM_GRP1_EV_IZ 0x81 /* MOV Ev,Gv */ #define UCM_BISTRO_X86_MOV_EV_GV 0x89 /* MOV immediate word or double into word, double, or quad register * "mov $imm32, %reg" */ #define UCM_BISTRO_X86_MOV_IR_MASK 0xF8 /* Mask */ #define UCM_BISTRO_X86_MOV_IR 0xB8 /* Value */ /* ModR/M encoding: * [ mod | reg | r/m ] * [ 7 6 | 5 4 3 | 2 1 0 ] */ #define UCM_BISTRO_X86_MODRM_MOD_SHIFT 6 /* mod */ #define UCM_BISTRO_X86_MODRM_REG_SHIFT 3 /* reg */ #define UCM_BISTRO_X86_MODRM_RM_BITS 3 /* r/m */ /* Table 2-2 */ #define UCM_BISTRO_X86_MODRM_MOD_DISP8 1 /* 0b01 */ #define UCM_BISTRO_X86_MODRM_MOD_DISP32 2 /* 0b10 */ #define UCM_BISTRO_X86_MODRM_MOD_REG 3 /* 0b11 */ #define UCM_BISTRO_X86_MODRM_RM_SIB 4 /* 0b100 */ /* ModR/M encoding for SUB RSP * mod=0b11, reg=0b101 (SUB as opcode extension), r/m=0b100 */ #define UCM_BISTRO_X86_MODRM_SUB_SP 0xEC /* 11 101 100 */ /* ModR/M encoding for EBP/BP/CH/MM5/XMM5, AH/SP/ESP/MM4/XMM4 */ #define UCM_BISTRO_X86_MODRM_BP_SP 0xE5 /* 11 100 101 */ /* * Find the minimal length of initial instructions in the function which can be * safely executed from any memory location. * Uses a very simplified disassembler which supports only the typical * instructions found in function prologue. */ static size_t ucm_bistro_detect_pic_prefix(const void *func, size_t min_length) { uint8_t rex, opcode, modrm, mod; size_t offset, prev_offset; offset = 0; while (offset < min_length) { prev_offset = offset; opcode = *(uint8_t*)UCS_PTR_BYTE_OFFSET(func, offset++); /* check for REX prefix */ if ((opcode & UCM_BISTRO_X86_REX_MASK) == UCM_BISTRO_X86_REX) { rex = opcode; opcode = *(uint8_t*)UCS_PTR_BYTE_OFFSET(func, offset++); } else { rex = 0; } /* check the opcode */ if (((rex == 0) || rex == UCM_BISTRO_X86_REX_B) && ((opcode & UCM_BISTRO_X86_PUSH_R_MASK) == UCM_BISTRO_X86_PUSH_R)) { continue; } else if ((rex == UCM_BISTRO_X86_REX_W) && (opcode == UCM_BISTRO_X86_IMM_GRP1_EV_IZ)) { modrm = *(uint8_t*)UCS_PTR_BYTE_OFFSET(func, offset++); if (modrm == UCM_BISTRO_X86_MODRM_SUB_SP) { /* sub $imm32, %rsp */ offset += sizeof(uint32_t); continue; } } else if ((rex == UCM_BISTRO_X86_REX_W) && (opcode == UCM_BISTRO_X86_MOV_EV_GV)) { modrm = *(uint8_t*)UCS_PTR_BYTE_OFFSET(func, offset++); if (modrm == UCM_BISTRO_X86_MODRM_BP_SP) { /* mov %rsp, %rbp */ continue; } mod = modrm >> UCM_BISTRO_X86_MODRM_MOD_SHIFT; if ((mod != UCM_BISTRO_X86_MODRM_MOD_REG) && ((modrm & UCS_MASK(UCM_BISTRO_X86_MODRM_RM_BITS)) == UCM_BISTRO_X86_MODRM_RM_SIB)) { /* r/m = 0b100, mod = 0b00/0b01/0b10 */ ++offset; /* skip SIB */ if (mod == UCM_BISTRO_X86_MODRM_MOD_DISP8) { offset += sizeof(uint8_t); /* skip disp8 */ } else if (mod == UCM_BISTRO_X86_MODRM_MOD_DISP32) { offset += sizeof(uint32_t); /* skip disp32 */ } continue; } } else if ((rex == 0) && ((opcode & UCM_BISTRO_X86_MOV_IR_MASK) == UCM_BISTRO_X86_MOV_IR)) { offset += sizeof(uint32_t); continue; } /* unsupported instruction - bail */ return prev_offset; } return offset; } static ucs_status_t ucm_bistro_construct_orig_func(const void *func_ptr, size_t patch_len, const char *symbol, void **orig_func_p) { ucm_bistro_jmp_indirect_t *jmp_back; ucm_bistro_orig_func_t *orig_func; size_t prefix_len, code_size; prefix_len = ucm_bistro_detect_pic_prefix(func_ptr, patch_len); ucm_debug("'%s' at %p prefix length %zu/%zu", symbol, func_ptr, prefix_len, patch_len); if (prefix_len < patch_len) { return UCS_ERR_UNSUPPORTED; } /* Allocate executable page */ code_size = sizeof(*orig_func) + patch_len + sizeof(*jmp_back); orig_func = ucm_bistro_allocate_code(code_size); if (orig_func == NULL) { return UCS_ERR_NO_MEMORY; } /* Copy code fragment from original function */ memcpy(orig_func->code, func_ptr, prefix_len); /* Indirect jump to *orig_func->jmp_address */ orig_func->jmp_addr = UCS_PTR_BYTE_OFFSET(func_ptr, prefix_len); jmp_back = UCS_PTR_BYTE_OFFSET(orig_func->code, prefix_len); jmp_back->opcode = 0xff; jmp_back->modrm = 0x25; jmp_back->displ = UCS_PTR_BYTE_DIFF(jmp_back + 1, &orig_func->jmp_addr); *orig_func_p = orig_func->code; return UCS_OK; } ucs_status_t ucm_bistro_patch(void *func_ptr, void *hook, const char *symbol, void **orig_func_p, ucm_bistro_restore_point_t **rp) { ucm_bistro_jmp_r11_patch_t jmp_r11 = { .mov_r11 = {0x49, 0xbb}, .jmp_r11 = {0x41, 0xff, 0xe3} }; ucm_bistro_jmp_near_patch_t jmp_near = { .jmp_rel = 0xe9 }; void *patch, *jmp_base; ucs_status_t status; ptrdiff_t jmp_disp; size_t patch_len; jmp_base = UCS_PTR_BYTE_OFFSET(func_ptr, sizeof(jmp_near)); jmp_disp = UCS_PTR_BYTE_DIFF(jmp_base, hook); if (labs(jmp_disp) < INT32_MAX) { /* if 32-bit near jump is possible, use it, since it's a short 5-byte * instruction which reduces the chances of racing with other thread */ jmp_near.disp = jmp_disp; patch = &jmp_near; patch_len = sizeof(jmp_near); } else { jmp_r11.ptr = hook; patch = &jmp_r11; patch_len = sizeof(jmp_r11); } if (orig_func_p != NULL) { status = ucm_bistro_construct_orig_func(func_ptr, patch_len, symbol, orig_func_p); if (status != UCS_OK) { return status; } } status = ucm_bistro_create_restore_point(func_ptr, patch_len, rp); if (UCS_STATUS_IS_ERR(status)) { return status; } return ucm_bistro_apply_patch(func_ptr, patch, patch_len); } #endif
2.109375
2
2024-11-18T21:09:38.554605+00:00
2020-11-02T18:03:40
ac35c0a1096d8b95725caf500f9d9c6ee52b0fab
{ "blob_id": "ac35c0a1096d8b95725caf500f9d9c6ee52b0fab", "branch_name": "refs/heads/master", "committer_date": "2020-11-02T18:03:40", "content_id": "920e22ab2c7a8a46c345cd0badbff42668395b89", "detected_licenses": [ "MIT" ], "directory_id": "f065da047d8322e91784638ac64caab0a4ee27e1", "extension": "c", "filename": "queue.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 306511483, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2670, "license": "MIT", "license_type": "permissive", "path": "/queue.c", "provenance": "stackv2-0065.json.gz:14245", "repo_name": "ArenaGrenade/feature-rich-xv6-os", "revision_date": "2020-11-02T18:03:40", "revision_id": "65639f57cfbe5e25fd0807a8d01c0597a8c6bfd2", "snapshot_id": "f7c89ebcaa9d1fffe3dbe9238ef996a2812430ee", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ArenaGrenade/feature-rich-xv6-os/65639f57cfbe5e25fd0807a8d01c0597a8c6bfd2/queue.c", "visit_date": "2023-01-08T01:46:49.383046" }
stackv2
/* Circular queue implementation in an array */ #include "types.h" #include "defs.h" #include "param.h" #include "memlayout.h" #include "mmu.h" #include "x86.h" #include "proc.h" void push(Queue* queue, struct proc* proc) { // cprintf("Pushing now "); if ((queue->front == 0 && queue->rear == NPROC - 1) || (queue->front == queue->rear + 1)) { // cprintf("Queue %d has overflown\n", queue->queue_id); return; } if (queue->front == -1) { // This is the case when the queue is empty queue->front = 0; queue->rear = 0; } else { if (queue->rear == NPROC - 1) // Last element to be isnerted queue->rear = 0; else queue->rear = queue->rear + 1; } queue->arr[queue->rear] = proc; // cprintf(" - %d \n", queue->arr[queue->rear]->pid); return; } struct proc* pop(Queue* queue) { if (queue->front == -1) { // cprintf("Queue %d has underflown\n", queue->queue_id); return 0; } int ret_ind = queue->front; if (queue->front == queue->rear) { // There is only one element in queue queue->front = -1; queue->rear = -1; } else { if (queue->front == NPROC - 1) queue->front = 0; else queue->front = queue->front + 1; } return queue->arr[ret_ind]; } void display(Queue* queue) { int front_pos = queue->front; int rear_pos = queue->rear; if (front_pos == -1) { cprintf("Queue is empty - Unable to display\n"); return; } cprintf("Queue %d: \n", queue->queue_id); if (front_pos <= rear_pos) while(front_pos <= rear_pos) { cprintf("%d ", queue->arr[front_pos]->pid); front_pos++; } else { while (front_pos <= MLFQSIZE - 1) { cprintf("%d ", queue->arr[front_pos]->pid); front_pos++; } front_pos = 0; while (front_pos <= rear_pos) { cprintf("%d ", queue->arr[front_pos]->pid); front_pos++; } } cprintf("\n"); return; } int get_size(Queue* queue) { int front_pos = queue->front; int rear_pos = queue->rear; int size = 0; if (front_pos == -1) return 0; if (front_pos <= rear_pos) while(front_pos <= rear_pos) { size++; front_pos++; } else { while (front_pos <= MLFQSIZE - 1) { size++; front_pos++; } front_pos = 0; while (front_pos <= rear_pos) { size++; front_pos++; } } return size; }
3.390625
3
2024-11-18T21:09:38.600586+00:00
2021-05-11T00:32:34
113c02909fda53f3d144e2fc9a9331d1c2014059
{ "blob_id": "113c02909fda53f3d144e2fc9a9331d1c2014059", "branch_name": "refs/heads/main", "committer_date": "2021-05-11T00:32:34", "content_id": "0ac64d704fd1f62850a878e9dff109fc6b00cf5e", "detected_licenses": [ "MIT" ], "directory_id": "9a76bdd18fbb808f6916d4edbc489994ec97ba1e", "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": 366211749, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 572, "license": "MIT", "license_type": "permissive", "path": "/main/ulp/main.c", "provenance": "stackv2-0065.json.gz:14373", "repo_name": "bitmandu/esp32s2-ulp-riscv-blinky", "revision_date": "2021-05-11T00:32:34", "revision_id": "2a4958057ca075148580801ff626b3151ca129f1", "snapshot_id": "e30033ece695d6b65019f40161e7910be5b46fe0", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/bitmandu/esp32s2-ulp-riscv-blinky/2a4958057ca075148580801ff626b3151ca129f1/main/ulp/main.c", "visit_date": "2023-04-19T14:52:47.140413" }
stackv2
/** * @file main.c * * Blinky stuff running on the ULP-RISC-V. */ #include "ulp_riscv/ulp_riscv.h" #include "ulp_riscv/ulp_riscv_utils.h" #include "soc/rtc_io_reg.h" #include "ulp_gpio.h" volatile int pin; volatile uint32_t count; int main(void) { ulp_gpio_init(pin); ulp_gpio_set_direction(pin, ULP_GPIO_MODE_OUTPUT_ONLY); ulp_gpio_hold_dis(pin); if (count % 2) { ulp_gpio_set_level(pin, 1); } else { ulp_gpio_set_level(pin, 0); } ++count; ulp_gpio_hold_en(pin); // hold GPIO level during sleep return 0; }
2.5
2
2024-11-18T21:09:39.101832+00:00
2021-05-05T03:26:47
c6e5549586fdad5090018a3afdbc0be0c0ca8b33
{ "blob_id": "c6e5549586fdad5090018a3afdbc0be0c0ca8b33", "branch_name": "refs/heads/master", "committer_date": "2021-05-05T03:26:47", "content_id": "dfbedccd448b3fa4e130e191737c854aef9b25e6", "detected_licenses": [ "MIT" ], "directory_id": "071f5216d37f1d6a944758bd591a7601738e126f", "extension": "c", "filename": "f_userListPrint.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 219109577, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 716, "license": "MIT", "license_type": "permissive", "path": "/test/ll/f_userListPrint.c", "provenance": "stackv2-0065.json.gz:14760", "repo_name": "tollesonpdx/Last_Minute_Camping_With_C", "revision_date": "2021-05-05T03:26:47", "revision_id": "29942c8ce6840d42b6f1cad1ea97ecfd9826a083", "snapshot_id": "56ffcea91c0d0e24e4a16973cffb2b315a43b751", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tollesonpdx/Last_Minute_Camping_With_C/29942c8ce6840d42b6f1cad1ea97ecfd9826a083/test/ll/f_userListPrint.c", "visit_date": "2021-06-23T18:20:21.625338" }
stackv2
// Chad Tolleson Copyright (c) 2019 // New Beginnings 2018 - Capstone Project // filename: f_printUserList.c #include "headers.h" int userListPrint(struct userList* L) { printf("printing user linked list\n"); if (L->head == NULL) { printf("no head, returning to main\n"); return 0; } struct userData* current = L->head; int tempCount = 0; while (current != NULL) { tempCount++; printf("#%d = location: %s\tlat,lng: %lf, %lf\n", tempCount,current->userLocation, current->u_lat, current->u_long); current = current->next; } printf("done printing linked list\n"); return 0; }
2.890625
3
2024-11-18T21:09:39.872783+00:00
2015-10-08T11:00:20
cfdba4bdf8f114a8c061a54cf39aaed4fe6206f8
{ "blob_id": "cfdba4bdf8f114a8c061a54cf39aaed4fe6206f8", "branch_name": "refs/heads/master", "committer_date": "2015-10-08T11:00:20", "content_id": "97a3bea8a4900978599fb18c6e19bb90f813c8f4", "detected_licenses": [ "MIT" ], "directory_id": "f10addf7be0d0921f669ea4df323fe860df4fb15", "extension": "c", "filename": "writer.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 42935697, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 428, "license": "MIT", "license_type": "permissive", "path": "/src/writer.c", "provenance": "stackv2-0065.json.gz:15274", "repo_name": "ryutaroikeda/gatherers", "revision_date": "2015-10-08T11:00:20", "revision_id": "10248996c41f97b4e7e960c54a3fb187dd824772", "snapshot_id": "7ba22a0c0d253d9ba6d1f72e3948016b55d2cd7c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ryutaroikeda/gatherers/10248996c41f97b4e7e960c54a3fb187dd824772/src/writer.c", "visit_date": "2021-01-10T20:28:51.009230" }
stackv2
#include "writer.h" static int GTWriter_Init(GTWriter* w) { w->err = GTWriterError_None; return 0; } int GTWriter_InitString(GTWriter* w, char* str, int size) { w->stream.str.s = str; w->stream.str.cap = size; w->mode = GTWriterMode_String; GTWriter_Init(w); return 0; } int GTWriter_InitFile(GTWriter* w, FILE* file) { w->stream.file = file; w->mode = GTWriterMode_File; GTWriter_Init(w); return 0; }
2.140625
2
2024-11-18T21:09:45.217471+00:00
2022-02-12T15:29:32
d0fb9995018434953767b75a9a44dc5075ddcdfa
{ "blob_id": "d0fb9995018434953767b75a9a44dc5075ddcdfa", "branch_name": "refs/heads/master", "committer_date": "2022-02-13T14:41:20", "content_id": "6bc0fa3f9e2beeaf57ef1900541a0cc6b01fd345", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b11834ff2347dfbb26584656552662d2996c904e", "extension": "h", "filename": "pb.h", "fork_events_count": 0, "gha_created_at": "2020-04-07T19:12:28", "gha_event_created_at": "2020-04-07T19:12:28", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 253888886, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 37041, "license": "Apache-2.0", "license_type": "permissive", "path": "/c/pb.h", "provenance": "stackv2-0065.json.gz:16045", "repo_name": "spall/ChezScheme", "revision_date": "2022-02-12T15:29:32", "revision_id": "7391daa9033a61946b42b7fba9f92ccb2b8a2a52", "snapshot_id": "714902c76a295e0dd0657b74d292e6a5cf5f5ab2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/spall/ChezScheme/7391daa9033a61946b42b7fba9f92ccb2b8a2a52/c/pb.h", "visit_date": "2022-05-14T08:13:11.072987" }
stackv2
/* Interpreter for portable bytecode. See "pb.ss". */ /* Machine state is in the thread context: */ typedef struct machine_state { ptr machine_regs[pb_reg_count]; double machine_fpregs[pb_fpreg_count]; /* scratch space for libffi-based foreign calls, somewhat analogous to the C stack: */ ptr machine_call_arena[pb_call_arena_size]; } machine_state; #define regs (ms->machine_regs) #define fpregs (ms->machine_fpregs) #define call_arena (ms->machine_call_arena) /* The flag register doesn't have to be in the thread context, because it set and then used only in the next instruction. */ /* All instructions are 32 bits wide: */ typedef uint32_t instruction_t; #define INSTR_op(instr) ((instr) & 0xFF) #define INSTR_d_dest(instr) (((instr) >> 8) & 0xF) #define INSTR_dr_dest(instr) INSTR_d_dest(instr) #define INSTR_dr_reg(instr) (((instr) >> 16) & 0xF) #define INSTR_di_dest(instr) INSTR_d_dest(instr) #define INSTR_di_imm(instr) (((int32_t)(instr)) >> 16) #define INSTR_di_imm_unsigned(instr) ((instr) >> 16) #define INSTR_adr_dest(instr) INSTR_di_dest(instr) #define INSTR_adr_imm(instr) (((int32_t)(instr)) >> 12) #define INSTR_drr_dest(instr) INSTR_d_dest(instr) #define INSTR_drr_reg1(instr) (((instr) >> 12) & 0xF) #define INSTR_drr_reg2(instr) (((instr) >> 16) & 0xF) #define INSTR_dri_dest(instr) INSTR_d_dest(instr) #define INSTR_dri_reg(instr) (((instr) >> 12) & 0xF) #define INSTR_dri_imm(instr) (((int32_t)(instr)) >> 16) #define INSTR_i_imm(instr) (((int32_t)(instr)) >> 8) #define INSTR_ii_low(instr) (((instr) >> 8) & 0xFF) #define INSTR_ii_high(instr) ((instr) >> 16) #define SHIFT_MASK(v) ((v) & (ptr_bits-1)) enum { Cretval = 9, Carg1 = 9, Carg2, Carg3, Carg4, Carg5, Carg6, Carg7 }; enum { Cfpretval = 1, Cfparg1 = 1, Cfparg2, Cfparg3, Cfparg4, Cfparg5, Cfparg6 }; #define SIGN_FLIP(r, a, b) ((~((a ^ b) | (r ^ ~b))) >> (ptr_bits-1)) #if (__GNUC__ >= 5) || defined(__clang__) # define USE_OVERFLOW_INTRINSICS 1 #else # define USE_OVERFLOW_INTRINSICS 0 #endif /* Use `machine_state * RESTRICT_PTR`, because machine registers won't be modified in any way other than through the machine-state pointer */ #if (__GNUC__ >= 4) || defined(__clang__) # define RESTRICT_PTR __restrict__ #endif #ifdef _MSC_VER # define RESTRICT_PTR __restrict #endif #ifndef RESTRICT_PTR /* `restrict` is available in C99 and later, but we stick to C89 for now: */ # define RESTRICT_PTR /* restrict */ #endif /* ********************************************************************** */ /* Implementations for instructions that can be used either within the interpreter loop or within a generated chunk. */ #define do_pb_mov16_pb_zero_bits_pb_shift0(instr) \ regs[INSTR_di_dest(instr)] = (uptr)INSTR_di_imm_unsigned(instr) #define do_pb_mov16_pb_zero_bits_pb_shift1(instr) \ regs[INSTR_di_dest(instr)] = (uptr)INSTR_di_imm_unsigned(instr) << 16 #if ptr_bits == 64 # define do_pb_mov16_pb_zero_bits_pb_shift2(instr) \ regs[INSTR_di_dest(instr)] = (uptr)INSTR_di_imm_unsigned(instr) << 32 #else # define do_pb_mov16_pb_zero_bits_pb_shift2(instr) \ regs[INSTR_di_dest(instr)] = 0 #endif #if ptr_bits == 64 # define do_pb_mov16_pb_zero_bits_pb_shift3(instr) \ regs[INSTR_di_dest(instr)] = (uptr)INSTR_di_imm_unsigned(instr) << 48 #else # define do_pb_mov16_pb_zero_bits_pb_shift3(instr) \ regs[INSTR_di_dest(instr)] = 0 #endif #define do_pb_mov16_pb_keep_bits_pb_shift0(instr) \ regs[INSTR_di_dest(instr)] |= (uptr)INSTR_di_imm_unsigned(instr) #define do_pb_mov16_pb_keep_bits_pb_shift1(instr) \ regs[INSTR_di_dest(instr)] |= (uptr)INSTR_di_imm_unsigned(instr) << 16 #if ptr_bits == 64 # define do_pb_mov16_pb_keep_bits_pb_shift2(instr) \ regs[INSTR_di_dest(instr)] |= (uptr)INSTR_di_imm_unsigned(instr) << 32 #else # define do_pb_mov16_pb_keep_bits_pb_shift2(instr) \ do { } while (0) #endif #if ptr_bits == 64 # define do_pb_mov16_pb_keep_bits_pb_shift3(instr) \ regs[INSTR_di_dest(instr)] |= (uptr)INSTR_di_imm_unsigned(instr) << 48 #else # define do_pb_mov16_pb_keep_bits_pb_shift3(instr) \ do { } while (0) #endif #define do_pb_mov_pb_i_i(instr) \ regs[INSTR_dr_dest(instr)] = regs[INSTR_dr_reg(instr)] #define do_pb_mov_pb_d_d(instr) \ fpregs[INSTR_dr_dest(instr)] = fpregs[INSTR_dr_reg(instr)] #define do_pb_mov_pb_i_d(instr) \ fpregs[INSTR_dr_dest(instr)] = (double)(iptr)regs[INSTR_dr_reg(instr)] #define do_pb_mov_pb_d_i(instr) \ regs[INSTR_dr_dest(instr)] = (iptr)fpregs[INSTR_dr_reg(instr)] #if ptr_bits == 64 # define do_pb_mov_pb_i_bits_d_bits(instr) \ memcpy(&fpregs[INSTR_dr_dest(instr)], &regs[INSTR_dr_reg(instr)], sizeof(double)) # define do_pb_mov_pb_d_bits_i_bits(instr) \ memcpy(&regs[INSTR_dr_dest(instr)], &fpregs[INSTR_dr_reg(instr)], sizeof(double)) #else # define do_pb_mov_pb_i_i_bits_d_bits(instr) \ do { \ uint64_t d; \ d = regs[INSTR_drr_reg1(instr)] | ((uint64_t)regs[INSTR_drr_reg2(instr)] << 32); \ memcpy(&fpregs[INSTR_drr_dest(instr)], &d, sizeof(double)); \ } while (0) # define do_pb_mov_pb_d_lo_bits_i_bits(instr) \ do { \ uint64_t d; \ memcpy(&d, &fpregs[INSTR_dr_reg(instr)], sizeof(double)); \ regs[INSTR_dr_dest(instr)] = d; \ } while (0) #define do_pb_mov_pb_d_hi_bits_i_bits(instr) \ do { \ uint64_t d; \ memcpy(&d, &fpregs[INSTR_dr_reg(instr)], sizeof(double)); \ d >>= 32; \ regs[INSTR_dr_dest(instr)] = d; \ } while (0) #endif #ifdef PORTABLE_BYTECODE_BIGENDIAN # define FP_REG_FLOAT_START(p) ((char *)&(p) + 4) #else # define FP_REG_FLOAT_START(p) &(p) #endif #define do_pb_mov_pb_s_d(instr) \ do { \ float f; \ memcpy(&f, FP_REG_FLOAT_START(fpregs[INSTR_dr_reg(instr)]), sizeof(float)); \ fpregs[INSTR_dr_dest(instr)] = f; \ } while (0) #define do_pb_mov_pb_d_s(instr) \ do { \ float f; \ f = fpregs[INSTR_dr_reg(instr)]; \ memcpy(FP_REG_FLOAT_START(fpregs[INSTR_dr_dest(instr)]), &f, sizeof(float)); \ } while (0) #define do_pb_mov_pb_d_s_d(instr) \ do { \ float f; \ f = fpregs[INSTR_dr_reg(instr)]; \ fpregs[INSTR_dr_dest(instr)] = (double)f; \ } while (0) #define do_pb_bin_op_pb_no_signal_pb_add_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)] #define do_pb_bin_op_pb_no_signal_pb_add_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = regs[INSTR_dri_reg(instr)] + (uptr)INSTR_dri_imm(instr) #define do_pb_bin_op_pb_no_signal_pb_sub_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = regs[INSTR_drr_reg1(instr)] - regs[INSTR_drr_reg2(instr)] #define do_pb_bin_op_pb_no_signal_pb_sub_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = regs[INSTR_dri_reg(instr)] - (uptr)INSTR_dri_imm(instr) #define do_pb_bin_op_pb_no_signal_pb_mul_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = regs[INSTR_drr_reg1(instr)] * regs[INSTR_drr_reg2(instr)] #define do_pb_bin_op_pb_no_signal_pb_mul_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = (uptr)regs[INSTR_dri_reg(instr)] * (uptr)INSTR_dri_imm(instr) #define do_pb_bin_op_pb_no_signal_pb_div_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = (iptr)regs[INSTR_drr_reg1(instr)] / (iptr)regs[INSTR_drr_reg2(instr)] #define do_pb_bin_op_pb_no_signal_pb_div_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = (iptr)regs[INSTR_dri_reg(instr)] / (iptr)INSTR_dri_imm(instr) #define do_pb_bin_op_pb_no_signal_pb_and_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = regs[INSTR_drr_reg1(instr)] & regs[INSTR_drr_reg2(instr)] #define do_pb_bin_op_pb_no_signal_pb_and_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = regs[INSTR_dri_reg(instr)] & (uptr)INSTR_dri_imm(instr) #define do_pb_bin_op_pb_no_signal_pb_ior_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = regs[INSTR_drr_reg1(instr)] | regs[INSTR_drr_reg2(instr)] #define do_pb_bin_op_pb_no_signal_pb_ior_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = regs[INSTR_dri_reg(instr)] | (uptr)INSTR_dri_imm(instr) #define do_pb_bin_op_pb_no_signal_pb_xor_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = regs[INSTR_drr_reg1(instr)] ^ regs[INSTR_drr_reg2(instr)] #define do_pb_bin_op_pb_no_signal_pb_xor_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = regs[INSTR_dri_reg(instr)] ^ (uptr)INSTR_dri_imm(instr) #define do_pb_bin_op_pb_no_signal_pb_lsl_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = regs[INSTR_drr_reg1(instr)] << SHIFT_MASK(regs[INSTR_drr_reg2(instr)]) #define do_pb_bin_op_pb_no_signal_pb_lsl_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = regs[INSTR_dri_reg(instr)] << SHIFT_MASK(INSTR_dri_imm(instr)) #define do_pb_bin_op_pb_no_signal_pb_lsr_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = regs[INSTR_drr_reg1(instr)] >> SHIFT_MASK(regs[INSTR_drr_reg2(instr)]) #define do_pb_bin_op_pb_no_signal_pb_lsr_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = regs[INSTR_dri_reg(instr)] >> SHIFT_MASK(INSTR_dri_imm(instr)) #define do_pb_bin_op_pb_no_signal_pb_asr_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = (iptr)regs[INSTR_drr_reg1(instr)] >> SHIFT_MASK(regs[INSTR_drr_reg2(instr)]) #define do_pb_bin_op_pb_no_signal_pb_asr_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = (iptr)regs[INSTR_dri_reg(instr)] >> SHIFT_MASK(INSTR_dri_imm(instr)) #ifdef PORTABLE_BYTECODE_BIGENDIAN # define do_pb_bin_op_pb_no_signal_pb_lslo_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = regs[INSTR_drr_reg1(instr)] >> regs[INSTR_drr_reg2(instr)] #else # define do_pb_bin_op_pb_no_signal_pb_lslo_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = regs[INSTR_drr_reg1(instr)] << regs[INSTR_drr_reg2(instr)] #endif #ifdef PORTABLE_BYTECODE_BIGENDIAN # define do_pb_bin_op_pb_no_signal_pb_lslo_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = regs[INSTR_dri_reg(instr)] >> INSTR_dri_imm(instr) #else # define do_pb_bin_op_pb_no_signal_pb_lslo_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = regs[INSTR_dri_reg(instr)] << INSTR_dri_imm(instr); #endif #if USE_OVERFLOW_INTRINSICS # define do_pb_bin_op_pb_signal_pb_add_pb_register(instr) \ do { \ iptr a = (iptr)regs[INSTR_drr_reg1(instr)]; \ iptr b = (iptr)regs[INSTR_drr_reg2(instr)]; \ iptr r; \ flag = __builtin_add_overflow(a, b, &r); \ regs[INSTR_drr_dest(instr)] = (uptr)r; \ } while (0) #else # define do_pb_bin_op_pb_signal_pb_add_pb_register(instr) \ do { \ uptr a = regs[INSTR_drr_reg1(instr)]; \ uptr b = regs[INSTR_drr_reg2(instr)]; \ uptr r = a + b; \ regs[INSTR_drr_dest(instr)] = r; \ flag = SIGN_FLIP(r, a, b); \ } while (0) #endif #if USE_OVERFLOW_INTRINSICS # define do_pb_bin_op_pb_signal_pb_add_pb_immediate(instr) \ do { \ iptr a = (iptr)regs[INSTR_dri_reg(instr)]; \ iptr b = INSTR_dri_imm(instr); \ iptr r; \ flag = __builtin_add_overflow(a, b, &r); \ regs[INSTR_drr_dest(instr)] = (uptr)r; \ } while (0) #else # define do_pb_bin_op_pb_signal_pb_add_pb_immediate(instr) \ do { \ uptr a = regs[INSTR_dri_reg(instr)]; \ uptr b = (uptr)INSTR_dri_imm(instr); \ uptr r = a + b; \ regs[INSTR_dri_dest(instr)] = r; \ flag = SIGN_FLIP(r, a, b); \ } while (0) #endif #if USE_OVERFLOW_INTRINSICS #define do_pb_bin_op_pb_signal_pb_sub_pb_register(instr) \ do { \ iptr a = (iptr)regs[INSTR_drr_reg1(instr)]; \ iptr b = (iptr)regs[INSTR_drr_reg2(instr)]; \ iptr r; \ flag = __builtin_sub_overflow(a, b, &r); \ regs[INSTR_drr_dest(instr)] = (uptr)r; \ } while (0) #else #define do_pb_bin_op_pb_signal_pb_sub_pb_register(instr) \ do { \ uptr a = regs[INSTR_drr_reg1(instr)]; \ uptr b = regs[INSTR_drr_reg2(instr)]; \ uptr r = a - b; \ regs[INSTR_drr_dest(instr)] = r; \ flag = SIGN_FLIP(r, a, ~b); \ } while (0) #endif #if USE_OVERFLOW_INTRINSICS # define do_pb_bin_op_pb_signal_pb_sub_pb_immediate(instr) \ do { \ iptr a = (iptr)regs[INSTR_dri_reg(instr)]; \ iptr b = INSTR_dri_imm(instr); \ iptr r; \ flag = __builtin_sub_overflow(a, b, &r); \ regs[INSTR_drr_dest(instr)] = (uptr)r; \ } while (0) #else # define do_pb_bin_op_pb_signal_pb_sub_pb_immediate(instr) \ do { \ uptr a = regs[INSTR_dri_reg(instr)]; \ uptr b = (uptr)INSTR_dri_imm(instr); \ uptr r = a - b; \ regs[INSTR_dri_dest(instr)] = r; \ flag = SIGN_FLIP(r, a, ~b); \ } while (0) #endif #if USE_OVERFLOW_INTRINSICS #define do_pb_bin_op_pb_signal_pb_mul_pb_register(instr) \ do { \ iptr a = (iptr)regs[INSTR_drr_reg1(instr)]; \ iptr b = (iptr)regs[INSTR_drr_reg2(instr)]; \ iptr r; \ flag = __builtin_mul_overflow(a, b, &r); \ regs[INSTR_drr_dest(instr)] = (uptr)r; \ } while (0) #else #define do_pb_bin_op_pb_signal_pb_mul_pb_register(instr) \ do { \ uptr a = regs[INSTR_drr_reg1(instr)]; \ uptr b = regs[INSTR_drr_reg2(instr)]; \ uptr r = a * b; \ regs[INSTR_drr_dest(instr)] = r; \ if (b != 0) { \ if (b == (uptr)-1) \ flag = (a != r * (uptr)-1); \ else \ flag = ((iptr)a != (iptr)r / (iptr)b); \ } else \ flag = 0; \ } while (0) #endif #if USE_OVERFLOW_INTRINSICS # define do_pb_bin_op_pb_signal_pb_mul_pb_immediate(instr) \ do { \ iptr a = (iptr)regs[INSTR_dri_reg(instr)]; \ iptr b = INSTR_dri_imm(instr); \ iptr r; \ flag = __builtin_mul_overflow(a, b, &r); \ regs[INSTR_drr_dest(instr)] = (uptr)r; \ } while (0) #else # define do_pb_bin_op_pb_signal_pb_mul_pb_immediate(instr) \ do { \ uptr a = regs[INSTR_dri_reg(instr)]; \ uptr b = (uptr)INSTR_dri_imm(instr); \ uptr r = a * b; \ regs[INSTR_dri_dest(instr)] = r; \ if (b != 0) { \ if (b == (uptr)-1) \ flag = (a != r * (uptr)-1); \ else \ flag = ((iptr)a != (iptr)r / (iptr)b); \ } else \ flag = 0; \ } while (0) #endif #define do_pb_bin_op_pb_signal_pb_subz_pb_register(instr) \ do { \ iptr r = regs[INSTR_drr_reg1(instr)] - regs[INSTR_drr_reg2(instr)]; \ regs[INSTR_drr_dest(instr)] = r; \ flag = (r == 0); \ } while (0) #define do_pb_bin_op_pb_signal_pb_subz_pb_immediate(instr) \ do { \ iptr r = regs[INSTR_dri_reg(instr)] - (uptr)INSTR_dri_imm(instr); \ regs[INSTR_dri_dest(instr)] = r; \ flag = (r == 0); \ } while (0) #define do_pb_bin_op_pb_signal_pb_subp_pb_register(instr) \ do { \ iptr r = regs[INSTR_drr_reg1(instr)] - regs[INSTR_drr_reg2(instr)]; \ regs[INSTR_drr_dest(instr)] = r; \ flag = (r > 0); \ } while (0) #define do_pb_bin_op_pb_signal_pb_subp_pb_immediate(instr) \ do { \ iptr r = regs[INSTR_dri_reg(instr)] - (uptr)INSTR_dri_imm(instr); \ regs[INSTR_dri_dest(instr)] = r; \ flag = (r > 0); \ } while (0) #define do_pb_cmp_op_pb_eq_pb_register(instr) \ flag = regs[INSTR_dr_dest(instr)] == regs[INSTR_dr_reg(instr)] #define do_pb_cmp_op_pb_eq_pb_immediate(instr) \ flag = regs[INSTR_di_dest(instr)] == (uptr)INSTR_di_imm(instr) #define do_pb_cmp_op_pb_lt_pb_register(instr) \ flag = (iptr)regs[INSTR_dr_dest(instr)] < (iptr)regs[INSTR_dr_reg(instr)] #define do_pb_cmp_op_pb_lt_pb_immediate(instr) \ flag = (iptr)regs[INSTR_di_dest(instr)] < (iptr)INSTR_di_imm(instr) #define do_pb_cmp_op_pb_gt_pb_register(instr) \ flag = (iptr)regs[INSTR_dr_dest(instr)] > (iptr)regs[INSTR_dr_reg(instr)] #define do_pb_cmp_op_pb_gt_pb_immediate(instr) \ flag = (iptr)regs[INSTR_di_dest(instr)] > (iptr)INSTR_di_imm(instr) #define do_pb_cmp_op_pb_le_pb_register(instr) \ flag = (iptr)regs[INSTR_dr_dest(instr)] <= (iptr)regs[INSTR_dr_reg(instr)] #define do_pb_cmp_op_pb_le_pb_immediate(instr) \ flag = (iptr)regs[INSTR_di_dest(instr)] <= (iptr)INSTR_di_imm(instr) #define do_pb_cmp_op_pb_ge_pb_register(instr) \ flag = (iptr)regs[INSTR_dr_dest(instr)] >= (iptr)regs[INSTR_dr_reg(instr)] #define do_pb_cmp_op_pb_ge_pb_immediate(instr) \ flag = (iptr)regs[INSTR_di_dest(instr)] >= (iptr)INSTR_di_imm(instr) #define do_pb_cmp_op_pb_ab_pb_register(instr) \ flag = regs[INSTR_dr_dest(instr)] > regs[INSTR_dr_reg(instr)] #define do_pb_cmp_op_pb_ab_pb_immediate(instr) \ flag = regs[INSTR_di_dest(instr)] > (uptr)INSTR_di_imm(instr) #define do_pb_cmp_op_pb_bl_pb_register(instr) \ flag = regs[INSTR_dr_dest(instr)] < regs[INSTR_dr_reg(instr)] #define do_pb_cmp_op_pb_bl_pb_immediate(instr) \ flag = regs[INSTR_di_dest(instr)] < (uptr)INSTR_di_imm(instr) #define do_pb_cmp_op_pb_cs_pb_register(instr) \ flag = ((regs[INSTR_dr_dest(instr)] & regs[INSTR_dr_reg(instr)]) != 0) #define do_pb_cmp_op_pb_cs_pb_immediate(instr) \ flag = ((regs[INSTR_di_dest(instr)] & (uptr)INSTR_di_imm(instr)) != 0) #define do_pb_cmp_op_pb_cc_pb_register(instr) \ flag = ((regs[INSTR_dr_dest(instr)] & regs[INSTR_dr_reg(instr)]) == 0) #define do_pb_cmp_op_pb_cc_pb_immediate(instr) \ flag = ((regs[INSTR_di_dest(instr)] & (uptr)INSTR_di_imm(instr)) == 0) #define do_pb_fp_bin_op_pb_add_pb_register(instr) \ fpregs[INSTR_drr_dest(instr)] = fpregs[INSTR_drr_reg1(instr)] + fpregs[INSTR_drr_reg2(instr)] #define do_pb_fp_bin_op_pb_sub_pb_register(instr) \ fpregs[INSTR_drr_dest(instr)] = fpregs[INSTR_drr_reg1(instr)] - fpregs[INSTR_drr_reg2(instr)] #define do_pb_fp_bin_op_pb_mul_pb_register(instr) \ fpregs[INSTR_drr_dest(instr)] = fpregs[INSTR_drr_reg1(instr)] * fpregs[INSTR_drr_reg2(instr)] #define do_pb_fp_bin_op_pb_div_pb_register(instr) \ fpregs[INSTR_drr_dest(instr)] = fpregs[INSTR_drr_reg1(instr)] / fpregs[INSTR_drr_reg2(instr)] #define do_pb_un_op_pb_not_pb_register(instr) \ regs[INSTR_dr_dest(instr)] = ~(regs[INSTR_dr_reg(instr)]) #define do_pb_un_op_pb_not_pb_immediate(instr) \ regs[INSTR_di_dest(instr)] = ~((uptr)(iptr)INSTR_di_imm(instr)) #define do_pb_fp_un_op_pb_sqrt_pb_register(instr) \ fpregs[INSTR_dr_dest(instr)] = sqrt(fpregs[INSTR_dr_reg(instr)]) #define do_pb_fp_cmp_op_pb_eq_pb_register(instr) \ flag = fpregs[INSTR_dr_dest(instr)] == fpregs[INSTR_dr_reg(instr)] #define do_pb_fp_cmp_op_pb_lt_pb_register(instr) \ flag = fpregs[INSTR_dr_dest(instr)] < fpregs[INSTR_dr_reg(instr)] #define do_pb_fp_cmp_op_pb_le_pb_register(instr) \ flag = fpregs[INSTR_dr_dest(instr)] <= fpregs[INSTR_dr_reg(instr)] #if ptr_bits == 64 #define do_pb_rev_op_pb_int16_pb_register(instr) \ regs[INSTR_dr_dest(instr)] = ((uptr)((iptr)(regs[INSTR_dr_reg(instr)] << 56) >> 48) \ | ((regs[INSTR_dr_reg(instr)] & 0xFF00) >> 8)) #else #define do_pb_rev_op_pb_int16_pb_register(instr) \ regs[INSTR_dr_dest(instr)] = ((uptr)((iptr)(regs[INSTR_dr_reg(instr)] << 24) >> 16) \ | ((regs[INSTR_dr_reg(instr)] & 0xFF00) >> 8)) #endif #define do_pb_rev_op_pb_uint16_pb_register(instr) \ regs[INSTR_dr_dest(instr)] = (((regs[INSTR_dr_reg(instr)] & 0x00FF) << 8) \ | ((regs[INSTR_dr_reg(instr)] & 0xFF00) >> 8)) #if ptr_bits == 64 # define do_pb_rev_op_pb_int32_pb_register(instr) \ regs[INSTR_dr_dest(instr)] = ((uptr)((iptr)(regs[INSTR_dr_reg(instr)] << 56) >> 32) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0xFF000000) >> 24) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x00FF0000) >> 8) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x0000FF00) << 8)) #else # define do_pb_rev_op_pb_int32_pb_register(instr) \ regs[INSTR_dr_dest(instr)] = ((regs[INSTR_dr_reg(instr)] << 24) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0xFF000000) >> 24) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x00FF0000) >> 8) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x0000FF00) << 8)) #endif #define do_pb_rev_op_pb_uint32_pb_register(instr) \ regs[INSTR_dr_dest(instr)] = (((regs[INSTR_dr_reg(instr)] & (uptr)0x000000FF) << 24) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0xFF000000) >> 24) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x00FF0000) >> 8) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x0000FF00) << 8)) #if ptr_bits == 64 # define do_pb_rev_op_pb_int64_pb_register(instr) \ regs[INSTR_dr_dest(instr)] = (((regs[INSTR_dr_reg(instr)] & (uptr)0x00000000000000FF) << 56) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x000000000000FF00) << 40) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x0000000000FF0000) << 24) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x00000000FF000000) << 8) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x000000FF00000000) >> 8) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x0000FF0000000000) >> 24) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x00FF000000000000) >> 40) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0xFF00000000000000) >> 56)) #else # define do_pb_rev_op_pb_int64_pb_register(instr) \ regs[INSTR_dr_dest(instr)] = (((regs[INSTR_dr_reg(instr)] & (uptr)0x000000FF) << 24) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0xFF000000) >> 24) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x00FF0000) >> 8) \ | ((regs[INSTR_dr_reg(instr)] & (uptr)0x0000FF00) << 8)) #endif #define do_pb_ld_op_pb_int8_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = *(int8_t *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) #if defined(__arm__) /* Complicated load to avoid an internal compiler error from an old gcc on Raspbian: */ # define do_pb_ld_op_pb_int8_pb_immediate(instr) \ do { \ int8_t v; \ memcpy(&v, TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)), sizeof(int8_t)); \ regs[INSTR_dri_dest(instr)] = v; \ } while (0) #else # define do_pb_ld_op_pb_int8_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = *(int8_t *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) #endif #define do_pb_ld_op_pb_uint8_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = *(uint8_t *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) #define do_pb_ld_op_pb_uint8_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = *(uint8_t *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) #define do_pb_ld_op_pb_int16_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = *(int16_t *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) #define do_pb_ld_op_pb_int16_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = *(int16_t *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) #define do_pb_ld_op_pb_uint16_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = *(uint16_t *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) #define do_pb_ld_op_pb_uint16_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = *(uint16_t *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) #define do_pb_ld_op_pb_int32_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = *(int32_t *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) #define do_pb_ld_op_pb_int32_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = *(int32_t *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) #define do_pb_ld_op_pb_uint32_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = *(uint32_t *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) #define do_pb_ld_op_pb_uint32_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = *(uint32_t *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) #define do_pb_ld_op_pb_int64_pb_register(instr) \ regs[INSTR_drr_dest(instr)] = *(uptr *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) #define do_pb_ld_op_pb_int64_pb_immediate(instr) \ regs[INSTR_dri_dest(instr)] = *(uptr *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) #define do_pb_ld_op_pb_double_pb_register(instr) \ fpregs[INSTR_drr_dest(instr)] = *(double *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) #define do_pb_ld_op_pb_double_pb_immediate(instr) \ fpregs[INSTR_dri_dest(instr)] = *(double *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) #define do_pb_ld_op_pb_single_pb_register(instr) \ fpregs[INSTR_drr_dest(instr)] = *(float *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) #define do_pb_ld_op_pb_single_pb_immediate(instr) \ fpregs[INSTR_dri_dest(instr)] = *(float *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) #define do_pb_st_op_pb_int8_pb_register(instr) \ *(char *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) = (char)regs[INSTR_drr_dest(instr)] #define do_pb_st_op_pb_int8_pb_immediate(instr) \ *(char *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) = (char)regs[INSTR_dri_dest(instr)] #define do_pb_st_op_pb_int16_pb_register(instr) \ *(short *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) = (short)regs[INSTR_drr_dest(instr)] #define do_pb_st_op_pb_int16_pb_immediate(instr) \ *(short *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) = (short)regs[INSTR_dri_dest(instr)] #define do_pb_st_op_pb_int32_pb_register(instr) \ *(int *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) = (int)regs[INSTR_drr_dest(instr)] #define do_pb_st_op_pb_int32_pb_immediate(instr) \ *(int *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) = (int)regs[INSTR_dri_dest(instr)] #define do_pb_st_op_pb_int64_pb_register(instr) \ *(uptr *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) = regs[INSTR_drr_dest(instr)] #define do_pb_st_op_pb_int64_pb_immediate(instr) \ *(uptr *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) = regs[INSTR_dri_dest(instr)] #define do_pb_st_op_pb_double_pb_register(instr) \ *(double *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) = fpregs[INSTR_drr_dest(instr)] #define do_pb_st_op_pb_double_pb_immediate(instr) \ *(double *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) = fpregs[INSTR_dri_dest(instr)] #define do_pb_st_op_pb_single_pb_register(instr) \ *(float *)TO_VOIDP(regs[INSTR_drr_reg1(instr)] + regs[INSTR_drr_reg2(instr)]) = fpregs[INSTR_drr_dest(instr)] #define do_pb_st_op_pb_single_pb_immediate(instr) \ *(float *)TO_VOIDP(regs[INSTR_dri_reg(instr)] + INSTR_dri_imm(instr)) = fpregs[INSTR_dri_dest(instr)] #if defined(PTHREADS) # define CAS_ANY_FENCE_SEQOK(addr, old_r, r) \ CAS_ANY_FENCE(TO_VOIDP(addr), TO_VOIDP(old_r), TO_VOIDP(r)) #else # define CAS_ANY_FENCE_SEQOK(addr, old_r, r) \ (*(uptr *)TO_VOIDP(addr) = r, 1) #endif #define do_pb_inc_pb_register(instr) \ do { \ uptr addr = regs[INSTR_dr_dest(instr)]; \ while (1) { \ uptr old_r = *(uptr *)TO_VOIDP(addr); \ uptr r = old_r + regs[INSTR_dr_reg(instr)]; \ if (CAS_ANY_FENCE_SEQOK(addr, old_r, r)) { \ flag = (r == 0); \ break; \ } \ } \ } while (0) #define do_pb_inc_pb_immediate(instr) \ do { \ uptr addr = regs[INSTR_di_dest(instr)]; \ while (1) { \ uptr old_r = *(uptr *)TO_VOIDP(addr); \ uptr r = old_r + INSTR_di_imm(instr); \ if (CAS_ANY_FENCE_SEQOK(addr, old_r, r)) { \ flag = (r == 0); \ break; \ } \ } \ } while (0) #if defined(PTHREADS) # define do_pb_lock(instr) \ do { \ uptr *l = TO_VOIDP(regs[INSTR_d_dest(instr)]); \ flag = CAS_ANY_FENCE(l, TO_VOIDP(0), TO_VOIDP(1)); \ } while (0) #else # define do_pb_lock(instr) \ do { \ uptr *l = TO_VOIDP(regs[INSTR_d_dest(instr)]); \ if (*l == 0) { \ *l = 1; \ flag = 1; \ } else \ flag = 0; \ } while (0) #endif #if defined(PTHREADS) # define do_pb_cas(instr) \ do { \ uptr *l = TO_VOIDP(regs[INSTR_drr_dest(instr)]); \ uptr old = regs[INSTR_drr_reg1(instr)]; \ uptr new = regs[INSTR_drr_reg2(instr)]; \ flag = CAS_ANY_FENCE(l, TO_VOIDP(old), TO_VOIDP(new)); \ } while (0) #else #define do_pb_cas(instr) \ do { \ uptr *l = TO_VOIDP(regs[INSTR_drr_dest(instr)]); \ uptr old = regs[INSTR_drr_reg1(instr)]; \ uptr new = regs[INSTR_drr_reg2(instr)]; \ if (*l == old) { \ *l = new; \ flag = 1; \ } else \ flag = 0; \ } while (0) #endif #define do_pb_fence_pb_fence_store_store(instr) \ STORE_FENCE() #define do_pb_fence_pb_fence_acquire(instr) \ ACQUIRE_FENCE() #define do_pb_fence_pb_fence_release(instr) \ RELEASE_FENCE() #define do_pb_call_arena_in(instr) \ *(ptr *)TO_VOIDP(((uptr)TO_PTR(call_arena) + INSTR_di_imm(instr))) = regs[INSTR_di_dest(instr)] #define do_pb_fp_call_arena_in(instr) \ *(double *)TO_VOIDP(((uptr)TO_PTR(call_arena) + INSTR_di_imm(instr))) = fpregs[INSTR_di_dest(instr)] #define do_pb_call_arena_out(instr) \ regs[INSTR_di_dest(instr)] = *(ptr *)TO_VOIDP((uptr)TO_PTR(call_arena) + INSTR_di_imm(instr)) #define do_pb_fp_call_arena_out(instr) \ fpregs[INSTR_di_dest(instr)] = *(double *)TO_VOIDP((uptr)TO_PTR(call_arena) + INSTR_di_imm(instr)) #define do_pb_stack_call(instr) \ S_ffi_call(regs[INSTR_dr_reg(instr)], regs[INSTR_dr_dest(instr)], (ptr *)call_arena) #define pb_bs_op_pb_register_addr(instr) \ (*(uptr *)TO_VOIDP(regs[INSTR_dr_dest(instr)] + regs[INSTR_dr_reg(instr)])) #define pb_bs_op_pb_immediate_addr(instr) \ (*(uptr *)TO_VOIDP(regs[INSTR_di_dest(instr)] + INSTR_di_imm(instr))) #if ptr_bits == 64 # define decode_relocation(instr, ip) \ ((uptr)INSTR_di_imm_unsigned(instr) \ | ((uptr)INSTR_di_imm_unsigned((ip)[1]) << 16) \ | ((uptr)INSTR_di_imm_unsigned((ip)[2]) << 32) \ | ((uptr)INSTR_di_imm_unsigned((ip)[3]) << 48)) #else # define decode_relocation(instr, ip) \ ((uptr)INSTR_di_imm_unsigned(instr) \ | ((uptr)INSTR_di_imm_unsigned((ip)[1]) << 16)) #endif /* ********************************************************************** */ /* Support for generated chunks */ #define load_from_relocation(dest, ip) \ regs[dest] = *(ptr *)TO_VOIDP(ip) #define load_code_relative(dest, ip) \ regs[dest] = ip #define code_rel(start_i, i) ((i)-(start_i)) #define MACHINE_STATE machine_state * RESTRICT_PTR
2.109375
2
2024-11-18T21:09:46.030687+00:00
2020-06-06T13:46:59
b66f1d9a1b9f29b6e4a2fd2053f443dd9c31794c
{ "blob_id": "b66f1d9a1b9f29b6e4a2fd2053f443dd9c31794c", "branch_name": "refs/heads/master", "committer_date": "2020-06-06T13:46:59", "content_id": "92057c32aa8e521dcbf4de6aaeb5c0efcb93f966", "detected_licenses": [ "Apache-2.0" ], "directory_id": "661f1a492d679c0533f2245fa94a4798cb83356d", "extension": "c", "filename": "rewrite.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 137484709, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2428, "license": "Apache-2.0", "license_type": "permissive", "path": "/cby/rewrite.c", "provenance": "stackv2-0065.json.gz:16304", "repo_name": "minad/crts", "revision_date": "2020-06-06T13:46:59", "revision_id": "0986b9f8b9375bd12bbf11de80fc52fdba80f5d4", "snapshot_id": "6a773bd08bd89be7e768379e88e1c02546158e0c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/minad/crts/0986b9f8b9375bd12bbf11de80fc52fdba80f5d4/cby/rewrite.c", "visit_date": "2023-08-22T17:20:34.395854" }
stackv2
#include "bytecode/decode.h" #include "bytecode/opcodes.h" #include "cby.h" #include "ffisupport.h" #include "native/sink.h" typedef struct { uintptr_t start; uint32_t size; uint32_t op; } DispatchInfo; #define S_ELEM DispatchInfo #define S_SUFFIX DispatchInfoByStart #define S_LESS(a, b) ((a)->start < (b)->start) #include "native/generic/sort.h" #define S_ELEM DispatchInfo #define S_SUFFIX DispatchInfoBySize #define S_LESS(a, b) ((a)->size < (b)->size) #include "native/generic/sort.h" static void dumpDispatchInfo(ChiSink* sink, const char* name, uint8_t** start) { DispatchInfo info[OPCODE_COUNT]; for (uint32_t i = 0; i < OPCODE_COUNT; ++i) { info[i].op = i; info[i].start = (uintptr_t)start[i]; info[i].size = 0; } sortDispatchInfoByStart(info, OPCODE_COUNT); for (uint32_t i = 0; i < OPCODE_COUNT - 1; ++i) info[i].size = (uint32_t)(info[i + 1].start - info[i].start); sortDispatchInfoBySize(info, OPCODE_COUNT); chiSinkFmt(sink, "===== Dispatch Info %s =====\n", name); for (uint32_t i = 0; i < OPCODE_COUNT - 1; ++i) chiSinkFmt(sink, "%-20s %8zu %8zu\n", cbyOpName[info[i].op], info[i].size, info[i].start); } void cbyDirectDispatchInit(const char* name, void** start, void** stop, void* startAddress) { bool fail = false; for (uint32_t i = 0; i < OPCODE_COUNT; ++i) { intptr_t opOffset = ((uint8_t*)start[i] - (uint8_t*)startAddress) >> CBY_DIRECT_DISPATCH_SHIFT; start[i] = (void*)opOffset; if (opOffset > 0xFFFF) { chiWarn("%s: Offset for instruction %u is out of range: %zd", name, i, opOffset); fail = true; } } if (0) dumpDispatchInfo(chiStderr, name, (uint8_t**)start); if (fail || stop - start < OPCODE_COUNT) chiErr("%s: Invalid instruction offsets found.", name); } void cbyDirectDispatchRewrite(void** start, CbyCode* codeStart, const CbyCode* codeEnd) { for (CbyCode* IP = codeStart; IP < codeEnd; ) { IP += CBY_FNHEADER - 4; uint32_t fnSize = FETCH32; for (CbyCode* fnEnd = IP + fnSize; IP < fnEnd;) { uint16_t opCode = FETCH16; chiPokeUInt16(IP - 2, (uint16_t)(uintptr_t)start[opCode]); CHI_WARN_OFF(unused-variable) switch (opCode) { #include "bytecode/rewrite.h" } CHI_WARN_ON } } }
2.078125
2
2024-11-18T21:09:46.774596+00:00
2022-12-24T07:12:30
a61e8e5118b03e51cf097a200e6f6e6b7812f0a6
{ "blob_id": "a61e8e5118b03e51cf097a200e6f6e6b7812f0a6", "branch_name": "refs/heads/master", "committer_date": "2022-12-24T07:12:30", "content_id": "b0a1a9391427274a2bfd0c247a31fef9c68bf6b9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "280855bafb616d8d0c54e534d94c7f675e50a35a", "extension": "c", "filename": "sensor_asair_aht10.c", "fork_events_count": 14, "gha_created_at": "2018-08-16T08:01:20", "gha_event_created_at": "2022-12-22T02:23:59", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 144956490, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4002, "license": "Apache-2.0", "license_type": "permissive", "path": "/sensor_asair_aht10.c", "provenance": "stackv2-0065.json.gz:16688", "repo_name": "RT-Thread-packages/aht10", "revision_date": "2022-12-24T07:12:30", "revision_id": "1e2860b6ef7403bfe34af7a936d23cd09690b26e", "snapshot_id": "be875595221e177e5f5c9e57ddc61345d7768d94", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/RT-Thread-packages/aht10/1e2860b6ef7403bfe34af7a936d23cd09690b26e/sensor_asair_aht10.c", "visit_date": "2022-12-24T08:30:42.037198" }
stackv2
/* * Copyright (c) 2006-2022, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2019-05-08 yangjie the first version */ #include "sensor_asair_aht10.h" #define DBG_TAG "sensor.asair.aht10" #define DBG_LVL DBG_INFO #include <rtdbg.h> static rt_ssize_t _aht10_polling_get_data(rt_sensor_t sensor, rt_sensor_data_t data) { struct aht10_device *aht10_dev = (struct aht10_device *)sensor->parent.user_data; if (sensor->info.type == RT_SENSOR_TYPE_TEMP) { data->data.temp = aht10_read_temperature(aht10_dev); data->timestamp = rt_sensor_get_ts(); return 1; } else if (sensor->info.type == RT_SENSOR_TYPE_HUMI) { data->data.humi = aht10_read_humidity(aht10_dev); data->timestamp = rt_sensor_get_ts(); return 1; } else { return -RT_EINVAL; } } static rt_ssize_t aht10_fetch_data(rt_sensor_t sensor, rt_sensor_data_t buf, rt_size_t len) { RT_ASSERT(buf); if (RT_SENSOR_MODE_GET_FETCH(sensor->info.mode) == RT_SENSOR_MODE_FETCH_POLLING) { return _aht10_polling_get_data(sensor, buf); } else { return -RT_EINVAL; } } static rt_err_t aht10_control(rt_sensor_t sensor, int cmd, void *args) { rt_err_t result = -RT_EINVAL; return result; } static struct rt_sensor_ops sensor_ops = { aht10_fetch_data, aht10_control }; static const char *sensor_name = "aht10"; int rt_hw_aht10_init(const char *name, struct rt_sensor_config *cfg) { rt_int8_t result; rt_sensor_t sensor_temp = RT_NULL, sensor_humi = RT_NULL; struct aht10_device *aht10_dev = aht10_init(cfg->intf.dev_name); if (aht10_dev == RT_NULL) { LOG_E("aht10 init failure!"); return -1; } /* temperature sensor register */ sensor_temp = rt_calloc(1, sizeof(struct rt_sensor_device)); if (sensor_temp == RT_NULL) return -1; sensor_temp->info.type = RT_SENSOR_TYPE_TEMP; sensor_temp->info.vendor = RT_SENSOR_VENDOR_ASAIR; sensor_temp->info.name = sensor_name; sensor_temp->info.unit = RT_SENSOR_UNIT_CELSIUS; sensor_temp->info.intf_type = RT_SENSOR_INTF_I2C; sensor_temp->info.acquire_min = 1000; sensor_temp->info.accuracy.resolution = 0.01; sensor_temp->info.accuracy.error = 0.3; sensor_temp->info.scale.range_min = -40.0; sensor_temp->info.scale.range_max = 85.0; rt_memcpy(&sensor_temp->config, cfg, sizeof(struct rt_sensor_config)); sensor_temp->ops = &sensor_ops; result = rt_hw_sensor_register(sensor_temp, name, RT_DEVICE_FLAG_RDONLY, aht10_dev); if (result != RT_EOK) { LOG_E("device register err code: %d", result); goto __exit; } /* humidity sensor register */ sensor_humi = rt_calloc(1, sizeof(struct rt_sensor_device)); if (sensor_humi == RT_NULL) { return -1; } sensor_humi->info.type = RT_SENSOR_TYPE_HUMI; sensor_humi->info.vendor = RT_SENSOR_VENDOR_ASAIR; sensor_humi->info.name = sensor_name; sensor_humi->info.unit = RT_SENSOR_UNIT_PERCENTAGE; sensor_humi->info.intf_type = RT_SENSOR_INTF_I2C; sensor_humi->info.acquire_min = 1000; sensor_humi->info.accuracy.resolution = 0.024; sensor_humi->info.accuracy.error = 2.0; sensor_humi->info.scale.range_min = 0.0; sensor_humi->info.scale.range_max = 100.0; rt_memcpy(&sensor_humi->config, cfg, sizeof(struct rt_sensor_config)); sensor_humi->ops = &sensor_ops; result = rt_hw_sensor_register(sensor_humi, name, RT_DEVICE_FLAG_RDONLY, aht10_dev); if (result != RT_EOK) { LOG_E("device register err code: %d", result); goto __exit; } return RT_EOK; __exit: if (sensor_temp) rt_free(sensor_temp); if (sensor_humi) rt_free(sensor_humi); if (aht10_dev) aht10_deinit(aht10_dev); return -RT_ERROR; }
2.25
2
2024-11-18T21:09:46.858668+00:00
2019-02-23T04:01:03
331e8cac42bed5eb4616329cd94c2e3d67a0a799
{ "blob_id": "331e8cac42bed5eb4616329cd94c2e3d67a0a799", "branch_name": "refs/heads/master", "committer_date": "2019-02-23T04:01:03", "content_id": "dfc5b8bf31516e2fa0afd50f5ff3a50ea03267e7", "detected_licenses": [ "MIT" ], "directory_id": "f978be8bc90cbb22cfbb18bc8656ca130c4e7bf5", "extension": "c", "filename": "pwmpca.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 81998147, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6634, "license": "MIT", "license_type": "permissive", "path": "/e23_genpwm_pcax/pwmpca.c", "provenance": "stackv2-0065.json.gz:16817", "repo_name": "olekmali/8051f120_superloop", "revision_date": "2019-02-23T04:01:03", "revision_id": "5023203900be8ecee030d40f082a4c7999cc632f", "snapshot_id": "453f687c4ef81164c02b9f7873d13a273f108ce8", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/olekmali/8051f120_superloop/5023203900be8ecee030d40f082a4c7999cc632f/e23_genpwm_pcax/pwmpca.c", "visit_date": "2021-01-14T09:41:54.813005" }
stackv2
#include "pwmpca.h" #include <C8051F120.h> #include "C8051F120_io.h" //------------------------------------------------------------------------------------ // Hardware IO CONSTANTS //------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------ // Global CONSTANTS //------------------------------------------------------------------------------------ //----------------------------------------------------------------------------- // Global Variables //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // PCA0_Init //----------------------------------------------------------------------------- // // Configure the Programmable Counters // void PCA0_Init() { uint8_t SFRPAGE_SAVE = SFRPAGE; // Save the current SFR page uint8_t modeN = 0xCB; // 0x4- sets counter to 16-bit comparator mode // AM: do not set to C to enforce 16bit mode separately // 0x-8 to enable comparator match to be detected and set // 0x-1 to enable comparator interrupt after match is detected // 0x-4 to (toggle) output for PWM - it can be routed to port pins or/and read from reg SFRPAGE = CONFIG_PAGE; // set the SFR page to allow access to the necessary SFRs P0MDOUT |= 0xFC; // Set P0.2 through P0.8 to push-pull, keep current state of P0.0 and P0.1 XBR0 = 0x30; // Close UART0, open UART1, _but_ Close CP0 and /INT0 which prevents Ethernet drivers from working // ** Don't do it if Ethernet extension board AB_4 is present which is the case in the lab ** XBR1 = 0x00; // Open PCA counters 0 through 5 to P0.2 through P0.7 pins which creates problems on Ethernet extensions XBR2 = 0x44; // Enable crossbar and weak pull-up SFRPAGE = PCA0_PAGE; // set the SFR page to allow access to the necessary SFRs PCA0CN = 0x00; // reset counter interrupt bits and disable the counter -0------ PCA0MD = 0x03; // ----SRC- controls the SouRCe of the counting // 000 - SYSCLK/12 // 001 - SYSCLK/4 // 010 - Timer0 overflow (but Timer0 will be used later for something) // 100 - SYSCK, also can use external inputs and external oscillator/8 // -------1 - enables counter roll-over interrupt // Program all of the comparators the same way PCA0CPM0 = modeN; PCA0CPM1 = modeN; PCA0CPM2 = modeN; PCA0CPM3 = modeN; PCA0CPM4 = modeN; PCA0CPM5 = modeN; // Important: set the low byte first (stops comparing), and the high byte next (starts comparing again) PCA0CPL0 = 0x00; PCA0CPH0 = 0x20; PCA0CPL1 = 0x00; PCA0CPH1 = 0x40; PCA0CPL2 = 0x00; PCA0CPH2 = 0x60; PCA0CPL3 = 0x00; // Duty cycle of 50% for CP3 PCA0CPH3 = 0x80; // Duty cycle of 50% for CP3 PCA0CPL4 = 0x00; PCA0CPH4 = 0xA0; PCA0CPL5 = 0x00; PCA0CPH5 = 0xC0; PCA0L = 0x00; // Reset PCA Counter Value to 0x0000 PCA0H = 0x00; PCA0CN |= 0x40; // enable the counter - -1------ SFRPAGE = CONFIG_PAGE; // EIE1 &= ~0x08; // Disable PCA0 interrupt at EIE1.3 SFRPAGE = SFRPAGE_SAVE; // Restore the original SFR page } void PCA0_SetOn(uint8_t channel, PWMstate newstate) { __bit EA_SAVE = EA; // Preserve the current Interrupt Status EA = 0; // disable interrupts if (newstate==ON) { switch(channel) { case 0: PCA0CPM0 |= 0x02; break; case 1: PCA0CPM1 |= 0x02; break; case 2: PCA0CPM2 |= 0x02; break; case 3: PCA0CPM3 |= 0x02; break; case 4: PCA0CPM4 |= 0x02; break; case 5: PCA0CPM5 |= 0x02; break; } } else { switch(channel) { case 0: PCA0CPM0 &= ~0x02; break; case 1: PCA0CPM1 &= ~0x02; break; case 2: PCA0CPM2 &= ~0x02; break; case 3: PCA0CPM3 &= ~0x02; break; case 4: PCA0CPM4 &= ~0x02; break; case 5: PCA0CPM5 &= ~0x02; break; } } EA = EA_SAVE; // restore interrupts } void PCA0_SetDuty(uint8_t channel, uint8_t newduty) { uint16_t value; uint8_t hi, lo; uint8_t SFRPAGE_SAVE = SFRPAGE; // Save the current SFR page __bit EA_SAVE = EA; // Preserve the current Interrupt Status EA = 0; // disable interrupts value = (uint16_t)((((( 100 - newduty) * 0xFFFFL) / 50) +1)>>1); // Mr. Dexter Travis Pro tips: //since timer counts up from reload to overflow we have to //subtract from 100% to get right ratios. Alternately we could //negate the bits of the result value after multiply and divide //multiply the new % by full scale value (0xFFFF) then //divide by 100. To divide by 100 and not lose precision due to //integer arithmetic truncation we first divide by 50, check the low //order bit and add 1 if that bit is set. The result is a //correctly rounded (if >= .5 round up if less round down) lo = (uint8_t) value; hi = (uint8_t) (value >> 8); // Note: PCA0 requires that we load low byte first and must follow with high byte next SFRPAGE = PCA0_PAGE; // set the SFR page to access PCA switch(channel) { case 0: PCA0CPL0 = lo; PCA0CPH0 = hi; break; case 1: PCA0CPL1 = lo; PCA0CPH1 = hi; break; case 2: PCA0CPL2 = lo; PCA0CPH2 = hi; break; case 3: PCA0CPL3 = lo; PCA0CPH3 = hi; break; case 4: PCA0CPL4 = lo; PCA0CPH4 = hi; break; case 5: PCA0CPL5 = lo; PCA0CPH5 = hi; break; } // Mr. Dexter Travis Pro tips: // Do not update immediately as we do it here, use a buffer to store the new value and // read from it on the PCA0 counter overflow to avoid strange spikes EA = EA_SAVE; // restore interrupts SFRPAGE = SFRPAGE_SAVE; // Restore the original SFR page }
2.21875
2
2024-11-18T21:09:47.229608+00:00
2016-06-07T18:55:51
801009c82dc473decc2d941f60ea56f4acf9ad36
{ "blob_id": "801009c82dc473decc2d941f60ea56f4acf9ad36", "branch_name": "refs/heads/master", "committer_date": "2016-06-07T18:55:51", "content_id": "ec6a445971541d673928fcb1748e5a57deea9aac", "detected_licenses": [ "MIT" ], "directory_id": "271d05cd4c3e0a54dee3cfeb951e7fff7ad48fbd", "extension": "c", "filename": "memmanager.c", "fork_events_count": 0, "gha_created_at": "2016-06-03T08:13:23", "gha_event_created_at": "2016-06-03T08:13:23", "gha_language": null, "gha_license_id": null, "github_id": 60330471, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 671, "license": "MIT", "license_type": "permissive", "path": "/memmanager.c", "provenance": "stackv2-0065.json.gz:17073", "repo_name": "mtbar131/memmanager", "revision_date": "2016-06-07T18:55:51", "revision_id": "c948a0f8e26483b4c157eb9b8bf235e4a125fd20", "snapshot_id": "058337d72bd48e74898f9852891f9f2e6a5f1fcf", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mtbar131/memmanager/c948a0f8e26483b4c157eb9b8bf235e4a125fd20/memmanager.c", "visit_date": "2021-01-18T19:46:44.118362" }
stackv2
#include "memmanager.h" memmanager * mem_manager_get(int type) { memmanager *m = (memmanager *) malloc(sizeof(memmanager)); m->type = type; m->data = NULL; switch (type) { case KERNEL: break; case BEST_FIT: m->m_malloc = malloc_best_fit; m->m_free = free_best_fit; break; case FIRST_FIT: m->m_malloc = malloc_first_fit; m->m_free = free_first_fit; break; default: free(m); return NULL; } return m; } void * mem_malloc(memmanager *m, size_t size) { return m->type == KERNEL ? malloc(size) : m->m_malloc(m, size); } void mem_free(memmanager *m, void *ptr) { m->type == KERNEL ? free(ptr) : m->m_free(m, ptr); } int main() { }
2.65625
3
2024-11-18T21:09:47.905825+00:00
2022-09-28T00:33:57
d9046bd2c3364439fcb7d768915692e6697a50c0
{ "blob_id": "d9046bd2c3364439fcb7d768915692e6697a50c0", "branch_name": "refs/heads/master", "committer_date": "2022-09-28T00:33:57", "content_id": "bcc141976fb1fc1411c801f567c071ed5da602f0", "detected_licenses": [ "MIT" ], "directory_id": "0425361139089a497a5b9341017fcba7d4542722", "extension": "h", "filename": "application_layer.h", "fork_events_count": 0, "gha_created_at": "2022-03-19T07:40:23", "gha_event_created_at": "2022-09-28T07:26:58", "gha_language": null, "gha_license_id": "MIT", "github_id": 471625826, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5015, "license": "MIT", "license_type": "permissive", "path": "/sonar/src/application_layer/application_layer.h", "provenance": "stackv2-0065.json.gz:17970", "repo_name": "mcx/anchor", "revision_date": "2022-09-28T00:33:57", "revision_id": "b751b7b1cd129066a80ccb8068097cf985a16899", "snapshot_id": "40f55ea1f5bbb53633805ca7a75a022f735aad01", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mcx/anchor/b751b7b1cd129066a80ccb8068097cf985a16899/sonar/src/application_layer/application_layer.h", "visit_date": "2022-10-15T18:01:45.053961" }
stackv2
#pragma once #include "../common/buffer_chain.h" #include <inttypes.h> #include <stdbool.h> #define _SONAR_APPLICATION_LAYER_CONTEXT_SIZE ( \ sizeof(uintptr_t) + /* pending_request_info_t.{is_active,header} */ \ sizeof(buffer_chain_entry_t) * 2 + /* pending_request_info_t.{header_buffer_chain,data_buffer_chain} */ \ sizeof(sonar_application_layer_init_t)) // Handle type passed to send_data_function() typedef void* sonar_application_layer_send_data_handle_t; // Handle type passed to attribute_*_handler() typedef void* sonar_application_layer_attribute_handler_handle_t; // Handle type passed to *_request_complete_handler() typedef void* sonar_application_layer_request_complete_handler_handle_t; typedef struct { // Whether or not this is the server (vs. client) bool is_server; // Function which is called to write a buffer chain over the physical link bool (*send_data_function)(sonar_application_layer_send_data_handle_t handle, const buffer_chain_entry_t* data); // Function which is called to set the response while handling a request void (*set_response_function)(sonar_application_layer_send_data_handle_t handle, const uint8_t* data, uint32_t length); // Handle passed to send_data_function() sonar_application_layer_send_data_handle_t send_data_handle; // Handler for attribute read requests // NOTE: This must call sonar_application_layer_read_response() with the response data bool (*attribute_read_handler)(sonar_application_layer_attribute_handler_handle_t handle, uint16_t attribute_id); // Handler for attribute write requests bool (*attribute_write_handler)(sonar_application_layer_attribute_handler_handle_t handle, uint16_t attribute_id, const uint8_t* data, uint32_t length); // Handler for attribute notify requests bool (*attribute_notify_handler)(sonar_application_layer_attribute_handler_handle_t handle, uint16_t attribute_id, const uint8_t* data, uint32_t length); // Handle passed to attribute_*_handler() sonar_application_layer_attribute_handler_handle_t attr_handler_handle; // Handler for read request completion void(*read_request_complete_handler)(sonar_application_layer_request_complete_handler_handle_t handle, uint16_t attribute_id, bool success, const uint8_t* data, uint32_t length); // Handler for write request completion void(*write_request_complete_handler)(sonar_application_layer_request_complete_handler_handle_t handle, uint16_t attribute_id, bool success); // Handler for notify request completion void(*notify_request_complete_handler)(sonar_application_layer_request_complete_handler_handle_t handle, uint16_t attribute_id, bool success); // Handle passed to *_request_complete_handler() sonar_application_layer_request_complete_handler_handle_t request_complete_handle; } sonar_application_layer_init_t; // The handle is a pointer to a pre-allocated context type (to be accessed by the SONAR implementation only) typedef uint8_t sonar_application_layer_context_t[_SONAR_APPLICATION_LAYER_CONTEXT_SIZE]; typedef sonar_application_layer_context_t* sonar_application_layer_handle_t; // Initializes the sonar application layer code void sonar_application_layer_init(sonar_application_layer_handle_t handle, const sonar_application_layer_init_t* init); // Sends a SONAR application layer read request for a given attribute, with the handler specified in sonar_application_layer_init_t being being called on completion bool sonar_application_layer_read_request(sonar_application_layer_handle_t handle, uint16_t attribute_id); // Sends a SONAR application layer write request for a given attribute, with the handler specified in sonar_application_layer_init_t being called on completion // NOTE: the data pointer must remain valid until the handler is called bool sonar_application_layer_write_request(sonar_application_layer_handle_t handle, uint16_t attribute_id, const uint8_t* data, uint32_t length); // Sends a SONAR application layer notify request for a given attribute, with the handler specified in sonar_application_layer_init_t being being called on completion // NOTE: the data pointer must remain valid until the handler is called bool sonar_application_layer_notify_request(sonar_application_layer_handle_t handle, uint16_t attribute_id, const uint8_t* data, uint32_t length); // Handles a received SONAR application layer request, populating the response as applicable bool sonar_application_layer_handle_request(sonar_application_layer_handle_t handle, const uint8_t* data, uint32_t length); // Handles a received SONAR application layer response void sonar_application_layer_handle_response(sonar_application_layer_handle_t handle, bool success, const uint8_t* data, uint32_t length); // Sends a SONAR application layer read response - should only (and must) be called from attribute_read_handler() void sonar_application_layer_read_response(sonar_application_layer_handle_t handle, const uint8_t* data, uint32_t length);
2.390625
2
2024-11-18T21:09:48.316967+00:00
2023-01-03T22:58:14
ccdc6c9f7e576c10847117808ca2c45049ae98b2
{ "blob_id": "ccdc6c9f7e576c10847117808ca2c45049ae98b2", "branch_name": "refs/heads/master", "committer_date": "2023-01-03T22:58:14", "content_id": "9cce7dcd7d89f421d1e928fefc3893b17f391673", "detected_licenses": [ "MIT" ], "directory_id": "942ca1c822a197d4b409bc50e6f46392343281c5", "extension": "c", "filename": "ppd42ns.c", "fork_events_count": 6, "gha_created_at": "2016-05-16T16:42:37", "gha_event_created_at": "2017-06-05T18:04:29", "gha_language": "C", "gha_license_id": null, "github_id": 58949404, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2008, "license": "MIT", "license_type": "permissive", "path": "/samples/upm/ppd42ns/src/ppd42ns.c", "provenance": "stackv2-0065.json.gz:18099", "repo_name": "intel-iot-devkit/zupm", "revision_date": "2023-01-03T22:58:14", "revision_id": "ca4dc4248b18cf28dd6c466a8c88cf50ba541ac7", "snapshot_id": "4e9d8b58f16f9f90771b1c9ad59eae405c975e4c", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/intel-iot-devkit/zupm/ca4dc4248b18cf28dd6c466a8c88cf50ba541ac7/samples/upm/ppd42ns/src/ppd42ns.c", "visit_date": "2023-01-20T20:30:54.701231" }
stackv2
/* * Author: Jon Trulson <jtrulson@ics.com> * Copyright (c) 2016 Intel Corporation. * * 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 <unistd.h> #include <stdio.h> #include <signal.h> #include <upm_utilities.h> #include <ppd42ns.h> int shouldRun = true; void sig_handler(int signo) { if (signo == SIGINT) shouldRun = false; } int main() { signal(SIGINT, sig_handler); //! [Interesting] // Instantiate a dust sensor on GPIO pin D8 ppd42ns_context dust = ppd42ns_init(8); ppd42ns_dust_data data; printf("This program will give readings every 30 seconds until " "you stop it\n"); while (shouldRun) { data = ppd42ns_get_data(dust); printf("Low pulse occupancy: %d\n", data.lowPulseOccupancy); printf("Ratio: %f\n", data.ratio); printf("Concentration: %f\n\n", data.concentration); } printf("Exiting...\n"); ppd42ns_close(dust); //! [Interesting] return 0; }
2.421875
2
2024-11-18T21:09:48.364806+00:00
2018-11-21T08:34:00
e9d975ff3d265b84eb85d6524bd506cea9ef2d4c
{ "blob_id": "e9d975ff3d265b84eb85d6524bd506cea9ef2d4c", "branch_name": "refs/heads/master", "committer_date": "2018-11-21T08:34:00", "content_id": "fbadb4a8d4632dbc736ae8d7c84816090b6408a0", "detected_licenses": [ "MIT" ], "directory_id": "21ba7180accb369cd9e78ba4e692dffc2f8cfb63", "extension": "c", "filename": "test_rokkit_hash.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 158117975, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 698, "license": "MIT", "license_type": "permissive", "path": "/test_rokkit_hash.c", "provenance": "stackv2-0065.json.gz:18227", "repo_name": "scherbatey/python-rokkit", "revision_date": "2018-11-21T08:34:00", "revision_id": "6413ee84fbc9e621941adaee58e5f11a6d359d62", "snapshot_id": "ee296b1a554a715d55468688b72a8f41f12eb5ab", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/scherbatey/python-rokkit/6413ee84fbc9e621941adaee58e5f11a6d359d62/test_rokkit_hash.c", "visit_date": "2020-04-07T05:59:34.336195" }
stackv2
#include "SuperFastHash.h" #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> int main(int argc, char * argv[]) { if (argc > 1) { size_t data_arg = argc > 2 ? 2 : 1; const char * data = argv[data_arg]; const size_t len = strlen(argv[data_arg]); uint32_t seed; if (argc > 2) { char * end; seed = (uint32_t)strtoul(argv[1], &end, 10); if (errno != 0) { printf("Invalid seed value!"); return -1; } } else seed = (uint32_t)len; uint32_t hash = SuperFastHash(data, (int)len, seed); printf("%u\n", hash); } }
2.625
3
2024-11-18T21:09:48.511279+00:00
2019-07-29T23:42:07
664fd732426c031f8ed1d0d88d0dcd778196dd16
{ "blob_id": "664fd732426c031f8ed1d0d88d0dcd778196dd16", "branch_name": "refs/heads/master", "committer_date": "2019-07-29T23:42:07", "content_id": "fdce846f6c88d2994022f1944fdd00fec3feb71f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "565fcb5c72eb641de24b0fb874bf143f7b973aad", "extension": "c", "filename": "mesh_prv_common.c", "fork_events_count": 2, "gha_created_at": "2020-06-05T06:10:13", "gha_event_created_at": "2020-06-05T06:10:14", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 269545011, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5730, "license": "Apache-2.0", "license_type": "permissive", "path": "/ble-mesh-profile/sources/provisioning/mesh_prv_common.c", "provenance": "stackv2-0065.json.gz:18484", "repo_name": "tuyafei/cordio", "revision_date": "2019-07-29T23:42:07", "revision_id": "eb18d61b2c139963cb9b67c0057f5be5c6fb5521", "snapshot_id": "9b5b743a409559fcd714f6213410ac580af2570b", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/tuyafei/cordio/eb18d61b2c139963cb9b67c0057f5be5c6fb5521/ble-mesh-profile/sources/provisioning/mesh_prv_common.c", "visit_date": "2022-03-14T16:08:34.458416" }
stackv2
/*************************************************************************************************/ /*! * \file mesh_prv_common.c * * \brief Mesh Provisioning common module implementation. * * Copyright (c) 2010-2018 Arm Ltd. * * Copyright (c) 2019 Packetcraft, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*************************************************************************************************/ #include <string.h> #include "wsf_types.h" #include "wsf_msg.h" #include "util/bstream.h" #include "sec_api.h" #include "mesh_prv.h" #include "mesh_prv_defs.h" #include "mesh_prv_common.h" /************************************************************************************************** Global Functions **************************************************************************************************/ /*************************************************************************************************/ /*! * \brief Generates a random string of alphanumeric characters. * * \param[in] pOutArray Pointer to the output buffer. * \param[in] size Size of the output buffer. * * \return None. */ /*************************************************************************************************/ void meshPrvGenerateRandomAlphanumeric(uint8_t* pOutArray, uint8_t size) { uint8_t alphaCount = 'Z' - 'A' + 1; uint8_t numCount = '9' - '0' + 1; uint8_t index; uint32_t random; for (uint8_t j = 0; j < size; j++) { /* Generate random integer between 0 and 4.294.967.295 */ SecRand((uint8_t*)&random, sizeof(uint32_t)); /* Reduce the large integer modulo number of symbols. The loss of entropy is, on average, negligible. */ index = (uint8_t)(random % (alphaCount + numCount)); /* Map the index to the corresponding symbol */ if (index < alphaCount) { pOutArray[j] = 'A' + index; } else { index -= alphaCount; pOutArray[j] = '0' + index; } } } /*************************************************************************************************/ /*! * \brief Generates a random number on a given number of digits. * * \param[in] digits Number of digits, range 1-8. * * \return The 4-octet random number. */ /*************************************************************************************************/ uint32_t meshPrvGenerateRandomNumeric(uint8_t digits) { uint32_t random; uint32_t max; switch (digits) { case 1: max = 9; break; case 2: max = 99; break; case 3: max = 999; break; case 4: max = 9999; break; case 5: max = 99999; break; case 6: max = 999999; break; case 7: max = 9999999; break; case 8: max = 99999999; break; default: return 0; } /* Generate random integer between 0 and 4.294.967.295 */ SecRand((uint8_t*)&random, sizeof(uint32_t)); /* Reduce the large integer modulo the maximum representable on the given number of digits. The loss of entropy is, on average, negligible. */ random = random % (max + 1); return random; } /*************************************************************************************************/ /*! * \brief Checks that an array contains only alphanumeric characters. * * \param[in] pArray Array of characters. * \param[in] size Array size. * * \return TRUE if all characters are alphanumeric, FALSE otherwise. */ /*************************************************************************************************/ bool_t meshPrvIsAlphanumericArray(uint8_t *pArray, uint8_t size) { bool_t isUppercase; bool_t isDigit; for (uint8_t j = 0; j < size; j++) { isUppercase = (pArray[j] >= 'A' && pArray[j] <= 'Z'); isDigit = (pArray[j] >= '0' && pArray[j] <= '9'); if (!isUppercase && !isDigit) { return FALSE; } } /* No illegal character was found */ return TRUE; } /*************************************************************************************************/ /*! * \brief Packs OOB data into the AuthValue array. * * \param[in] pOutOobArray16B Authentication value array of 16 octets. * \param[in] oobData OOB data obtained from the application. * \param[in] oobSize Size of alphanumeric OOB data, or 0 if OOB data is numeric. * * \return None. */ /*************************************************************************************************/ void meshPrvPackInOutOobToAuthArray(uint8_t* pOutOobArray16B, meshPrvInOutOobData_t oobData, uint8_t oobSize) { if (oobSize > 0) { /* OOB data is alphanumeric - copy as array right-padded with zeros */ memcpy(pOutOobArray16B, oobData.alphanumericOob, oobSize); memset(pOutOobArray16B + oobSize, 0x00, MESH_PRV_AUTH_VALUE_SIZE - oobSize); } else { /* OOB data is numeric - copy as big-endian 4-octet number, left-padded with zeros */ memset(pOutOobArray16B, 0x00, MESH_PRV_AUTH_VALUE_SIZE - MESH_PRV_NUMERIC_OOB_SIZE_OCTETS); UINT32_TO_BE_BUF((pOutOobArray16B + MESH_PRV_AUTH_VALUE_SIZE - MESH_PRV_NUMERIC_OOB_SIZE_OCTETS), oobData.numericOob); } }
2.46875
2
2024-11-18T21:09:48.686856+00:00
2023-08-30T17:21:10
f310ac1d187f2167f8c9b463e83815ed9a419c70
{ "blob_id": "f310ac1d187f2167f8c9b463e83815ed9a419c70", "branch_name": "refs/heads/master", "committer_date": "2023-08-30T17:21:10", "content_id": "b895daf90dbbd5ccb0504dd390da239d793e5d68", "detected_licenses": [ "MIT" ], "directory_id": "a9d15aa7ba2bc1b9ae7edfd54ee49c9b3cf8a4c4", "extension": "c", "filename": "shared.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 356388244, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3423, "license": "MIT", "license_type": "permissive", "path": "/archive/benchmarksv3/tealeaf-parallel/shared.c", "provenance": "stackv2-0065.json.gz:18743", "repo_name": "tallendev/uvm-eval", "revision_date": "2023-08-30T17:21:10", "revision_id": "6ae77eb71c902f5bf6f16ae0fce148f18627d9c1", "snapshot_id": "d712bb7b152b1bbc34d08e66d4bd0a412d3ac58b", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/tallendev/uvm-eval/6ae77eb71c902f5bf6f16ae0fce148f18627d9c1/archive/benchmarksv3/tealeaf-parallel/shared.c", "visit_date": "2023-09-06T05:30:00.101667" }
stackv2
#include "comms.h" #include "shared.h" // Initialises the log file pointer void initialise_log( struct Settings* settings) { // Only write to log in master rank if(settings->rank != MASTER) { return; } printf("Opening %s as log file.\n", settings->tea_out_filename); settings->tea_out_fp = fopen(settings->tea_out_filename, "w"); if(!settings->tea_out_fp) { die(__LINE__, __FILE__, "Could not open log %s\n", settings->tea_out_filename); } } // Prints to stdout and then logs message in log file void print_and_log( struct Settings* settings, const char* format, ...) { // Only master rank should print if(settings->rank != MASTER) { return; } va_list arglist; va_start(arglist, format); vprintf(format, arglist); va_end(arglist); if(!settings->tea_out_fp) { die(__LINE__, __FILE__, "Attempted to write to log before it was initialised\n"); } // Obtuse, but necessary va_list arglist2; va_start(arglist2, format); vfprintf(settings->tea_out_fp, format, arglist2); va_end(arglist2); } // Logs message in log file void print_to_log( struct Settings* settings, const char* format, ...) { // Only master rank should log if(settings->rank != MASTER) { return; } if(!settings->tea_out_fp) { die(__LINE__, __FILE__, "Attempted to write to log before it was initialised\n"); } va_list arglist; va_start(arglist, format); vfprintf(settings->tea_out_fp, format, arglist); va_end(arglist); } // Plots a two-dimensional dat file. void plot_2d(int x, int y, double* buffer, const char* name) { // Open the plot file FILE* fp = fopen("plot2d.dat", "wb"); if(!fp) { printf("Could not open plot file.\n"); } double b_sum = 0.0; for(int jj = 0; jj < y; ++jj) { for(int kk = 0; kk < x; ++kk) { double val = buffer[kk+jj*x]; fprintf(fp, "%d %d %.12E\n", kk, jj, val); b_sum+=val; } } printf("%s: %.12E\n", name, b_sum); fclose(fp); } // Aborts the application. void die(int lineNum, const char* file, const char* format, ...) { // Print location of error printf("\x1b[31m"); printf("\nError at line %d in %s:", lineNum, file); printf("\x1b[0m \n"); va_list arglist; va_start(arglist, format); vprintf(format, arglist); va_end(arglist); abort_comms(); } // Write out data for visualisation in visit void write_to_visit( const int nx, const int ny, const int x_off, const int y_off, const double* data, const char* name, const int step, const double time) { char bovname[256]; char datname[256]; sprintf(bovname, "%s%d.bov", name, step); sprintf(datname, "%s%d.dat", name, step); FILE* bovfp = fopen(bovname, "w"); if(!bovfp) { printf("Could not open file %s\n", bovname); exit(1); } fprintf(bovfp, "TIME: %.4f\n", time); fprintf(bovfp, "DATA_FILE: %s\n", datname); fprintf(bovfp, "DATA_SIZE: %d %d 1\n", nx, ny); fprintf(bovfp, "DATA_FORMAT: DOUBLE\n"); fprintf(bovfp, "VARIABLE: density\n"); fprintf(bovfp, "DATA_ENDIAN: LITTLE\n"); fprintf(bovfp, "CENTERING: zone\n"); fprintf(bovfp, "BRICK_ORIGIN: 0. 0. 0.\n"); fprintf(bovfp, "BRICK_SIZE: %d %d 1\n", nx, ny); fclose(bovfp); FILE* datfp = fopen(datname, "wb"); if(!datfp) { printf("Could not open file %s\n", datname); exit(1); } fwrite(data, sizeof(double), nx*ny, datfp); fclose(datfp); }
2.453125
2
2024-11-18T21:09:49.043235+00:00
2020-07-05T19:41:06
84532e4a71db0154186020300193c150320ec63b
{ "blob_id": "84532e4a71db0154186020300193c150320ec63b", "branch_name": "refs/heads/master", "committer_date": "2020-07-05T19:41:06", "content_id": "c0b8c0233fe5f168069ee8b86660f4e29fb71a0e", "detected_licenses": [ "MIT" ], "directory_id": "529f55e91e75fde98f7e0a8b88400761531cebf6", "extension": "h", "filename": "accessibility.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 277371526, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 962, "license": "MIT", "license_type": "permissive", "path": "/accessibility.h", "provenance": "stackv2-0065.json.gz:19130", "repo_name": "p10q/wmctrl", "revision_date": "2020-07-05T19:41:06", "revision_id": "290fd635fedcadedc2194fbd204f4a98fa2d5fef", "snapshot_id": "a128e8eab16a80bd79072e500758a0c7a7b56e33", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/p10q/wmctrl/290fd635fedcadedc2194fbd204f4a98fa2d5fef/accessibility.h", "visit_date": "2022-11-15T06:10:07.366115" }
stackv2
#ifndef __utils_h__ #define __utils_h__ inline bool CheckAccessibilityPrivileges() { const void *Keys[] = { kAXTrustedCheckOptionPrompt }; const void *Values[] = { kCFBooleanTrue }; CFDictionaryRef Options = CFDictionaryCreate(kCFAllocatorDefault, Keys, Values, sizeof(Keys) / sizeof(*Keys), &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); bool Result = AXIsProcessTrustedWithOptions(Options); CFRelease(Options); return Result; } inline AXUIElementRef SystemWideElement() { static AXUIElementRef Element; static dispatch_once_t Token; dispatch_once(&Token, ^{ Element = AXUIElementCreateSystemWide(); }); return Element; } #endif
2.015625
2
2024-11-18T21:09:54.030992+00:00
2021-04-29T07:38:01
af1dabd00d976259165f0961f0d73b102351e9db
{ "blob_id": "af1dabd00d976259165f0961f0d73b102351e9db", "branch_name": "refs/heads/master", "committer_date": "2021-04-29T07:38:01", "content_id": "8c798ebf6f0c545c242fb895804dc20dcf2aad06", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "93a5dbd77f67719345447c7fee7f69bf2584333b", "extension": "h", "filename": "utils.h", "fork_events_count": 3, "gha_created_at": "2018-03-01T19:41:29", "gha_event_created_at": "2021-04-29T07:38:02", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 123483862, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 658, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/include/rawrtcc/utils.h", "provenance": "stackv2-0065.json.gz:19647", "repo_name": "rawrtc/rawrtc-common", "revision_date": "2021-04-29T07:38:01", "revision_id": "2d4aa340a358773b1f05deeeb05e17738a65694a", "snapshot_id": "b69ce70e1faa585795993292781bfa1accaa1312", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rawrtc/rawrtc-common/2d4aa340a358773b1f05deeeb05e17738a65694a/include/rawrtcc/utils.h", "visit_date": "2021-06-02T23:23:01.697840" }
stackv2
#pragma once #include "code.h" /// Translate a rawrtc return code to a string. char const* rawrtc_code_to_str(enum rawrtc_code const code); /// Translate an re error to a rawrtc code. enum rawrtc_code rawrtc_error_to_code(const int code); /// Duplicate a string. /// `*destinationp` will be set to a copy of `source` and must be /// unreferenced. enum rawrtc_code rawrtc_strdup( char** const destinationp, // de-referenced char const* const source); /// Print a formatted string to a dynamically allocated buffer. /// `*destinationp` must be unreferenced. enum rawrtc_code rawrtc_sdprintf(char** const destinationp, char* const formatter, ...);
2.203125
2
2024-11-18T21:09:54.136682+00:00
2021-04-26T01:45:13
a6b776c948eac4ea8c8796548a055506935c8704
{ "blob_id": "a6b776c948eac4ea8c8796548a055506935c8704", "branch_name": "refs/heads/master", "committer_date": "2021-04-26T01:45:13", "content_id": "68995c32397a0f5eb99a739ef0c08a786ec04036", "detected_licenses": [ "MIT" ], "directory_id": "d734c8e7fea96ae8d9a7df29ef34e8b303a8f889", "extension": "h", "filename": "cleaner.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": 1456, "license": "MIT", "license_type": "permissive", "path": "/magicians_socd_cleaner/magicians_socd_cleaner/cleaner.h", "provenance": "stackv2-0065.json.gz:19776", "repo_name": "rkennesson/Magicians-SOCD-Cleaner", "revision_date": "2021-04-26T01:45:13", "revision_id": "64366da79eca7063224246e6cb42f65cc1b19a9e", "snapshot_id": "8f982ab2437f9c31396b34c6ba23685eac3c277b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rkennesson/Magicians-SOCD-Cleaner/64366da79eca7063224246e6cb42f65cc1b19a9e/magicians_socd_cleaner/magicians_socd_cleaner/cleaner.h", "visit_date": "2023-04-15T05:43:07.324850" }
stackv2
/* Header Guard */ #ifndef CLEANER_H_ #define CLEANER_H_ /* Includes */ #include <avr/io.h> #include "direction.h" #include "modeswitches.h" /* Macros */ // X axis states for last input cleaner #define NEUTRAL_X 0 #define LEFT 1 #define LEFT_LOST 2 #define RIGHT 3 #define RIGHT_LOST 4 // Y axis states for last input cleaner #define NEUTRAL_Y 0 #define DOWN 1 #define DOWN_LOST 2 #define UP 3 #define UP_LOST 4 // Y axis states for last input cleaner #define NEUTRAL_TETRIS 10 #define LEFT_TETRIS 11 #define LEFT_LOST_TETRIS 12 #define RIGHT_TETRIS 13 #define RIGHT_LOST_TETRIS 14 #define DOWN_TETRIS 15 #define DOWN_LOST_TETRIS 16 #define UP_TETRIS 17 #define UP_LOST_TETRIS 18 /* Variables */ // State trackers for last input cleaner static uint8_t CleanerXAxisState; static uint8_t CleanerYAxisState; static uint8_t CleanerDirectionState = NEUTRAL_TETRIS; /* Function Declarations */ // SOCD Cleaners void CleanerXNeutral(uint8_t, uint8_t); void CleanerXLeft(uint8_t, uint8_t); void CleanerXRight(uint8_t, uint8_t); void CleanerXLastInput(uint8_t, uint8_t); void CleanerYNeutral(uint8_t, uint8_t); void CleanerYDown(uint8_t, uint8_t); void CleanerYUp(uint8_t, uint8_t); void CleanerYLastInput(uint8_t, uint8_t); void CleanerTetris(uint8_t, uint8_t, uint8_t, uint8_t); // Helper functions void CleanerDetectThreeReleasedButtons(); #endif // CLEANER_H_
2.171875
2
2024-11-18T21:09:54.307874+00:00
2019-10-14T16:14:08
9aea300d90dabf0e2b47b621aad1c99b85227c1b
{ "blob_id": "9aea300d90dabf0e2b47b621aad1c99b85227c1b", "branch_name": "refs/heads/master", "committer_date": "2019-10-14T16:14:08", "content_id": "0c94c88370257268d8693bcc706f09f51b12d8f9", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "f837a5d8e9cfe1595cf0e059830007a1cdc25678", "extension": "h", "filename": "ring.h", "fork_events_count": 0, "gha_created_at": "2019-10-13T15:15:45", "gha_event_created_at": "2019-10-13T15:15:45", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 214842468, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1460, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/include/quiet/ring.h", "provenance": "stackv2-0065.json.gz:20032", "repo_name": "thaytan/quiet", "revision_date": "2019-10-14T16:14:08", "revision_id": "7a3863f765a996871f0b7008bbd6c35d3effbfc2", "snapshot_id": "05e1b5abca0f5a5fcca203715a84a413b6343a61", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/thaytan/quiet/7a3863f765a996871f0b7008bbd6c35d3effbfc2/include/quiet/ring.h", "visit_date": "2020-08-12T21:01:51.414181" }
stackv2
#include "quiet/common.h" typedef struct { size_t length; uint8_t *base; uint8_t *reader; // reader points to next block to be read uint8_t *writer; // writer points to next block to be written bool is_closed; size_t partial_write_length; uint8_t *partial_writer; // partial_writer points to the next block to be partial written bool partial_write_in_progress; } ring; ring *ring_create(size_t length); void ring_destroy(ring *r); size_t ring_calculate_distance(const ring *r, const uint8_t *src, const uint8_t *dst); uint8_t *ring_calculate_advance(const ring *r, uint8_t *p, size_t adv); ssize_t ring_write(ring *r, const void *buf, size_t len); ssize_t ring_read(ring *r, void *dst, size_t len); void ring_close(ring *r); bool ring_is_closed(ring *r); void ring_advance_reader(ring *r, size_t len); ssize_t ring_write_partial_init(ring *r, size_t len); ssize_t ring_write_partial(ring *r, const void *buf, size_t len); ssize_t ring_write_partial_commit(ring *r); // stubs for unusable feature void ring_set_reader_blocking(ring *r, time_t sec, long nano); void ring_set_reader_nonblocking(ring *r); void ring_set_writer_blocking(ring *r, time_t sec, long nano); void ring_set_writer_nonblocking(ring *r); // these are nops so that this can easily be used in place of the threadsafe rings void ring_writer_lock(ring *r); void ring_writer_unlock(ring *r); void ring_reader_lock(ring *r); void ring_reader_unlock(ring *r);
2
2
2024-11-18T21:09:54.412814+00:00
2021-11-28T21:39:00
b278527e3f526a3fb04e3412d46000f76103fe6a
{ "blob_id": "b278527e3f526a3fb04e3412d46000f76103fe6a", "branch_name": "refs/heads/master", "committer_date": "2021-11-28T21:39:00", "content_id": "51859f894566b93e1a365620e553c0880bf1211c", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e4ea5deda6670d4477291be5f6234bb3147ef696", "extension": "c", "filename": "main.c", "fork_events_count": 10, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 6235766, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1068, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/ZP1/procviceni-uciva/mincovka/src/main.c", "provenance": "stackv2-0065.json.gz:20160", "repo_name": "FrostyX/School", "revision_date": "2021-11-28T21:39:00", "revision_id": "1d20ba132be941125a832c5b252d6890932c2419", "snapshot_id": "53e80cf3a4a3a61d8225841658326970c5d31dcb", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/FrostyX/School/1d20ba132be941125a832c5b252d6890932c2419/ZP1/procviceni-uciva/mincovka/src/main.c", "visit_date": "2021-11-29T08:31:35.299970" }
stackv2
/* Zadání: http://jazykc.inf.upol.cz/procviceni-uciva-i/mincovka.htm * * Jakub Kadlčík [jakub.kadlcik01@upol.cz] * * Product is under The BSD 3-Clause License * Copyright (c) 2012, Jakub Kadlčík * All rights reserved. */ #include <stdio.h> #include <stdlib.h> int mincovka(unsigned int castka, unsigned int **platidla); int main(int argc, char **argv) { int castka; printf("Zadejte částku: "); scanf("%i", &castka); unsigned int *platidla; int n = mincovka(castka, &platidla); int i; for(i=0; i<n; i++) printf("%i\n", platidla[i]); return 0; } int mincovka(unsigned int castka, unsigned int **platidla) { int n = 0; int hodnoty[] = {5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1}; // Lze se obejít bez malloc? Očividně není potřeba nastavovat // výchozí velikost tohoto pole, ani ji nijak zvětšovat. unsigned int *out = (unsigned int *) malloc(0); *platidla = out; int i=0; while(castka>0) { while(castka<hodnoty[i]) i++; castka -= hodnoty[i]; *out = hodnoty[i]; out++; n++; } return n; }
3.171875
3
2024-11-18T21:09:54.626493+00:00
2017-12-15T14:00:03
430cf9a4a262903c455237d7523e706852da3b7b
{ "blob_id": "430cf9a4a262903c455237d7523e706852da3b7b", "branch_name": "refs/heads/master", "committer_date": "2017-12-15T14:00:03", "content_id": "30b73429eb0a969a5ac3ff77cae45f62a8f973e5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b59165ebda7542b0c1a6f16d0e3e522819100813", "extension": "h", "filename": "thread_pool.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 113856159, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 921, "license": "Apache-2.0", "license_type": "permissive", "path": "/system_interface/bin/thread_pool.h", "provenance": "stackv2-0065.json.gz:20417", "repo_name": "victory1355/LinuxAPI", "revision_date": "2017-12-15T14:00:03", "revision_id": "bf61a57c59ff6cecfc2b128240065ba4525cfd86", "snapshot_id": "387b28ff28431427640d8214603eaed8c7a1854f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/victory1355/LinuxAPI/bf61a57c59ff6cecfc2b128240065ba4525cfd86/system_interface/bin/thread_pool.h", "visit_date": "2021-08-30T01:15:54.622547" }
stackv2
#ifndef __THREAD_POOL_H #define __THREAD_POOL_H #include <stdio.h> #include <unistd.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <errno.h> #include <pthread.h> #define MAX_WAITING_TASKS 1000 #define MAX_ACTIVE_THREADS 20 struct task { void *(*task)(void *arg); void *arg; struct task *next; }; typedef struct thread_pool { pthread_mutex_t lock; pthread_cond_t cond; struct task *task_list; pthread_t *tids; unsigned waiting_tasks; unsigned active_threads; bool shutdown; }thread_pool; bool init_pool(thread_pool *pool, unsigned int threads_number); bool add_task(thread_pool *pool, void *(task)(void *arg), void *arg); int add_thread(thread_pool *pool, unsigned int additional_threads_number); int remove_thread(thread_pool *pool, unsigned int removing_threads_number); bool destroy_pool(thread_pool *pool); void *routine(void *arg); #endif
2.15625
2
2024-11-18T21:09:55.883207+00:00
2023-01-06T03:34:58
aec27d6a21ebe2fd53c888c092e31f20468a12fe
{ "blob_id": "aec27d6a21ebe2fd53c888c092e31f20468a12fe", "branch_name": "refs/heads/master", "committer_date": "2023-01-06T03:34:58", "content_id": "9674f7ef15de228db6594ad42bac53ebb940d359", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "8ca1729df63fbadc2079d40c9bd18d06db0f09ad", "extension": "c", "filename": "t_hash.c", "fork_events_count": 31, "gha_created_at": "2019-07-08T07:47:13", "gha_event_created_at": "2022-12-06T07:51:39", "gha_language": "C++", "gha_license_id": null, "github_id": 195762073, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 25456, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/pika/third/redisdb/t_hash.c", "provenance": "stackv2-0065.json.gz:21061", "repo_name": "XimalayaCloud/xcache", "revision_date": "2023-01-06T03:34:58", "revision_id": "2a96417b9a62358a97ce7f65d7d4ecfdb5b0ae65", "snapshot_id": "386996ade35e77642ea36942e7f611852d929464", "src_encoding": "UTF-8", "star_events_count": 192, "url": "https://raw.githubusercontent.com/XimalayaCloud/xcache/2a96417b9a62358a97ce7f65d7d4ecfdb5b0ae65/pika/third/redisdb/t_hash.c", "visit_date": "2023-01-16T05:57:22.103244" }
stackv2
#include <string.h> #include <assert.h> #include <limits.h> #include "redisdbIF.h" #include "commondef.h" #include "commonfunc.h" #include "object.h" #include "zmalloc.h" #include "db.h" #include "ziplist.h" #include "util.h" extern dictType hashDictType; /* Structure to hold hash iteration abstraction. Note that iteration over * hashes involves both fields and values. Because it is possible that * not both are required, store pointers in the iterator to avoid * unnecessary memory allocation for fields/values. */ typedef struct { robj *subject; int encoding; unsigned char *fptr, *vptr; dictIterator *di; dictEntry *de; } hashTypeIterator; /* Get the field or value at iterator cursor, for an iterator on a hash value * encoded as a hash table. Prototype is similar to * `hashTypeGetFromHashTable`. */ sds hashTypeCurrentFromHashTable(hashTypeIterator *hi, int what) { assert(hi->encoding == OBJ_ENCODING_HT); if (what & OBJ_HASH_KEY) { return dictGetKey(hi->de); } else { return dictGetVal(hi->de); } } /* Get the field or value at iterator cursor, for an iterator on a hash value * encoded as a ziplist. Prototype is similar to `hashTypeGetFromZiplist`. */ void hashTypeCurrentFromZiplist(hashTypeIterator *hi, int what, unsigned char **vstr, unsigned int *vlen, long long *vll) { int ret; assert(hi->encoding == OBJ_ENCODING_ZIPLIST); if (what & OBJ_HASH_KEY) { ret = ziplistGet(hi->fptr, vstr, vlen, vll); assert(ret); } else { ret = ziplistGet(hi->vptr, vstr, vlen, vll); assert(ret); } } /* Higher level function of hashTypeCurrent*() that returns the hash value * at current iterator position. * * The returned element is returned by reference in either *vstr and *vlen if * it's returned in string form, or stored in *vll if it's returned as * a number. * * If *vll is populated *vstr is set to NULL, so the caller * can always check the function return by checking the return value * type checking if vstr == NULL. */ void hashTypeCurrentObject(hashTypeIterator *hi, int what, unsigned char **vstr, unsigned int *vlen, long long *vll) { if (hi->encoding == OBJ_ENCODING_ZIPLIST) { *vstr = NULL; hashTypeCurrentFromZiplist(hi, what, vstr, vlen, vll); } else if (hi->encoding == OBJ_ENCODING_HT) { sds ele = hashTypeCurrentFromHashTable(hi, what); *vstr = (unsigned char*) ele; *vlen = sdslen(ele); } else { // serverPanic("Unknown hash encoding"); } } /* Return the key or value at the current iterator position as a new * SDS string. */ sds hashTypeCurrentObjectNewSds(hashTypeIterator *hi, int what) { unsigned char *vstr; unsigned int vlen; long long vll; hashTypeCurrentObject(hi,what,&vstr,&vlen,&vll); if (vstr) return sdsnewlen(vstr,vlen); return sdsfromlonglong(vll); } /* Move to the next entry in the hash. Return C_OK when the next entry * could be found and C_ERR when the iterator reaches the end. */ int hashTypeNext(hashTypeIterator *hi) { if (hi->encoding == OBJ_ENCODING_ZIPLIST) { unsigned char *zl; unsigned char *fptr, *vptr; zl = hi->subject->ptr; fptr = hi->fptr; vptr = hi->vptr; if (fptr == NULL) { /* Initialize cursor */ assert(vptr == NULL); fptr = ziplistIndex(zl, 0); } else { /* Advance cursor */ assert(vptr != NULL); fptr = ziplistNext(zl, vptr); } if (fptr == NULL) return C_ERR; /* Grab pointer to the value (fptr points to the field) */ vptr = ziplistNext(zl, fptr); assert(vptr != NULL); /* fptr, vptr now point to the first or next pair */ hi->fptr = fptr; hi->vptr = vptr; } else if (hi->encoding == OBJ_ENCODING_HT) { if ((hi->de = dictNext(hi->di)) == NULL) return C_ERR; } else { // serverPanic("Unknown hash encoding"); } return C_OK; } hashTypeIterator *hashTypeInitIterator(robj *subject) { hashTypeIterator *hi = zmalloc(sizeof(hashTypeIterator)); hi->subject = subject; hi->encoding = subject->encoding; if (hi->encoding == OBJ_ENCODING_ZIPLIST) { hi->fptr = NULL; hi->vptr = NULL; } else if (hi->encoding == OBJ_ENCODING_HT) { hi->di = dictGetIterator(subject->ptr); } else { // serverPanic("Unknown hash encoding"); } return hi; } void hashTypeReleaseIterator(hashTypeIterator *hi) { if (hi->encoding == OBJ_ENCODING_HT) dictReleaseIterator(hi->di); zfree(hi); } void hashTypeConvertZiplist(robj *o, int enc) { assert(o->encoding == OBJ_ENCODING_ZIPLIST); if (enc == OBJ_ENCODING_ZIPLIST) { /* Nothing to do... */ } else if (enc == OBJ_ENCODING_HT) { hashTypeIterator *hi; dict *dict; int ret; hi = hashTypeInitIterator(o); dict = dictCreate(&hashDictType, NULL); while (hashTypeNext(hi) != C_ERR) { sds key, value; key = hashTypeCurrentObjectNewSds(hi,OBJ_HASH_KEY); value = hashTypeCurrentObjectNewSds(hi,OBJ_HASH_VALUE); ret = dictAdd(dict, key, value); if (ret != DICT_OK) { // serverLogHexDump(LL_WARNING,"ziplist with dup elements dump", // o->ptr,ziplistBlobLen(o->ptr)); // serverPanic("Ziplist corruption detected"); } } hashTypeReleaseIterator(hi); zfree(o->ptr); o->encoding = OBJ_ENCODING_HT; o->ptr = dict; } else { // serverPanic("Unknown hash encoding"); } } void hashTypeConvert(robj *o, int enc) { if (o->encoding == OBJ_ENCODING_ZIPLIST) { hashTypeConvertZiplist(o, enc); } else if (o->encoding == OBJ_ENCODING_HT) { // serverPanic("Not implemented"); } else { // serverPanic("Unknown hash encoding"); } } /* Delete an element from a hash. * Return 1 on deleted and 0 on not found. */ int hashTypeDelete(robj *o, sds field) { int deleted = 0; if (o->encoding == OBJ_ENCODING_ZIPLIST) { unsigned char *zl, *fptr; zl = o->ptr; fptr = ziplistIndex(zl, ZIPLIST_HEAD); if (fptr != NULL) { fptr = ziplistFind(fptr, (unsigned char*)field, sdslen(field), 1); if (fptr != NULL) { zl = ziplistDelete(zl,&fptr); /* Delete the key. */ zl = ziplistDelete(zl,&fptr); /* Delete the value. */ o->ptr = zl; deleted = 1; } } } else if (o->encoding == OBJ_ENCODING_HT) { if (dictDelete((dict*)o->ptr, field) == C_OK) { deleted = 1; /* Always check if the dictionary needs a resize after a delete. */ if (htNeedsResize(o->ptr)) dictResize(o->ptr); } } else { // serverPanic("Unknown hash encoding"); } return deleted; } /* Return the number of elements in a hash. */ unsigned long hashTypeLength(const robj *o) { unsigned long length = ULONG_MAX; if (o->encoding == OBJ_ENCODING_ZIPLIST) { length = ziplistLen(o->ptr) / 2; } else if (o->encoding == OBJ_ENCODING_HT) { length = dictSize((const dict*)o->ptr); } else { // serverPanic("Unknown hash encoding"); } return length; } /* Get the value from a ziplist encoded hash, identified by field. * Returns -1 when the field cannot be found. */ int hashTypeGetFromZiplist(robj *o, sds field, unsigned char **vstr, unsigned int *vlen, long long *vll) { unsigned char *zl, *fptr = NULL, *vptr = NULL; int ret; assert(o->encoding == OBJ_ENCODING_ZIPLIST); zl = o->ptr; fptr = ziplistIndex(zl, ZIPLIST_HEAD); if (fptr != NULL) { fptr = ziplistFind(fptr, (unsigned char*)field, sdslen(field), 1); if (fptr != NULL) { /* Grab pointer to the value (fptr points to the field) */ vptr = ziplistNext(zl, fptr); assert(vptr != NULL); } } if (vptr != NULL) { ret = ziplistGet(vptr, vstr, vlen, vll); assert(ret); return 0; } return -1; } /* Get the value from a hash table encoded hash, identified by field. * Returns NULL when the field cannot be found, otherwise the SDS value * is returned. */ sds hashTypeGetFromHashTable(robj *o, sds field) { dictEntry *de; assert(o->encoding == OBJ_ENCODING_HT); de = dictFind(o->ptr, field); if (de == NULL) return NULL; return dictGetVal(de); } /* Higher level function of hashTypeGet*() that returns the hash value * associated with the specified field. If the field is found C_OK * is returned, otherwise C_ERR. The returned object is returned by * reference in either *vstr and *vlen if it's returned in string form, * or stored in *vll if it's returned as a number. * * If *vll is populated *vstr is set to NULL, so the caller * can always check the function return by checking the return value * for C_OK and checking if vll (or vstr) is NULL. */ int hashTypeGetValue(robj *o, sds field, unsigned char **vstr, unsigned int *vlen, long long *vll) { if (o->encoding == OBJ_ENCODING_ZIPLIST) { *vstr = NULL; if (hashTypeGetFromZiplist(o, field, vstr, vlen, vll) == 0) return C_OK; } else if (o->encoding == OBJ_ENCODING_HT) { sds value; if ((value = hashTypeGetFromHashTable(o, field)) != NULL) { *vstr = (unsigned char*) value; *vlen = sdslen(value); return C_OK; } } else { // serverPanic("Unknown hash encoding"); } return C_ERR; } /* Higher level function using hashTypeGet*() to return the length of the * object associated with the requested field, or 0 if the field does not * exist. */ size_t hashTypeGetValueLength(robj *o, sds field) { size_t len = 0; if (o->encoding == OBJ_ENCODING_ZIPLIST) { unsigned char *vstr = NULL; unsigned int vlen = UINT_MAX; long long vll = LLONG_MAX; if (hashTypeGetFromZiplist(o, field, &vstr, &vlen, &vll) == 0) len = vstr ? vlen : sdigits10(vll); } else if (o->encoding == OBJ_ENCODING_HT) { sds aux; if ((aux = hashTypeGetFromHashTable(o, field)) != NULL) len = sdslen(aux); } else { // serverPanic("Unknown hash encoding"); } return len; } /* Test if the specified field exists in the given hash. Returns 1 if the field * exists, and 0 when it doesn't. */ int hashTypeExists(robj *o, sds field) { if (o->encoding == OBJ_ENCODING_ZIPLIST) { unsigned char *vstr = NULL; unsigned int vlen = UINT_MAX; long long vll = LLONG_MAX; if (hashTypeGetFromZiplist(o, field, &vstr, &vlen, &vll) == 0) return 1; } else if (o->encoding == OBJ_ENCODING_HT) { if (hashTypeGetFromHashTable(o, field) != NULL) return 1; } else { // serverPanic("Unknown hash encoding"); } return 0; } /* Add a new field, overwrite the old with the new value if it already exists. * Return 0 on insert and 1 on update. * * By default, the key and value SDS strings are copied if needed, so the * caller retains ownership of the strings passed. However this behavior * can be effected by passing appropriate flags (possibly bitwise OR-ed): * * HASH_SET_TAKE_FIELD -- The SDS field ownership passes to the function. * HASH_SET_TAKE_VALUE -- The SDS value ownership passes to the function. * * When the flags are used the caller does not need to release the passed * SDS string(s). It's up to the function to use the string to create a new * entry or to free the SDS string before returning to the caller. * * HASH_SET_COPY corresponds to no flags passed, and means the default * semantics of copying the values if needed. * */ #define HASH_SET_TAKE_FIELD (1<<0) #define HASH_SET_TAKE_VALUE (1<<1) #define HASH_SET_COPY 0 int hashTypeSet(robj *o, sds field, sds value, int flags) { int update = 0; if (o->encoding == OBJ_ENCODING_ZIPLIST) { unsigned char *zl, *fptr, *vptr; zl = o->ptr; fptr = ziplistIndex(zl, ZIPLIST_HEAD); if (fptr != NULL) { fptr = ziplistFind(fptr, (unsigned char*)field, sdslen(field), 1); if (fptr != NULL) { /* Grab pointer to the value (fptr points to the field) */ vptr = ziplistNext(zl, fptr); assert(vptr != NULL); update = 1; /* Delete value */ zl = ziplistDelete(zl, &vptr); /* Insert new value */ zl = ziplistInsert(zl, vptr, (unsigned char*)value, sdslen(value)); } } if (!update) { /* Push new field/value pair onto the tail of the ziplist */ zl = ziplistPush(zl, (unsigned char*)field, sdslen(field), ZIPLIST_TAIL); zl = ziplistPush(zl, (unsigned char*)value, sdslen(value), ZIPLIST_TAIL); } o->ptr = zl; /* Check if the ziplist needs to be converted to a hash table */ if (hashTypeLength(o) > OBJ_ZSET_MAX_ZIPLIST_ENTRIES) hashTypeConvert(o, OBJ_ENCODING_HT); } else if (o->encoding == OBJ_ENCODING_HT) { dictEntry *de = dictFind(o->ptr,field); if (de) { sdsfree(dictGetVal(de)); if (flags & HASH_SET_TAKE_VALUE) { dictGetVal(de) = value; value = NULL; } else { dictGetVal(de) = sdsdup(value); } update = 1; } else { sds f,v; if (flags & HASH_SET_TAKE_FIELD) { f = field; field = NULL; } else { f = sdsdup(field); } if (flags & HASH_SET_TAKE_VALUE) { v = value; value = NULL; } else { v = sdsdup(value); } dictAdd(o->ptr,f,v); } } else { // serverPanic("Unknown hash encoding"); } /* Free SDS strings we did not referenced elsewhere if the flags * want this function to be responsible. */ if (flags & HASH_SET_TAKE_FIELD && field) sdsfree(field); if (flags & HASH_SET_TAKE_VALUE && value) sdsfree(value); return update; } /* Check the length of a number of objects to see if we need to convert a * ziplist to a real hash. Note that we only check string encoded objects * as their string length can be queried in constant time. */ void hashTypeTryConversion(robj *o, robj **argv, int start, int end) { int i; if (o->encoding != OBJ_ENCODING_ZIPLIST) return; for (i = start; i <= end; i++) { if (sdsEncodedObject(argv[i]) && sdslen(argv[i]->ptr) > OBJ_HASH_MAX_ZIPLIST_VALUE) { hashTypeConvert(o, OBJ_ENCODING_HT); break; } } } robj *hashTypeLookupWriteOrCreate(redisDb *redis_db, robj *key) { robj *o = lookupKeyWrite(redis_db,key); if (o == NULL) { o = createHashObject(); dbAdd(redis_db,key,o); } else { if (o->type != OBJ_HASH) { return NULL; } } return o; } static int HSet(redisDb *redis_db, robj *kobj, robj *fobj, robj *vobj) { robj *o; if ((o = hashTypeLookupWriteOrCreate(redis_db,kobj)) == NULL) return C_ERR; robj *argv[2]; argv[0] = fobj; argv[1] = vobj; hashTypeTryConversion(o,argv,0,1); hashTypeSet(o, argv[0]->ptr,argv[1]->ptr,HASH_SET_COPY); return C_OK; } static int HMSet(redisDb *redis_db, robj *kobj, robj *items[], unsigned long items_size) { robj *o; if ((o = hashTypeLookupWriteOrCreate(redis_db,kobj)) == NULL) return C_ERR; hashTypeTryConversion(o,items,0,items_size-1); unsigned long i; for (i = 0; i < items_size; i += 2) hashTypeSet(o,items[i]->ptr,items[i+1]->ptr,HASH_SET_COPY); return C_OK; } static int HSetnx(redisDb *redis_db, robj *kobj, robj *fobj, robj *vobj) { robj *o; if ((o = hashTypeLookupWriteOrCreate(redis_db,kobj)) == NULL) return C_ERR; robj *argv[2]; argv[0] = fobj; argv[1] = vobj; hashTypeTryConversion(o,argv,0,1); if (!hashTypeExists(o,argv[0]->ptr)) { hashTypeSet(o,argv[0]->ptr,argv[1]->ptr,HASH_SET_COPY); } return C_OK; } static int GetHashFieldValue(robj *o, sds field, sds *val) { if (o->encoding == OBJ_ENCODING_ZIPLIST) { unsigned char *vstr = NULL; unsigned int vlen = UINT_MAX; long long vll = LLONG_MAX; if (0 > hashTypeGetFromZiplist(o, field, &vstr, &vlen, &vll)) { return REDIS_ITEM_NOT_EXIST; } else { if (vstr) { *val = sdsnewlen(vstr, vlen); } else { *val = sdsfromlonglong(vll); } } } else if (o->encoding == OBJ_ENCODING_HT) { sds value = hashTypeGetFromHashTable(o, field); if (value == NULL) { return REDIS_ITEM_NOT_EXIST; } else { *val = sdsdup(value); } } else { return C_ERR; } return C_OK; } static void addHashIteratorCursorToReply(hashTypeIterator *hi, int what, sds *out) { if (hi->encoding == OBJ_ENCODING_ZIPLIST) { unsigned char *vstr = NULL; unsigned int vlen = UINT_MAX; long long vll = LLONG_MAX; hashTypeCurrentFromZiplist(hi, what, &vstr, &vlen, &vll); if (vstr) { *out = sdsnewlen(vstr, vlen); } else { *out = sdsfromlonglong(vll); } } else if (hi->encoding == OBJ_ENCODING_HT) { sds value = hashTypeCurrentFromHashTable(hi, what); *out = sdsdup(value); } else { // serverPanic("Unknown hash encoding"); } } static int genericHgetall(redisDb *redis_db, robj *kobj, hitem **items, unsigned long *items_size, int flags) { robj *o; hashTypeIterator *hi; if ((o = lookupKeyRead(redis_db,kobj)) == NULL || checkType(o,OBJ_HASH)) return REDIS_KEY_NOT_EXIST; *items_size = hashTypeLength(o); *items = (hitem*)zcalloc(sizeof(hitem) * (*items_size)); hi = hashTypeInitIterator(o); unsigned long i = 0; while (hashTypeNext(hi) != C_ERR) { if (flags & OBJ_HASH_KEY) { addHashIteratorCursorToReply(hi, OBJ_HASH_KEY, &((*items+i)->field)); } if (flags & OBJ_HASH_VALUE) { addHashIteratorCursorToReply(hi, OBJ_HASH_VALUE, &((*items+i)->value)); } ++i; if (i >= *items_size) break; } hashTypeReleaseIterator(hi); return C_OK; } int RsHDel(redisDbIF *db, robj *key, robj *fields[], unsigned long fields_size, unsigned long *ret) { if (NULL == db || NULL == key || NULL == fields) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; robj *o; if ((o = lookupKeyRead(redis_db,key)) == NULL || checkType(o,OBJ_HASH)) { return REDIS_KEY_NOT_EXIST; } unsigned long i, deleted = 0; for (i = 0; i < fields_size; i++) { if (hashTypeDelete(o,fields[i]->ptr)) { deleted++; if (hashTypeLength(o) == 0) { dbDelete(redis_db,key); break; } } } *ret = deleted; return C_OK; } int RsHSet(redisDbIF *db, robj *key, robj *field, robj *val) { if (NULL == db || NULL == key || NULL == field || NULL == val) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; return HSet(redis_db, key, field, val); } int RsHSetnx(redisDbIF *db, robj *key, robj *field, robj *val) { if (NULL == db || NULL == key || NULL == field || NULL == val) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; return HSetnx(redis_db, key, field, val); } int RsHMSet(redisDbIF *db, robj *key, robj *items[], unsigned long items_size) { if (NULL == db || NULL == key || NULL == items) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; return HMSet(redis_db, key, items, items_size); } int RsHGet(redisDbIF *db, robj *key, robj *field, sds *val) { if (NULL == db || NULL == key || NULL == field) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; robj *o; if ((o = lookupKeyRead(redis_db,key)) == NULL || checkType(o,OBJ_HASH)) { return REDIS_KEY_NOT_EXIST; } return GetHashFieldValue(o, field->ptr, val); } int RsHMGet(redisDbIF *db, robj *key, hitem *items, unsigned long items_size) { if (NULL == db || NULL == key || NULL == items) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; robj *o; if ((o = lookupKeyRead(redis_db,key)) == NULL || checkType(o,OBJ_HASH)) { return REDIS_KEY_NOT_EXIST; } unsigned long i; for (i = 0; i < items_size; ++i) { items[i].status = GetHashFieldValue(o, items[i].field, &(items[i].value)); } return C_OK; } int RsHGetAll(redisDbIF *db, robj *key, hitem **items, unsigned long *items_size) { if (NULL == db || NULL == key) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; return genericHgetall(redis_db, key, items, items_size, OBJ_HASH_KEY|OBJ_HASH_VALUE); } int RsHKeys(redisDbIF *db, robj *key, hitem **items, unsigned long *items_size) { if (NULL == db || NULL == key) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; return genericHgetall(redis_db, key, items, items_size, OBJ_HASH_KEY); } int RsHVals(redisDbIF *db, robj *key, hitem **items, unsigned long *items_size) { if (NULL == db || NULL == key) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; return genericHgetall(redis_db, key, items, items_size, OBJ_HASH_VALUE); } int RsHExists(redisDbIF *db, robj *key, robj *field, int *is_exist) { if (NULL == db || NULL == key || NULL == field) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; robj *o; if ((o = lookupKeyRead(redis_db,key)) == NULL || checkType(o,OBJ_HASH)) { return REDIS_KEY_NOT_EXIST; } *is_exist = hashTypeExists(o,field->ptr); return C_OK; } int RsHIncrby(redisDbIF *db, robj *key, robj *field, long long val, long long *ret) { if (NULL == db || NULL == key || NULL == field) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; long long value, oldvalue; robj *o; sds new; unsigned char *vstr; unsigned int vlen; if ((o = hashTypeLookupWriteOrCreate(redis_db,key)) == NULL) { return C_ERR; } if (hashTypeGetValue(o,field->ptr,&vstr,&vlen,&value) == C_OK) { if (vstr) { if (string2ll((char*)vstr,vlen,&value) == 0) { return C_ERR; } } /* Else hashTypeGetValue() already stored it into &value */ } else { value = 0; } oldvalue = value; if ((val < 0 && oldvalue < 0 && val < (LLONG_MIN-oldvalue)) || (val > 0 && oldvalue > 0 && val > (LLONG_MAX-oldvalue))) { return REDIS_OVERFLOW; } value += val; *ret = value; new = sdsfromlonglong(value); hashTypeSet(o,field->ptr,new,HASH_SET_TAKE_VALUE); return C_OK; } int RsHIncrbyfloat(redisDbIF *db, robj *key, robj *field, long double val, long double *ret) { if (NULL == db || NULL == key || NULL == field) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; long double value; long long ll; robj *o; sds new; unsigned char *vstr; unsigned int vlen; if ((o = hashTypeLookupWriteOrCreate(redis_db,key)) == NULL) { return C_ERR; } if (hashTypeGetValue(o,field->ptr,&vstr,&vlen,&ll) == C_OK) { if (vstr) { if (string2ld((char*)vstr,vlen,&value) == 0) { return C_ERR; } } else { value = (long double)ll; } } else { value = 0; } value += val; *ret = value; char buf[MAX_LONG_DOUBLE_CHARS]; int len = ld2string(buf,sizeof(buf),value,1); new = sdsnewlen(buf,len); hashTypeSet(o,field->ptr,new,HASH_SET_TAKE_VALUE); return C_OK; } int RsHlen(redisDbIF *db, robj *key, unsigned long *len) { if (NULL == db || NULL == key) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; robj *o; if ((o = lookupKeyRead(redis_db,key)) == NULL || checkType(o,OBJ_HASH)) { return REDIS_KEY_NOT_EXIST; } *len = hashTypeLength(o); return C_OK; } int RsHStrlen(redisDbIF *db, robj *key, robj *field, unsigned long *len) { if (NULL == db || NULL == key || NULL == field) { return REDIS_INVALID_ARG; } redisDb *redis_db = (redisDb*)db; robj *o; if ((o = lookupKeyRead(redis_db,key)) == NULL || checkType(o,OBJ_HASH)) { return REDIS_KEY_NOT_EXIST; } *len = hashTypeGetValueLength(o,field->ptr); return C_OK; }
2.578125
3
2024-11-18T21:09:56.043362+00:00
2016-04-06T00:58:03
ebfcb99b956954e4a00290148e46f3130473507e
{ "blob_id": "ebfcb99b956954e4a00290148e46f3130473507e", "branch_name": "refs/heads/master", "committer_date": "2016-04-06T00:58:03", "content_id": "442f3e73bf187d355fa1a6722cc5a88b3c09a971", "detected_licenses": [ "MIT" ], "directory_id": "252b5b03d1bc40eb624e2135185af820bbed57a2", "extension": "c", "filename": "SysRestore.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 52923545, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4701, "license": "MIT", "license_type": "permissive", "path": "/SysRestore.c", "provenance": "stackv2-0065.json.gz:21189", "repo_name": "hsluoyz/SysRestore", "revision_date": "2016-04-06T00:58:03", "revision_id": "45f768e43eea877a76c5e5f346c0580d439e24d7", "snapshot_id": "367f06c16c2650d7dd89e2fd4ebe1e1d27ec2061", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/hsluoyz/SysRestore/45f768e43eea877a76c5e5f346c0580d439e24d7/SysRestore.c", "visit_date": "2021-01-10T10:06:39.371602" }
stackv2
/* * SysRestore plug-in for NSIS * * Written by Jason Ross aka JasonFriday13 on the forums. * * SysRestore.c */ /* Include the windows.h file, and the NSIS plugin header. */ #include <windows.h> #include <srrestoreptapi.h> #include "nsis\pluginapi.h" /* This means NSIS 2.42 or higher is required. */ /* Handle for the plugin. */ HANDLE hInstance; /* Variables for the System Restore API */ PRESTOREPOINTINFO pRestPtInfo; STATEMGRSTATUS SMgrStatus; INT64 SequenceNumber = 0; /* Internal variables. */ BOOL RestorePointStarted = FALSE, Initialized = FALSE; void Destroy(void) { if (pRestPtInfo) GlobalFree(pRestPtInfo); } /* Our callback function so that our dll stays loaded. */ UINT_PTR __cdecl NSISPluginCallback(enum NSPIM Event) { if (Event == NSPIM_GUIUNLOAD) Destroy(); return 0; } void Initialize(extra_parameters* xp) { if (!Initialized) { xp->RegisterPluginCallback(hInstance, NSISPluginCallback); Initialized = TRUE; } } /* This function is common to all functions. To reduce size, having one copy instead of two saves space (I think). */ int SetRestorePoint(void) { TCHAR *pTemp; pTemp = GlobalAlloc(GPTR, sizeof(TCHAR) * 64); SRSetRestorePoint(pRestPtInfo, &SMgrStatus); SequenceNumber = SMgrStatus.llSequenceNumber; wsprintf(pTemp, TEXT("%u"), SMgrStatus.nStatus); pushstring(pTemp); GlobalFree(pTemp); return SMgrStatus.nStatus; } /* These functions must be internal to the dll, because they use a global variable. It does not work if these functions are exported. */ int Begin(BOOL Uninstaller) { SecureZeroMemory(pRestPtInfo, sizeof(RESTOREPOINTINFO)); SecureZeroMemory(&SMgrStatus, sizeof(STATEMGRSTATUS)); /* Initialize the RESTOREPOINTINFO structure. */ pRestPtInfo->dwEventType = BEGIN_NESTED_SYSTEM_CHANGE; /* Notify the system that changes are about to be made. An application is to be installed (or uninstalled). */ if (Uninstaller) pRestPtInfo->dwRestorePtType = APPLICATION_UNINSTALL; else pRestPtInfo->dwRestorePtType = APPLICATION_INSTALL; /* Set RestPtInfo.llSequenceNumber. */ pRestPtInfo->llSequenceNumber = 0; /* String to be displayed by System Restore for this restore point. */ popstring(pRestPtInfo->szDescription); /* Notify the system that changes are to be made and that the beginning of the restore point should be marked. */ return SetRestorePoint(); } int Finish(void) { /* Re-initialize the RESTOREPOINTINFO structure to notify the system that the operation is finished. */ pRestPtInfo->dwEventType = END_NESTED_SYSTEM_CHANGE; /* End the system change by returning the sequence number received from the first call to SRSetRestorePoint. */ pRestPtInfo->llSequenceNumber = SequenceNumber; /* Notify the system that the operation is done and that this is the end of the restore point. */ return SetRestorePoint(); } int Remove(void) { int result; result = SRRemoveRestorePoint((DWORD)SequenceNumber); if (result == ERROR_SUCCESS) return 1; else return 0; } __declspec(dllexport) void StartRestorePoint(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop, extra_parameters* xp) { EXDLL_INIT(); Initialize(xp); /* This is to prevent multiple calls to SRSetRestorePoint. */ if (!RestorePointStarted) { if (Begin(FALSE) == ERROR_SUCCESS) RestorePointStarted = TRUE; } else pushint(1); } __declspec(dllexport) void StartUnRestorePoint(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop, extra_parameters* xp) { EXDLL_INIT(); Initialize(xp); /* This is to prevent multiple calls to SRSetRestorePoint. */ if (!RestorePointStarted) { if (Begin(TRUE) == ERROR_SUCCESS) RestorePointStarted = TRUE; } else pushint(1); } __declspec(dllexport) void FinishRestorePoint(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop, extra_parameters* xp) { EXDLL_INIT(); Initialize(xp); /* This is to prevent multiple calls to SRSetRestorePoint. */ if (RestorePointStarted) { if (Finish() == ERROR_SUCCESS) RestorePointStarted = FALSE; } else pushint(2); } void __declspec(dllexport) RemoveRestorePoint(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop, extra_parameters* xp) { EXDLL_INIT(); Initialize(xp); /* This is to prevent multiple calls to SRSetRestorePoint. */ if (SequenceNumber) { if (Remove()) SequenceNumber = 0; } else pushint(3); } BOOL WINAPI _DllMainCRTStartup(HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) { hInstance = hInst; if (ul_reason_for_call == DLL_PROCESS_ATTACH) pRestPtInfo = GlobalAlloc(GPTR, sizeof(RESTOREPOINTINFO)); if (ul_reason_for_call == DLL_PROCESS_DETACH) Destroy(); return TRUE; }
2.28125
2
2024-11-18T21:09:56.824360+00:00
2021-07-28T18:15:31
10a369dbd66604fe24de3fc5aa2228e61d927243
{ "blob_id": "10a369dbd66604fe24de3fc5aa2228e61d927243", "branch_name": "refs/heads/main", "committer_date": "2021-07-28T18:15:31", "content_id": "96edcf17e352a4b56e8eddebd3764c41a8937d26", "detected_licenses": [ "MIT" ], "directory_id": "f9ce4663d2d72c967636dd54d55da606c6a0a4bf", "extension": "h", "filename": "bitmap.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": 1462, "license": "MIT", "license_type": "permissive", "path": "/shell2/bitmap.h", "provenance": "stackv2-0065.json.gz:21833", "repo_name": "forkotherproject/PogoShell", "revision_date": "2021-07-28T18:15:31", "revision_id": "11cc1dc0edd6bf9c30f1f494b2adbef94e7fd635", "snapshot_id": "f9a046a5e66dc520c4b8d909be43b91c85fdb974", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/forkotherproject/PogoShell/11cc1dc0edd6bf9c30f1f494b2adbef94e7fd635/shell2/bitmap.h", "visit_date": "2023-06-27T19:37:24.827603" }
stackv2
#ifndef BITMAP_H #define BITMAP_H #include <pogo.h> typedef struct { uint16 x; uint16 y; uint16 w; uint16 h; } Rect; typedef struct { uchar r; uchar g; uchar b; uchar a; } Color; typedef struct { uint16 width; uint16 height; uint32 format; void *pixels; } BitMap; enum { BPP8 = 1, BPP16 = 2, DONT_ALLOC = 2048, TRANSPARENT = 4096, VIDEOMEM = 8192, }; #define COL16(col) (((col[0]>>3)&0x1F)<<10)|(((col[1]>>3)&0x1F)<<5)|((col[2]>>3)&0x1F); BitMap *bitmap_new(int w, int h, int fmt); #define bitmap_getscreen() bitmap_new(0, 0, VIDEOMEM); void bitmap_free(BitMap *bm); void bitmap_blit(BitMap *dst, int dx, int dy, BitMap *src, int sx, int sy, int sw, int sh); void bitmap_clear(BitMap *dst, int val); BitMap *bitmap_readbmp(FILE *fp); BitMap *bitmap_readbm(FILE *fp); BitMap *bitmap_loadbm(char *name); void bitmap_avgbox(BitMap *dst, Rect *r, uint16 col); void bitmap_avgshiftbox(BitMap *dst, Rect *r, uint16 col, uint16 shift); void bitmap_addshiftbox(BitMap *dst, Rect *r, uint16 col, uint16 shift); void bitmap_addbox(BitMap *dst, Rect *r, uint16 col); void bitmap_negbox(BitMap *dst, Rect *r, uint16 col); void bitmap_fillbox(BitMap *dst, Rect *r, uint16 col); void bitmap_fillsubrange(BitMap *bm, Rect *r, Rect *subr, Color *color0, Color *color1, uint16 style); void bitmap_fillrange(BitMap *bm, Rect *r, Color *color0, Color *color1, uint16 style); #endif
2.015625
2
2024-11-18T21:09:57.163053+00:00
2021-01-12T11:38:06
6255d99d49a819327ebf4a7f173ecefa52667161
{ "blob_id": "6255d99d49a819327ebf4a7f173ecefa52667161", "branch_name": "refs/heads/main", "committer_date": "2021-01-12T11:38:06", "content_id": "023abc1399202f41989315dd537d574c065b2fee", "detected_licenses": [ "MIT" ], "directory_id": "8136ab0386041e7189ba4ace152efea44afae4f3", "extension": "h", "filename": "typedefs.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 328945547, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1510, "license": "MIT", "license_type": "permissive", "path": "/src/Include/typedefs.h", "provenance": "stackv2-0065.json.gz:22090", "repo_name": "Elexir-Stefan/ray-microkernel", "revision_date": "2021-01-12T11:38:06", "revision_id": "b45c9bcd59ea432e791512004ee481b9cb9e4814", "snapshot_id": "bbddc7ab08380709fa1c42f825f0a557666ba16b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Elexir-Stefan/ray-microkernel/b45c9bcd59ea432e791512004ee481b9cb9e4814/src/Include/typedefs.h", "visit_date": "2023-02-12T03:21:37.537417" }
stackv2
#ifndef _TYPEDEFS_H #define _TYPEDEFS_H /** * @file typedefs.h * @author Stefan Nuernberger * @date 02-25-2006 * @brief Common type definitions of the RAY kernel * Common type definitions */ #define UNUSED __attribute__ ((unused)) #define DONTPROFILE __attribute__ ((no_instrument_function)) #define NORETURN __attribute__((noreturn)) // Decide, whether to profile memory-related functions or not #define MEMPROFILE DONTPROFILE #define PACKED __attribute__ ((packed)) typedef unsigned char UINT8; typedef unsigned short UINT16; typedef unsigned int UINT32; typedef unsigned long long UINT64; typedef signed char SINT8; typedef signed short SINT16; typedef signed int SINT32; typedef signed long long SINT64; typedef char* String; typedef const char* CString; typedef enum { FALSE = 0, TRUE = 1 } PACKED BOOL; typedef void* POINTER; typedef const void* CPOINTER; #ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((POINTER)0) #endif #endif #define NewType(baseType, newType) typedef union {baseType Value; UINT32 CastIntValue; UINT8 GetByte[4];} newType; #ifndef __cplusplus #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) #else /* C++ */ /* The reference cast is necessary to thwart an operator& that might be applicable to MEMBER's type. See DR 273 for details. */ #define offsetof(TYPE, MEMBER) (reinterpret_cast <size_t> \ (&reinterpret_cast <char &>(static_cast <TYPE *> (0)->MEMBER))) #endif /* C++ */ #include "compilerspec.h" #endif
2.0625
2
2024-11-18T21:09:57.393904+00:00
2022-09-24T07:36:47
e65680c935e38ed12a04961aea05b0cd17f3bb5a
{ "blob_id": "e65680c935e38ed12a04961aea05b0cd17f3bb5a", "branch_name": "refs/heads/main", "committer_date": "2022-09-24T07:36:47", "content_id": "cf5c35a260422976f1773c8b911afc85487f07c1", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c628d83da0ec6cf65ba966744b35e056b6b3e58a", "extension": "c", "filename": "example-2-harness.c", "fork_events_count": 11, "gha_created_at": "2016-10-06T19:31:41", "gha_event_created_at": "2022-09-02T13:45:20", "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 70186243, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 437, "license": "Apache-2.0", "license_type": "permissive", "path": "/test-harnesses/example-2-harness.c", "provenance": "stackv2-0065.json.gz:22475", "repo_name": "sosy-lab/sv-witnesses", "revision_date": "2022-09-24T07:36:47", "revision_id": "49f0e026928e76a1e0a095aa9b5f71cc3751b40c", "snapshot_id": "dca4b9c0d86d06a7b531cf19192861a33e3ca599", "src_encoding": "UTF-8", "star_events_count": 15, "url": "https://raw.githubusercontent.com/sosy-lab/sv-witnesses/49f0e026928e76a1e0a095aa9b5f71cc3751b40c/test-harnesses/example-2-harness.c", "visit_date": "2023-09-01T22:54:00.428385" }
stackv2
#include <stdlib.h> void __VERIFIER_error(void) { exit(EXIT_FAILURE); } void __VERIFIER_assume(int cond) { if (!(cond)) { exit(EXIT_SUCCESS); }} unsigned int __VERIFIER_nondet_int_index__ = 0; int __VERIFIER_nondet_int() { int retval; switch (__VERIFIER_nondet_int_index__) { case 0: retval = 2; break; case 1: retval = 524800; break; case 2: retval = 40; break; } ++__VERIFIER_nondet_int_index__; return retval; }
2.328125
2
2024-11-18T21:09:57.592339+00:00
2018-07-09T12:35:21
8464ed2e310397f07ae7f427646ba100a7aeb8ac
{ "blob_id": "8464ed2e310397f07ae7f427646ba100a7aeb8ac", "branch_name": "refs/heads/master", "committer_date": "2018-07-09T12:35:21", "content_id": "d5d4299aa098bfd13503976535d975fdf6251842", "detected_licenses": [ "Apache-2.0" ], "directory_id": "2f9d80069086105963fe895ff033d77c410adaf1", "extension": "c", "filename": "shared_write.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 49102558, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 410, "license": "Apache-2.0", "license_type": "permissive", "path": "/assets/posts/torch-internals/shared_mem/shared_write.c", "provenance": "stackv2-0065.json.gz:22603", "repo_name": "byronwwang/byronwwang.github.io", "revision_date": "2018-07-09T12:35:21", "revision_id": "bc7564f9807b388a02e9dd664f1d090ec45a7cdf", "snapshot_id": "1bbdf03fef04942ea6ab78eebc0610140f15accd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/byronwwang/byronwwang.github.io/bc7564f9807b388a02e9dd664f1d090ec45a7cdf/assets/posts/torch-internals/shared_mem/shared_write.c", "visit_date": "2021-01-12T22:30:40.981442" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <signal.h> extern char *data; extern void die(int code, char *msg); static pid_t reader_pid; void do_job() { scanf("%s", data); kill(reader_pid, SIGUSR1); } void setup(int argc, char *argv[]) { if (argc > 1) { printf("%s\n", argv[1]); reader_pid = atoi(argv[1]); } else { die(11, "No reader PID specified\n"); } }
2.203125
2
2024-11-18T21:09:57.731821+00:00
2016-06-13T15:07:23
8266c986d7915642e313e099c3338c44781d866f
{ "blob_id": "8266c986d7915642e313e099c3338c44781d866f", "branch_name": "refs/heads/master", "committer_date": "2016-06-13T15:07:23", "content_id": "9d91feac2925f45355709d6855adc52113194f48", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "b6cca374b8f5443558df5040418fd3540093169b", "extension": "c", "filename": "FLASH_Lyap_cntl_init.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": 2373, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/base/flamec/control/init/lapack/flash/FLASH_Lyap_cntl_init.c", "provenance": "stackv2-0065.json.gz:22731", "repo_name": "siddhesh-singh/libflame", "revision_date": "2016-06-13T15:07:23", "revision_id": "6e6ccb273c59eee7d61995a8edf821c125134af3", "snapshot_id": "d49f92d4ef957101b2c062d7d0110b90867399f8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/siddhesh-singh/libflame/6e6ccb273c59eee7d61995a8edf821c125134af3/src/base/flamec/control/init/lapack/flash/FLASH_Lyap_cntl_init.c", "visit_date": "2021-01-21T05:40:23.538394" }
stackv2
/* Copyright (C) 2014, The University of Texas at Austin This file is part of libflame and is available under the 3-Clause BSD license, which can be found in the LICENSE file at the top-level directory, or at http://opensource.org/licenses/BSD-3-Clause */ #include "FLAME.h" extern fla_scal_t* flash_scal_cntl; extern fla_gemm_t* flash_gemm_cntl_pm; extern fla_hemm_t* flash_hemm_cntl_mp; extern fla_her2k_t* flash_her2k_cntl_ip; extern fla_sylv_t* flash_sylv_cntl; fla_lyap_t* flash_lyap_cntl_leaf; fla_lyap_t* flash_lyap_cntl; fla_blocksize_t* flash_lyap_bsize; void FLASH_Lyap_cntl_init() { // Set blocksize for hierarchical storage. flash_lyap_bsize = FLA_Blocksize_create( 1, 1, 1, 1 ); // Create a control tree that assumes A and C are b x b blocks. flash_lyap_cntl_leaf = FLA_Cntl_lyap_obj_create( FLA_HIER, FLA_SUBPROBLEM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ); // Create a control tree that assumes A is a matrix and C is a matrix. flash_lyap_cntl = FLA_Cntl_lyap_obj_create( FLA_HIER, FLA_BLOCKED_VARIANT1, flash_lyap_bsize, flash_scal_cntl, flash_lyap_cntl_leaf, flash_sylv_cntl, NULL, //flash_gemm_cntl_pm, NULL, //flash_gemm_cntl_pm, flash_hemm_cntl_mp, flash_her2k_cntl_ip ); } void FLASH_Lyap_cntl_finalize() { FLA_Cntl_obj_free( flash_lyap_cntl_leaf ); FLA_Cntl_obj_free( flash_lyap_cntl ); FLA_Blocksize_free( flash_lyap_bsize ); }
2.0625
2
2024-11-18T21:09:58.319734+00:00
2020-04-24T23:20:40
842d8193489761c8f6c220fad513304520255959
{ "blob_id": "842d8193489761c8f6c220fad513304520255959", "branch_name": "refs/heads/master", "committer_date": "2020-04-24T23:20:40", "content_id": "9d50ea5947e178aa00bd8f3e2245b87abe58cce0", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "48c2d779adc3ec016b996d1bb03c5f9b2605bb3f", "extension": "c", "filename": "cisco_pix.c", "fork_events_count": 0, "gha_created_at": "2020-04-29T11:44:55", "gha_event_created_at": "2020-04-29T11:44:56", "gha_language": null, "gha_license_id": null, "github_id": 259910011, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1093, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/pwdalgos/cisco/cisco_pix.c", "provenance": "stackv2-0065.json.gz:23245", "repo_name": "wqweto/tinycrypt", "revision_date": "2020-04-24T23:20:40", "revision_id": "b6100cf07b7355643085dda326c13dcfcc804077", "snapshot_id": "6aa72dab0fc553de87f7d925dd075fbc4347211b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/wqweto/tinycrypt/b6100cf07b7355643085dda326c13dcfcc804077/pwdalgos/cisco/cisco_pix.c", "visit_date": "2022-04-24T00:13:25.536111" }
stackv2
// Cisco PIX password algorithm // Odzhan #include <stdint.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <openssl/md5.h> unsigned char itoa64[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; void to64(char *s, unsigned long v, int n) { while (--n >= 0) { *s++ = itoa64[v&0x3f]; v >>= 6; } } char *pix_pwd (char *pwd) { char x[16]; MD5_CTX ctx; static char r[16+1]; uint8_t dgst[MD5_DIGEST_LENGTH]; char *p; int i; memset (x, 0, sizeof x); strncpy (x, pwd, 16); MD5_Init (&ctx); MD5_Update (&ctx, x, 16); MD5_Final (dgst, &ctx); p = r; to64(p, *(uint32_t*) (dgst+0), 4); p += 4; to64(p, *(uint32_t*) (dgst+4), 4); p += 4; to64(p, *(uint32_t*) (dgst+8), 4); p += 4; to64(p, *(uint32_t*) (dgst+12),4); p += 4; return r; } int main (int argc, char *argv[]) { if (argc != 2) { printf ("\n usage: cisco_pix <password>\n"); return 0; } printf ("\n Cisco PIX : %s\n", pix_pwd (argv[1])); return 0; }
2.734375
3
2024-11-18T21:09:58.686306+00:00
2014-03-17T08:34:19
4be64a35a1f5053fc6d917956e083cec82ec7d05
{ "blob_id": "4be64a35a1f5053fc6d917956e083cec82ec7d05", "branch_name": "refs/heads/master", "committer_date": "2014-03-17T08:49:25", "content_id": "a12b2a6fe1359242a7c595e84840d21c1f6344e3", "detected_licenses": [ "MIT" ], "directory_id": "6c7fc92b2627710a04de1b75fdcf9be37f1a72fd", "extension": "h", "filename": "tree.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 17816358, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7114, "license": "MIT", "license_type": "permissive", "path": "/lib/ulib/src/base/tree.h", "provenance": "stackv2-0065.json.gz:23501", "repo_name": "rdeva31/tinygrind", "revision_date": "2014-03-17T08:34:19", "revision_id": "b520516b3dbbdb94b18c6eeb84604910c7177b3e", "snapshot_id": "5b8d08d660bbf83181914ff6baac3c12037f6c0a", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/rdeva31/tinygrind/b520516b3dbbdb94b18c6eeb84604910c7177b3e/lib/ulib/src/base/tree.h", "visit_date": "2021-01-01T18:18:38.001964" }
stackv2
/* The MIT License Copyright (C) 2011, 2012 Zilong Tan (eric.zltan@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __ULIB_TREE_H #define __ULIB_TREE_H #ifdef __cplusplus #define new _new_ #endif struct tree_root { struct tree_root *left, *right; struct tree_root *parent; }; /* avl_root is derived from tree_root */ struct avl_root { struct avl_root *left, *right; struct avl_root *parent; int balance:3; }; #define NIL (void *)0 #define TREE_ROOT_INIT { NIL, NIL, NIL } #define TREE_ROOT(name) \ struct tree_root name = TREE_ROOT_INIT #define INIT_TREE_ROOT(ptr) do { \ (ptr)->left = NIL; (ptr)->right = NIL; \ (ptr)->parent = NIL; \ } while (0) #define AVL_ROOT_INIT { NIL, NIL, NIL, 0 } #define AVL_ROOT(name) \ struct avl_root name = AVL_ROOT_INIT; #define INIT_AVL_ROOT(ptr) do { \ INIT_TREE_ROOT(ptr); \ (ptr)->balance = 0; \ } while (0) /* emptiness tests */ #define TREE_EMPTY(ptr) ((ptr) == NIL) #define SPLAY_EMPTY(ptr) TREE_EMPTY(ptr) #define AVL_EMPTY(ptr) TREE_EMPTY(ptr) #ifdef __cplusplus extern "C" { #endif /* applies to other trees derived from BST also */ struct tree_root * tree_search(struct tree_root *entry, int (*compare) (const void *, const void *), struct tree_root *root); struct tree_root * tree_min(struct tree_root *root); struct tree_root * tree_max(struct tree_root *root); struct tree_root * tree_successor(struct tree_root *root); struct tree_root * tree_predecessor(struct tree_root *root); /* add a new entry regardless of any duplicates */ void tree_add(struct tree_root *new, int (*compare) (const void *, const void *), struct tree_root **root); /* add a unique entry if the entry already exists, return the old one. Otherwise the new entry will be returned. */ struct tree_root * tree_map(struct tree_root *new, int (*compare) (const void *, const void *), struct tree_root **root); void tree_del(struct tree_root *entry, struct tree_root **root); /* similar to tree_map, but it involves an additional splay operation */ struct tree_root * splay_map(struct tree_root *new, int (*compare) (const void *, const void *), struct tree_root **root); /* accelerate splay_map at the expense of invalidating parent pointers */ struct tree_root * splay_map_nparent(struct tree_root *new, int (*compare) (const void *, const void *), struct tree_root **root); /* similar to tree_search, but it involves an additional splay operation */ struct tree_root * splay_search(struct tree_root *entry, int (*compare) (const void *, const void *), struct tree_root **root); /* accelerate splay_search at the expense of invalidating parent pointers */ struct tree_root * splay_search_nparent(struct tree_root *entry, int (*compare) (const void *, const void *), struct tree_root **root); void avl_add(struct avl_root *new, int (*compare) (const void *, const void *), struct avl_root **root); struct avl_root * avl_map(struct avl_root *new, int (*compare) (const void *, const void *), struct avl_root **root); void avl_del(struct avl_root *entry, struct avl_root **root); #ifdef __cplusplus } #endif /* retrieve the host struct * @ptr: node pointer * @type: host type * @member: node member name */ #define tree_entry(ptr, type, member) \ ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) #define avl_entry(ptr, type, member) tree_entry(ptr, type, member) #define tree_for_each(pos, root) \ for (pos = tree_min(root); pos != NIL; \ pos = tree_successor(pos)) /* traversal in reversed order */ #define tree_for_each_prev(pos, root) \ for (pos = tree_max(root); pos != NIL; \ pos = tree_predecessor(pos)) /* @pos is safe for removal */ #define tree_for_each_safe(pos, n, root) \ for (pos = tree_min(root), n = tree_successor(pos); \ pos != NIL; \ pos = n, n = n != NIL? tree_successor(n): NIL) /* traverse the host struct instead of node */ #define tree_for_each_entry(pos, root, member) \ for (pos = tree_entry(tree_min(root), typeof(*pos), member); \ &pos->member != NIL; \ pos = tree_entry(tree_successor(&pos->member), typeof(*pos), member)) #define tree_for_each_entry_safe(pos, n, root, member) \ for (pos = tree_entry(tree_min(root), typeof(*pos), member), \ n = tree_entry(tree_successor(&pos->member), typeof(*pos), member); \ &pos->member != NIL; pos = n, \ n = tree_entry(&n->member != NIL? tree_successor(&n->member): NIL, typeof(*n), member)) #define avl_for_each(pos, root) \ for (pos = (struct avl_root *)tree_min((struct tree_root *)root); pos != NIL; \ pos = (struct avl_root *)tree_successor((struct tree_root *)pos)) #define avl_for_each_prev(pos, root) \ for (pos = (struct avl_root *)tree_max((struct tree_root *)root); pos != NIL; \ pos = (struct avl_root *)tree_predecessor((struct tree_root *)pos)) #define avl_for_each_safe(pos, n, root) \ for (pos = (struct avl_root *)tree_min((struct tree_root *)root), \ n = (struct avl_root *)tree_successor((struct tree_root *)pos); pos != NIL; \ pos = n, \ n = n != NIL? (struct avl_root *)tree_successor((struct tree_root *)n): NIL) #define avl_for_each_entry(pos, root, member) \ for (pos = tree_entry(tree_min((struct tree_root *)root), typeof(*pos), member); \ &pos->member != NIL; \ pos = tree_entry(tree_successor((struct tree_root *)&pos->member), typeof(*pos), member)) #define avl_for_each_entry_safe(pos, n, root, member) \ for (pos = tree_entry(tree_min((struct tree_root *)root), typeof(*pos), member), \ n = tree_entry(tree_successor((struct tree_root *)&pos->member), typeof(*pos), member); \ &pos->member != NIL; \ pos = n, \ n = tree_entry(&n->member != NIL? tree_successor((struct tree_root *)&n->member): NIL, typeof(*n), member)) #ifdef __cplusplus #undef new #endif #endif /* __ULIB_TREE_H */
2.328125
2
2024-11-18T21:09:58.824125+00:00
2016-10-27T15:18:04
7920f2baafd8cee7aea93c82f99fded14f987e49
{ "blob_id": "7920f2baafd8cee7aea93c82f99fded14f987e49", "branch_name": "refs/heads/master", "committer_date": "2016-10-27T15:18:04", "content_id": "1cb7def5011de3a6db0928b78e917000887f5fcc", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c030553b79a5decbbc703096ded188fb892677f1", "extension": "c", "filename": "main.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 72072257, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 383, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main.c", "provenance": "stackv2-0065.json.gz:23630", "repo_name": "Akasurde/DigisparkHOTP", "revision_date": "2016-10-27T15:18:04", "revision_id": "96c2243d5e28d81d95c6dbab0c2244c7743b34a9", "snapshot_id": "1857755961a9d9e625b65a1186a002d200afd8bc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Akasurde/DigisparkHOTP/96c2243d5e28d81d95c6dbab0c2244c7743b34a9/src/main.c", "visit_date": "2021-01-13T09:28:15.184367" }
stackv2
// // main.c // HOTP // // Created by Abhijeet Kasurde on 29/09/16. // Copyright © 2016 Abhijeet Kasurde. All rights reserved. // #include <stdio.h> #include "digispark.h" #define MAX_OTP 16 #define MAX_KEY_LENGTH 21 int main() { for (int i = 0; i <= 10; i++) { char *c = generateCode("12345678901234567890", i); printf("%s\n", c); } return 0; }
2.078125
2
2024-11-18T21:09:59.224471+00:00
2021-02-13T02:44:28
6c23f1f146bd50d28263e2982f689e8acd470a5a
{ "blob_id": "6c23f1f146bd50d28263e2982f689e8acd470a5a", "branch_name": "refs/heads/main", "committer_date": "2021-02-13T02:44:28", "content_id": "ee80e7a91c9d2b697956bbe18326b20fdccc6036", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "b95f6912c74cf059107887d470d249582b9f1eb8", "extension": "c", "filename": "mfMenuDrawTables.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 338482868, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16469, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/mfmenu/mfMenuDrawTables.c", "provenance": "stackv2-0065.json.gz:23887", "repo_name": "PSP-Archive/MacroFire", "revision_date": "2021-02-13T02:44:28", "revision_id": "8a9b51b90f32fb42a4bc807779cc86da9b194644", "snapshot_id": "4f52925427213851d8c925b0d52ec7e047253c05", "src_encoding": "SHIFT_JIS", "star_events_count": 1, "url": "https://raw.githubusercontent.com/PSP-Archive/MacroFire/8a9b51b90f32fb42a4bc807779cc86da9b194644/mfmenu/mfMenuDrawTables.c", "visit_date": "2023-03-04T19:00:42.448708" }
stackv2
/* mfMenuDrawTables.c */ #include "mfmenu_types.h" static bool mf_menu_move_table( enum MfMenuMoveDirection dir, MfMenuTable *menu, unsigned int menucnt, struct MfMenuPosition *pos ); static bool mf_menu_nearest_table( unsigned int pri, unsigned int sec, unsigned int *save_pri, unsigned int *save_sec ); static bool mf_menu_farest_table( unsigned int pri, unsigned int sec, unsigned int *save_pri, unsigned int *save_sec ); static bool mf_menu_select_table_horizontal( MfMenuTable *menu, unsigned int targ_tid, struct MfMenuPosition *pos, bool reverse ); static bool mf_menu_select_table_vertical( MfMenuTable *menu, unsigned int targ_tid, struct MfMenuPosition *pos, bool reverse ); static unsigned int mf_label_width( char *str ); int mfMenuDrawTables( MfMenuTable menu[], unsigned int cnt, unsigned int opt ) { /* 選択可能な項目(コントロールが設定されていてActivateされている)が一つもないと無限ループ */ int ret = CG_OK; unsigned int i, row, col; unsigned int col_width, width, col_offset, row_offset; struct MfMenuPosition dupe_pos; bool refind = true; /* ラベルを描画 */ for( i = 0; i < cnt; i++ ){ if( menu[i].label ){ col_offset = pbOffsetChar( 2 ); row_offset = pbOffsetLine( 1 ) + 2; pbPrint( menu[i].x, menu[i].y, MF_COLOR_TEXT_LABEL, MF_COLOR_TEXT_BG, menu[i].label ); pbLine( menu[i].x + pbMeasureString( menu[i].label ) + ( pbOffsetChar( 1 ) >> 1 ), menu[i].y + ( pbOffsetLine( 1 ) >>1 ), SCR_WIDTH - pbOffsetChar( 6 ), menu[i].y + ( pbOffsetLine( 1 ) >>1 ), MF_COLOR_TEXT_LABEL ); } else{ col_offset = 0; row_offset = 0; } for( col = 0, col_width = 0; col < menu[i].cols; col++ ){ if( col && menu[i].colsWidth && menu[i].colsWidth[col - 1] > 0 ){ col_width = menu[i].colsWidth[col - 1]; } else if( col_width ){ col_width += pbOffsetChar( 2 ); } col_offset += col_width; for( row = 0; row < menu[i].rows; row++ ){ char labelbuf[MF_CTRL_BUFFER_LENGTH] = "\0"; if( menu[i].entry[row][col].ctrl ){ ( menu[i].entry[row][col].ctrl )( MF_CM_LABEL | __mfmenu__gParams->Message.Sub, menu[i].entry[row][col].label, menu[i].entry[row][col].var, menu[i].entry[row][col].arg, labelbuf ); } if( labelbuf[0] == '\0' ) strutilCopy( labelbuf, menu[i].entry[row][col].label, sizeof( labelbuf ) ); if( labelbuf[0] != '\0' ){ pbPrint( menu[i].x + col_offset, menu[i].y + row_offset + pbOffsetLine( row ), ( i == __mfmenu__gParams->Menu.CurTable && row == __mfmenu__gParams->Menu.CurRow && col == __mfmenu__gParams->Menu.CurCol ? MF_COLOR_TEXT_FC : menu[i].entry[row][col].active ? MF_COLOR_TEXT_FG : MF_COLOR_TEXT_INACT ), MF_COLOR_TEXT_BG, labelbuf ); width = mf_label_width( labelbuf ); if( col_width < width ) col_width = width; } } } } if( ! ( opt & MF_MENU_DISPLAY_ONLY ) ){ MfCtrlMessage ctrlmsg; if( __mfmenu__gParams->Extra.Proc ){ /* 拡張関数が設定されていれば実行 */ int extraret = ( __mfmenu__gParams->Extra.Proc )( MF_MM_PROC | __mfmenu__gParams->Message.Sub, __mfmenu__gParams->Extra.Argp ); if( CG_IS_ERROR( extraret ) ){ mfMenuExitExtra(); mfMenuError( extraret, NULL ); } ctrlmsg = ( __mfmenu__gParams->Extra.Proc ? MF_CM_WAIT : MF_CM_CONTINUE ); } else if( mfMenuMaskDialogMessage( __mfmenu__gParams->Message.Sub ) ){ ctrlmsg = ( ! ( __mfmenu__gParams->Message.Sub & MF_DM_FINISH ) ? MF_CM_WAIT : MF_CM_CONTINUE ); } else{ ctrlmsg = MF_CM_PROC; } if( menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].active ){ if( menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].ctrl ){ ret = ( menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].ctrl )( ctrlmsg | __mfmenu__gParams->Message.Sub, menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].label, menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].var, menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].arg, NULL ); } if( __mfmenu__gParams->Message.Sub & ( MF_DM_START | MF_DM_UPDATE ) ) return ret; } } else{ return ret; } /* 拡張関数が設定されていればここまで */ if( __mfmenu__gParams->Extra.Proc ) return ret; /* BACKの検出 */ if( mfMenuIsPressed( mfMenuCancelButton() ) || ( __mfmenu__gParams->Message.Main & MF_MENU_IM_BACK ) ) return MF_MENU_BACK; /* 情報バーのデータを取得 */ if( __mfmenu__gParams->Info.Text[0] == '\0' ){ unsigned int opt = menu[__mfmenu__gParams->Menu.CurTable].cols == 1 ? 0 : MF_MENU_INFOTEXT_MULTICOLUMN_CTRL; if( menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].active ){ ( menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].ctrl )( MF_CM_INFO | __mfmenu__gParams->Message.Sub, menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].label, menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].var, menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].arg, &opt ); } if( __mfmenu__gParams->Info.Text[0] == '\0' ) mfMenuSetInfoText( MF_MENU_INFOTEXT_COMMON_CTRL, "" ); } /* 現在の位置をバックアップ */ dupe_pos = __mfmenu__gParams->Menu; /* 操作 */ while( refind ){ refind = false; if( mfMenuIsPressed( PSP_CTRL_UP ) ){ if( __mfmenu__gParams->Menu.CurRow ){ __mfmenu__gParams->Menu.CurRow--; } else if( ! mf_menu_move_table( MF_MENU_MOVE_UP, menu, cnt, &(__mfmenu__gParams->Menu) ) ){ refind = true; break; } } else if( mfMenuIsPressed( PSP_CTRL_DOWN ) ){ if( __mfmenu__gParams->Menu.CurRow < menu[__mfmenu__gParams->Menu.CurTable].rows - 1 ){ __mfmenu__gParams->Menu.CurRow++; } else if( ! mf_menu_move_table( MF_MENU_MOVE_DOWN, menu, cnt, &(__mfmenu__gParams->Menu) ) ){ refind = true; break; } } else if( mfMenuIsPressed( PSP_CTRL_LEFT ) ){ if( __mfmenu__gParams->Menu.CurCol ){ __mfmenu__gParams->Menu.CurCol--; } else if( ! mf_menu_move_table( MF_MENU_MOVE_LEFT, menu, cnt, &(__mfmenu__gParams->Menu) ) ){ refind = true; break; } } else if( mfMenuIsPressed( PSP_CTRL_RIGHT ) ){ if( __mfmenu__gParams->Menu.CurCol < menu[__mfmenu__gParams->Menu.CurTable].cols - 1 ){ __mfmenu__gParams->Menu.CurCol++; } else if( ! mf_menu_move_table( MF_MENU_MOVE_RIGHT, menu, cnt, &(__mfmenu__gParams->Menu) ) ){ refind = true; break; } } if( ! menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][__mfmenu__gParams->Menu.CurCol].active ){ int pos_pos, pos_neg; if( mfMenuIsAnyPressed( PSP_CTRL_UP | PSP_CTRL_DOWN ) ){ refind = true; pos_pos = __mfmenu__gParams->Menu.CurCol + 1; pos_neg = __mfmenu__gParams->Menu.CurCol - 1; while( refind && ( pos_pos >= 0 || pos_neg >= 0 ) ){ if( pos_pos >= menu[__mfmenu__gParams->Menu.CurTable].cols ) pos_pos = -1; if( pos_neg >= 0 ){ if( menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][pos_neg].active ){ __mfmenu__gParams->Menu.CurCol = pos_neg; refind = false; } pos_neg--; }else if( pos_pos >= 0 ){ if( menu[__mfmenu__gParams->Menu.CurTable].entry[__mfmenu__gParams->Menu.CurRow][pos_pos].active ){ __mfmenu__gParams->Menu.CurCol = pos_pos; refind = false; } pos_pos++; } } } else if( mfMenuIsAnyPressed( PSP_CTRL_RIGHT | PSP_CTRL_LEFT ) ){ refind = true; pos_pos = __mfmenu__gParams->Menu.CurRow + 1; pos_neg = __mfmenu__gParams->Menu.CurRow - 1; while( refind && ( pos_pos >= 0 || pos_neg >= 0 ) ){ if( pos_pos >= menu[__mfmenu__gParams->Menu.CurTable].rows ) pos_pos = -1; if( pos_neg >= 0 ){ if( menu[__mfmenu__gParams->Menu.CurTable].entry[pos_neg][__mfmenu__gParams->Menu.CurCol].active ){ __mfmenu__gParams->Menu.CurRow = pos_neg; refind = false; } pos_neg--; }else if( pos_pos >= 0 ){ if( menu[__mfmenu__gParams->Menu.CurTable].entry[pos_pos][__mfmenu__gParams->Menu.CurCol].active ){ __mfmenu__gParams->Menu.CurRow = pos_pos; refind = false; } pos_pos++; } } } } } if( refind ) __mfmenu__gParams->Menu = dupe_pos; return ret; } static bool mf_menu_move_table( enum MfMenuMoveDirection dir, MfMenuTable *menu, unsigned int menucnt, struct MfMenuPosition *pos ) { unsigned int i; unsigned int target_table = pos->CurTable; unsigned int save_diff_x = ~0; unsigned int save_diff_y = ~0; /* 入力方向にもっとも近いテーブルを探す */ dbgprint( "Out of menu-range. find a next table..." ); switch( dir ){ case MF_MENU_MOVE_UP: for( i = 0; i < menucnt; i++ ){ if( menu[pos->CurTable].y <= menu[i].y ) continue; if( mf_menu_nearest_table( abs( menu[pos->CurTable].y - menu[i].y ), abs( menu[pos->CurTable].x - menu[i].x ), &save_diff_y, &save_diff_x ) ){ target_table = i; } } if( target_table != pos->CurTable ){ return mf_menu_select_table_vertical( menu, target_table, pos, false ); } else{ break; } case MF_MENU_MOVE_RIGHT: for( i = 0; i < menucnt; i++ ){ if( menu[pos->CurTable].x >= menu[i].x ) continue; if( mf_menu_nearest_table( abs( menu[pos->CurTable].x - menu[i].x ), abs( menu[pos->CurTable].y - menu[i].y ), &save_diff_x, &save_diff_y ) ){ target_table = i; } } if( target_table != pos->CurTable ){ return mf_menu_select_table_horizontal( menu, target_table, pos, false ); } else{ break; } case MF_MENU_MOVE_DOWN: for( i = 0; i < menucnt; i++ ){ if( menu[pos->CurTable].y >= menu[i].y ) continue; if( mf_menu_nearest_table( abs( menu[pos->CurTable].y - menu[i].y ), abs( menu[pos->CurTable].x - menu[i].x ), &save_diff_y, &save_diff_x ) ){ target_table = i; } } if( target_table != pos->CurTable ){ return mf_menu_select_table_vertical( menu, target_table, pos, false ); } else{ break; } case MF_MENU_MOVE_LEFT: for( i = 0; i < menucnt; i++ ){ if( menu[pos->CurTable].x <= menu[i].x ) continue; if( mf_menu_nearest_table( abs( menu[pos->CurTable].x - menu[i].x ), abs( menu[pos->CurTable].y - menu[i].y ), &save_diff_x, &save_diff_y ) ){ target_table = i; } } if( target_table != pos->CurTable ){ return mf_menu_select_table_horizontal( menu, target_table, pos, false ); } else{ break; } } /* 見つからなければ、入力方向と逆方向のもっとも遠いテーブルを探す */ dbgprint( "Next table not found. position wrap." ); save_diff_x = ~0; save_diff_y = ~0; switch( dir ){ case MF_MENU_MOVE_UP: for( i = 0; i < menucnt; i++ ){ if( menu[pos->CurTable].y >= menu[i].y ) continue; if( mf_menu_farest_table( abs( menu[pos->CurTable].y - menu[i].y ), abs( menu[pos->CurTable].x - menu[i].x ), &save_diff_y, &save_diff_x ) ){ target_table = i; } } return mf_menu_select_table_vertical( menu, target_table, pos, true ); case MF_MENU_MOVE_RIGHT: for( i = 0; i < menucnt; i++ ){ if( menu[pos->CurTable].x <= menu[i].x ) continue; if( mf_menu_farest_table( abs( menu[pos->CurTable].x - menu[i].x ), abs( menu[pos->CurTable].y - menu[i].y ), &save_diff_x, &save_diff_y ) ){ target_table = i; } } return mf_menu_select_table_horizontal( menu, target_table, pos, true ); case MF_MENU_MOVE_DOWN: for( i = 0; i < menucnt; i++ ){ if( menu[pos->CurTable].y <= menu[i].y ) continue; if( mf_menu_farest_table( abs( menu[pos->CurTable].y - menu[i].y ), abs( menu[pos->CurTable].x - menu[i].x ), &save_diff_y, &save_diff_x ) ){ target_table = i; } } return mf_menu_select_table_vertical( menu, target_table, pos, true ); case MF_MENU_MOVE_LEFT: for( i = 0; i < menucnt; i++ ){ if( menu[pos->CurTable].x >= menu[i].x ) continue; if( mf_menu_farest_table( abs( menu[pos->CurTable].x - menu[i].x ), abs( menu[pos->CurTable].y - menu[i].y ), &save_diff_x, &save_diff_y ) ){ target_table = i; } } return mf_menu_select_table_horizontal( menu, target_table, pos, true ); } return false; } static bool mf_menu_nearest_table( unsigned int pri, unsigned int sec, unsigned int *save_pri, unsigned int *save_sec ) { /* *save_pri, *save_sec は、全ビット1(~0)の場合のみ、特別に未定義値として扱う。 従って、*save_pri, *save_sec に渡す変数はかならず ~0 で初期化した状態で渡す。 */ if( *save_pri == ~0 || pri < *save_pri ){ *save_pri = pri; return true; } else if( *save_sec == sec ){ if( ! *save_sec || sec < *save_sec ){ *save_sec = sec; return true; } } return false; } static bool mf_menu_farest_table( unsigned int pri, unsigned int sec, unsigned int *save_pri, unsigned int *save_sec ) { /* *save_pri, *save_sec は、全ビット1(~0)の場合のみ、特別に未定義値として扱う。 従って、*save_pri, *save_sec に渡す変数はかならず ~0 で初期化した状態で渡す。 */ if( *save_pri == ~0 || pri > *save_pri ){ *save_pri = pri; return true; } else if( *save_sec == sec ){ if( ! *save_sec || sec > *save_sec ){ *save_sec = sec; return true; } } return false; } static bool mf_menu_select_table_horizontal( MfMenuTable *menu, unsigned int targ_tid, struct MfMenuPosition *pos, bool reverse ) { if( pos->CurTable == targ_tid ){ dbgprintf( "Selected same table id: Col %d, %d", pos->CurCol, menu[targ_tid].cols ); pos->CurCol = pos->CurCol ? 0 : menu[targ_tid].cols - 1; } else{ unsigned int i, targ_row = 0, targ_col = 0; unsigned int current_y = menu[pos->CurTable].y + pbOffsetLine( pos->CurRow ); unsigned int diff_y, last_diff_y = ~0; for( i = 0; i < menu[targ_tid].rows; i++ ){ diff_y = abs( current_y - ( menu[targ_tid].y + pbOffsetLine( i ) ) ); if( last_diff_y == ~0 || last_diff_y > diff_y ){ last_diff_y = diff_y; targ_row = i; } } if( menu[pos->CurTable].x > menu[targ_tid].x ){ targ_col = reverse ? 0 : menu[targ_tid].cols - 1; } else{ targ_col = reverse ? menu[targ_tid].cols - 1 : 0; } pos->CurTable = targ_tid;; pos->CurRow = targ_row; pos->CurCol = targ_col; } return true; } static bool mf_menu_select_table_vertical( MfMenuTable *menu, unsigned int targ_tid, struct MfMenuPosition *pos, bool reverse ) { if( pos->CurTable == targ_tid ){ dbgprintf( "Selected same table id: Row %d, %d", pos->CurRow, menu[targ_tid].rows ); pos->CurRow = pos->CurRow ? 0 : menu[targ_tid].rows - 1; } else{ unsigned int i, targ_row = 0, targ_col = 0; unsigned int current_x = menu[pos->CurTable].x; unsigned int comp_x, diff_x, last_diff_x = ~0; if( menu[pos->CurTable].colsWidth ){ for( i = 0; i < pos->CurCol; i++ ){ current_x += menu[pos->CurTable].colsWidth[i]; } } comp_x = menu[targ_tid].x; for( i = 0; i < menu[targ_tid].cols; i++ ){ diff_x = abs( current_x - comp_x ); if( last_diff_x == ~0 || last_diff_x > diff_x ){ last_diff_x = diff_x; targ_col = i; } if( menu[targ_tid].colsWidth ) comp_x += menu[targ_tid].colsWidth[i]; } if( menu[pos->CurTable].y > menu[targ_tid].y ){ targ_row = reverse ? 0 : menu[targ_tid].rows - 1; } else{ targ_row = reverse ? menu[targ_tid].rows - 1 : 0; } pos->CurTable = targ_tid; pos->CurRow = targ_row; pos->CurCol = targ_col; } return true; } static unsigned int mf_label_width( char *str ) { unsigned int max_width = 0; unsigned int cur_width; char *lnstart, *lnend; if( ! str ) return 0; lnstart = str; while( ( lnend = strchr( str, '\n' ) ) ){ cur_width = lnend - lnstart; if( cur_width > max_width ) max_width = cur_width; lnstart = lnend++; } return pbOffsetChar( max_width ? max_width : strlen( str ) ); }
2.328125
2
2024-11-18T21:09:59.448366+00:00
2021-04-13T08:59:08
f82596aac90fd64d0e6210e8708d1ae3dfb6d6a1
{ "blob_id": "f82596aac90fd64d0e6210e8708d1ae3dfb6d6a1", "branch_name": "refs/heads/master", "committer_date": "2021-04-13T08:59:08", "content_id": "bd4575ffe1afa0bf35563df18d63ff0481f77692", "detected_licenses": [ "MIT" ], "directory_id": "15a7889ae1bb5948b4f6e0626510679fd3a71fa0", "extension": "c", "filename": "tree234_test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 337798205, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 800, "license": "MIT", "license_type": "permissive", "path": "/4_lab/src/tree234/tree234_test.c", "provenance": "stackv2-0065.json.gz:24143", "repo_name": "ne-bknn/c_labs", "revision_date": "2021-04-13T08:59:08", "revision_id": "28e45e08526aaa0a8174e003681bae9d3b86b69f", "snapshot_id": "baa4f15eaa72644a6aa475ac1c5b55695d7bd515", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/ne-bknn/c_labs/28e45e08526aaa0a8174e003681bae9d3b86b69f/4_lab/src/tree234/tree234_test.c", "visit_date": "2023-04-06T13:03:15.185436" }
stackv2
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include "tree234.h" #include "../tuilib.h" int get_rnd_int(int lower_than) { if (lower_than == 0) { return 0; } return rand() % lower_than; } int main() { time_t t; time(&t); printf("Time: %lu\n", t); //srand((unsigned)t); srand(228); struct BTree* btree = btree_create(); for (size_t i = 0; i < 50; ++i) { char* data = malloc(10); strcpy(data, "qwerqwera"); int index = get_rnd_int(100); btree_insert(btree->root, btree, index, data); btree_save(btree, i); printf("Inserted %d\n", index); } for (size_t i = 0; i < 100; ++i) { struct Entry* entry = btree_search(btree, i); if (NULL != entry) { btree_entry_print(entry); } else { printf("%lu not found\n", i); } } return 0; }
2.625
3
2024-11-18T21:10:02.634226+00:00
2019-12-11T08:16:03
7086061c0a818f468e4e82fcfdd3b5d21068e8e4
{ "blob_id": "7086061c0a818f468e4e82fcfdd3b5d21068e8e4", "branch_name": "refs/heads/master", "committer_date": "2019-12-11T08:16:03", "content_id": "e8d1fd44a78e7885bda7825f4969816011576ca9", "detected_licenses": [ "MIT" ], "directory_id": "2b61f326ad9ba01601ed6658d33ed0d576255244", "extension": "c", "filename": "binarytree.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 198652640, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5873, "license": "MIT", "license_type": "permissive", "path": "/binarytree.c", "provenance": "stackv2-0065.json.gz:24400", "repo_name": "samyakgaur/DataStructures", "revision_date": "2019-12-11T08:16:03", "revision_id": "bda9b0ddcbe51454b6a8b6ee05485248391b383f", "snapshot_id": "614bccdfb471f106b5a5aa78a16b42c0c4076655", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/samyakgaur/DataStructures/bda9b0ddcbe51454b6a8b6ee05485248391b383f/binarytree.c", "visit_date": "2020-06-23T14:41:59.522118" }
stackv2
/* Samyak Gaur(8604) Batch B A program to implement binary tree */ #include<stdio.h> #include<stdlib.h> #define max 25 struct node { int info; struct node *left , *right; };//End of structure struct node *root = NULL; struct node *getnode(){ struct node *p; p=(struct node *)malloc(sizeof(struct node)); return p; }//End of getnode function void insert(int x){ struct node *newnode,*t,*parent=NULL; newnode=getnode(); newnode->info= x; newnode->right= NULL; newnode->left= NULL; if(root == NULL) root=newnode; else{ parent=root; t=root; while(t!=NULL){ if(newnode->info < t->info){ parent=t; t=t->left; }//if condition to insert to the left else if(newnode->info > t->info){ parent=t; t=t->right; }//if condition to insert to the right else printf("node exists"); }//End of while loop if(newnode->info < parent->info) parent->left=newnode; else parent->right=newnode; }//End of else case }//End of insert_first function void inorder(struct node *t){ if(t!=NULL){ inorder(t->left); printf("%d ",t->info); inorder(t->right); }//End of if condition }//End of inorder function void preorder(struct node *t){ if(t!=NULL){ printf("%d ",t->info); preorder(t->left); preorder(t->right); }//End of if condition }//End of preorder function void postorder(struct node *t){ if(t!=NULL){ postorder(t->left); postorder(t->right); printf("%d ",t->info); }//End of if condition }//End of postorder function void delete(struct node *p ,int val){ //p has the value of root passed by the calling function int flag=0; struct node *t,*parent,*r; t=p; parent=NULL; while(t!=NULL){ if(val < t->info){ parent=t; t=t->left; }//end of if case going to the left else if(val > t->info){ parent=t; t=t->right; }//end of if case going to the right else{ flag=1; break; }//End of else case }//end of while loop if(flag==1){ if(t->left==NULL && t->right==NULL){ if(parent->left==t) parent->left=NULL; else if (parent->right==t) parent->right=NULL; free(t); }//End of leaf node condition else if(t->left!=NULL && t->right==NULL){ if(parent->left==t) parent->left=t->left; else parent->right=t->left; }//end if theres a element in left else if(t->left==NULL && t->right!=NULL){ if(parent->left==t) parent->left=t->right; else parent->right=t->right; }//End if the node has a right element else{ r=t->left; while(r->right!=NULL){ r=r->right; t->info=r->info; delete(t->left,r->info); }//End of while condition }//end of else condition if it has both children }//End of if flag condition }//End of delete function int main(){ struct node *p,*previous,*ptr; int choice,x,val; p=(struct node *)malloc(sizeof(struct node)); while(1){ printf("\n Enter your choice: \n 1.Insert \n 2.Inorder display \n 3.Preorder display \n 4.Postorder display \n 5.Delete \n 6.Exit \n"); scanf("%d",&choice); switch(choice){ case 1: printf("Enter the value: "); scanf("%d",&x); insert(x); break; case 2: inorder(root); break; case 3: preorder(root); break; case 4: postorder(root); break; case 5: printf("Enter the value to be deleted: "); scanf("%d",&val); delete(root,val); break; case 6: exit(0); default: printf("Please enter a valid choice:"); break; }//End of switch case }//End of while loop return 0; }//End of main function /* Output of the following code is: (base) Samyaks-MacBook-Air:DataStructures samyakgaur$ gcc binarytree.c (base) Samyaks-MacBook-Air:DataStructures samyakgaur$ ./a.out Enter your choice: 1.Insert 2.Inorder display 3.Preorder display 4.Postorder display 5.Delete 6.Exit 1 Enter the value: 25 Enter your choice: 1.Insert 2.Inorder display 3.Preorder display 4.Postorder display 5.Delete 6.Exit 1 Enter the value: 15 Enter your choice: 1.Insert 2.Inorder display 3.Preorder display 4.Postorder display 5.Delete 6.Exit 1 Enter the value: 12 Enter your choice: 1.Insert 2.Inorder display 3.Preorder display 4.Postorder display 5.Delete 6.Exit 1 Enter the value: 18 Enter your choice: 1.Insert 2.Inorder display 3.Preorder display 4.Postorder display 5.Delete 6.Exit 1 Enter the value: 16 Enter your choice: 1.Insert 2.Inorder display 3.Preorder display 4.Postorder display 5.Delete 6.Exit 1 Enter the value: 38 Enter your choice: 1.Insert 2.Inorder display 3.Preorder display 4.Postorder display 5.Delete 6.Exit 1 Enter the value: 32 Enter your choice: 1.Insert 2.Inorder display 3.Preorder display 4.Postorder display 5.Delete 6.Exit 1 Enter the value: 36 Enter your choice: 1.Insert 2.Inorder display 3.Preorder display 4.Postorder display 5.Delete 6.Exit 1 Enter the value: 45 Enter your choice: 1.Insert 2.Inorder display 3.Preorder display 4.Postorder display 5.Delete 6.Exit 1 Enter the value: 48 Enter your choice: 1.Insert 2.Inorder display 3.Preorder display 4.Postorder display 5.Delete 6.Exit 2 12 15 16 18 25 32 36 38 45 48 */
3.921875
4