blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
268
content_id
stringlengths
40
40
detected_licenses
listlengths
0
58
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
816 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.31k
677M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
151 values
src_encoding
stringclasses
33 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.3M
extension
stringclasses
119 values
content
stringlengths
3
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
228
0bee629c0f2fb373bf8156c355d29fb1899f1a9d
82bcfb954c148bf96ced0e2bd93b3b5c9c7f78ee
/tranceiver/main/main.c
d6db71811abb7abdf5845724bc1df8b89dd5e315
[]
no_license
sdfgeoff/esp32-unreliable-connection
43b51a585a933c88c8064a8d7412f303a7d32650
9ba3ba5bb30a26155976e479794721cc9fb23ffc
refs/heads/master
2020-03-23T03:32:20.053250
2018-07-28T19:39:08
2018-07-28T19:39:08
141,035,653
1
1
null
null
null
null
UTF-8
C
false
false
2,127
c
#include <stdio.h> #include <string.h> #include "nvs_flash.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_wifi.h" //~ #include "esp_wifi_internal.h" #include "esp_event_loop.h" //~ #include "driver/gpio.h" //~ #include "sdkconfig.h" //~ #include "lwip/err.h" #include "tranceiver.h" typedef struct { float x; float y; } control_packet; #define CONTROL_PACKET_ID 0x1 uint8_t tranceiver_id[6] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 }; esp_err_t event_handler(void *ctx, system_event_t *event) { return ESP_OK; } void send_task(void *pvParameter){ printf("Arrgh\n"); control_packet packet; packet.x = 0.0; packet.y = 0.0; tranceiver_init(); tranceiver_set_id(tranceiver_id); tranceiver_set_channel(1); tranceiver_set_power(44); // ~10mw while(1){ vTaskDelay(100 / portTICK_PERIOD_MS); packet.x += 0.1; tranceiver_send_packet( CONTROL_PACKET_ID, (uint8_t*)&packet, sizeof(packet) ); printf("Send: x=%f, y=%f\n", packet.x, packet.y); } } void receive_task(void *pvParameter){ QueueHandle_t rx_packet_queue = xQueueCreate(2, TRANCEIVER_MIN_QUEUE_SIZE + sizeof(control_packet)); tranceiver_set_queue(CONTROL_PACKET_ID, rx_packet_queue); uint8_t latest_packet_raw[TRANCEIVER_MIN_QUEUE_SIZE + sizeof(control_packet)] = {0}; tranceiver_packet_stats* latest_packet = (tranceiver_packet_stats*)&latest_packet_raw; control_packet* parsed_packet = (control_packet*)&latest_packet->data; while(1){ xQueueReceive(rx_packet_queue, &latest_packet_raw, portMAX_DELAY); printf("RSSI: %d\nNoiseFloor: %d\nSize %d\n", latest_packet->rssi, latest_packet->noise_floor, latest_packet->data_length ); if (sizeof(control_packet) == latest_packet->data_length){ printf("Got: x=%f, y=%f\n\n", parsed_packet->x, parsed_packet->y); } } } void app_main() { nvs_flash_init(); tcpip_adapter_init(); ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) ); xTaskCreate(&send_task, "send_test", configMINIMAL_STACK_SIZE+1000, NULL, 5, NULL); xTaskCreate(&receive_task, "receive_test", configMINIMAL_STACK_SIZE+1000, NULL, 5, NULL); }
[ "geoffrey.irons@simedis.com" ]
geoffrey.irons@simedis.com
152d85563098f45bfff74ff0face2ea39e9cc63f
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/SoftwareFeatureSAPImplementation/UNIX_SoftwareFeatureSAPImplementationProvider.h
60f158f43b1aca901f899e76bbd31cf8ce95144b
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C
false
false
2,354
h
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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 __UNIX_SoftwareFeatureSAPImplementation_PROVIDER_H #define __UNIX_SoftwareFeatureSAPImplementation_PROVIDER_H #include "UNIX_SoftwareFeatureSAPImplementation.h" #define UNIX_PROVIDER UNIX_SoftwareFeatureSAPImplementationProvider #define CLASS_IMPLEMENTATION UNIX_SoftwareFeatureSAPImplementation #define CLASS_IMPLEMENTATION_NAME "UNIX_SoftwareFeatureSAPImplementation" #define BASE_CLASS_NAME "CIM_SoftwareFeatureSAPImplementation" #define NUMKEYS_CLASS_IMPLEMENTATION 2 #include "UNIXProviderBase.h" #endif #undef UNIX_PROVIDER #undef CLASS_IMPLEMENTATION #undef CLASS_IMPLEMENTATION_NAME #undef BASE_CLASS_NAME #undef NUMKEYS_CLASS_IMPLEMENTATION
[ "brunolauze@msn.com" ]
brunolauze@msn.com
7711d7ab20e15d0e99e473d05f033aff2bfe3023
9d6a7aa17f8a6f4147062549f025e58df2d997c8
/s203372_lab08/es01/main.c
98a7b76d411706f760f0aabc6c94d05d39567fe6
[]
no_license
LucaMazzucco/C-Algorithms
ce12753d3310836a2f0ca17be3a2c90349ca205b
641becd8e903c0f8199363b12046272cd5bd8812
refs/heads/master
2020-08-03T17:56:53.752676
2019-09-30T10:35:10
2019-09-30T10:35:10
211,835,530
0
0
null
null
null
null
IBM852
C
false
false
2,735
c
#include <stdio.h> #include <stdlib.h> #include "table.h" int main(int argc, char*argv[]) { TABLE tab = NULL; FILE *f; int scelta; if((f = fopen(argv[1], "r")) == NULL) return -1; while (scelta!=0){ printf("Seleziona una scelta:\n\n"); printf("1 - Inizializza tabella di simboli;\n"); printf("2 - Carica dati da file;\n"); printf("3 - Ricerca dato tramite chiave di ricerca;\n"); printf("4 - Stampa tabella di simboli;\n"); printf("5 - Ordina tabella di simboli;\n"); printf("6 - Inserisci un nuovo item;\n"); printf("7 - Elimina item in base alla chiave di ricerca;\n"); printf("0 - Termina programma.\n"); printf("Scelta: "); scanf("%d", &scelta); switch (scelta){ case 1: if (tab == NULL){ tab = table_init(f, tab); printf("\nTabella inizializzata con successo\n"); } else printf("\nTabella giÓ inizializzata\n"); break; case 2: if (tab != NULL){ table_upload(f, tab); printf("\nTabella caricata con successo\n"); } else printf("\nTabella non ancora inizializzata\n"); break; case 3: if (tab != NULL) table_search(tab); else printf("\nTabella non ancora inizializzata\n"); break; case 4: if (tab != NULL) table_print(tab); else printf("\nTabella non ancora inizializzata\n"); break; case 5: if (tab != NULL) table_quicksort(tab); else printf("\nTabella non ancora inizializzata\n"); break; case 6: if (tab != NULL) tab = table_push(tab); else printf("\nTabella non ancora inizializzata\n"); break; case 7: if (tab != NULL) table_pop(); else printf("\nTabella non ancora inizializzata\n"); break; case 0: if (tab != NULL) table_free(tab); else printf("\nTabella non ancora inizializzata\n"); break; default: printf("\nValore inserito non corretto\n"); break; } } return 0; }
[ "s241968@studenti.polito.it" ]
s241968@studenti.polito.it
bc87f339b8d083b28dc6c6657ddb5f36307d4b46
b36a813be47305affb1fc7c936d77c125a18197c
/stringlib.c
8b9c63f9aa495d217c2a70e590d3cfb373eba6e1
[]
no_license
mortazaderakhshani/mdCode-PosVelForce
46ef390c0a67d99a289340b3a9cb3cacef4a8d82
b7d2092d1e707d91423bb9b7a5544bf33839cd45
refs/heads/master
2020-05-02T12:16:59.972577
2015-05-14T13:41:52
2015-05-14T13:41:52
35,226,323
0
0
null
null
null
null
UTF-8
C
false
false
2,784
c
#include "stringlib.h" /* String Related Subroutines */ char *trim ( char *s ) { int i = 0; int j = strlen ( s ) - 1; int k = 0; while ( isspace ( s[i] ) && s[i] != '\0' ) i++; while ( isspace ( s[j] ) && j >= 0 ) j--; while ( i <= j ) s[k++] = s[i++]; s[k] = '\0'; return s; } char *string_firstword ( char *s ) { int i = 0; int j = strlen ( s ) - 1; int k = 0; while ( isspace ( s[i] ) && s[i] != '\0' ) i++; j=i; while ( s[j] != '\0') { if (isspace(s[j])) { j--; break; } j++; } while ( i <= j ) s[k++] = s[i++]; s[k] = '\0'; return s; } char *string_secondword ( char *s ) { int i = 0; int j = strlen ( s ) - 1; int k = 0; // skip beginning white space if any while ( isspace ( s[i] ) && s[i] != '\0' ) i++; // skip first word while ( s[i] != '\0') { if (isspace(s[i])) break; i++; } // skip white space while ( isspace ( s[i] ) && s[i] != '\0' ) i++; // find end of second word j=i; while ( s[j] != '\0') { if (isspace(s[j])) { j--; break; } j++; } // copy second word to new string while ( i <= j ) s[k++] = s[i++]; s[k] = '\0'; return s; } char *string_thirdword ( char *s ) { int i = 0; int j = strlen ( s ) - 1; int k = 0; // skip beginning white space if any while ( isspace ( s[i] ) && s[i] != '\0' ) i++; // skip first word while ( s[i] != '\0') { if (isspace(s[i])) break; i++; } // skip white space while ( isspace ( s[i] ) && s[i] != '\0' ) i++; // skip the second word while ( s[i] != '\0') { if (isspace(s[i])) { break; } i++; } // skip white space while ( isspace ( s[i] ) && s[i] != '\0' ) i++; // find the end of the third word j=i; while ( s[j] != '\0') { if (isspace(s[j])) { j--; break; } j++; } // copy third word to new string while ( i <= j ) s[k++] = s[i++]; s[k] = '\0'; return s; } char *string_word ( char *s, int wordNumber) { int i = 0; int j = strlen ( s ) - 1; int k = 0; int word; // skip white space if any while ( isspace ( s[i] ) && s[i] != '\0' ) i++; for (word=0;word<(wordNumber-1);word++) { // skip word while ( s[i] != '\0') { if (isspace(s[i])) break; i++; } // skip white space if any while ( isspace ( s[i] ) && s[i] != '\0' ) i++; } // find end target word j=i; while ( s[j] != '\0') { if (isspace(s[j])) { j--; break; } j++; } // copy second word to new string while ( i <= j ) s[k++] = s[i++]; s[k] = '\0'; return s; }
[ "mortaza.derakhshanimolayousefi@colostate.edu" ]
mortaza.derakhshanimolayousefi@colostate.edu
d99d0452cce4ecedc790dea3a2be6007f534b390
2e1f7eeac06527d83784034592dbe15caaa9e5eb
/rx/Core/Inc/stm32f1xx_it.h
49e133046c9ce0673cf95783b0ecc8924792e437
[]
no_license
yxnan/tplinkcup-zjuieee7
52a654e9a8e083f440462ef02cb44d2b47e06b65
85e18d565f9d0334cdc74bc2416b5fd22bb506de
refs/heads/master
2023-07-03T04:34:43.716816
2021-08-08T06:29:33
2021-08-08T06:29:33
null
0
0
null
null
null
null
UTF-8
C
false
false
2,175
h
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file stm32f1xx_it.h * @brief This file contains the headers of the interrupt handlers. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F1xx_IT_H #define __STM32F1xx_IT_H #ifdef __cplusplus extern "C" { #endif /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Exported types ------------------------------------------------------------*/ /* USER CODE BEGIN ET */ /* USER CODE END ET */ /* Exported constants --------------------------------------------------------*/ /* USER CODE BEGIN EC */ /* USER CODE END EC */ /* Exported macro ------------------------------------------------------------*/ /* USER CODE BEGIN EM */ /* USER CODE END EM */ /* Exported functions prototypes ---------------------------------------------*/ void NMI_Handler(void); void HardFault_Handler(void); void MemManage_Handler(void); void BusFault_Handler(void); void UsageFault_Handler(void); void SVC_Handler(void); void DebugMon_Handler(void); void PendSV_Handler(void); void SysTick_Handler(void); void USART3_IRQHandler(void); void DMA2_Channel3_IRQHandler(void); /* USER CODE BEGIN EFP */ /* USER CODE END EFP */ #ifdef __cplusplus } #endif #endif /* __STM32F1xx_IT_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
[ "yxnan@pm.me" ]
yxnan@pm.me
d32c1b5c95347b41cf0c0a0d48525bf8e4a01b99
81494e2d44733cf67c37a0b8478c166f08b9191a
/Source/SmoothZoom/Private/SmoothZoomPrivatePCH.h
e70f66aabf564fb239305016a253301d2c2c4a33
[ "MIT" ]
permissive
ycllz/SmoothZoom
995784c92216f6269c9adc92cd676b6ad8e47751
6b5d67c69b1c1322d971d9e1c395ed414d9d4e4b
refs/heads/master
2020-06-05T20:23:23.065059
2019-03-31T21:46:01
2019-03-31T21:46:01
null
0
0
null
null
null
null
UTF-8
C
false
false
295
h
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "SmoothZoom.h" #include "Engine.h" // You should place include statements to your module's private header files here. You only need to // add includes for headers that are used in most of your module's source files though.
[ "gaskinml@gmail.com" ]
gaskinml@gmail.com
dcddd81bc59efced5f1c9582eb2eaf2601bc87cd
8f7bfa5e2b457057e18cb232b60d3f75c612c28f
/mono-2.0/mono/utils/mono-publib.h
a805025de467f8252a0d03b47ddd371d5514fb00
[]
no_license
NicholasKangZH/SaltyToastMono
9f6f76969a563bc34098724db1988970b994c406
2c8e61a04535643a880b328b3d9b3ef3f95716c1
refs/heads/master
2020-08-02T10:48:05.182131
2019-09-28T06:44:20
2019-09-28T06:44:20
211,322,932
0
0
null
null
null
null
UTF-8
C
false
false
5,393
h
/** * \file */ #ifndef __MONO_PUBLIB_H__ #define __MONO_PUBLIB_H__ /* * Minimal general purpose header for use in public mono header files. * We can't include config.h, so we use compiler-specific preprocessor * directives where needed. */ #ifdef __cplusplus #define MONO_BEGIN_DECLS extern "C" { #define MONO_END_DECLS } #else #define MONO_BEGIN_DECLS /* nothing */ #define MONO_END_DECLS /* nothing */ #endif MONO_BEGIN_DECLS /* VS 2010 and later have stdint.h */ #if defined(_MSC_VER) #if _MSC_VER < 1600 typedef __int8 int8_t; typedef unsigned __int8 uint8_t; typedef __int16 int16_t; typedef unsigned __int16 uint16_t; typedef __int32 int32_t; typedef unsigned __int32 uint32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #else #include <stdint.h> #endif #define MONO_API_EXPORT __declspec(dllexport) #define MONO_API_IMPORT __declspec(dllimport) #else #include <stdint.h> #if defined (__clang__) || defined (__GNUC__) #define MONO_API_EXPORT __attribute__ ((__visibility__ ("default"))) #else #define MONO_API_EXPORT #endif #define MONO_API_IMPORT #endif /* end of compiler-specific stuff */ #include <stdlib.h> #ifdef __cplusplus #define MONO_EXTERN_C extern "C" #else #define MONO_EXTERN_C /* nothing */ #endif #if defined(MONO_DLL_EXPORT) #define MONO_API_NO_EXTERN_C MONO_API_EXPORT #elif defined(MONO_DLL_IMPORT) #define MONO_API_NO_EXTERN_C MONO_API_IMPORT #else #define MONO_API_NO_EXTERN_C /* nothing */ #endif #define MONO_API MONO_EXTERN_C MONO_API_NO_EXTERN_C // extern "C" extern int c; // warning: duplicate 'extern' declaration specifier [-Wduplicate-decl-specifier] // // Therefore, remove extern on functions as always meaningless/redundant, // and provide MONO_API_DATA for data, that always has one and only one extern. #ifdef __cplusplus #define MONO_API_DATA MONO_API #else #define MONO_API_DATA extern MONO_API #endif typedef int32_t mono_bool; typedef uint8_t mono_byte; typedef mono_byte MonoBoolean; #ifdef _WIN32 MONO_END_DECLS #include <wchar.h> typedef wchar_t mono_unichar2; MONO_BEGIN_DECLS #else typedef uint16_t mono_unichar2; #endif typedef uint32_t mono_unichar4; typedef void (*MonoFunc) (void* data, void* user_data); typedef void (*MonoHFunc) (void* key, void* value, void* user_data); MONO_API void mono_free (void *); #define MONO_ALLOCATOR_VTABLE_VERSION 1 typedef struct { int version; void *(*malloc) (size_t size); void *(*realloc) (void *mem, size_t count); void (*free) (void *mem); void *(*calloc) (size_t count, size_t size); } MonoAllocatorVTable; MONO_API mono_bool mono_set_allocator_vtable (MonoAllocatorVTable* vtable); #define MONO_CONST_RETURN const /* * When embedding, you have to define MONO_ZERO_LEN_ARRAY before including any * other Mono header file if you use a different compiler from the one used to * build Mono. */ #ifndef MONO_ZERO_LEN_ARRAY #ifdef __GNUC__ #define MONO_ZERO_LEN_ARRAY 0 #else #define MONO_ZERO_LEN_ARRAY 1 #endif #endif #if defined (MONO_INSIDE_RUNTIME) #if defined (__CENTRINEL__) /* Centrinel is an analyzer that warns about raw pointer to managed objects * inside Mono. */ #define MONO_RT_MANAGED_ATTR __CENTRINEL_MANAGED_ATTR #define MONO_RT_CENTRINEL_SUPPRESS __CENTRINEL_SUPPRESS_ATTR(1) #else #define MONO_RT_MANAGED_ATTR #define MONO_RT_CENTRINEL_SUPPRESS #endif #if defined (__clang__) || defined (__GNUC__) // attribute(deprecated(message)) was introduced in gcc 4.5. // attribute(deprecated)) was introduced in gcc 4.0. // Compare: https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Function-Attributes.html // https://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Function-Attributes.html // https://gcc.gnu.org/onlinedocs/gcc-4.5.0/gcc/Function-Attributes.html #if defined (__clang__) || (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) #define MONO_RT_EXTERNAL_ONLY \ __attribute__ ((__deprecated__ ("The mono runtime must not call this function."))) \ MONO_RT_CENTRINEL_SUPPRESS #elif __GNUC__ >= 4 #define MONO_RT_EXTERNAL_ONLY __attribute__ ((__deprecated__)) MONO_RT_CENTRINEL_SUPPRESS #else #define MONO_RT_EXTERNAL_ONLY MONO_RT_CENTRINEL_SUPPRESS #endif #if defined (__clang__) || (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2) // Pragmas for controlling diagnostics appear to be from gcc 4.2. // This is used in place of configure gcc -Werror=deprecated-declarations: // 1. To be portable across build systems. // 2. configure is very sensitive to compiler flags; they break autoconf's probes. // Though #2 can be mitigated by being late in configure. #pragma GCC diagnostic error "-Wdeprecated-declarations" #endif #else #define MONO_RT_EXTERNAL_ONLY MONO_RT_CENTRINEL_SUPPRESS #endif // clang or gcc #else #define MONO_RT_EXTERNAL_ONLY #define MONO_RT_MANAGED_ATTR #endif /* MONO_INSIDE_RUNTIME */ #if defined (__clang__) || defined (__GNUC__) #define _MONO_DEPRECATED __attribute__ ((__deprecated__)) #elif defined (_MSC_VER) #define _MONO_DEPRECATED __declspec (deprecated) #else #define _MONO_DEPRECATED #endif #define MONO_DEPRECATED MONO_API MONO_RT_EXTERNAL_ONLY _MONO_DEPRECATED MONO_END_DECLS #endif /* __MONO_PUBLIB_H__ */
[ "noreply@github.com" ]
NicholasKangZH.noreply@github.com
6ac441661cee349dff2d53f234cab2b22850c249
ca06b5e4cb6a6830f04176bce4ec6bb4ab44658b
/107.c
6f54623645d5a1c91cbba53e5e70517fb598b73c
[]
no_license
wobushiludahai/HWonlineTest
25db179c4842081fe17e20776aa9acdea97bc1b0
8b3535b57dbd320de4ade061df239f7742a02a48
refs/heads/master
2020-09-21T02:09:11.622287
2020-01-09T16:07:56
2020-01-09T16:07:56
224,649,369
0
0
null
null
null
null
UTF-8
C
false
false
608
c
/** * @description: 求解立方根 * @param {type} * @return: */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> double testnum; double i; int flag; int main(void) { while(scanf("%lf", &testnum) != EOF) { flag = 0; if(testnum < 0) { flag = 1; testnum = -testnum; } for(i = 0; i*i*i < testnum; i+=0.05); if(flag == 0) { printf("%0.1lf\n",i); } else { printf("%0.1lf\n",-i); } } return 0; }
[ "wobushiludahai@163.com" ]
wobushiludahai@163.com
30d721358613293e00b1fb6849a600d8a6dd6da2
a39d3440ec4d17c892058aef6d5db6bfcc8c95fc
/Bsp/timer.c
8888ee9dc3979d4bf94d3fac39ddfe2a2b62a4ca
[]
no_license
mhj258258/RM_QY50
f396ea16e40a5d980dcad9c39c415c279a37698d
5d0bda28e82bc73e811e72d71ea174c1875a47f6
refs/heads/master
2020-12-05T07:31:26.595168
2020-01-08T11:40:32
2020-01-08T11:40:32
232,047,905
0
0
null
null
null
null
WINDOWS-1252
C
false
false
2,024
c
#include "gd32f30x.h" #include "systick.h" #include "uart.h" #include <stdio.h> #include "led.h" #include "timer.h" void nvic_config(void); void timer_config(void); /** \brief user timer init \param[in] none \param[out] none \retval none */ void user_timer_init(void) { nvic_config(); timer_config(); } /** \brief configure the nested vectored interrupt controller \param[in] none \param[out] none \retval none */ void nvic_config(void) { nvic_irq_enable(TIMER0_UP_IRQn, 0, 1); } /** \brief configure the TIMER peripheral \param[in] none \param[out] none \retval none */ void timer_config(void) { /* TIMER0 configuration: generate PWM signals with different duty cycles: TIMER0CLK = SystemCoreClock / 120 = 1MHz */ timer_parameter_struct timer_initpara; rcu_periph_clock_enable(RCU_TIMER0); timer_deinit(TIMER0); /* TIMER0 configuration */ timer_initpara.prescaler = 479;//·ÖƵ 479 - 200ms ((1199+1)*50000)/ 120000000 = 500ms timer_initpara.alignedmode = TIMER_COUNTER_EDGE; timer_initpara.counterdirection = TIMER_COUNTER_UP; timer_initpara.period = 50000;//ÖÜÆÚ timer_initpara.clockdivision = TIMER_CKDIV_DIV1; timer_initpara.repetitioncounter = 0; timer_init(TIMER0,&timer_initpara); /* TIMER0 channel control update interrupt enable */ timer_interrupt_enable(TIMER0,TIMER_INT_UP); /* TIMER0 break interrupt disable */ timer_interrupt_disable(TIMER0,TIMER_INT_BRK); /* auto-reload preload enable */ timer_auto_reload_shadow_enable(TIMER0); timer_enable(TIMER0); } /** \brief interrupt deal \param[in] none \param[out] none \retval none */ void TIMER0_UP_IRQHandler(void) { if(timer_interrupt_flag_get (TIMER0, TIMER_INT_FLAG_UP)!= RESET) { } timer_interrupt_flag_clear (TIMER0, TIMER_INT_FLAG_UP); }
[ "412451509@qq.com" ]
412451509@qq.com
138843cc8b456e45002f71c310dd1eaad39f917f
71600e51fe97720a67f4979eb12739667362795d
/source/libs/HALlib/inc/gpio.h
9a6153abdcf8fa5f99be3895833fc96edc807d64
[ "MIT" ]
permissive
danalsan/uxbot-es
9a02f69790f1ff8aa67f1e2450609ae72e34edfa
11495601ebcea7f811871ce69c09aa4f79cdf676
refs/heads/master
2021-01-16T21:50:01.289311
2016-07-21T14:37:27
2016-07-21T14:37:27
63,876,731
0
0
null
null
null
null
UTF-8
C
false
false
2,627
h
/***************************************************************************** * gpio.h: Header file for NXP LPC13xx Family Microprocessors * * Copyright(C) 2008, NXP Semiconductor * All rights reserved. * * History * 2008.09.01 ver 1.00 Preliminary version, first Release * 2009.12.09 ver 1.05 Mod to use mask registers for GPIO writes + inlining (.h) * ******************************************************************************/ #ifndef __GPIO_H #define __GPIO_H #define PORT0 0 #define PORT1 1 #define PORT2 2 #define PORT3 3 void GPIO_IRQHandler(void); void GPIOInit( void ); void GPIOSetInterrupt( uint32_t portNum, uint32_t bitPosi, uint32_t sense, uint32_t single, uint32_t event ); void GPIOIntEnable( uint32_t portNum, uint32_t bitPosi ); void GPIOIntDisable( uint32_t portNum, uint32_t bitPosi ); uint32_t GPIOIntStatus( uint32_t portNum, uint32_t bitPosi ); void GPIOIntClear( uint32_t portNum, uint32_t bitPosi ); static LPC_GPIO_TypeDef (* const LPC_GPIO[4]) = { LPC_GPIO0, LPC_GPIO1, LPC_GPIO2, LPC_GPIO3 }; static __INLINE uint32_t GPIOReadValue( uint32_t portNum, uint32_t bitPosi) { uint32_t val; val = LPC_GPIO[portNum]->MASKED_ACCESS[(1<<bitPosi)]; return (val >> bitPosi); } /***************************************************************************** ** Function name: GPIOSetValue ** ** Descriptions: Set/clear a bitvalue in a specific bit position ** in GPIO portX(X is the port number.) ** ** parameters: port num, bit position, bit value ** Returned value: None ** *****************************************************************************/ static __INLINE void GPIOSetValue( uint32_t portNum, uint32_t bitPosi, uint32_t bitVal ) { LPC_GPIO[portNum]->MASKED_ACCESS[(1<<bitPosi)] = (bitVal<<bitPosi); } /***************************************************************************** ** Function name: GPIOSetDir ** ** Descriptions: Set the direction in GPIO port ** ** parameters: port num, bit position, direction (1 out, 0 input) ** Returned value: None ** *****************************************************************************/ static __INLINE void GPIOSetDir( uint32_t portNum, uint32_t bitPosi, uint32_t dir ) { if(dir) LPC_GPIO[portNum]->DIR |= 1<<bitPosi; else LPC_GPIO[portNum]->DIR &= ~(1<<bitPosi); } #endif /* end __GPIO_H */ /***************************************************************************** ** End Of File ******************************************************************************/
[ "dani@localhost.localdomain" ]
dani@localhost.localdomain
b65a94295e543ba11f503191964bfd750571afd8
271aadc580d125a05e02f69ed944dfc370fc5d5e
/source/ti/devices/cc13x2_cc26x2/driverlib/sw_ecrypt-machine.h
4d2a2e559b770768e219e1070b8b4daab71ba467
[ "BSD-3-Clause" ]
permissive
contiki-ng/coresdk_cc13xx_cc26xx
452f826f6c4238930b03f4211ea750760fa66f57
eb87aebdd6735a77ebca55a97e06a6cf17864fc5
refs/heads/master
2023-08-16T23:09:32.195988
2023-07-12T12:41:20
2023-07-12T12:41:20
148,461,951
8
10
BSD-3-Clause
2023-09-08T14:51:14
2018-09-12T10:19:34
C
UTF-8
C
false
false
1,431
h
/****************************************************************************** * Filename: sw_ecrypt-machine.h * Revised: 2016-10-05 12:42:03 +0200 (Wed, 05 Oct 2016) * Revision: 47308 ******************************************************************************/ /* ecrypt-machine.h */ /* * This file is included by 'ecrypt-portable.h'. It allows to override * the default macros for specific platforms. Please carefully check * the machine code generated by your compiler (with optimisations * turned on) before deciding to edit this file. */ /* ------------------------------------------------------------------------- */ #if (defined(ECRYPT_DEFAULT_ROT) && !defined(ECRYPT_MACHINE_ROT)) #define ECRYPT_MACHINE_ROT #if (defined(WIN32) && defined(_MSC_VER)) #undef ROTL32 #undef ROTR32 #undef ROTL64 #undef ROTR64 #include <stdlib.h> #define ROTL32(v, n) _lrotl(v, n) #define ROTR32(v, n) _lrotr(v, n) #define ROTL64(v, n) _rotl64(v, n) #define ROTR64(v, n) _rotr64(v, n) #endif #endif /* ------------------------------------------------------------------------- */ #if (defined(ECRYPT_DEFAULT_SWAP) && !defined(ECRYPT_MACHINE_SWAP)) #define ECRYPT_MACHINE_SWAP /* * If you want to overwrite the default swap macros, put it here. And so on. */ #endif /* ------------------------------------------------------------------------- */
[ "a0132644@ti.com" ]
a0132644@ti.com
28d2e920b5d69ac35c282a5aabfb4d377d45889d
b45b27637c8e28e82e95111d3dbf455aa772d7b3
/bin/Reapr_1.0.18/third_party/cmake-2.8.7/Utilities/cmlibarchive/libarchive/test/test_compat_zip.c
24529303690664511b136683f7da1478063147ee
[ "LicenseRef-scancode-public-domain", "BSD-3-Clause", "LicenseRef-scancode-bsd-unchanged", "GPL-3.0-only" ]
permissive
Fu-Yilei/VALET
caa5e1cad5188cbb94418ad843ea32791e50974b
8741d984056d499af2fd3585467067d1729c73c4
refs/heads/master
2020-08-09T12:17:34.989915
2019-10-10T05:10:12
2019-10-10T05:10:12
214,085,217
1
0
MIT
2019-10-10T04:18:34
2019-10-10T04:18:34
null
UTF-8
C
false
false
3,082
c
/*- * Copyright (c) 2003-2007 Tim Kientzle * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.h" __FBSDID("$FreeBSD: src/lib/libarchive/test/test_compat_zip.c,v 1.3 2008/09/01 05:38:33 kientzle Exp $"); /* Copy this function for each test file and adjust it accordingly. */ static void test_compat_zip_1(void) { char name[] = "test_compat_zip_1.zip"; struct archive_entry *ae; struct archive *a; int r; assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_compression_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); extract_reference_file(name); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, name, 10240)); /* Read first entry. */ assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("META-INF/MANIFEST.MF", archive_entry_pathname(ae)); /* Read second entry. */ r = archive_read_next_header(a, &ae); if (r != ARCHIVE_OK) { if (strcmp(archive_error_string(a), "libarchive compiled without deflate support (no libz)") == 0) { skipping("Skipping ZIP compression check: %s", archive_error_string(a)); goto finish; } } assertEqualIntA(a, ARCHIVE_OK, r); assertEqualString("tmp.class", archive_entry_pathname(ae)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualInt(archive_compression(a), ARCHIVE_COMPRESSION_NONE); assertEqualInt(archive_format(a), ARCHIVE_FORMAT_ZIP); assertEqualInt(ARCHIVE_OK, archive_read_close(a)); finish: #if ARCHIVE_VERSION_NUMBER < 2000000 archive_read_finish(a); #else assertEqualInt(ARCHIVE_OK, archive_read_finish(a)); #endif } DEFINE_TEST(test_compat_zip) { test_compat_zip_1(); }
[ "yf20@gho.cs.rice.edu" ]
yf20@gho.cs.rice.edu
02498346e60d399086cc8f819a37d1fd28f69022
7fd5311d8039fbf9b4d0d270230147eacdc33dc0
/C51/INC/Infineon/XC835.H
9b76c6d4a96abb904e0ed0feb2c0ba1de80d0d5a
[ "MIT", "HPND", "Apache-2.0" ]
permissive
AllRoundeer/Keil
6da43b81ed358d74e5157d3bcbd0a8ee0883db9b
43cad8de348ff206c02395fca86bdb08c9725142
refs/heads/main
2023-05-10T08:22:21.768865
2021-06-12T15:17:48
2021-06-12T15:17:48
376,322,290
0
0
null
null
null
null
UTF-8
C
false
false
30,449
h
//**************************************************************************** // @Module Project Settings // @Filename XC835.H // @Project XC835.dav //---------------------------------------------------------------------------- // @Controller Infineon XC835MT-2F // // @Compiler Keil // // @Codegenerator 0.1 // // @Description This is the include header file for all other modules. // //---------------------------------------------------------------------------- // @Date 26.05.2010 11:22:13 // //**************************************************************************** #ifndef _XC835_H_ #define _XC835_H_ //**************************************************************************** // @Macros //**************************************************************************** // Please ensure that SCU_PAGE is switched to Page 1 before using these macros #define MAIN_vUnlockProtecReg() PASSWD = 0x9B #define MAIN_vlockProtecReg() PASSWD = 0xAB //**************************************************************************** // @Defines //**************************************************************************** #define bool bit #define ulong unsigned long #define uword unsigned int #define ubyte unsigned char // ------------------------------------------------------------------------- // Declaration of SFRs // ------------------------------------------------------------------------- // Notes: You can avoid the problem that your compiler does not yet support // the latest derivatives if you use the SFR definitions generated // by DAvE instead of those that come along with your compiler (in // the "Register File"). // PORT SFRs are defined in file 'IO.H'. #define SBIT(name, addr, bit) sbit name = (addr^bit) #define SFR(name, addr) sfr name = addr #define SFR16(name, addr) sfr16 name = addr // defines for sbit definitions #define BIT0 0 #define BIT1 1 #define BIT2 2 #define BIT3 3 #define BIT4 4 #define BIT5 5 #define BIT6 6 #define BIT7 7 // SFR byte definitions SFR(ACC , 0xE0); SFR(ADC_ALR0 , 0xCF); SFR(ADC_CHCTR0, 0xCA); SFR(ADC_CHCTR1, 0xCB); SFR(ADC_CHCTR2, 0xCC); SFR(ADC_CHCTR3, 0xCD); SFR(ADC_CHCTR4, 0xCE); SFR(ADC_CHCTR5, 0xCF); SFR(ADC_CHCTR6, 0xD2); SFR(ADC_CHCTR7, 0xD3); SFR(ADC_CHINCR, 0xCB); SFR(ADC_CHINFR, 0xCA); SFR(ADC_CHINSR, 0xCC); SFR(ADC_CNF , 0xD2); SFR(ADC_CRCR1 , 0xCA); SFR(ADC_CRMR1 , 0xCC); SFR(ADC_CRPR1 , 0xCB); SFR(ADC_ENORC , 0xD3); SFR(ADC_ETRCR , 0xD3); SFR(ADC_EVINCR, 0xCF); SFR(ADC_EVINFR, 0xCE); SFR(ADC_EVINSR, 0xD2); SFR(ADC_GLOBCTR, 0xCA); SFR(ADC_GLOBSTR, 0xCB); SFR(ADC_INPCR0, 0xCE); SFR(ADC_LCBR0 , 0xCD); SFR(ADC_LCBR1 , 0xCF); SFR(ADC_LORE , 0xD2); SFR(ADC_PAGE , 0xD1); SFR(ADC_PRAR , 0xCC); SFR(ADC_Q0R0 , 0xCF); SFR(ADC_QBUR0 , 0xD2); SFR(ADC_QINR0 , 0xD2); SFR(ADC_QMR0 , 0xCD); SFR(ADC_QSR0 , 0xCE); SFR(ADC_RCR0 , 0xCA); SFR(ADC_RCR1 , 0xCB); SFR(ADC_RCR2 , 0xCC); SFR(ADC_RCR3 , 0xCD); SFR(ADC_RESR0H, 0xCB); SFR(ADC_RESR0L, 0xCA); SFR(ADC_RESR1H, 0xCD); SFR(ADC_RESR1L, 0xCC); SFR(ADC_RESR2H, 0xCF); SFR(ADC_RESR2L, 0xCE); SFR(ADC_RESR3H, 0xD3); SFR(ADC_RESR3L, 0xD2); SFR(ADC_VFCR , 0xCE); SFR(B , 0xF0); SFR(BCON , 0xF2); SFR(BGH , 0xF4); SFR(BGL , 0xF3); SFR(CCU6_CC60RH, 0xFB); SFR(CCU6_CC60RL, 0xFA); SFR(CCU6_CC60SRH, 0xFB); SFR(CCU6_CC60SRL, 0xFA); SFR(CCU6_CC61RH, 0xFD); SFR(CCU6_CC61RL, 0xFC); SFR(CCU6_CC61SRH, 0xFD); SFR(CCU6_CC61SRL, 0xFC); SFR(CCU6_CC62RH, 0xFF); SFR(CCU6_CC62RL, 0xFE); SFR(CCU6_CC62SRH, 0xFF); SFR(CCU6_CC62SRL, 0xFE); SFR(CCU6_CC63RH, 0x9B); SFR(CCU6_CC63RL, 0x9A); SFR(CCU6_CC63SRH, 0x9B); SFR(CCU6_CC63SRL, 0x9A); SFR(CCU6_CMPMODIFH, 0xA7); SFR(CCU6_CMPMODIFL, 0xA6); SFR(CCU6_CMPSTATH, 0xFF); SFR(CCU6_CMPSTATL, 0xFE); SFR(CCU6_IENH , 0x9D); SFR(CCU6_IENL , 0x9C); SFR(CCU6_INPH , 0x9F); SFR(CCU6_INPL , 0x9E); SFR(CCU6_ISH , 0x9D); SFR(CCU6_ISL , 0x9C); SFR(CCU6_ISRH , 0xA5); SFR(CCU6_ISRL , 0xA4); SFR(CCU6_ISSH , 0xA5); SFR(CCU6_ISSL , 0xA4); SFR(CCU6_MCMCTR, 0xA7); SFR(CCU6_MCMOUTH, 0x9B); SFR(CCU6_MCMOUTL, 0x9A); SFR(CCU6_MCMOUTSH, 0x9F); SFR(CCU6_MCMOUTSL, 0x9E); SFR(CCU6_MODCTRH, 0xFD); SFR(CCU6_MODCTRL, 0xFC); SFR(CCU6_PAGE , 0xA3); SFR(CCU6_PISEL0H, 0x9F); SFR(CCU6_PISEL0L, 0x9E); SFR(CCU6_PISEL2, 0xA4); SFR(CCU6_PSLR , 0xA6); SFR(CCU6_T12DTCH, 0xA5); SFR(CCU6_T12DTCL, 0xA4); SFR(CCU6_T12H , 0xFB); SFR(CCU6_T12L , 0xFA); SFR(CCU6_T12MSELH, 0x9B); SFR(CCU6_T12MSELL, 0x9A); SFR(CCU6_T12PRH, 0x9D); SFR(CCU6_T12PRL, 0x9C); SFR(CCU6_T13H , 0xFD); SFR(CCU6_T13L , 0xFC); SFR(CCU6_T13PRH, 0x9F); SFR(CCU6_T13PRL, 0x9E); SFR(CCU6_TCTR0H, 0xA7); SFR(CCU6_TCTR0L, 0xA6); SFR(CCU6_TCTR2H, 0xFB); SFR(CCU6_TCTR2L, 0xFA); SFR(CCU6_TCTR4H, 0x9D); SFR(CCU6_TCTR4L, 0x9C); SFR(CCU6_TRPCTRH, 0xFF); SFR(CCU6_TRPCTRL, 0xFE); SFR(CD_CON , 0xA1); SFR(CD_CORDXH , 0xBB); SFR(CD_CORDXL , 0xBA); SFR(CD_CORDYH , 0xBD); SFR(CD_CORDYL , 0xBC); SFR(CD_CORDZH , 0xBF); SFR(CD_CORDZL , 0xBE); SFR(CD_STATC , 0xA0); SFR(DPH , 0x83); SFR(DPL , 0x82); SFR(EO , 0xA2); SFR(EXICON0 , 0xEF); SFR(EXICON1 , 0xF4); SFR(FEAH , 0xF7); SFR(FEAL , 0xF6); SFR(HWBPDR , 0xF7); SFR(HWBPSR , 0xF6); SFR(ID , 0xF5); SFR(IEN0 , 0xA8); SFR(IEN1 , 0xE8); SFR(IIC_ADDR , 0xDA); SFR(IIC_ADDRX , 0xDE); SFR(IIC_BRCR , 0xDD); SFR(IIC_CNTR , 0xDC); SFR(IIC_DATA , 0xDB); SFR(IIC_SRST , 0xDF); SFR(IIC_STAT , 0xDD); SFR(IP , 0xB8); SFR(IP1 , 0xF8); SFR(IPH , 0xB9); SFR(IPH1 , 0xF9); SFR(IRCON0 , 0xF2); SFR(IRCON1 , 0xF3); SFR(IRCON2 , 0xF5); SFR(IRCON3 , 0xF6); SFR(LINST , 0xF5); SFR(LTS_COMPARE, 0xD4); SFR(LTS_GLOBCTL0, 0x97); SFR(LTS_GLOBCTL1, 0xD8); SFR(LTS_LDLINE, 0xD5); SFR(LTS_LDTSCTL, 0xD6); SFR(LTS_TSCTL , 0xD7); SFR(LTS_TSVAL , 0xD9); SFR(MDU_MD0 , 0xB2); SFR(MDU_MD1 , 0xB3); SFR(MDU_MD2 , 0xB4); SFR(MDU_MD3 , 0xB5); SFR(MDU_MD4 , 0xB6); SFR(MDU_MD5 , 0xB7); SFR(MDU_MDUCON, 0xB1); SFR(MDU_MDUSTAT, 0xB0); SFR(MDU_MR0 , 0xB2); SFR(MDU_MR1 , 0xB3); SFR(MDU_MR2 , 0xB4); SFR(MDU_MR3 , 0xB5); SFR(MDU_MR4 , 0xB6); SFR(MDU_MR5 , 0xB7); SFR(MMICR , 0xF4); SFR(MMWR2 , 0xEC); SFR(MODIEN , 0xF7); SFR(MODPISEL , 0xF3); SFR(MODPISEL1 , 0xF4); SFR(MODPISEL2 , 0xF5); SFR(MODPISEL3 , 0xEE); SFR(MODSUSP , 0xF6); SFR(NMICON , 0xEE); SFR(NMISR , 0xF7); SFR(OSC_CON , 0xF4); SFR(P0_ALTSEL0, 0x80); SFR(P0_ALTSEL1, 0x86); SFR(P0_ALTSEL2, 0x85); SFR(P0_DATAIN , 0x86); SFR(P0_DATAOUT, 0x80); SFR(P0_OD , 0x80); SFR(P0_PUDEN , 0x86); SFR(P0_PUDSEL , 0x80); SFR(P1_ALTSEL0, 0x90); SFR(P1_ALTSEL1, 0x91); SFR(P1_DATAIN , 0x91); SFR(P1_DATAOUT, 0x90); SFR(P1_OCD , 0x92); SFR(P1_OCPEN , 0x92); SFR(P1_OD , 0x90); SFR(P1_PUDEN , 0x91); SFR(P1_PUDSEL , 0x90); SFR(P1_SLEW , 0x92); SFR(P2_DATAIN , 0x94); SFR(P2_EN , 0x94); SFR(P2_PUDEN , 0x94); SFR(P2_PUDSEL , 0x93); SFR(P3_ALTSEL0, 0xC8); SFR(P3_ALTSEL1, 0xC9); SFR(P3_DATAIN , 0xC9); SFR(P3_DATAOUT, 0xC8); SFR(P3_OD , 0xC8); SFR(P3_PUDEN , 0xC9); SFR(P3_PUDSEL , 0xC8); SFR(PASSWD , 0xF2); SFR(PCON , 0x87); SFR(PMCON0 , 0xF3); SFR(PMCON1 , 0xEF); SFR(PORT_PAGE , 0x8E); SFR(PSW , 0xD0); SFR(RSTCON , 0xF7); SFR(RTC_CNT0 , 0xE1); SFR(RTC_CNT1 , 0xE2); SFR(RTC_CNT2 , 0xE3); SFR(RTC_CNT3 , 0xE4); SFR(RTC_CNT4 , 0xE5); SFR(RTC_CNT5 , 0xE6); SFR(RTC_RTCCR0, 0xE7); SFR(RTC_RTCCR1, 0xE9); SFR(RTC_RTCCR2, 0xEA); SFR(RTC_RTCCR3, 0xEB); SFR(RTC_RTCCR4, 0xEC); SFR(RTC_RTCCR5, 0xED); SFR(RTC_RTCON , 0x95); SFR(RTC_RTCON1, 0x96); SFR(SBUF , 0x99); SFR(SCON , 0x98); SFR(SCU_PAGE , 0xF1); SFR(SDCON , 0xEE); SFR(SP , 0x81); SFR(SSC_BRH , 0xAF); SFR(SSC_BRL , 0xAE); SFR(SSC_CONH_O, 0xAB); SFR(SSC_CONH_P, 0xAB); SFR(SSC_CONL_O, 0xAA); SFR(SSC_CONL_P, 0xAA); SFR(SSC_RBL , 0xAD); SFR(SSC_TBL , 0xAC); SFR(SYSCON0 , 0x8F); SFR(T2_RC2H , 0xC3); SFR(T2_RC2L , 0xC2); SFR(T2_T2CON , 0xC0); SFR(T2_T2CON1 , 0xC6); SFR(T2_T2H , 0xC5); SFR(T2_T2L , 0xC4); SFR(T2_T2MOD , 0xC1); SFR(TCON , 0x88); SFR(TH0 , 0x8C); SFR(TH1 , 0x8D); SFR(TL0 , 0x8A); SFR(TL1 , 0x8B); SFR(TMOD , 0x89); SFR(WDTCON , 0xF6); SFR(WDTH , 0xF6); SFR(WDTL , 0xF5); SFR(WDTREL , 0xF3); SFR(WDTWINB , 0xF4); SFR(XADDRH , 0xF2); // SFR bit definitions // CD_STATC #define CD_STATC_BASE 0xA0 SBIT(CD_BSY ,CD_STATC_BASE,BIT0); SBIT(DMAP ,CD_STATC_BASE,BIT4); SBIT(EOC ,CD_STATC_BASE,BIT2); SBIT(ERROR ,CD_STATC_BASE,BIT1); SBIT(INT_EN ,CD_STATC_BASE,BIT3); SBIT(KEEPX ,CD_STATC_BASE,BIT5); SBIT(KEEPY ,CD_STATC_BASE,BIT6); SBIT(KEEPZ ,CD_STATC_BASE,BIT7); #undef CD_STATC_BASE // IEN0 #define IEN0_BASE 0xA8 SBIT(EA ,IEN0_BASE,BIT7); SBIT(ES ,IEN0_BASE,BIT4); SBIT(ET0 ,IEN0_BASE,BIT1); SBIT(ET1 ,IEN0_BASE,BIT3); SBIT(ET2 ,IEN0_BASE,BIT5); SBIT(EX0 ,IEN0_BASE,BIT0); SBIT(EX1 ,IEN0_BASE,BIT2); #undef IEN0_BASE // IEN1 #define IEN1_BASE 0xE8 SBIT(EADC ,IEN1_BASE,BIT0); SBIT(ECCIP0 ,IEN1_BASE,BIT4); SBIT(ECCIP1 ,IEN1_BASE,BIT5); SBIT(ECCIP2 ,IEN1_BASE,BIT6); SBIT(ECCIP3 ,IEN1_BASE,BIT7); SBIT(ESSC ,IEN1_BASE,BIT1); SBIT(EX2 ,IEN1_BASE,BIT2); SBIT(EXM ,IEN1_BASE,BIT3); #undef IEN1_BASE // IP1 #define IP1_BASE 0xF8 SBIT(PADC ,IP1_BASE,BIT0); SBIT(PCCIP0 ,IP1_BASE,BIT4); SBIT(PCCIP1 ,IP1_BASE,BIT5); SBIT(PCCIP2 ,IP1_BASE,BIT6); SBIT(PCCIP3 ,IP1_BASE,BIT7); SBIT(PSSC ,IP1_BASE,BIT1); SBIT(PX2 ,IP1_BASE,BIT2); SBIT(PXM ,IP1_BASE,BIT3); #undef IP1_BASE // IP #define IP_BASE 0xB8 SBIT(PS ,IP_BASE,BIT4); SBIT(PT0 ,IP_BASE,BIT1); SBIT(PT1 ,IP_BASE,BIT3); SBIT(PT2 ,IP_BASE,BIT5); SBIT(PX0 ,IP_BASE,BIT0); SBIT(PX1 ,IP_BASE,BIT2); #undef IP_BASE // LTS_GLOBCTL1 #define LTS_GLOBCTL1_BASE 0xD8 SBIT(CLKSEL ,LTS_GLOBCTL1_BASE,BIT3); SBIT(FNCOL ,LTS_GLOBCTL1_BASE,BIT2); SBIT(ITF_EN ,LTS_GLOBCTL1_BASE,BIT4); SBIT(ITS_EN ,LTS_GLOBCTL1_BASE,BIT6); SBIT(TFF ,LTS_GLOBCTL1_BASE,BIT5); SBIT(TSF ,LTS_GLOBCTL1_BASE,BIT7); #undef LTS_GLOBCTL1_BASE // MDU_MDUSTAT #define MDU_MDUSTAT_BASE 0xB0 SBIT(IERR ,MDU_MDUSTAT_BASE,BIT1); SBIT(IRDY ,MDU_MDUSTAT_BASE,BIT0); SBIT(MDU_BSY ,MDU_MDUSTAT_BASE,BIT2); #undef MDU_MDUSTAT_BASE // PSW #define PSW_BASE 0xD0 SBIT(AC ,PSW_BASE,BIT6); SBIT(CY ,PSW_BASE,BIT7); SBIT(F0 ,PSW_BASE,BIT5); SBIT(F1 ,PSW_BASE,BIT1); SBIT(OV ,PSW_BASE,BIT2); SBIT(P ,PSW_BASE,BIT0); SBIT(RS0 ,PSW_BASE,BIT3); SBIT(RS1 ,PSW_BASE,BIT4); #undef PSW_BASE // SCON #define SCON_BASE 0x98 SBIT(RB8 ,SCON_BASE,BIT2); SBIT(REN ,SCON_BASE,BIT4); SBIT(RI ,SCON_BASE,BIT0); SBIT(SM0 ,SCON_BASE,BIT7); SBIT(SM1 ,SCON_BASE,BIT6); SBIT(SM2 ,SCON_BASE,BIT5); SBIT(TB8 ,SCON_BASE,BIT3); SBIT(TI ,SCON_BASE,BIT1); #undef SCON_BASE // T2_T2CON #define T2_T2CON_BASE 0xC0 SBIT(CP_RL2 ,T2_T2CON_BASE,BIT0); SBIT(C_T2 ,T2_T2CON_BASE,BIT1); SBIT(EXEN2 ,T2_T2CON_BASE,BIT3); SBIT(EXF2 ,T2_T2CON_BASE,BIT6); SBIT(TF2 ,T2_T2CON_BASE,BIT7); SBIT(TR2 ,T2_T2CON_BASE,BIT2); #undef T2_T2CON_BASE // TCON #define TCON_BASE 0x88 SBIT(IE0 ,TCON_BASE,BIT1); SBIT(IE1 ,TCON_BASE,BIT3); SBIT(IT0 ,TCON_BASE,BIT0); SBIT(IT1 ,TCON_BASE,BIT2); SBIT(TF0 ,TCON_BASE,BIT5); SBIT(TF1 ,TCON_BASE,BIT7); SBIT(TR0 ,TCON_BASE,BIT4); SBIT(TR1 ,TCON_BASE,BIT6); #undef TCON_BASE // Definition of the 16-bit SFR // sfr16 data type to access two 8-bit SFRs as a single 16-bit SFR. SFR16( ADC_RESR0LH, 0xCA); // 16-bit Address SFR16( ADC_RESR1LH, 0xCC); // 16-bit Address SFR16( ADC_RESR2LH, 0xCE); // 16-bit Address SFR16( ADC_RESR3LH, 0xD2); // 16-bit Address SFR16( CCU6_CC60RLH, 0xFA); // 16-bit Address SFR16( CCU6_CC60SRLH, 0xFA); // 16-bit Address SFR16( CCU6_CC61RLH, 0xFC); // 16-bit Address SFR16( CCU6_CC61SRLH, 0xFC); // 16-bit Address SFR16( CCU6_CC62RLH, 0xFE); // 16-bit Address SFR16( CCU6_CC62SRLH, 0xFE); // 16-bit Address SFR16( CCU6_CC63RLH, 0x9A); // 16-bit Address SFR16( CCU6_CC63SRLH, 0x9A); // 16-bit Address SFR16( CCU6_T12LH, 0xFA); // 16-bit Address SFR16( CCU6_T12PRLH, 0x9C); // 16-bit Address SFR16( CCU6_T13LH, 0xFC); // 16-bit Address SFR16( CCU6_T13PRLH, 0x9E); // 16-bit Address SFR16( CD_CORDXLH, 0xBA); // 16-bit Address SFR16( CD_CORDYLH, 0xBC); // 16-bit Address SFR16( CD_CORDZLH, 0xBE); // 16-bit Address SFR16( DPLH, 0x82); // 16-bit Address SFR16( MDU_MD01, 0xB2); // 16-bit Address SFR16( MDU_MD23, 0xB4); // 16-bit Address SFR16( MDU_MD45, 0xB6); // 16-bit Address SFR16( MDU_MR01, 0xB2); // 16-bit Address SFR16( MDU_MR23, 0xB4); // 16-bit Address SFR16( MDU_MR45, 0xB6); // 16-bit Address SFR16( T2_RC2LH, 0xC2); // 16-bit Address SFR16( T2_T2LH, 0xC4); // 16-bit Address // Definition of the PAGE SFR // PORT_PAGE #define _pp0 PORT_PAGE=0 // PORT_PAGE postfix #define _pp1 PORT_PAGE=1 // PORT_PAGE postfix #define _pp2 PORT_PAGE=2 // PORT_PAGE postfix #define _pp3 PORT_PAGE=3 // PORT_PAGE postfix // New Definition of the PORT PAGE SFR #define P0_DATAOUT_PAGE PORT_PAGE=0 // PORT_PAGE postfix #define P0_DATAIN_PAGE PORT_PAGE=0 // PORT_PAGE postfix #define P0_PUDSEL_PAGE PORT_PAGE=1 // PORT_PAGE postfix #define P0_PUDEN_PAGE PORT_PAGE=1 // PORT_PAGE postfix #define P0_ALTSEL0_PAGE PORT_PAGE=2 // PORT_PAGE postfix #define P0_ALTSEL1_PAGE PORT_PAGE=2 // PORT_PAGE postfix #define P0_ALTSEL2_PAGE PORT_PAGE=2 // PORT_PAGE postfix #define P0_OD_PAGE PORT_PAGE=3 // PORT_PAGE postfix #define P1_DATAOUT_PAGE PORT_PAGE=0 // PORT_PAGE postfix #define P1_DATAIN_PAGE PORT_PAGE=0 // PORT_PAGE postfix #define P1_OCD_PAGE PORT_PAGE=0 // PORT_PAGE postfix #define P1_PUDSEL_PAGE PORT_PAGE=1 // PORT_PAGE postfix #define P1_PUDEN_PAGE PORT_PAGE=1 // PORT_PAGE postfix #define P1_OCPEN_PAGE PORT_PAGE=1 // PORT_PAGE postfix #define P1_ALTSEL0_PAGE PORT_PAGE=2 // PORT_PAGE postfix #define P1_ALTSEL1_PAGE PORT_PAGE=2 // PORT_PAGE postfix #define P1_OD_PAGE PORT_PAGE=3 // PORT_PAGE postfix #define P1_SLEW_PAGE PORT_PAGE=3 // PORT_PAGE postfix #define P2_DATAIN_PAGE PORT_PAGE=0 // PORT_PAGE postfix #define P2_PUDSEL_PAGE PORT_PAGE=1 // PORT_PAGE postfix #define P2_PUDEN_PAGE PORT_PAGE=1 // PORT_PAGE postfix #define P2_EN_PAGE PORT_PAGE=3 // PORT_PAGE postfix #define P3_DATAOUT_PAGE PORT_PAGE=0 // PORT_PAGE postfix #define P3_DATAIN_PAGE PORT_PAGE=0 // PORT_PAGE postfix #define P3_PUDSEL_PAGE PORT_PAGE=1 // PORT_PAGE postfix #define P3_PUDEN_PAGE PORT_PAGE=1 // PORT_PAGE postfix #define P3_ALTSEL0_PAGE PORT_PAGE=2 // PORT_PAGE postfix #define P3_ALTSEL1_PAGE PORT_PAGE=2 // PORT_PAGE postfix #define P3_OD_PAGE PORT_PAGE=3 // PORT_PAGE postfix // ADC_PAGE #define _ad0 ADC_PAGE=0 // ADC_PAGE postfix #define _ad1 ADC_PAGE=1 // ADC_PAGE postfix #define _ad2 ADC_PAGE=2 // ADC_PAGE postfix #define _ad3 ADC_PAGE=3 // ADC_PAGE postfix #define _ad4 ADC_PAGE=4 // ADC_PAGE postfix #define _ad5 ADC_PAGE=5 // ADC_PAGE postfix #define _ad6 ADC_PAGE=6 // ADC_PAGE postfix // New Definition of the ADC PAGE SFR #define ADC_GLOBCTR_PAGE ADC_PAGE=0 // ADC_PAGE postfix #define ADC_GLOBSTR_PAGE ADC_PAGE=0 // ADC_PAGE postfix #define ADC_PRAR_PAGE ADC_PAGE=0 // ADC_PAGE postfix #define ADC_LCBR0_PAGE ADC_PAGE=0 // ADC_PAGE postfix #define ADC_LCBR1_PAGE ADC_PAGE=0 // ADC_PAGE postfix #define ADC_INPCR0_PAGE ADC_PAGE=0 // ADC_PAGE postfix #define ADC_LORE_PAGE ADC_PAGE=0 // ADC_PAGE postfix #define ADC_ENORC_PAGE ADC_PAGE=0 // ADC_PAGE postfix #define ADC_CHCTR0_PAGE ADC_PAGE=1 // ADC_PAGE postfix #define ADC_CHCTR1_PAGE ADC_PAGE=1 // ADC_PAGE postfix #define ADC_CHCTR2_PAGE ADC_PAGE=1 // ADC_PAGE postfix #define ADC_CHCTR3_PAGE ADC_PAGE=1 // ADC_PAGE postfix #define ADC_RESR0L_PAGE ADC_PAGE=2 // ADC_PAGE postfix #define ADC_RESR0H_PAGE ADC_PAGE=2 // ADC_PAGE postfix #define ADC_RESR1L_PAGE ADC_PAGE=2 // ADC_PAGE postfix #define ADC_RESR1H_PAGE ADC_PAGE=2 // ADC_PAGE postfix #define ADC_RESR2L_PAGE ADC_PAGE=2 // ADC_PAGE postfix #define ADC_RESR2H_PAGE ADC_PAGE=2 // ADC_PAGE postfix #define ADC_RESR3L_PAGE ADC_PAGE=2 // ADC_PAGE postfix #define ADC_RESR3H_PAGE ADC_PAGE=2 // ADC_PAGE postfix #define ADC_RCR0_PAGE ADC_PAGE=4 // ADC_PAGE postfix #define ADC_RCR1_PAGE ADC_PAGE=4 // ADC_PAGE postfix #define ADC_RCR2_PAGE ADC_PAGE=4 // ADC_PAGE postfix #define ADC_RCR3_PAGE ADC_PAGE=4 // ADC_PAGE postfix #define ADC_VFCR_PAGE ADC_PAGE=4 // ADC_PAGE postfix #define ADC_ALR0_PAGE ADC_PAGE=4 // ADC_PAGE postfix #define ADC_CNF_PAGE ADC_PAGE=4 // ADC_PAGE postfix #define ADC_ETRCR_PAGE ADC_PAGE=4 // ADC_PAGE postfix #define ADC_CHINFR_PAGE ADC_PAGE=5 // ADC_PAGE postfix #define ADC_CHINCR_PAGE ADC_PAGE=5 // ADC_PAGE postfix #define ADC_CHINSR_PAGE ADC_PAGE=5 // ADC_PAGE postfix #define ADC_EVINFR_PAGE ADC_PAGE=5 // ADC_PAGE postfix #define ADC_EVINCR_PAGE ADC_PAGE=5 // ADC_PAGE postfix #define ADC_EVINSR_PAGE ADC_PAGE=5 // ADC_PAGE postfix #define ADC_CRCR1_PAGE ADC_PAGE=6 // ADC_PAGE postfix #define ADC_CRPR1_PAGE ADC_PAGE=6 // ADC_PAGE postfix #define ADC_CRMR1_PAGE ADC_PAGE=6 // ADC_PAGE postfix #define ADC_QMR0_PAGE ADC_PAGE=6 // ADC_PAGE postfix #define ADC_QSR0_PAGE ADC_PAGE=6 // ADC_PAGE postfix #define ADC_Q0R0_PAGE ADC_PAGE=6 // ADC_PAGE postfix #define ADC_QBUR0_PAGE ADC_PAGE=6 // ADC_PAGE postfix #define ADC_QINR0_PAGE ADC_PAGE=6 // ADC_PAGE postfix // SCU_PAGE #define _su0 SCU_PAGE=0 // SCU_PAGE postfix #define _su1 SCU_PAGE=1 // SCU_PAGE postfix #define _su2 SCU_PAGE=2 // SCU_PAGE postfix #define _su3 SCU_PAGE=3 // SCU_PAGE postfix #define _su4 SCU_PAGE=4 // SCU_PAGE postfix #define _su5 SCU_PAGE=5 // SCU_PAGE postfix // New Definition of the SCU PAGE SFR #define IRCON0_PAGE SCU_PAGE=0 // SCU_PAGE postfix #define IRCON1_PAGE SCU_PAGE=0 // SCU_PAGE postfix #define IRCON2_PAGE SCU_PAGE=0 // SCU_PAGE postfix #define IRCON3_PAGE SCU_PAGE=0 // SCU_PAGE postfix #define EXICON0_PAGE SCU_PAGE=0 // SCU_PAGE postfix #define EXICON1_PAGE SCU_PAGE=0 // SCU_PAGE postfix #define NMISR_PAGE SCU_PAGE=0 // SCU_PAGE postfix #define NMICON_PAGE SCU_PAGE=0 // SCU_PAGE postfix #define PASSWD_PAGE SCU_PAGE=1 // SCU_PAGE postfix #define PMCON0_PAGE SCU_PAGE=1 // SCU_PAGE postfix #define PMCON1_PAGE SCU_PAGE=1 // SCU_PAGE postfix #define OSC_CON_PAGE SCU_PAGE=1 // SCU_PAGE postfix #define ID_PAGE SCU_PAGE=1 // SCU_PAGE postfix #define WDTCON_PAGE SCU_PAGE=1 // SCU_PAGE postfix #define RSTCON_PAGE SCU_PAGE=1 // SCU_PAGE postfix #define SDCON_PAGE SCU_PAGE=1 // SCU_PAGE postfix #define XADDRH_PAGE SCU_PAGE=3 // SCU_PAGE postfix #define MODPISEL_PAGE SCU_PAGE=3 // SCU_PAGE postfix #define MODPISEL1_PAGE SCU_PAGE=3 // SCU_PAGE postfix #define MODPISEL2_PAGE SCU_PAGE=3 // SCU_PAGE postfix #define MODPISEL3_PAGE SCU_PAGE=3 // SCU_PAGE postfix #define MODSUSP_PAGE SCU_PAGE=3 // SCU_PAGE postfix #define MODIEN_PAGE SCU_PAGE=3 // SCU_PAGE postfix #define WDTREL_PAGE SCU_PAGE=4 // SCU_PAGE postfix #define WDTWINB_PAGE SCU_PAGE=4 // SCU_PAGE postfix #define WDTL_PAGE SCU_PAGE=4 // SCU_PAGE postfix #define WDTH_PAGE SCU_PAGE=4 // SCU_PAGE postfix #define BCON_PAGE SCU_PAGE=5 // SCU_PAGE postfix #define BGL_PAGE SCU_PAGE=5 // SCU_PAGE postfix #define BGH_PAGE SCU_PAGE=5 // SCU_PAGE postfix #define LINST_PAGE SCU_PAGE=5 // SCU_PAGE postfix #define FEAL_PAGE SCU_PAGE=5 // SCU_PAGE postfix #define FEAH_PAGE SCU_PAGE=5 // SCU_PAGE postfix // CCU6_PAGE #define _cc0 CCU6_PAGE=0 // CCU6_PAGE postfix #define _cc1 CCU6_PAGE=1 // CCU6_PAGE postfix #define _cc2 CCU6_PAGE=2 // CCU6_PAGE postfix #define _cc3 CCU6_PAGE=3 // CCU6_PAGE postfix // New Definition of the CCU6 PAGE SFR #define CCU6_CC63SRL_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_CC63SRH_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_TCTR4L_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_TCTR4H_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_MCMOUTSL_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_MCMOUTSH_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_ISRL_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_ISRH_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_CMPMODIFL_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_CMPMODIFH_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_CC60SRL_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_CC60SRH_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_CC61SRL_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_CC61SRH_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_CC62SRL_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_CC62SRH_PAGE CCU6_PAGE=0 // CCU6_PAGE postfix #define CCU6_CC63RL_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_CC63RH_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_T12PRL_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_T12PRH_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_T13PRL_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_T13PRH_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_T12DTCL_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_T12DTCH_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_TCTR0L_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_TCTR0H_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_CC60RL_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_CC60RH_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_CC61RL_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_CC61RH_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_CC62RL_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_CC62RH_PAGE CCU6_PAGE=1 // CCU6_PAGE postfix #define CCU6_T12MSELL_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_T12MSELH_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_IENL_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_IENH_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_INPL_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_INPH_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_ISSL_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_ISSH_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_PSLR_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_MCMCTRL_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_TCTR2L_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_TCTR2H_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_MODCTRL_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_MODCTRH_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_TRPCTRL_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_TRPCTRH_PAGE CCU6_PAGE=2 // CCU6_PAGE postfix #define CCU6_MCMOUTL_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_MCMOUTH_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_ISL_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_ISH_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_PISEL0L_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_PISEL0H_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_PISEL2_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_T12L_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_T12H_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_T13L_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_T13H_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_CMPSTATL_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define CCU6_CMPSTATH_PAGE CCU6_PAGE=3 // CCU6_PAGE postfix #define SST0 0x80 // Save SFR page to ST0 #define RST0 0xC0 // Restore SFR page from ST0 #define SST1 0x90 // Save SFR page to ST1 #define RST1 0xD0 // Restore SFR page from ST1 #define SST2 0xA0 // Save SFR page to ST2 #define RST2 0xE0 // Restore SFR page from ST2 #define SST3 0xB0 // Save SFR page to ST3 #define RST3 0xF0 // Restore SFR page from ST3 #define noSST 0x00 // Switch page without saving #define SFR_PAGE(pg,op) pg+op // SYSCON0_RMAP // The access to the mapped SFR area is enabled. #define SET_RMAP() SYSCON0 |= 0x01 // The access to the standard SFR area is enabled. #define RESET_RMAP() SYSCON0 &= ~0x01 #define _su SCU_PAGE // SCU_PAGE #define STR_PAGE(pg,op) { _push_(op); \ pg ; } #define RST_PAGE(op) _pop_(op) //**************************************************************************** // @Prototypes Of Global Functions //**************************************************************************** //**************************************************************************** // @Function bit BR_FEATURE_SETTING(char ubOption, char ubData) // //---------------------------------------------------------------------------- // @Description This is the BootROM routine for clock mode setting (to // switch the clock between 8 MHz and 24 MHz) and programming // the user id.Function will returns the status based on // success or fail. // //---------------------------------------------------------------------------- // @Returnvalue Status of the operation // 0 - Correct // option is selected // 1 - Invalid option // is selected // 0 - Programming of User ID // is successful (for Option 1) // 1 - // Programming of User ID has failed (for Option 1) // // 1 - Routine is exited as NMISR is not 0x00 - error (for // Option 1) // //---------------------------------------------------------------------------- // @Parameters ubOption: // ubOption : Option 0 and Option 1 for clock mode setting and // programming user id // 0x00 - (Option 0) // for BR_CLKMODE_SETTING // 0x01 - (Option 1) // for BR_PROG_USER_ID // for Option 1, 4-byte // User ID Information (in IRAM) is required // and all interrupts including NMI must be disabled // (NMICON=00H),(SFR NMISR = 0x00) // @Parameters ubData: // ubData : Values based on Option 0 and Option 1 // // For Option 0 (BR_CLKMODE_SETTING) // 0x00-for 8MHz clock // 0x80-for 24MHz // clock // For Option 1 (BR_PROG_USER_ID) // USER_ID_3,USER_ID_2,USER_ID_1 and USER_ID_0 // //---------------------------------------------------------------------------- // @Date 26.05.2010 // //**************************************************************************** //bit BR_FEATURE_SETTING(char ubOption, char ubData); #define BR_FEATURE_SETTING(_ubOption, _ubData) (((bit (code *)(char ubOption, char ubData)) 0xDFE4)(_ubOption, _ubData)) //**************************************************************************** // @Function void BR_AUTO_BAUD(void) // //---------------------------------------------------------------------------- // @Description This is the BootROM routine for automatically detecting // UART baud rate. // //---------------------------------------------------------------------------- // @Returnvalue None // //---------------------------------------------------------------------------- // @Parameters None // //---------------------------------------------------------------------------- // @Date 26.05.2010 // //**************************************************************************** //void BR_AUTO_BAUD(void); #define BR_AUTO_BAUD() (((void (code *)(void)) 0xDFE7)()) //**************************************************************************** // @Function void BR_UART_BSL(void) // //---------------------------------------------------------------------------- // @Description This is the BootROM routine for re-entering into UART BSL // Mode. // //---------------------------------------------------------------------------- // @Returnvalue None // //---------------------------------------------------------------------------- // @Parameters None // //---------------------------------------------------------------------------- // @Date 26.05.2010 // //**************************************************************************** //void BR_UART_BSL(void); #define BR_UART_BSL() (((void (code *)(void)) 0xDFEA)()) //**************************************************************************** // @Project Includes //**************************************************************************** #include <intrins.h> #endif // ifndef _XC835_H_
[ "thehackerz66@gmail.com" ]
thehackerz66@gmail.com
aa018a6ccc20a7aa99574f5ac6d3f46ddf57cb4c
085ad18f32b351f8b416573331cf4e283da084ed
/NumericalCalculation/Power/main.c
7bb872b231116f54cfead2a0bb139a1639f18e72
[]
no_license
GitHubyangjunyi/APUEMac
13d90ee7caab95d6644cd044373cecb2a9e4753d
2497c91529a2f1cdf0606baaf17de227b697b1ab
refs/heads/master
2020-06-03T13:03:03.308679
2019-10-12T01:14:09
2019-10-12T01:14:09
191,577,850
0
0
null
null
null
null
UTF-8
C
false
false
1,300
c
// // main.c // Power // // Created by 杨俊艺 on 2019/7/7. // Copyright © 2019 杨俊艺. All rights reserved. // #include <stdio.h> #include <math.h> int power(int m, int n);//此函数原型中的参数名不要求与下面函数声明中的参数名相同,事实上参数名是可选的,可写成 //int power(int, int);//但合适的参数名可以提高可读性 int powers(int base, int n); int main(int argc, const char * argv[]) { int i; printf("i power(2, i) powers(-3, i)\n"); for ( i = 0; i <= 10; ++i) { printf("%d %6d %6d\n", i, power(2, i), powers(-3, i)); } return 0; } int power(int base, int n)//计算整数base的n次幂,其中n >= 0,对函数调用power(2,5)来说,结果值为32 { int i, p; p = 1; for ( i = 1; i <= n; ++i) p = p * base; return p; } int powers(int base, int n) { int p; for (p = 1; n > 0; --n)//powers函数内部对n的任何操作将不会影响到调用函数中n的原始参数值 p = p * base; return p; } //int power(base, n)//早期C语言与ANSI C的区别 //int base, n; //{ // int i, p; // p = 1; // // for (i = 1; i <= n; ++i) // { // p = p * base; // } // return p; //} //计算整数base的n次幂
[ "1209032479@qq.com" ]
1209032479@qq.com
1c381371e5d2a411f7f5a3ac39ebd6e262929ff6
4c59549d7a43572efd8379689ed3eb6be4bc5732
/src/item/item.c
2d90940ca3fcb2e31df8f9678a00e4d3f6cef89b
[]
no_license
Floriane4321/myRPG
66c0925a93ddce30a497d004df91451d258fcb73
4fa157dcba15637bfd7656e030d59901b478e272
refs/heads/master
2023-06-14T08:23:35.023125
2021-07-17T17:51:35
2021-07-17T17:51:35
386,769,250
0
0
null
null
null
null
UTF-8
C
false
false
2,023
c
/* ** EPITECH PROJECT, 2021 ** item.c ** File description: ** function loading craft */ #include "c_star.h" #include "utility.h" #include "button.h" #include <stdlib.h> #include "my.h" void click_drag(level_t *lvl, event_t *even, button_t *but); char *reading_map(char const *path); sfText *text_create(char *str, sfVector2f pos, sfFont *font); item_t *init_item(button_t *but, char *name); prefab_craft_t *load_craft(char *str) { int len = count_lign(str); prefab_craft_t *new = malloc(sizeof(prefab_craft_t) * (1 + len)); char **word; char **parc = parc_word(str, '\n'); for (int i = 0; i < len; i++) { word = parc_word(parc[i], ' '); new[i].first = word[0]; new[i].second = word[1]; new[i].res = word[2]; free(word); } return (new); } prefab_craft_t *init_all_craft(void) { char *str = reading_map("craft.txt"); if (str != NULL) return (load_craft(str)); my_putstr("can't read"); return (NULL); } button_list_t *new_item(button_list_t *blist, texture_t *tex, char *item) { button_t *but; sfIntRect base = {0, 0, 128, 64}; sfVector2f size = {1, 1}; sfVector2f pos = {0, 0}; but = button_creat(base, get_textur(tex, TCADRRE), pos, size); (but->action) = (click_drag); but->status = 0; but->nbr_anim = 0; but->delay = 1; but->type = DRAG; but->text = text_create("", pos, tex->font); but->item = init_item(but, item); blist = add_button(blist, but); return (blist); } int matching_craft(prefab_craft_t *str, char *s1, char *s2) { if (my_strcmp(str->first, s1) == 0) { if (my_strcmp(str->second, s2) == 0) { return (1); } } return (0); } char *find_craft(prefab_craft_t *fab, item_t *s1, item_t *s2) { if (s1 == NULL || s2 == NULL) return (NULL); for (int i = 0; i < NB_CRAFT - 1; i++) { if (matching_craft(&fab[i], s1->name, s2->name) == 1) return (fab[i].res); } return (NULL); }
[ "floriane.peteau@epitech.eu" ]
floriane.peteau@epitech.eu
fffbce8328dc59e4b4b0ad40ac016f9e542c3330
a074b4cd3170f65822f23916ceb3e4ae28681247
/roms/read_byte.c
8aec0a209814d61cd2741013963d3594d85352fc
[ "MIT" ]
permissive
ben-martinez/CS107E-GB-Emulator
a977cca51559d8ba361ad041a50ca738147b4706
413d2ae52fbbbaaa7e99f80bbcdde7e1c1a0b4be
refs/heads/master
2021-06-06T08:25:04.693825
2016-09-18T20:20:41
2016-09-18T20:20:41
null
0
0
null
null
null
null
UTF-8
C
false
false
163
c
#include <stdio.h> #include "bgl.h" int main() { for(int i=0x150; i<0x160; i++) { printf("At 0x%04x : 0x%02x\n",i, GB_ROM[i]); } return 0; }
[ "guillean@stanford.edu" ]
guillean@stanford.edu
8e4dbe9ecf5c03ea866c72407fe3831c8fbfd04c
63d9ede316cb67288795a688cc345eeb53ba26ad
/J1900_FreeBSD/c/str_len/str_len.c
84726cc3fc60eaac759bb26b112845de9e1b06a6
[ "BSD-2-Clause" ]
permissive
BoKoIsMe/J1900_FreeBSD
6a271b053712902819ca64252075e426c9c264d6
19c4f7f01a37f4eda11a64040dad307a06563fb9
refs/heads/master
2022-05-14T09:16:31.936018
2022-01-30T02:48:42
2022-01-30T02:48:42
163,841,300
0
0
null
null
null
null
UTF-8
C
false
false
367
c
#include <stdio.h> #define MYSTR "greastyeer" int str_len(char str[]); int main(void) { char str[sizeof MYSTR + 1] = MYSTR; str[sizeof MYSTR] = 0; int result = str_len(&str[0]); printf("string count result = %d\n",result); return 0; } int str_len(char str[]) { int number = 0; for(int index = 0;str[index] != '\0';index++) number += 1; return number; }
[ "typebackup@hotmail.com" ]
typebackup@hotmail.com
d98c8b311e4d2efb0e9f4d2b17f25006f8f56f65
e5fd9380dc1467d1a2c257875225acbe209f36a2
/lexer.c
379928e00689531275131891e3f30b60e43ec688
[]
no_license
joesonw/compiler
373e10bc33a205babff399bb363035a17263b8df
4314a38c35a87ab41b1fcbf97d89536647580234
refs/heads/master
2021-03-12T20:38:39.806992
2014-02-19T18:35:01
2014-02-19T18:35:01
null
0
0
null
null
null
null
UTF-8
C
false
false
54,216
c
#line 2 "lexer.c" #line 4 "lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart(yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif extern int yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static int yy_n_chars; /* number of characters read into yy_ch_buf */ int yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void yyrestart (FILE *input_file ); void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); void yy_delete_buffer (YY_BUFFER_STATE b ); void yy_flush_buffer (YY_BUFFER_STATE b ); void yypush_buffer_state (YY_BUFFER_STATE new_buffer ); void yypop_buffer_state (void ); static void yyensure_buffer_stack (void ); static void yy_load_buffer_state (void ); static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len ); void *yyalloc (yy_size_t ); void *yyrealloc (void *,yy_size_t ); void yyfree (void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ typedef unsigned char YY_CHAR; FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; typedef int yy_state_type; extern int yylineno; int yylineno = 1; extern char *yytext; #define yytext_ptr yytext static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 47 #define YY_END_OF_BUFFER 48 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[131] = { 0, 0, 0, 0, 0, 48, 42, 40, 41, 27, 18, 42, 32, 42, 42, 34, 35, 30, 29, 37, 28, 2, 31, 23, 38, 15, 36, 15, 22, 11, 12, 33, 42, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 7, 42, 8, 47, 46, 47, 40, 41, 15, 18, 0, 16, 0, 43, 39, 25, 0, 0, 24, 44, 0, 23, 22, 22, 0, 22, 22, 22, 22, 22, 22, 5, 22, 22, 22, 22, 22, 26, 45, 0, 16, 18, 18, 17, 17, 0, 0, 0, 22, 22, 22, 22, 22, 22, 14, 1, 22, 22, 22, 22, 16, 0, 0, 0, 22, 22, 22, 22, 6, 22, 22, 22, 22, 9, 3, 22, 22, 4, 22, 22, 13, 22, 19, 21, 10, 20, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 5, 6, 1, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 1, 19, 20, 21, 22, 1, 1, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 25, 26, 27, 28, 1, 29, 30, 31, 32, 33, 34, 35, 36, 37, 23, 38, 39, 23, 40, 41, 42, 23, 43, 44, 45, 46, 23, 47, 23, 48, 23, 49, 50, 51, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[52] = { 0, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 4, 1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1 } ; static yyconst flex_int16_t yy_base[139] = { 0, 0, 0, 49, 50, 200, 201, 197, 0, 177, 51, 0, 176, 188, 170, 201, 201, 173, 172, 201, 171, 173, 43, 41, 201, 169, 168, 167, 0, 201, 201, 201, 159, 143, 142, 148, 150, 143, 140, 26, 137, 146, 133, 141, 201, 126, 201, 201, 201, 158, 172, 0, 201, 60, 53, 201, 62, 0, 201, 201, 164, 59, 154, 201, 153, 53, 0, 0, 142, 126, 135, 138, 39, 122, 122, 0, 119, 126, 117, 118, 123, 201, 201, 69, 72, 76, 83, 201, 150, 149, 148, 139, 115, 107, 86, 89, 90, 93, 0, 0, 84, 77, 85, 80, 67, 75, 78, 85, 70, 79, 84, 72, 0, 66, 63, 65, 65, 0, 0, 53, 62, 0, 53, 56, 0, 56, 0, 0, 0, 0, 201, 130, 134, 138, 142, 146, 148, 78, 152 } ; static yyconst flex_int16_t yy_def[139] = { 0, 130, 1, 131, 131, 130, 130, 130, 132, 130, 133, 134, 130, 130, 135, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 136, 130, 130, 130, 137, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 130, 130, 130, 130, 130, 130, 130, 132, 130, 133, 138, 130, 138, 134, 130, 130, 130, 130, 130, 130, 130, 130, 136, 136, 137, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 130, 130, 138, 133, 133, 133, 130, 130, 130, 130, 130, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 138, 138, 138, 138, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 0, 130, 130, 130, 130, 130, 130, 130, 130 } ; static yyconst flex_int16_t yy_nxt[253] = { 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 6, 30, 31, 32, 33, 34, 35, 36, 37, 38, 28, 28, 39, 28, 28, 28, 28, 40, 41, 42, 28, 28, 43, 28, 44, 45, 46, 48, 48, 54, 63, 55, 64, 55, 65, 75, 49, 49, 54, 58, 55, 76, 84, 88, 64, 95, 65, 55, 96, 104, 54, 56, 55, 83, 54, 104, 104, 67, 55, 89, 56, 54, 85, 55, 129, 84, 128, 83, 127, 105, 126, 125, 56, 124, 90, 105, 107, 86, 83, 91, 123, 122, 86, 56, 106, 85, 121, 120, 119, 106, 106, 86, 118, 117, 116, 106, 86, 115, 114, 113, 86, 112, 111, 110, 99, 86, 47, 47, 47, 47, 51, 109, 51, 51, 53, 53, 53, 53, 57, 108, 57, 57, 60, 87, 60, 60, 66, 66, 54, 54, 54, 54, 87, 87, 87, 103, 102, 101, 100, 99, 98, 97, 94, 93, 92, 68, 62, 62, 87, 50, 82, 81, 80, 79, 78, 77, 74, 73, 72, 71, 70, 69, 68, 52, 52, 52, 62, 58, 58, 58, 61, 59, 58, 52, 50, 130, 5, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130 } ; static yyconst flex_int16_t yy_chk[253] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 4, 10, 22, 10, 23, 54, 23, 39, 3, 4, 53, 22, 53, 39, 56, 61, 65, 72, 65, 104, 72, 83, 84, 10, 84, 54, 85, 105, 85, 137, 106, 61, 53, 86, 56, 86, 125, 107, 123, 104, 122, 83, 120, 119, 84, 116, 61, 105, 85, 56, 106, 61, 115, 114, 56, 86, 83, 107, 113, 111, 110, 83, 105, 85, 109, 108, 103, 105, 85, 102, 101, 100, 107, 97, 96, 95, 94, 107, 131, 131, 131, 131, 132, 93, 132, 132, 133, 133, 133, 133, 134, 92, 134, 134, 135, 91, 135, 135, 136, 136, 138, 138, 138, 138, 90, 89, 88, 80, 79, 78, 77, 76, 74, 73, 71, 70, 69, 68, 64, 62, 60, 50, 49, 45, 43, 42, 41, 40, 38, 37, 36, 35, 34, 33, 32, 27, 26, 25, 21, 20, 18, 17, 14, 13, 12, 9, 7, 5, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[48] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, }; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int yy_flex_debug; int yy_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #line 1 "lexer.l" #line 2 "lexer.l" using namespace std; #include <iostream> #include <fstream> #include <string> #include "parser.tab.h" extern int yylex(); extern int yyline; extern void yyerror(string); unsigned yycol = 0; string yybuffer; #define YY_USER_ACTION yycol += yyleng; #line 596 "lexer.c" #define INITIAL 0 #define C_COMMENT 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy (void ); int yyget_debug (void ); void yyset_debug (int debug_flag ); YY_EXTRA_TYPE yyget_extra (void ); void yyset_extra (YY_EXTRA_TYPE user_defined ); FILE *yyget_in (void ); void yyset_in (FILE * in_str ); FILE *yyget_out (void ); void yyset_out (FILE * out_str ); int yyget_leng (void ); char *yyget_text (void ); int yyget_lineno (void ); void yyset_lineno (int line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap (void ); #else extern int yywrap (void ); #endif #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex (void); #define YY_DECL int yylex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; #line 61 "lexer.l" #line 784 "lexer.c" if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_load_buffer_state( ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 131 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 201 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { int yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) yylineno++; ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: YY_RULE_SETUP #line 63 "lexer.l" { yylval.istr=strdup(yytext);return TYPE; } YY_BREAK case 2: YY_RULE_SETUP #line 64 "lexer.l" { return METHOD_OP;} YY_BREAK case 3: YY_RULE_SETUP #line 65 "lexer.l" { return BREAK;} YY_BREAK case 4: YY_RULE_SETUP #line 66 "lexer.l" { return PRINT; } YY_BREAK case 5: YY_RULE_SETUP #line 67 "lexer.l" { return IF;} YY_BREAK case 6: YY_RULE_SETUP #line 68 "lexer.l" { return ELSE;} YY_BREAK case 7: YY_RULE_SETUP #line 69 "lexer.l" { return BR_START;} YY_BREAK case 8: YY_RULE_SETUP #line 70 "lexer.l" { return BR_END;} YY_BREAK case 9: YY_RULE_SETUP #line 71 "lexer.l" { return ARRAY;} YY_BREAK case 10: YY_RULE_SETUP #line 72 "lexer.l" { return STRING; } YY_BREAK case 11: YY_RULE_SETUP #line 73 "lexer.l" {return ARRAY_LEFT;} YY_BREAK case 12: YY_RULE_SETUP #line 74 "lexer.l" {return ARRAY_RIGHT;} YY_BREAK case 13: YY_RULE_SETUP #line 75 "lexer.l" { return WHILE_LOOP;} YY_BREAK case 14: YY_RULE_SETUP #line 76 "lexer.l" { return FOR_LOOP;} YY_BREAK case 15: YY_RULE_SETUP #line 77 "lexer.l" { yylval.istr=strdup(yytext); return COMPARE;} YY_BREAK case 16: /* rule 16 can match eol */ YY_RULE_SETUP #line 78 "lexer.l" { yylval.istr=strdup(yytext); return STATIC_STRING;} YY_BREAK case 17: YY_RULE_SETUP #line 79 "lexer.l" { yylval.istr=strdup(yytext); return STATIC_CHAR;} YY_BREAK case 18: YY_RULE_SETUP #line 80 "lexer.l" { cerr << "ERROR(line " << yylineno << "): Unterminated string." << endl;exit(EXIT_FAILURE);} YY_BREAK case 19: YY_RULE_SETUP #line 81 "lexer.l" {return DEFINE;} YY_BREAK case 20: YY_RULE_SETUP #line 82 "lexer.l" {return DECLARE;} YY_BREAK case 21: YY_RULE_SETUP #line 83 "lexer.l" { return RETURN;} YY_BREAK case 22: YY_RULE_SETUP #line 84 "lexer.l" { yylval.istr = strdup(yytext); return ID; } YY_BREAK case 23: YY_RULE_SETUP #line 85 "lexer.l" { yylval.iint=atoi(yytext); return STATIC_INT; } YY_BREAK case 24: YY_RULE_SETUP #line 86 "lexer.l" { yylval.ifloat=atof(yytext); return STATIC_FLOAT;} YY_BREAK case 25: YY_RULE_SETUP #line 87 "lexer.l" { return AND;} YY_BREAK case 26: YY_RULE_SETUP #line 88 "lexer.l" { return OR;} YY_BREAK case 27: YY_RULE_SETUP #line 89 "lexer.l" { return NOT;} YY_BREAK case 28: YY_RULE_SETUP #line 90 "lexer.l" { return SUB;} YY_BREAK case 29: YY_RULE_SETUP #line 91 "lexer.l" { return ADD;} YY_BREAK case 30: YY_RULE_SETUP #line 92 "lexer.l" { return MULT;} YY_BREAK case 31: YY_RULE_SETUP #line 93 "lexer.l" { return DIV;} YY_BREAK case 32: YY_RULE_SETUP #line 94 "lexer.l" { return MOD;} YY_BREAK case 33: YY_RULE_SETUP #line 95 "lexer.l" { return CARET;} YY_BREAK case 34: YY_RULE_SETUP #line 96 "lexer.l" { return OPENP;} YY_BREAK case 35: YY_RULE_SETUP #line 97 "lexer.l" { return CLOSEP;} YY_BREAK case 36: YY_RULE_SETUP #line 98 "lexer.l" { return ASSIGN; } YY_BREAK case 37: YY_RULE_SETUP #line 99 "lexer.l" { return SEPARATOR; } YY_BREAK case 38: YY_RULE_SETUP #line 100 "lexer.l" { return ENDLINE; } YY_BREAK case 39: YY_RULE_SETUP #line 101 "lexer.l" { yylval.istr=strdup(yytext);return COASSIGN; } YY_BREAK case 40: YY_RULE_SETUP #line 102 "lexer.l" {} YY_BREAK case 41: /* rule 41 can match eol */ YY_RULE_SETUP #line 103 "lexer.l" { yycol=0; yybuffer = yytext; yyless(1); } YY_BREAK case 42: YY_RULE_SETUP #line 104 "lexer.l" { cerr << "ERROR(line " << yylineno << "): Unknown Token '" << yytext << "'."<< endl;exit(EXIT_FAILURE); } YY_BREAK case 43: YY_RULE_SETUP #line 106 "lexer.l" {} YY_BREAK case 44: YY_RULE_SETUP #line 107 "lexer.l" { BEGIN(C_COMMENT); } YY_BREAK case 45: YY_RULE_SETUP #line 110 "lexer.l" { BEGIN(INITIAL); } YY_BREAK case 46: /* rule 46 can match eol */ YY_RULE_SETUP #line 111 "lexer.l" {} YY_BREAK case 47: YY_RULE_SETUP #line 114 "lexer.l" ECHO; YY_BREAK #line 1118 "lexer.c" case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(C_COMMENT): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_c_buf_p); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = (yytext_ptr); register int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), (size_t) num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart(yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { register yy_state_type yy_current_state; register char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 131 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { register int yy_is_jam; register char *yy_cp = (yy_c_buf_p); register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 131 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 130); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ int offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart(yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return EOF; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); if ( c == '\n' ) yylineno++; ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_init_buffer(YY_CURRENT_BUFFER,input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void yy_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ void yy_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree((void *) b->yy_ch_buf ); yyfree((void *) b ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; yy_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void yy_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (void) { int num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer(b ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) { return yy_scan_bytes(yystr,strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, int _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) yyalloc(n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer(buf,n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = (yy_hold_char); \ (yy_c_buf_p) = yytext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int yyget_lineno (void) { return yylineno; } /** Get the input stream. * */ FILE *yyget_in (void) { return yyin; } /** Get the output stream. * */ FILE *yyget_out (void) { return yyout; } /** Get the length of the current token. * */ int yyget_leng (void) { return yyleng; } /** Get the current token. * */ char *yyget_text (void) { return yytext; } /** Set the current line number. * @param line_number * */ void yyset_lineno (int line_number ) { yylineno = line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * * @see yy_switch_to_buffer */ void yyset_in (FILE * in_str ) { yyin = in_str ; } void yyset_out (FILE * out_str ) { yyout = out_str ; } int yyget_debug (void) { return yy_flex_debug; } void yyset_debug (int bdebug ) { yy_flex_debug = bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ /* We do not touch yylineno unless the option is enabled. */ yylineno = 1; (yy_buffer_stack) = 0; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *) 0; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size ) { return (void *) malloc( size ); } void *yyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void yyfree (void * ptr ) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 114 "lexer.l"
[ "joesonw@host-67113.dhcp.egr.msu.edu" ]
joesonw@host-67113.dhcp.egr.msu.edu
83da6eded3e8ed8c1130b8261e6d3288289cb1cf
f05041f45ff4f743433e3a457807b8867805ac2e
/Guia 4/Encoder/Encoder/source/drivers/source/gpio.c
1beb1299c79500e4b46452b7f2912e5829bc6721
[]
no_license
tlondero/LaboDeMicros
4c443c40c83304522319bbf854fc33b6adec2857
242e29ab4961a73b52354aba45b10dd0a0a4d5ad
refs/heads/master
2023-02-28T13:06:28.628166
2021-01-27T15:48:48
2021-01-27T15:48:48
287,032,219
0
0
null
null
null
null
UTF-8
C
false
false
6,288
c
/* * gpio.c * * Created on: 31 ago. 2020 * Author: MAGT */ #include "../headers/SysTick.h" #include "../headers/board.h" #include "MK64F12.h" #include "hardware.h" //Clock gating masks const static uint32_t SIM_SCGC5_PORT_MASKS[] = {SIM_SCGC5_PORTA_MASK, SIM_SCGC5_PORTB_MASK, SIM_SCGC5_PORTC_MASK, SIM_SCGC5_PORTD_MASK, SIM_SCGC5_PORTE_MASK}; //Port arrays const static PORT_Type *PORT_SELECTORS[] = {PORTA, PORTB, PORTC, PORTD, PORTE}; //GPIO arrays const static GPIO_Type *GPIO_SELECTORS[] = {PTA, PTB, PTC, PTD, PTE}; //GPIO_BASE_PTRS //Matriz de callbacks de cada puerto, cada pin pinIrqFun_t port_pin_interrupt[5][32]; uint32_t pin_irq_configured[5][32]; static void interrupt_init(uint32_t IRQn); static void interrupt_init(uint32_t IRQn) { if (!(NVIC_GetEnableIRQ(IRQn))) { //Si el puerto no tiene las IRQ habilitadas NVIC_EnableIRQ(IRQn); //las habilito } } void gpioCG(pin_t pin, uint8_t state) { //Enable Clock Gating if (state == CG_ON) { SIM->SCGC5 |= SIM_SCGC5_PORT_MASKS[PIN2PORT(pin)]; } //Disable Clock Gating else if (state == CG_OFF) { SIM->SCGC5 &= ~SIM_SCGC5_PORT_MASKS[PIN2PORT(pin)]; } } /** * @brief Configures the specified pin to behave either as an input or an output * @param pin the pin whose mode you wish to set (according PORTNUM2PIN) * @param mode INPUT, OUTPUT, INPUT_PULLUP or INPUT_PULLDOWN. */ void gpioMode(pin_t pin, uint8_t mode) { //Enable Port Clock Gating gpioCG(pin, CG_ON); //PCR CONFIG uint8_t port = PIN2PORT(pin); uint32_t number = PIN2NUM(pin); PORT_Type *port_pointer = PORT_SELECTORS[port]; GPIO_Type *gpio_pointer = GPIO_SELECTORS[port]; port_pointer->PCR[number] = 0x00; // Establecemos el pin como GPIO port_pointer->PCR[number] |= PORT_PCR_MUX(PORT_mGPIO); port_pointer->PCR[number] |= PORT_PCR_IRQC(0); if (mode == OUTPUT) { gpio_pointer->PDDR |= (1 << number); } else { // Set pin as INPUT gpio_pointer->PDDR &= ~(1 << number); switch (mode) { case INPUT_PULLDOWN: port_pointer->PCR[number] |= PORT_PCR_PE(number); // PULL ENABLE port_pointer->PCR[number] |= PORT_PCR_PS(0); //SET PULL DOWN break; case INPUT_PULLUP: port_pointer->PCR[number] |= PORT_PCR_PE(number); // PULL ENABLE port_pointer->PCR[number] |= PORT_PCR_PS(1); //SET PULL DOWN break; default: break; } } } /** * @brief Write a HIGH or a LOW value to a digital pin * @param pin the pin to write (according PORTNUM2PIN) * @param val Desired value (HIGH or LOW) */ void gpioWrite(pin_t pin, bool value) { uint8_t port = PIN2PORT(pin); uint32_t number = PIN2NUM(pin); PORT_Type *port_pointer = PORT_SELECTORS[port]; GPIO_Type *gpio_pointer = GPIO_SELECTORS[port]; if (value == HIGH) { gpio_pointer->PDOR |= (1 << number); } else if (value == LOW) { gpio_pointer->PDOR &= ~(1 << number); } } bool gpioIRQ(pin_t pin, uint8_t irqMode, pinIrqFun_t irqFun) { uint32_t port = PIN2PORT(pin); //Tomo el puerto uint32_t number = PIN2NUM(pin); //Tomo el numero PORT_Type *port_pointer = PORT_SELECTORS[port]; uint32_t IRQn = PORTA_IRQn + port; //Identifico a este pin como que tiene la interrupcion configurada if (irqMode == GPIO_IRQ_MODE_DISABLE) { pin_irq_configured[port][number] = 0; } else { pin_irq_configured[port][number] = 1; } port_pin_interrupt[port][number] = irqFun; //Me guardo el callback de ese pin port_pointer->PCR[number] &= ~PORT_PCR_IRQC_MASK; port_pointer->PCR[number] |= PORT_PCR_IRQC(irqMode); //Seteo el tipo de interrupcion para ese pin ///PENSAR: Esto de habilitar las irq del puerto en el nvic se tendria que hacer apenas se configura un pin ///como hice aca o deberia de ir en app_init despues de configurar TODOS los pines? (que pasa si por ya haberlo ///habilitado me viene una interrupcion de un pin que aun no le configure el PCR? o empieza por default el PCR ///de cada pin de manera tal que no puede tomar interrupciones?) interrupt_init(IRQn); } ///PENSAR: Que hacer con estos? Son los handlers de IRQ por puerto, pero yo tengo un callback por cada pin de cada puerto? __ISR__ PORTA_IRQHandler(void) { uint32_t i = 0; uint32_t exit_cond = 0; while (!exit_cond) { if (pin_irq_configured[PA][i] == 1) { if ((PORTA->PCR[i] & PORT_PCR_ISF_MASK) == PORT_PCR_ISF_MASK) { PORTA->PCR[i] |= PORT_PCR_ISF_MASK; port_pin_interrupt[PA][i](); exit_cond = 1; } } i++; if (i == 32) { exit_cond = 1; } } } __ISR__ PORTB_IRQHandler(void) { uint32_t i = 0; uint32_t exit_cond = 0; while (!exit_cond) { if (pin_irq_configured[PB][i] == 1) { if ((PORTB->PCR[i] & PORT_PCR_ISF_MASK) == PORT_PCR_ISF_MASK) { PORTB->PCR[i] |= PORT_PCR_ISF_MASK; port_pin_interrupt[PB][i](); exit_cond = 1; } } i++; if (i == 32) { exit_cond = 1; } } } __ISR__ PORTC_IRQHandler(void) { uint32_t i = 0; uint32_t exit_cond = 0; while (!exit_cond) { if (pin_irq_configured[PC][i] == 1) { if ((PORTC->PCR[i] & PORT_PCR_ISF_MASK) == PORT_PCR_ISF_MASK) { PORTC->PCR[i] |= PORT_PCR_ISF_MASK; port_pin_interrupt[PC][i](); exit_cond = 1; } } i++; if (i == 32) { exit_cond = 1; } } } __ISR__ PORTD_IRQHandler(void) { uint32_t i = 0; uint32_t exit_cond = 0; while (!exit_cond) { if (pin_irq_configured[PD][i] == 1) { if ((PORTD->PCR[i] & PORT_PCR_ISF_MASK) == PORT_PCR_ISF_MASK) { PORTD->PCR[i] |= PORT_PCR_ISF_MASK; port_pin_interrupt[PD][i](); exit_cond = 1; } } i++; if (i == 32) { exit_cond = 1; } } } __ISR__ PORTE_IRQHandler(void) { uint32_t i = 0; uint32_t exit_cond = 0; while (!exit_cond) { if (pin_irq_configured[PE][i] == 1) { if ((PORTE->PCR[i] & PORT_PCR_ISF_MASK) == PORT_PCR_ISF_MASK) { PORTE->PCR[i] |= PORT_PCR_ISF_MASK; port_pin_interrupt[PE][i](); exit_cond = 1; } } i++; if (i == 32) { exit_cond = 1; } } } void gpioToggle(pin_t pin) { uint32_t port = PIN2PORT(pin); uint32_t number = PIN2NUM(pin); GPIO_Type *gpio_pointer = GPIO_SELECTORS[port]; gpio_pointer->PTOR |= (1 << number); } bool gpioRead(pin_t pin) { uint32_t port = PIN2PORT(pin); uint32_t number = PIN2NUM(pin); GPIO_Type *gpio_pointer = GPIO_SELECTORS[port]; bool res = gpio_pointer->PDIR & (1 << number); return res; }
[ "mrodriguez@itba.edu.ar" ]
mrodriguez@itba.edu.ar
844debb66aa6c1e804ca3e12107466b1f63545cd
5ccaeb278ef69bf41d803f9bf339101c39bf2136
/framework/gfx/src/gfx_gol_scroll_bar.c
49cdc232627b38ffd49e0b905d08c11ed8965b62
[]
no_license
Mytrex/Harmony
6de69d5ebbb8cb7769a9ee7bd0330264c1d6ed3a
32dceb018139e59a12c26044b9f0252d1c0d67c9
refs/heads/master
2021-03-16T09:42:26.915713
2016-11-02T08:25:20
2016-11-02T08:25:20
71,403,438
0
1
null
null
null
null
UTF-8
C
false
false
58,750
c
/******************************************************************************* Module for Microchip Graphics Library - Graphic Object Layer Company: Microchip Technology Inc. File Name: gfx_gol_scroll_bar.c Summary: This implements the scroll bar object of the GOL. Description: Refer to Microchip Graphics Library for complete documentation of the Slider Object. *******************************************************************************/ // DOM-IGNORE-BEGIN /******************************************************************************* Copyright (c) 2013 released Microchip Technology Inc. All rights reserved. Microchip licenses to you the right to use, modify, copy and distribute Software only when embedded on a Microchip microcontroller or digital signal controller that is integrated into your product or third party product (pursuant to the sublicense terms in the accompanying license agreement). You should refer to the license agreement accompanying this Software for additional information regarding your rights and obligations. SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. *******************************************************************************/ // DOM-IGNORE-END #include <stdlib.h> #include <stdint.h> #include "system_config.h" #include "system_definitions.h" typedef union { struct { uint8_t uint328BitValue[4]; }; struct { uint16_t uint3216BitValue[2]; }; uint32_t uint32Value; }SLIDER_UINT32_UNION; /* Internal Functions */ int16_t GFX_GOL_ScrollBarThumbSizeSet(GFX_GOL_SCROLLBAR *pSld, int16_t high, int16_t low); void GFX_GOL_ScrollBarMinMaxPosGet(GFX_GOL_SCROLLBAR *pSld, uint16_t *minPos, uint16_t *maxPos); uint16_t GFX_GOL_ScrollBarWidthGet(GFX_GOL_SCROLLBAR *pSld); uint16_t GFX_GOL_ScrollBarHeightGet(GFX_GOL_SCROLLBAR *pSld); /********************************************************************* * Function: GFX_GOL_SCROLLBAR *SldCreate( SYS_MODULE_INDEX, gfxIndex , * uint16_t ID, * int16_t left, * int16_t top, * int16_t right, * int16_t bottom, * uint16_t state, * int16_t range, * int16_t page, * int16_t pos, * GFX_GOL_OBJ_SCHEME *pScheme ) * * Notes: Creates a GFX_GOL_SCROLLBAR object and adds it to the current active * list. If the creation is successful, the pointer to the created Object * is returned. If not successful, NULL is returned. * ********************************************************************/ GFX_GOL_SCROLLBAR *GFX_GOL_ScrollBarCreate( SYS_MODULE_INDEX gfxIndex, uint16_t ID, uint16_t left, uint16_t top, uint16_t right, uint16_t bottom, uint16_t state, uint16_t range, uint16_t page, uint16_t pos, GFX_GOL_OBJ_SCHEME *pScheme) { GFX_GOL_SCROLLBAR *pSld = NULL; pSld = (GFX_GOL_SCROLLBAR *)GFX_malloc(sizeof(GFX_GOL_SCROLLBAR)); if(pSld == NULL) return (pSld); pSld->hdr.gfxIndex = gfxIndex; /* unique id assigned for referencing */ pSld->hdr.ID = ID; pSld->hdr.pNxtObj = NULL; /* set object type */ pSld->hdr.type = GFX_GOL_SCROLLBAR_TYPE; /* left and right should be equal when oriented vertically */ pSld->hdr.left = left; /* top and bottom should be equal when oriented horizontally */ pSld->hdr.top = top; pSld->hdr.right = right; pSld->hdr.bottom = bottom; pSld->hdr.state = state; /* draw function */ pSld->hdr.DrawObj = GFX_GOL_ScrollBarDraw; /* message function */ pSld->hdr.actionGet = GFX_GOL_ScrollBarActionGet; /* default message function */ pSld->hdr.actionSet = GFX_GOL_ScrollBarActionSet; /* default free function */ pSld->hdr.FreeObj = NULL; // Parameters in the user defined range system (pos, page and range) // range of the scroll bar movement (always measured from 0 to range) if (range < 2) range = 2; else if((uint16_t) range > (uint16_t) 0x7FFF) range = 0x7FFF; pSld->range = range; // 0 refers to pSld->minPos and // range refers to pSld->maxpos where: minPos and maxPos are // the coordinate equivalent of 0 and range value // set the resolution if(page < 1) page = 1; else if(page > ((pSld->range) >> 1)) page = (pSld->range) >> 1; pSld->page = page; // set the initial position pSld->pos = pos; pSld->prevPos = pos; // Set the color scheme to be used pSld->hdr.pGolScheme = (GFX_GOL_OBJ_SCHEME *)pScheme; // calculate the thumb width and height pSld->thWidth = GFX_GOL_ScrollBarWidthGet(pSld); pSld->thHeight = GFX_GOL_ScrollBarHeightGet(pSld); // add the new object to the current list GFX_GOL_ObjectAdd(pSld->hdr.gfxIndex, (GFX_GOL_OBJ_HEADER *)pSld); return (pSld); } // ***************************************************************************** /* Function: void GFX_GOL_ScrollBarRangeSet( GFX_GOL_SCROLLBAR *pObject, uint16_t range) Summary: This function sets the range of the thumb of the scroll bar. Description: This function sets the range of the thumb of the scroll bar. When the range is modified, object must be completely redrawn to reflect the change. */ // ***************************************************************************** void GFX_GOL_ScrollBarRangeSet(GFX_GOL_SCROLLBAR *pObject, uint16_t range) { uint16_t newPos; SLIDER_UINT32_UNION dTemp; // this checks for limits of the range (minimum is 2) if(range < 2) range = 2; else if((uint16_t) range > (uint16_t) 0x7FFF) range = 0x7FFF; dTemp.uint32Value = range * pObject->pos; dTemp.uint32Value = dTemp.uint32Value / pObject->range; // get new range newPos = dTemp.uint3216BitValue[0]; // set the new range pObject->range = range; // now check the page, adjust when necessary // page maximum limit is range/2, minimum is 1 if(pObject->page > ((pObject->range) >> 1)) { if(!((pObject->range) >> 1)) pObject->page = 1; else pObject->page = (pObject->range) >> 1; } // calculate new thumb width and height pObject->thWidth = GFX_GOL_ScrollBarWidthGet(pObject); pObject->thHeight = GFX_GOL_ScrollBarHeightGet(pObject); GFX_GOL_ScrollBarPositionSet(pObject, newPos); } // ***************************************************************************** /* Function: uint16_t GFX_GOL_ScrollBarRangeGet( GFX_GOL_SCROLLBAR *pObject) Summary: This function returns the range of the thumb of the scroll bar. Description: This function returns the range of the thumb of the scroll bar. */ // ***************************************************************************** inline uint16_t GFX_GOL_ScrollBarRangeGet( GFX_GOL_SCROLLBAR *pObject) { return (pObject->range); } // ***************************************************************************** /* Function: void GFX_GOL_ScrollBarPageSet( GFX_GOL_SCROLLBAR *pObject, uint16_t page) Summary: This function sets the page size of the object. Description: This function sets the page size of the object. Page size defines the delta change of the thumb position when incremented via GFX_GOL_ScrollBarPositionIncrement() or decremented via GFX_GOL_ScrollBarPositionDecrement(). Page size minimum value is 1. Maximum value is range/2. Modifying the page size at run time may require a redraw of the object to show the visual effect of the change. */ // ***************************************************************************** void GFX_GOL_ScrollBarPageSet(GFX_GOL_SCROLLBAR *pObject, uint16_t page) { if(page < 1) page = 1; else if(page > ((pObject->range) >> 1)) page = (pObject->range) >> 1; pObject->page = page; // calculate new thumb width and height pObject->thWidth = GFX_GOL_ScrollBarWidthGet(pObject); pObject->thHeight = GFX_GOL_ScrollBarHeightGet(pObject); } // ***************************************************************************** /* Function: uint16_t GFX_GOL_ScrollBarPageGet( GFX_GOL_SCROLLBAR *pObject) Summary: This function returns the page size of the object. Description: This function returns the page size of the object. Page size defines the delta change of the thumb position when incremented via GFX_GOL_ScrollBarPositionIncrement() or decremented via GFX_GOL_ScrollBarPositionDecrement(). Page size minimum value is 1. Maximum value is range/2. */ // ***************************************************************************** inline uint16_t GFX_GOL_ScrollBarPageGet( GFX_GOL_SCROLLBAR *pObject) { return (pObject->page); } // ***************************************************************************** /* Function: void GFX_GOL_ScrollBarPositionSet( GFX_GOL_SCROLLBAR *pObject, uint16_t position) Summary: This function sets the position of the scroll bar thumb. Description: This function sets the position of the scroll bar thumb. The thumb is the rectangular area that slides left or right (for horizontal orientation) or slides up or down (for vertical orientation). The value used for the position should be within the range set for the object. Function will have an undefined behavior if the position is outside the range. */ // ***************************************************************************** void GFX_GOL_ScrollBarPositionSet(GFX_GOL_SCROLLBAR *pObject, uint16_t position) { uint16_t minPos, maxPos, relPos; SLIDER_UINT32_UNION dTemp; // get minimum and maximum positions GFX_GOL_ScrollBarMinMaxPosGet(pObject, &minPos, &maxPos); dTemp.uint32Value = 0; //#ifndef SLD_INVERT_VERTICAL // check if the new value is still in range if(position <= 0) { pObject->pos = 0; // set to zero in range domain if(GFX_GOL_ObjectStateGet(pObject, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { // min and max in vertical is inverted pObject->currPos = maxPos; // minimum position is the bottom } // position in coordinate domain else { pObject->currPos = minPos; // minimum is left most position // in coordinate domain } } else if(position >= pObject->range) { pObject->pos = pObject->range; // set to maximum value in range domain if(GFX_GOL_ObjectStateGet(pObject, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { // min and max in vertical is inverted pObject->currPos = minPos; // maximum position is the top } // position in coordinate domain else { pObject->currPos = maxPos; // maximum is right most position // in coordinate domain } } else { pObject->pos = position; // get new position in range domain dTemp.uint3216BitValue[1] = position; dTemp.uint32Value = dTemp.uint32Value / pObject->range; dTemp.uint32Value = (maxPos - minPos) * dTemp.uint32Value; // set current position in coordinate domain relPos = dTemp.uint3216BitValue[1] + minPos; // test if we need to transform min and max position if(GFX_GOL_ObjectStateGet(pObject, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { // min and max position is swapped in coordinate domain pObject->currPos = maxPos - (relPos - minPos); } else { // use position pObject->currPos = relPos; } } } // ***************************************************************************** /* Function: uint16_t GFX_GOL_ScrollBarPositionGet( GFX_GOL_SCROLLBAR *pObject) Summary: This function returns the current position of the scroll bar thumb. Description: This function returns the current position of the scroll bar thumb. The thumb is the rectangular area that slides left or right (for horizontal orientation) or slides up or down (for vertical orientation). */ // ***************************************************************************** inline uint16_t GFX_GOL_ScrollBarPositionGet( GFX_GOL_SCROLLBAR *pObject) { return (pObject->pos); } // ***************************************************************************** /* Function: void GFX_GOL_ScrollBarPositionIncrement( GFX_GOL_SCROLLBAR *pObject) Summary: This function increments the scroll bar position by the delta change (page) value set. Description: This function increments the scroll bar position by the delta change (page) value set. Object must be redrawn after this function is called to reflect the changes to the object. */ // ***************************************************************************** void GFX_GOL_ScrollBarPositionIncrement( GFX_GOL_SCROLLBAR *pObject) { int16_t value; value = pObject->pos + pObject->page; if (value > pObject->range) value = pObject->range; GFX_GOL_ScrollBarPositionSet(pObject, value); } // ***************************************************************************** /* Function: void GFX_GOL_ScrollBarPositionDecrement( GFX_GOL_SCROLLBAR *pObject) Summary: This function decrements the scroll bar position by the delta change (page) value set. Description: This function decrements the scroll bar position by the delta change (page) value set. Object must be redrawn after this function is called to reflect the changes to the object. Precondition: Object must exist in memory. Parameters: pObject - pointer to the object. Returns: None. Example: <code> void ControlSpeed( GFX_GOL_SCROLLBAR* pObj, int setSpeed, int curSpeed) { // set page size to 1 GFX_GOL_ScrollBarPageSet(pObj, 1); if (setSpeed < curSpeed) { while(GFX_GOL_ScrollBarPositionGet(pObj) < SetSpeed) // increment by 1 GFX_GOL_ScrollBarPositionIncrement(pObj); } else if (setSpeed > curSpeed) { while(GFX_GOL_ScrollBarPositionGet(pObj) > SetSpeed) // decrement by 1 GFX_GOL_ScrollBarPositionDecrement(pObj); } } </code> */ // ***************************************************************************** void GFX_GOL_ScrollBarPositionDecrement( GFX_GOL_SCROLLBAR *pObject) { int16_t value; value = pObject->pos - pObject->page; if (value < 0) value = 0; GFX_GOL_ScrollBarPositionSet(pObject, value); } /********************************************************************* * Function: int16_t GFX_GOL_ScrollBarThumbSizeSet( GFX_GOL_SCROLLBAR *pSld, * int16_t high, int16_t low) * * Notes: An INTERNAL function used to compute for the width or * height of the thumb. This function is created to save * code size. This function is called only to dynamically * compute for the thumb size. Used only when slider is * type Scrollbar. Parameter are defined as: * pSld - pointer to the object * high - higher value to be used * low - lower value to be used * ********************************************************************/ int16_t GFX_GOL_ScrollBarThumbSizeSet( GFX_GOL_SCROLLBAR *pSld, int16_t high, int16_t low ) { uint16_t temp, emboss; temp = (pSld->range / pSld->page); temp = (high - low) / temp; emboss = pSld->hdr.pGolScheme->EmbossSize; // when size is less than half of emboss size, set the // size to half the emboss size. This is to make sure // thumb will always have a size. if(temp < (emboss << 1)) temp = (emboss << 1); return (int16_t) temp; } /********************************************************************* * Function: uint16_t GFX_GOL_ScrollBarWidthGet(GFX_GOL_SCROLLBAR *pSld) * * Notes: An INTERNAL function that computes for the width * of the thumb. This function is created to save * code size. This function is called only to dynamically * compute for the thumb size. * ********************************************************************/ uint16_t GFX_GOL_ScrollBarWidthGet(GFX_GOL_SCROLLBAR *pSld) { uint16_t temp, emboss; /* Calculating the width is dependent on the mode type. If type Scrollbar, width is dependent on the ratio of the page/range = width/max-min (see SetThumbSize()) if type is Slider, width is dependent on height*3/8 When horizontal width is dynamic, height is contant. */ emboss = pSld->hdr.pGolScheme->EmbossSize; if (emboss < 3) emboss = 2; if(GFX_GOL_ObjectStateGet(pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { temp = pSld->hdr.right - pSld->hdr.left; if(GFX_GOL_ObjectStateGet(pSld, GFX_GOL_SCROLLBAR_SLIDER_MODE_STATE)) { temp = temp - (emboss << 1) - 2; } else { temp = temp - (emboss << 1); } } else { if(GFX_GOL_ObjectStateGet(pSld, GFX_GOL_SCROLLBAR_SLIDER_MODE_STATE)) { temp = (((pSld->hdr.bottom - pSld->hdr.top) - (emboss << 1) - 2) * 3) >> 3; } else { temp = GFX_GOL_ScrollBarThumbSizeSet( pSld, pSld->hdr.right, pSld->hdr.left); } } // to avoid calculations of dividing by two, we store half the width value return (temp >> 1); } /********************************************************************* * Function: uint16_t GFX_GOL_ScrollBarHeightGet(GFX_GOL_SCROLLBAR *pSld) * * Notes: An INTERNAL function that computes for the height * of the thumb. This function is created to save * code size. This function is called only to dynamically * compute for the thumb size. * ********************************************************************/ uint16_t GFX_GOL_ScrollBarHeightGet(GFX_GOL_SCROLLBAR *pSld) { uint16_t temp, emboss; /* Calculating the height is dependent on the mode type. If type Scrollbar, width is dependent on the ratio of the page/range = width/max-min (see SetThumbSize()) if type is Slider, width is dependent on width*3/8 When vertical height is dynamic, width is contant. */ emboss = pSld->hdr.pGolScheme->EmbossSize; if (emboss < 3) emboss = 2; if(GFX_GOL_ObjectStateGet(pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { if(GFX_GOL_ObjectStateGet(pSld, GFX_GOL_SCROLLBAR_SLIDER_MODE_STATE)) { temp = (((pSld->hdr.right - pSld->hdr.left) - (emboss << 1) - 2) * 3) >> 3; } else { temp = GFX_GOL_ScrollBarThumbSizeSet( pSld, pSld->hdr.bottom, pSld->hdr.top); } } else { temp = pSld->hdr.bottom - pSld->hdr.top; if(GFX_GOL_ObjectStateGet(pSld, GFX_GOL_SCROLLBAR_SLIDER_MODE_STATE)) { temp = temp - (emboss << 1) - 2; } else { temp = temp - (emboss << 1); } } // to avoid calculations of dividing by two, // we store half the height value return (temp >> 1); } /********************************************************************* * Function: void GFX_GOL_ScrollBarMinMaxPosGet( GFX_GOL_SCROLLBAR *pSld, * uint16_t *min, uint16_t *max) * * Notes: An INTERNAL function that computes for the minimum * and maximum pixel position in the screen. This function is * created to save code size. Used to define the minimum * & maximum position of the thumb when sliding. Parameters * used are defined as: * pSld - pointer to the object * min - pointer to the minimum variable * max - pointer to the maximum variable * ********************************************************************/ void GFX_GOL_ScrollBarMinMaxPosGet( GFX_GOL_SCROLLBAR *pSld, uint16_t *min, uint16_t *max) { uint16_t temp; // calculate maximum and minimum position if(GFX_GOL_ObjectStateGet(pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { temp = pSld->thHeight + pSld->hdr.pGolScheme->EmbossSize; *min = pSld->hdr.top + temp; *max = pSld->hdr.bottom - temp; } else { temp = pSld->thWidth + pSld->hdr.pGolScheme->EmbossSize; *min = pSld->hdr.left + temp; *max = pSld->hdr.right - temp; } // for aestetics. if(GFX_GOL_ObjectStateGet(pSld, GFX_GOL_SCROLLBAR_SLIDER_MODE_STATE)) { *min = *min + 2; *max = *max - 2; } } // ***************************************************************************** /* Function: void GFX_GOL_ScrollBarActionSet( GFX_GOL_TRANSLATED_ACTION translatedMsg, void *pObject, GFX_GOL_MESSAGE *pMessage) Summary: This function performs the state change of the object based on the translated action. Description: This function performs the state change of the object based on the translated action. This change can be overridden by the application by on the GFX_GOL_ObjectMessageCallback(). When the user message is determined to affect the object, application can perform the state change and return 0 on the GFX_GOL_ObjectMessageCallback(). */ // ***************************************************************************** void GFX_GOL_ScrollBarActionSet( GFX_GOL_TRANSLATED_ACTION translatedMsg, void *pObject, GFX_GOL_MESSAGE *pMessage) { GFX_GOL_SCROLLBAR *pSld; pSld = (GFX_GOL_SCROLLBAR *)pObject; #ifndef GFX_CONFIG_USE_TOUCHSCREEN_DISABLE int16_t newPos; uint16_t minPos, maxPos; SLIDER_UINT32_UNION dTemp; #ifndef GFX_CONFIG_FOCUS_DISABLE if(pMessage->type == TYPE_TOUCHSCREEN) { if(!GFX_GOL_ObjectStateGet(pSld, GFX_GOL_SCROLLBAR_FOCUSED_STATE)) { GFX_GOL_ObjectFocusSet(pSld->hdr.gfxIndex, (GFX_GOL_OBJ_HEADER *)pSld); } } #endif // if message was passive do not do anything if (translatedMsg == GFX_GOL_OBJECT_ACTION_PASSIVE) return; // get the min and max positions GFX_GOL_ScrollBarMinMaxPosGet(pSld, &minPos, &maxPos); if(pMessage->type == TYPE_TOUCHSCREEN) { if((translatedMsg == GFX_GOL_SCROLLBAR_ACTION_DEC) || (translatedMsg == GFX_GOL_SCROLLBAR_ACTION_INC)) { // newPos in this context is used in the coordinate domain // check if Horizontal or Vertical orientation if(!GFX_GOL_ObjectStateGet(pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { // Horizontal orientation: test x position if(pMessage->param1 <= minPos) { // beyond minimum, use min position newPos = minPos; } else if(pMessage->param1 >= maxPos) { // beyond maximum, use max position newPos = maxPos; } else { // within range: use x position given newPos = pMessage->param1; } } else { // Vertical orientation: test y position if(pMessage->param2 <= minPos) { // beyond minimum, use min position newPos = minPos; } else if(pMessage->param2 >= maxPos) { // beyond maximum, use max position newPos = maxPos; } else { // within range: use y position given newPos = pMessage->param2; } } // check if we need to redraw thumb if(newPos != pSld->currPos) { // yes redraw is needed, translate newPos into range domain // first get new position in range domain dTemp.uint32Value = (uint32_t) (newPos - minPos) * (uint32_t) pSld->range; dTemp.uint32Value = dTemp.uint32Value / (maxPos - minPos); newPos = dTemp.uint3216BitValue[0]; // check if we need to swap min and max in vertical if(GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { // min and max is swapped in vertical orientation newPos = pSld->range - newPos; } // set to new position GFX_GOL_ScrollBarPositionSet(pSld, newPos); // redraw the thumb only GFX_GOL_ObjectStateSet( pSld, GFX_GOL_SCROLLBAR_DRAW_THUMB_STATE); } else return; } else return; } #endif // GFX_CONFIG_USE_TOUCHSCREEN_DISABLE #ifndef GFX_CONFIG_USE_KEYBOARD_DISABLE // for keyboard if(pMessage->type == TYPE_KEYBOARD) { if(translatedMsg == GFX_GOL_SCROLLBAR_ACTION_INC) { // increment is requested GFX_GOL_ScrollBarPositionIncrement(pSld); } else if (translatedMsg == GFX_GOL_SCROLLBAR_ACTION_DEC) { // decrement is requested GFX_GOL_ScrollBarPositionDecrement(pSld); } else { // do nothing return; } // redraw the thumb only GFX_GOL_ObjectStateSet(pSld, GFX_GOL_SCROLLBAR_DRAW_THUMB_STATE); } #endif // #ifndef GFX_CONFIG_USE_KEYBOARD_DISABLE } // ***************************************************************************** /* Function: GFX_GOL_TRANSLATED_ACTION GFX_GOL_ScrollBarActionGet( void *pObject, GFX_GOL_MESSAGE *pMessage); Summary: This function evaluates the message from a user if the message will affect the object or not. Description: This function evaluates the message from a user if the message will affect the object or not. */ // ***************************************************************************** GFX_GOL_TRANSLATED_ACTION GFX_GOL_ScrollBarActionGet( void *pObject, GFX_GOL_MESSAGE *pMessage) { GFX_GOL_SCROLLBAR *pSld; pSld = (GFX_GOL_SCROLLBAR *)pObject; // Evaluate if the message is for the slider // Check if disabled first if(GFX_GOL_ObjectStateGet(pSld, GFX_GOL_SCROLLBAR_DISABLED_STATE)) return (GFX_GOL_OBJECT_ACTION_INVALID); #ifndef GFX_CONFIG_USE_TOUCHSCREEN_DISABLE if(pMessage->type == TYPE_TOUCHSCREEN) { /* Check if it falls to the left or right of the center of the thumb's face */ if( ((pMessage->uiEvent == EVENT_PRESS) || (pMessage->uiEvent == EVENT_MOVE)) && ((pSld->hdr.left < pMessage->param1) && (pSld->hdr.right > pMessage->param1) && (pSld->hdr.top < pMessage->param2) && (pSld->hdr.bottom > pMessage->param2)) ) { if(GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { if( (pSld->hdr.left < pMessage->param1) && (pSld->hdr.right > pMessage->param1) && (pSld->hdr.top < pMessage->param2) && (pSld->hdr.bottom > pMessage->param2)) { // add this check for jitter if (pMessage->param2 > pSld->currPos + 2) return (GFX_GOL_SCROLLBAR_ACTION_INC); else if (pMessage->param2 < pSld->currPos - 2) return (GFX_GOL_SCROLLBAR_ACTION_DEC); else return (GFX_GOL_OBJECT_ACTION_INVALID); } } else { if( (pSld->hdr.left < pMessage->param1) && (pSld->hdr.right > pMessage->param1) && (pSld->hdr.top < pMessage->param2) && (pSld->hdr.bottom > pMessage->param2)) { // add this check for jitter if (pMessage->param1 > pSld->currPos + 2) return (GFX_GOL_SCROLLBAR_ACTION_INC); else if (pMessage->param1 < pSld->currPos - 2) return (GFX_GOL_SCROLLBAR_ACTION_DEC); else return (GFX_GOL_OBJECT_ACTION_INVALID); } } } // end of if((pMsg->uiEvent == EVENT_PRESS) ... // when the event is release emit GFX_GOL_OBJECT_ACTION_PASSIVE this can // be used to detect that the release event happened on // the scroll bar. if(pMessage->uiEvent == EVENT_RELEASE) return GFX_GOL_OBJECT_ACTION_PASSIVE; return (GFX_GOL_OBJECT_ACTION_INVALID); } // end of if(pMsg->type == TYPE_TOUCHSCREEN #endif #ifndef GFX_CONFIG_USE_KEYBOARD_DISABLE if(pMessage->type == TYPE_KEYBOARD) { if((uint16_t)pMessage->param1 == pSld->hdr.ID) { if(pMessage->uiEvent == EVENT_KEYSCAN) { if( (pMessage->param2 == SCAN_RIGHT_PRESSED) || (pMessage->param2 == SCAN_UP_PRESSED)) { return (GFX_GOL_SCROLLBAR_ACTION_INC); } if( (pMessage->param2 == SCAN_LEFT_PRESSED) || (pMessage->param2 == SCAN_DOWN_PRESSED)) { return (GFX_GOL_SCROLLBAR_ACTION_DEC); } } } } #endif return (GFX_GOL_OBJECT_ACTION_INVALID); } // ***************************************************************************** /* Function: GFX_STATUS GFX_GOL_ScrollBarDraw(void *pObject) Summary: This function renders the object on the screen based on the current state of the object. Description: This function renders the object on the screen based on the current state of the object. Location of the object is determined by the left, top, right and bottom parameters. The colors used are dependent on the state of the object. The font used is determined by the style scheme set. The text on the face of the GFX_GOL_SCROLLBAR is drawn on top of the bitmap. Text alignment based on the alignment parameter set on the object. When rendering objects of the same type, each object must be rendered completely before the rendering of the next object is started. This is to avoid incomplete object rendering. Normally, application will just call GFX_GOL_ObjectListDraw() to allow the Graphics Library to manage all object rendering. See GFX_GOL_ObjectListDraw() for more information on object rendering. Precondition: Object must exist in memory. Parameters: pObject - Pointer to the object. Returns: GFX_STATUS_SUCCESS - When the object rendering is finished. GFX_STATUS_FAILURE - When the object rendering is not yet finished. Application needs to call this rendering function again to continue the rendering. Example: None. */ // ***************************************************************************** GFX_STATUS GFX_GOL_ScrollBarDraw(void *pObject) { typedef enum { SLD_STATE_IDLE, SLD_STATE_HIDE, SLD_STATE_PANEL, SLD_STATE_THUMBPATH1, SLD_STATE_THUMBPATH2, SLD_STATE_CLEARTHUMB_CHECK, SLD_STATE_CLEARTHUMB, SLD_STATE_REDRAWPATH1, SLD_STATE_REDRAWPATH2, SLD_STATE_THUMB, SLD_STATE_THUMBPANEL, SLD_STATE_FOCUS } SLD_DRAW_STATES; static GFX_COLOR colorTemp = 0; static SLD_DRAW_STATES state = SLD_STATE_IDLE; static uint16_t left, top, right, bottom; static uint16_t midPoint, thWidth, thHeight; static uint16_t minPos, maxPos, embossSize; static GFX_FILL_STYLE fillStyle; GFX_GOL_SCROLLBAR *pSld = (GFX_GOL_SCROLLBAR *)pObject; GFX_PREEMPTION_LEVEL preemptionLevel = GFX_GOL_PreemptionLevelGet(pSld->hdr.gfxIndex); while(1) { if (GFX_RenderStatusGet(pSld->hdr.gfxIndex) == GFX_STATUS_BUSY_BIT) return (GFX_STATUS_FAILURE); switch(state) { case SLD_STATE_IDLE: #ifdef GFX_CONFIG_BISTABLE_DISPLAY_AUTO_REFRESH_ENABLE GFX_DRIVER_SetupDrawUpdate( \ pSld->hdr.left, \ pSld->hdr.top, \ pSld->hdr.right, \ pSld->hdr.bottom); #endif // set the background information GFX_GOL_PanelBackgroundSet(pSld->hdr.gfxIndex, &pSld->hdr); #if defined (GFX_CONFIG_ALPHABLEND_DISABLE) && \ !defined (GFX_CONFIG_GRADIENT_DISABLE) // scroll bar will not draw gradient on the main // panel, only on the thumb fillStyle = GFX_FILL_STYLE_COLOR; #else fillStyle = pSld->hdr.pGolScheme->fillStyle; #endif // set the panel color if (!GFX_GOL_ObjectStateGet ( pSld, GFX_GOL_SCROLLBAR_DISABLED_STATE)) { // select enabled color colorTemp = pSld->hdr.pGolScheme->Color0; } else { // select disabled color colorTemp = pSld->hdr.pGolScheme->ColorDisabled; } if (GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_HIDE_STATE)) { // ************************************** // To be hidden // ************************************** // set to common background color GFX_ColorSet(pSld->hdr.gfxIndex, pSld->hdr.pGolScheme->CommonBkColor); state = SLD_STATE_HIDE; // no break here so it falls through to SLD_STATE_HIDE } else { // ************************************** // Not hidden // ************************************** GFX_GOL_ScrollBarMinMaxPosGet(pSld, &minPos, &maxPos); if (GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) midPoint = (pSld->hdr.left + pSld->hdr.right) >> 1; else midPoint = (pSld->hdr.top + pSld->hdr.bottom) >> 1; // calculate the thumb width and height. Actually gets the // half value(see calculation of width and height) // GFX_GOL_ScrollBarWidthGet() and // GFX_GOL_ScrollBarHeightGet() thWidth = pSld->thWidth; thHeight = pSld->thHeight; GFX_LineStyleSet(pSld->hdr.gfxIndex, GFX_LINE_STYLE_THIN_SOLID); embossSize = pSld->hdr.pGolScheme->EmbossSize; if (embossSize < 3) embossSize = 1; if(GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_DRAW_STATE)) { // draw the panel for the scroll bar // modify the color setting if scroll bar mode or // slider mode GFX_GOL_PanelParameterSet(pSld->hdr.gfxIndex, pSld->hdr.left, pSld->hdr.top, pSld->hdr.right, pSld->hdr.bottom, 0, colorTemp, (GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_SLIDER_MODE_STATE)) ? pSld->hdr.pGolScheme->EmbossLtColor : pSld->hdr.pGolScheme->EmbossDkColor, (GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_SLIDER_MODE_STATE)) ? pSld->hdr.pGolScheme->EmbossDkColor : pSld->hdr.pGolScheme->EmbossLtColor, NULL, fillStyle, embossSize); // initialize current and previous position GFX_GOL_ScrollBarPositionSet(pSld, pSld->pos); pSld->prevPos = pSld->currPos; state = SLD_STATE_PANEL; break; } else { // we do not need to draw the whole object // go to thumb drawing state = SLD_STATE_CLEARTHUMB_CHECK; break; } } if( GFX_PREEMPTION_LEVEL_2 == preemptionLevel ) { return GFX_STATUS_FAILURE; } case SLD_STATE_HIDE: // Hide the GFX_GOL_SCROLLBAR (remove from screen) if (GFX_GOL_ObjectHideDraw(pSld->hdr.gfxIndex, &(pSld->hdr)) != GFX_STATUS_SUCCESS) return (GFX_STATUS_FAILURE); state = SLD_STATE_IDLE; #ifdef GFX_CONFIG_BISTABLE_DISPLAY_AUTO_REFRESH_ENABLE GFX_DRIVER_CompleteDrawUpdate( pSld->hdr.left, pSld->hdr.top, pSld->hdr.right, pSld->hdr.bottom); #endif return (GFX_STATUS_SUCCESS); case SLD_STATE_PANEL: // draw the panel of the slider if(GFX_GOL_PanelDraw(pSld->hdr.gfxIndex) != GFX_STATUS_SUCCESS) return (GFX_STATUS_FAILURE); // check if slider or scroll bar if(GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_SLIDER_MODE_STATE)) { GFX_LineStyleSet(pSld->hdr.gfxIndex, GFX_LINE_STYLE_THIN_SOLID); // slider: draw thumb path next state = SLD_STATE_THUMBPATH1; } else { // scrollbar: go directly to thumb drawing // thumb path is not drawn in scrollbar state = SLD_STATE_THUMB; break; } if( GFX_PREEMPTION_LEVEL_2 == preemptionLevel ) { return GFX_STATUS_FAILURE; } case SLD_STATE_THUMBPATH1: GFX_ColorSet(pSld->hdr.gfxIndex, pSld->hdr.pGolScheme->EmbossDkColor); if(!GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { if(GFX_LineDraw(pSld->hdr.gfxIndex, minPos, midPoint, maxPos, midPoint) != GFX_STATUS_SUCCESS) { return (GFX_STATUS_FAILURE); } } else { if(GFX_LineDraw(pSld->hdr.gfxIndex, midPoint, minPos, midPoint, maxPos) != GFX_STATUS_SUCCESS) { return (GFX_STATUS_FAILURE); } } state = SLD_STATE_THUMBPATH2; if( GFX_PREEMPTION_LEVEL_2 == preemptionLevel ) { return GFX_STATUS_FAILURE; } case SLD_STATE_THUMBPATH2: GFX_ColorSet(pSld->hdr.gfxIndex, pSld->hdr.pGolScheme->EmbossLtColor); if(!GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { if(GFX_LineDraw(pSld->hdr.gfxIndex, minPos, midPoint + 1, maxPos, midPoint + 1) != GFX_STATUS_SUCCESS) { return (GFX_STATUS_FAILURE); } } else { if(GFX_LineDraw(pSld->hdr.gfxIndex, midPoint + 1, minPos, midPoint + 1, maxPos) != GFX_STATUS_SUCCESS) { return (GFX_STATUS_FAILURE); } } if(GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_DRAW_STATE)) { // if drawing the whole slider // go straight to drawing the thumb state = SLD_STATE_THUMB; break; } else { // if just drawing the thumb // go to state to remove current position state = SLD_STATE_CLEARTHUMB_CHECK; } if( GFX_PREEMPTION_LEVEL_2 == preemptionLevel ) { return GFX_STATUS_FAILURE; } case SLD_STATE_CLEARTHUMB_CHECK: // this removes the current thumb if(!GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_DRAW_THUMB_STATE)) { // GFX_GOL_SCROLLBAR_DRAW_THUMB_STATE is only set when // object type is GFX_GOL_SCROLLBAR state = SLD_STATE_FOCUS; break; } GFX_ColorSet(pSld->hdr.gfxIndex, colorTemp); // Remove the current thumb by drawing a bar // with the background GFX_GOL_ObjectBackGroundSet(pSld->hdr.gfxIndex, &pSld->hdr); #if defined (GFX_CONFIG_ALPHABLEND_DISABLE) && \ !defined (GFX_CONFIG_GRADIENT_DISABLE) // scroll bar will not draw gradient on the main // panel, only on the thumb fillStyle = GFX_FILL_STYLE_COLOR; #else fillStyle = pSld->hdr.pGolScheme->fillStyle; #endif state = SLD_STATE_CLEARTHUMB; if( GFX_PREEMPTION_LEVEL_2 == preemptionLevel ) { return GFX_STATUS_FAILURE; } case SLD_STATE_CLEARTHUMB: GFX_FillStyleSet(pSld->hdr.gfxIndex, fillStyle); if(!GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { if(GFX_RectangleFillDraw(pSld->hdr.gfxIndex, pSld->prevPos - thWidth, midPoint - thHeight, pSld->prevPos + thWidth, midPoint + thHeight) != GFX_STATUS_SUCCESS) { return (GFX_STATUS_FAILURE); } } else { if(GFX_RectangleFillDraw(pSld->hdr.gfxIndex, midPoint - thWidth, pSld->prevPos - thHeight, midPoint + thWidth, pSld->prevPos + thHeight) != GFX_STATUS_SUCCESS) { return (GFX_STATUS_FAILURE); } } // check if slider or scroll bar if(GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_SLIDER_MODE_STATE)) { state = SLD_STATE_REDRAWPATH1; } else { // go directly to thumb drawing // thumb path is not drawn in scrollbar state = SLD_STATE_THUMB; break; } if( GFX_PREEMPTION_LEVEL_2 == preemptionLevel ) { return GFX_STATUS_FAILURE; } case SLD_STATE_REDRAWPATH1: // redraws the lines that it covered GFX_ColorSet(pSld->hdr.gfxIndex, pSld->hdr.pGolScheme->EmbossDkColor); // Check if the redraw area exceeds the actual dimension. // This will adjust the redrawing area to just within // the parameters if(!GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { if(minPos + thWidth > pSld->prevPos) left = minPos; else left = pSld->prevPos - thWidth; if(maxPos - thWidth < pSld->prevPos) right = maxPos; else right = pSld->prevPos + thWidth; if(GFX_LineDraw(pSld->hdr.gfxIndex, left, midPoint, right, midPoint) != GFX_STATUS_SUCCESS) { return (GFX_STATUS_FAILURE); } } else { if(minPos + thHeight > pSld->prevPos) top = minPos; else top = pSld->prevPos - thHeight; if(maxPos - thHeight < pSld->prevPos) bottom = maxPos; else bottom = pSld->prevPos + thHeight; if(GFX_LineDraw(pSld->hdr.gfxIndex, midPoint, top, midPoint, bottom) != GFX_STATUS_SUCCESS) { return (GFX_STATUS_FAILURE); } } state = SLD_STATE_REDRAWPATH2; if( GFX_PREEMPTION_LEVEL_2 == preemptionLevel ) { return GFX_STATUS_FAILURE; } case SLD_STATE_REDRAWPATH2: GFX_ColorSet(pSld->hdr.gfxIndex, pSld->hdr.pGolScheme->EmbossLtColor); if(!GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { if(GFX_LineDraw(pSld->hdr.gfxIndex, left, midPoint + 1, right, midPoint + 1) != GFX_STATUS_SUCCESS) { return (GFX_STATUS_FAILURE); } } else { if (GFX_LineDraw(pSld->hdr.gfxIndex, midPoint + 1, top, midPoint + 1, bottom) != GFX_STATUS_SUCCESS) { return (GFX_STATUS_FAILURE); } } state = SLD_STATE_THUMB; if( GFX_PREEMPTION_LEVEL_2 == preemptionLevel ) { return GFX_STATUS_FAILURE; } case SLD_STATE_THUMB: if (!GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_VERTICAL_STATE)) { // Draw the slider thumb based on the // current position left = pSld->currPos - thWidth; top = midPoint - thHeight; right = pSld->currPos + thWidth; bottom = midPoint + thHeight; } else { left = midPoint - thWidth; top = pSld->currPos - thHeight; right = midPoint + thWidth; bottom = pSld->currPos + thHeight; } if (embossSize > 1) embossSize -= 1; #ifndef GFX_CONFIG_GRADIENT_DISABLE // scroll bar will draw gradient only on the thumb GFX_GOL_PanelGradientParameterSet(pSld->hdr.gfxIndex, pSld->hdr.pGolScheme->gradientStartColor, pSld->hdr.pGolScheme->gradientEndColor); #endif GFX_GOL_PanelParameterSet(pSld->hdr.gfxIndex, left, top, right, bottom, 0, // set the parameters of the thumb colorTemp, pSld->hdr.pGolScheme->EmbossLtColor, pSld->hdr.pGolScheme->EmbossDkColor, NULL, pSld->hdr.pGolScheme->fillStyle, embossSize); state = SLD_STATE_THUMBPANEL; if( GFX_PREEMPTION_LEVEL_2 == preemptionLevel ) { return GFX_STATUS_FAILURE; } case SLD_STATE_THUMBPANEL: // draw the panel of the thumb if (GFX_GOL_PanelDraw(pSld->hdr.gfxIndex) != GFX_STATUS_SUCCESS) return (GFX_STATUS_FAILURE); // record the current position as previous pSld->prevPos = pSld->currPos; // check if scroll bar focus is not used if (!GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_SLIDER_MODE_STATE)) { state = SLD_STATE_IDLE; // go back to idle state #ifdef GFX_CONFIG_BISTABLE_DISPLAY_AUTO_REFRESH_ENABLE GFX_DRIVER_CompleteDrawUpdate( pSld->hdr.left, pSld->hdr.top, pSld->hdr.right, pSld->hdr.bottom); #endif return (GFX_STATUS_SUCCESS); } if (!GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_DRAW_FOCUS_STATE)) { state = SLD_STATE_IDLE; #ifdef GFX_CONFIG_BISTABLE_DISPLAY_AUTO_REFRESH_ENABLE GFX_DRIVER_CompleteDrawUpdate(pSld->hdr.left, pSld->hdr.top, pSld->hdr.right, pSld->hdr.bottom); #endif return (GFX_STATUS_SUCCESS); } state = SLD_STATE_FOCUS; if( GFX_PREEMPTION_LEVEL_2 == preemptionLevel ) { return GFX_STATUS_FAILURE; } case SLD_STATE_FOCUS: if (GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_SLIDER_MODE_STATE)) { // do not draw focus when in scroll bar mode GFX_LineStyleSet(pSld->hdr.gfxIndex, GFX_LINE_STYLE_THIN_DASHED); if (GFX_GOL_ObjectStateGet( pSld, GFX_GOL_SCROLLBAR_FOCUSED_STATE)) { // draw the focus box GFX_ColorSet(pSld->hdr.gfxIndex, pSld->hdr.pGolScheme->TextColor0); } else { // remove the focus box, colorTemp GFX_ColorSet(pSld->hdr.gfxIndex, colorTemp); } if(GFX_RectangleDraw(pSld->hdr.gfxIndex, pSld->hdr.left + embossSize, pSld->hdr.top + embossSize, pSld->hdr.right - embossSize, pSld->hdr.bottom - embossSize) != GFX_STATUS_SUCCESS) { return (GFX_STATUS_FAILURE); } // reset line type GFX_LineStyleSet(pSld->hdr.gfxIndex, GFX_LINE_STYLE_THIN_SOLID); } state = SLD_STATE_IDLE; // set state to idle #ifdef GFX_CONFIG_BISTABLE_DISPLAY_AUTO_REFRESH_ENABLE GFX_DRIVER_CompleteDrawUpdate(pSld->hdr.left, pSld->hdr.top, pSld->hdr.right, pSld->hdr.bottom); #endif // return as done return (GFX_STATUS_SUCCESS); } } // end of while(1) }
[ "jared@mytrexinc.com" ]
jared@mytrexinc.com
869e2ce0dedebd339b12c70cf6e392c618f8b83a
e5694cdc45c5eb77f699bdccff936f341d0e87e2
/a/tz/tzvmpaaa.c
83ba244752e15c5b39aa9ea50549138368b0dba0
[]
no_license
arksoftgit/10d
2bee2f20d78dccf0b5401bb7129494499a3c547d
4940b9473beebfbc2f4d934fc013b86aa32f5887
refs/heads/master
2020-04-16T02:26:52.876019
2017-10-10T20:27:34
2017-10-10T20:27:34
49,138,607
0
3
null
2016-08-29T13:03:58
2016-01-06T14:02:53
C
UTF-8
C
false
false
67,470
c
///////////////////////////////////////////////////////////////////////////// // // MODULE NAME: tzvmpmaa.c - VML SubSystem Parser Main Module // DESCRIPTION: Setup/ Initialization/ Parse Call // This is the source file which contains the main functions // for the parser. It contains the functions to do all of // the setup as well as start the parse. // // ////////////////////////////////////////////////////////////////////////// // * Copyright (c) 1995 - 2016 QuinSoft, Inc. All rights reserved. * // * Confidential and Proprietary material subject to license - do not * // * reproduce or disclose. This material is an unpublished work and * // * is considered a trade secret belonging to the copyright holder. * // ////////////////////////////////////////////////////////////////////////// // // AUTHOR: Jeffrey S. Beam // DATE: 1992/07/13 // API: MicroSoft foundation classes and Windows 3.1 SDK // ENVIRONMENT: Windows 3.1 // REVISION: 0.9A 1995/08/30 // // LAST MESSAGE ID: VM01008 // // HISTORY: // // 1995/08/05: Beginning of 10B branch // ///////////////////////////////////////////////////////////////////////////// // /* CHANGE LOG 2002.08.29 DGC Added an argument to ParseSource(). 2002.05.08 HH reset scanner after fatal error exit. 2002.03.15 HH support fatal error exit. 2002.03.06 HH improve recognition of Global Operations. 2002.02.28 DKS Remove warnings. 2002.02.04 DGC When XPG is created, it is given the same timestamp as the VML file so that we can better determine when a VML file needs to be parsed. 2001.11.15 HH R55920, set g_szSourceMetaObjectName. 2001.09.09 HH initially delete generated operations from source meta. 2001.08.28 HH added PrintXPG. 2000.10.30 RG Z2000 GetViewByName: for parameter zLEVEL_TASK changed View --> 0 2000.10.25 SR Z2000 Length of path variables Modified the size of file specification variables in function ParseVMLSource and ParseSource because size of attributes ExecDir, MetaSrcDir and PgmSrcDir has been changed to 254 in datamodel. Adjust the size of messagetext variables. 2000.09.21 HH fix bug with empty source file. 2000.08.31 HH added ParserVersion attribute to TZVSPOOO (xpg). OLD CHANGE LOG 13.06.1997 DonC Eliminated reuse of existing XPG as it sometimes created problems and seemed not to help performance. 21.11.1997 HH Remove Tabs 14.03.1998 DonC Initialized variable g_bActivate; 04.11.1998 HH Error Message, if temp file cannot be written. 30.12.1998 HH Restructured German Umlaut Hack. */ #include "tzlodopr.h" #include "tz__oprs.h" #include "tzvsecaa.h" #include "tzvmpopr.hg" #include "ZeidonOp.H" #define LENWORK 256 zPCHAR szMessageListParse[ ] = { "1 -Profile Object could not be accessed, Parse Terminating", "2 -Expression Object could not be accessed, Parse Terminating", "3 -Application's Global Operation List could not be accessed from" "Configuration Management, Parse Terminating", "4 -TaskLPLR could not be accessed, Parse Terminating", "5 -TZOPSIGK.XGO could not be accessed, Parse Terminating", "6 -Could not get a list of LODs, Parse Terminating", "7 -Could not Load Error Object, Parse Terminating", "8 -Source file Meta could not be loaded, parse terminating", "9 -Could not get a list of Registered Views, Parse Terminating", "10 -The expression is too big for the LocalCode work area", "11 -Could not write to temp file, Parse Terminating" }; static zPCHAR RemoveTabs( zPCHAR pchWork, zLONG lMaxLth ); static zVOID fnDeleteGenerated( zVIEW vSourceMeta ); static zVOID fnPrintOperation( zVIEW vXPG ); static zVOID fnPrintVariable( zVIEW vXPG ); static zVOID fnPrintStatement( zVIEW vXPG, zLONG lLevel ); static zVOID fnPrintExpression( sQExprStruct *pWorkExpr, zLONG lLevel ); static zVOID fnPrintOperator( sQExprStruct *pWorkExpr, zCPCHAR szIndent ); ///////////////////////////////////////////////////////////////////////////// // // OPERATIONS: ParseVMLSource // ParseSource // PositionAtOperationInSource // DeleteAllOpersForSource // DeleteOneOperForSource // InitReadBuffer // InitGlobalDataForParse // InitErrorObject // InitExpressionObject // GetTextLine // SaveTextLine // GetProfileData // ReInitOperation // CompareFileToXPG // SkipRemainingFile // IncludeCoreHeader // ///////////////////////////////////////////////////////////////////////////// // // OPERATION: ParseVMLSource // // DESCRIPTION: ParseVMLSource is the main driving function for the parser. // It is passed a Subtask View and the name of the file to be parsed. This // function takes this name and does several things. First it activates // an empty object instance for the parsed vml object (TZVSPOOO). All // of the time saving mechanisms must be done prior to this. That is, // if the fast parsed object (or XPG) already exists, then it should // have been loaded prior to this. Once this function is called the // VML source will be parsed. Once the empty object instance is activated, // the parsing begins to build the instance. If the parsing is successful, // then the parsed object is stored as a fast file. If errors exist, the // instance is deleted. ParseVMLSoiurce initializes the global variables // necessary to parse then calls qqparse (output of yacc.). // // The file name that has been passed in can be either the name of the // source member to be parsed or, it could be the pointer to the // string already. (this allows for faster parsing if, say, the string // of text is already in memory; perhaps in the editor). Whether or not // this is the file name or a pointer to the string depends on the // nOpenMode parameter. If it is 0 then it is a file name, otherwise // it is a 1. // zOPER_EXPORT zLONG OPERATION ParseVMLSource( zVIEW vVML_Subtask, // pointer to the vml task zVIEW vSubtask, // pointer to the appl task zPCHAR pchSrcDirectory, // name of the text file to parse zPCHAR pchFileName, // name of the text file to parse zCPCHAR cpcGenLang ) { zCHAR szSrcDir[ zMAX_FILESPEC_LTH + 1 ]; zCHAR szSourceFileName[ 33 ]; zCHAR szXPGFileName[ 33 ]; zCHAR szOperationName[ 33 ]; zLONG lRC; // return code to test the returns of operation calls GetProfileData( vSubtask, szSrcDir, zsizeof( szSrcDir ), szSourceFileName, zsizeof( szSourceFileName ), szXPGFileName, zsizeof( szXPGFileName ), szOperationName, zsizeof( szOperationName ) ); lRC = ParseSource( vVML_Subtask, 0, /* pointer to the vml task */ g_lParseAction, g_lParseLimit, g_lParseSource, szSourceFileName, szOperationName, 0, 0, cpcGenLang ); return( lRC ); } // lControl - Allows caller to specify what to do with the XPG: // zPARSE_DONOTWRITEXPG - Doesn't drop the XPG object AND doesn't write it to a file. // zOPER_EXPORT zLONG OPERATION ParseSource( zVIEW vVML_Subtask, zVIEW vInSourceMeta, zLONG lIlParseAction, zLONG lIlParseLimit, zLONG lIlParseSource, zPCHAR pchSourceFileName, zPCHAR pchOperationName, zLONG lMetaType, zLONG lControl, zCPCHAR cpcGenLang ) { zVIEW vLPLR; zCHAR szSrcDirectory[ zMAX_FILESPEC_LTH + 1 ]; zCHAR szSrcDirectory2[ zMAX_FILESPEC_LTH + 1 ]; zCHAR szFullXPGPathName[ zMAX_FILESPEC_LTH + 1 ]; zCHAR szErrorFile[ zMAX_FILESPEC_LTH + 1 ]; zCHAR szVML_DateTime[ 30 ]; zCHAR szXGODirectory[ zMAX_FILESPEC_LTH + 1 ]; zCHAR szXPGFileName[ 33 ]; zCHAR szOpGenType[ 2 ]; zVIEW vError; zVIEW vViewObject; zLONG lCompare; zLONG lZKey; zLONG lOrigFile; zLONG lNewFile; zLONG lLineCount = 0; zLONG lRC; // a return code to test the returns of operation calls g_lfHandle = 0; g_szGenLang[ 0 ] = cpcGenLang[ 0 ]; g_szGenLang[ 1 ] = 0; //------------------------------------ Step One --------------------------------------------// // Initialize a global subtask so that every module in the parse has access to the parser subtask. //----------------- Step One ------------------------------// lpGlobalSubtask = vVML_Subtask; //------------------------------------ Step Two --------------------------------------------// // Initialize all of the global data that the parser needs to run. InitGlobalDataForParse( ); // Set the globals that need to be set from parameters. This is redundant if from the // ParseVMLSource call. g_lParseAction = lIlParseAction; g_lParseLimit = lIlParseLimit; g_lParseSource = lIlParseSource; //----------------------------------- Step Three -------------------------------------------// // Get All of the foreign information that is needed to parse ... file names directories etc. // DonC comment, 08/24/95. We are currently assuming that the view of the source meta (which // would be the LOD or the Dialog) is always passed in. We need to re-evaluate later. // Activate the source meta to get the other necessary information. vSource meta could be sent // in from the Editor (or another calling tool) This means that they have it checked out // therefore the parser cannot check it out, so use the view sent in. // If it was not sent in then it's an error. if ( vInSourceMeta == 0 ) { MessageSend( lpGlobalSubtask, "VM01001", "VML Parser", szMessageListParse[ 7 ], zMSGQ_OBJECT_CONSTRAINT_ERROR, zBEEP ); return( -1 ); } else { g_vSourceMeta = vInSourceMeta; // else use the one passed } SetNameForView( g_vSourceMeta, "vParseMeta", lpGlobalSubtask, zLEVEL_TASK ); // Get the Directory for the actual source file text. The directory information is found // in the root of the CM LPLR object. The LPLR object exists by name, "TaskLPLR". // DM - NOTE: szSrcDirectory will carry the full source file name. Bad naming - should get fixed sometime. GetViewByName( &vLPLR, "TaskLPLR", vVML_Subtask, zLEVEL_TASK ); GetStringFromAttribute( szSrcDirectory2, zsizeof( szSrcDirectory2 ), vLPLR, "LPLR", "PgmSrcDir" ); SysConvertEnvironmentString( szSrcDirectory, zsizeof( szSrcDirectory ), szSrcDirectory2 ); SysAppendcDirSep( szSrcDirectory ); strcpy_s( szSrcDirectory2, zsizeof( szSrcDirectory2 ), szSrcDirectory ); // Fill out directory for error file. strcpy_s( szErrorFile, zsizeof( szErrorFile ), szSrcDirectory ); // Stick in the file name. DM - I am assuming the file name was properly passed in!! strcat_s( szSrcDirectory, zsizeof( szSrcDirectory ), pchSourceFileName ); strcat_s( szErrorFile, zsizeof( szErrorFile ), pchSourceFileName ); // Tack on extensions. strcat_s( szSrcDirectory, zsizeof( szSrcDirectory ), ".VML" ); strcat_s( szErrorFile, zsizeof( szErrorFile ), ".ERR" ); // Get the dir name of the Zeidon tools so that we get the XGO directory. zgGetZeidonToolsDir( vVML_Subtask, szXGODirectory, zAPPL_DIR_OBJECT ); // The name of the system core operation list. strcat_s( szXGODirectory, zsizeof( szXGODirectory ), "TZOPSIGK.XGO" ); // Get a view to the TaskLPLR to get the executable dir off of the TaskLPLR Entity. Never // Never Drop this View. lRC = GetViewByName( &vViewObject, "TaskLPLR", vVML_Subtask, zLEVEL_TASK ); // If no LPLR exists get out now. if ( lRC != zLEVEL_TASK ) { MessageSend( lpGlobalSubtask, "VM01002", "VML Parser", szMessageListParse[ 3 ], zMSGQ_OBJECT_CONSTRAINT_ERROR, zBEEP ); return( -1 ); } // Get the ExecDir off of the LPLR Entity. This will be the directory where the xpg is now or will be saved to. GetStringFromAttribute( szFullXPGPathName, zsizeof( szFullXPGPathName ), vViewObject, "LPLR", "ExecDir" ); // Be sure the dir name is terminated with the delimiter. SysAppendcDirSep( szFullXPGPathName ); // For Global Operations and Domain Operations, a work object (type LOD) for the source meta was created and is to be used here // instead of the vInSourceMeta passed to the Parser. g_szSourceMetaObjectName[ 0 ] = 0; if ( lMetaType == zSOURCE_DOMAINGRP_META || lMetaType == zREFER_DOMAINGRP_META ) { // Should never come here, domain operations are not VML. GetViewByName( &g_vSourceMeta, "DGP_SourceFile", vVML_Subtask, zLEVEL_TASK ); strcpy_s( g_szSourceMetaObjectName, zsizeof( g_szSourceMetaObjectName ), "TZDGSRCO" ); } else if ( lMetaType == zSOURCE_GOPGRP_META || lMetaType == zREFER_GOPGRP_META ) { GetViewByName( &g_vSourceMeta, "GOP_SourceFile", vVML_Subtask, zLEVEL_TASK ); strcpy_s( g_szSourceMetaObjectName, zsizeof( g_szSourceMetaObjectName ), "TZOGSRCO" ); } else if ( lMetaType == zSOURCE_SRC_META || lMetaType == zREFER_SRC_META ) { // Special code to recognize a Global Operation, if called from "parsgen". // We must examine the operation type, which is "G" for a Global Operation. zCHAR szOpType[ 2 ] = { 0 }; GetStringFromAttribute( szOpType, zsizeof( szOpType ), g_vSourceMeta, "Operation", "Type" ); if ( szOpType[ 0 ] == 'G' ) { // We recognized the fake. strcpy_s( g_szSourceMetaObjectName, zsizeof( g_szSourceMetaObjectName ), "TZOGSRCO" ); } } if ( g_szSourceMetaObjectName[ 0 ] == 0 ) { // Store the type of the meta (TZZOLODO, TZWDLGSO, ...). MiGetObjectNameForView( g_szSourceMetaObjectName, g_vSourceMeta ); } strcpy_s( szXPGFileName, zsizeof( szXPGFileName ), pchSourceFileName ); strcat_s( szFullXPGPathName, zsizeof( szFullXPGPathName ), szXPGFileName ); // Concat the Extension onto the directory. if ( g_szGenLang[ 0 ] == 'J' ) strcat_s( szFullXPGPathName, zsizeof( szFullXPGPathName ), ".XPJ" ); else strcat_s( szFullXPGPathName, zsizeof( szFullXPGPathName ), ".XPG" ); //-------------------------------------- Step Four -------------------------------------------// // Delete "generated" operations from source meta. Set up support instance needed to parse // like error object expression object etc. fnDeleteGenerated( g_vSourceMeta ); lRC = InitErrorObject( vVML_Subtask, szErrorFile, szSrcDirectory ); // If we have an error, get out now. if ( lRC == -1 ) return( -1 ); // Activate a global expression to manipulate. lRC = InitExpressionObject( ); // If we have an error, get out now. if ( lRC == -1 ) return( -1 ); //-------------------------------------- Step Five -------------------------------------------// // Get or create other needed views from the system such as Get the View to the Global // operation list, LOD list etc. from CM GLOBAL OPERATION LIST. lRC = RetrieveViewForMetaList( vVML_Subtask, &g_lpGOListView, zREFER_GO_META ); // Failed, get out. if ( lRC < 0 ) { // Drop all views already retrieved so they don't hang around. DropObjectInstance( g_lpExprView ); g_lpGOListView = 0; MessageSend( lpGlobalSubtask, "VM01003", "VML Parser", szMessageListParse[ 2 ], zMSGQ_OBJECT_CONSTRAINT_ERROR, zBEEP ); return( -1 ); } // If there are no global operations, this is okay but drop the view and zero it out here // so we don't access it later. if ( CheckExistenceOfEntity( g_lpGOListView, "W_MetaDef" ) != zCURSOR_SET ) { DropView( g_lpGOListView ); g_lpGOListView = 0; } // Now that we have the name, try to load the operation list. lRC = ActivateOI_FromFile( &g_lpZOListView, "TZOPGRPO", vVML_Subtask, szXGODirectory, zSINGLE ); if ( lRC < 0 ) // failed { // Drop all views already retrieved so they dont hang around. g_lpZOListView = 0; if ( g_lpGOListView != 0 ) DropView( g_lpGOListView ); MessageSend( lpGlobalSubtask, "VM01004", "VML Parser", szMessageListParse[ 4 ], zMSGQ_OBJECT_CONSTRAINT_ERROR, zBEEP ); return( -1 ); } // KJS 04/23/13 - I am testing whether it is feasible to have two different zeidon operations one for c generation and one for java. // Loop through operations and delete the ones that are not for the language we are currently generating. lRC = SetCursorFirstEntity( g_lpZOListView, "Operation", "" ); while ( lRC >= zCURSOR_SET ) { szOpGenType[ 0 ] = 0; GetStringFromAttribute( szOpGenType, zsizeof( szOpGenType ), g_lpZOListView, "Operation", "GenerationType" ); if ( szOpGenType[ 0 ] == 'C' && g_szGenLang[ 0 ] == 'J' ) { DropEntity( g_lpZOListView, "Operation", zREPOS_NONE ); } else if ( szOpGenType[ 0 ] == 'J' && g_szGenLang[ 0 ] == 'C' ) { DropEntity( g_lpZOListView, "Operation", zREPOS_NONE ); } lRC = SetCursorNextEntity( g_lpZOListView, "Operation", "" ); } // Get access to the meta list for all LODs LOD LIST. lRC = RetrieveViewForMetaList( vVML_Subtask, &g_vLODList, zREFER_LOD_META ); if ( lRC < 0 ) // failed { // Drop all views already retrieved so they don't hang around. DropObjectInstance( g_lpExprView ); DropMetaOI( vVML_Subtask, g_lpGOListView ); DropMetaOI( vVML_Subtask, g_lpZOListView ); MessageSend( lpGlobalSubtask, "VM01005", "VML Parser", szMessageListParse[ 5 ], zMSGQ_OBJECT_CONSTRAINT_ERROR, zBEEP ); return( -1 ); } // Get access to the meta list for all VORs VOR LIST. lRC = RetrieveViewForMetaList( vVML_Subtask, &g_vVORList, zREFER_VOR_META ); if ( lRC < 0 ) // failed { // Drop all views already retrieved so they don't hang around. DropObjectInstance( g_lpExprView ); DropMetaOI( vVML_Subtask, g_vLODList ); DropMetaOI( vVML_Subtask, g_lpGOListView ); DropMetaOI( vVML_Subtask, g_lpZOListView ); MessageSend( lpGlobalSubtask, "VM01006", "VML Parser", szMessageListParse[ 8 ], zMSGQ_OBJECT_CONSTRAINT_ERROR, zBEEP ); return( -1 ); } // Initialize variables. g_bActivate = FALSE; //////////////////////////////////////////////////////////////////////// // // // At this point we have init'ed the globals, created an expression // // instance, gotten all of the profile data, loaded both Operation // // lists and accessed the lod reference list and have created an // // error object now we are ready to parse code // // // //////////////////////////////////////////////////////////////////////// //-------------------------------------- Step Six --------------------------------------------// // Try to activate the pi (parsed instance) use the NOI_OKAY parameter to NOT get an error // message on the open if it does not exist. // *** Eliminate reuse of old XPG at this time because an error in an old XPG can crash the system. 6/13/97 DonC ActivateEmptyObjectInstance( &g_lpPIView, "TZVSPOOO", vVML_Subtask, zSINGLE ); // Since we had no preexisting XPG, then we cannot parse incrementally therefore, what we need // to do is be sure the flags are set to parse full from a file. g_lParseLimit = zPARSE_LIMIT_SOURCE; g_lParseAction = zPARSE_ACTION_FULL; // Create the PI entities needed the root. CreateEntity( g_lpPIView, "VML_XSource", zPOS_AFTER ); // Set the name. SetAttributeFromString( g_lpPIView, "VML_XSource", "Name", szXPGFileName ); #define PARSER_VERSION 1 // Set The Parser version Attribute. We start with version, 2000.08.31, Version 10d. This is for // compatibility checking, so that interpreter and parser can be synchronized on parser version. SetAttributeFromInteger( g_lpPIView, "VML_XSource", "ParserVersion", PARSER_VERSION ); { // The TimeStamp is not actually used, but might be in future zCHAR szTimestamp[ 22 ]; SysGetDateTime( szTimestamp, zsizeof( szTimestamp ) ); SetAttributeFromString( g_lpPIView, "VML_XSource", "ParseTimeStamp", szTimestamp ); } // Include the sourcemeta into the XPG object. IncludeSubobjectFromSubobject( g_lpPIView, "SourceFile", g_vSourceMeta, "SourceFile", zPOS_AFTER ); // *** Eliminate reuse of old XPG at this time because an error in an old XPG can crash the system. 6/13/97 DonC // If the meta is a LOD, we want to put the LOD Name into the VML_XSource entity for use later // in generating the prefix for Operation Names. if ( zstrcmp( g_szSourceMetaObjectName, "TZZOLODO" ) == 0 ) { SetAttributeFromAttribute( g_lpPIView, "VML_XSource", "MetaName", g_vSourceMeta, "LOD", "Name" ); } // Now create the search global view to the PI. CreateViewFromViewForTask( &g_lpSGView, // view we search with g_lpPIView, 0 ); // view we create and delete with // *** TEMPORARY HACK *** //////////////////////////////////////////////////////////////////////// // // // Copy the source file to a work file, changing German umlaut chars to // a | + the equivalent regular char. Also get rid of any other chars // whose hex value is greater than 80, since the parser crashes if // such characters somehow got into the source. // // //////////////////////////////////////////////////////////////////////// // Build the temporary file name. The directory structure was built above. strcat_s( szSrcDirectory2, zsizeof( szSrcDirectory2 ), "z__temp.vml" ); lOrigFile = SysOpenFile( vVML_Subtask, szSrcDirectory, COREFILE_READ ); // Convert lines from original vml file to temp vml file. if ( lOrigFile >= 0 ) { zPCHAR pchLineIn; zCHAR szLineOut[ 256 ]; lNewFile = SysOpenFile( vVML_Subtask, szSrcDirectory2, COREFILE_WRITE ); if ( lNewFile < 0 ) { // Error opening temp file for write MessageSend( lpGlobalSubtask, "VM01011", "VML Parser", szMessageListParse[ 10 ], zMSGQ_OBJECT_CONSTRAINT_ERROR, zBEEP ); return( -1 ); } else while ( SysReadLine( vVML_Subtask, &pchLineIn, lOrigFile ) == 1 ) { // Copy the input line to the output line, converting German umlaut characters to |x and eliminating other characters with hex value > 80. GermanUmlautHack( pchLineIn, szLineOut, zsizeof( szLineOut ) - 1, FALSE ); SysWriteLine( vVML_Subtask, lNewFile, szLineOut ); lLineCount++; } SysCloseFile( vVML_Subtask, lNewFile, 0 ); SysCloseFile( vVML_Subtask, lOrigFile, 0 ); } else { // Right now we had better just return if there is an open error. return( 0 ); } // If the file is empty - just return. if ( lLineCount <= 0 ) return( 0 ); //------------------------------------- Step Seven -------------------------------------------// // Set up the read buffer to begin reading. Be sure the Source file can be checked out as SOURCE not REFER. lRC = InitReadBuffer( vVML_Subtask, szSrcDirectory2, // fully qualified source name g_lParseSource ); // parse amount flag if ( lRC == -1 ) { // On error drop all views already retrieved so they dont hang around. DropView( g_lpSGView ); DropObjectInstance( g_lpPIView ); DropView( g_vGlobalView ); DropObjectInstance( g_lpExprView ); if ( g_lpGOListView ) DropMetaOI( vVML_Subtask, g_lpGOListView ); DropMetaOI( vVML_Subtask, g_lpZOListView ); SysCloseFile( vVML_Subtask, g_lfErrorHandle, 0 ); return( -1 ); } // Verify that the core header file was included at some point during the parse. It is needed for all source to minimally define some // data types even if it was never referenced in the code. Never being referenced is rare but could possibly happen. lRC = IncludeCoreHeader( g_lpPIView, "KZOENGAA" ); //////////////////////////////////////////////////////////////////////// // // // Ready to do the actual parsing. // // // //////////////////////////////////////////////////////////////////////// // TRY to parse ==========> if ( setjmp( jbFatalError ) == 0 ) { //------------------------------------- Step Eight -------------------------------------------// // Finally we actually begin parsing. Begin parsing based on what flags are set. Switch based on how much code we are going to deal with. switch( g_lParseLimit ) { case zPARSE_LIMIT_SIGNATURES: // only signatures { // switch based on what type of parse we are going to deal with switch( g_lParseAction ) { // if only incremental, update sig that have changed case zPARSE_ACTION_INCREMENTAL: // update the operation entities only (i.e. update line numbers) g_lOperationFlag = 2; // update GetTextLine( ); SaveTextLine( ); // one Pass only will create/update signatures qqparse( vVML_Subtask ); break; // if full, delete all opers and recreate only signatures case zPARSE_ACTION_FULL: // delete all of the operations that exist for this source lRC = DeleteAllOpersForSource( g_lpPIView ); // create all new signatures g_lOperationFlag = 1; // create GetTextLine( ); SaveTextLine( ); // one Pass only will create/update signatures qqparse( vVML_Subtask ); break; } break; } case zPARSE_LIMIT_OPERATION: // do the operation, whose name was sent in { switch( g_lParseAction ) { // check it first to see if the text changed case zPARSE_ACTION_INCREMENTAL: { // do the text comparison first. lRC = GetIntegerFromAttribute( &lZKey, g_lpPIView, "OperationSource", "ZKey" ); lRC = PositionAtOperationInSource( lZKey ); lCompare = CompareFileToXPG( lZKey ); // if these was a change, then we need to reparse it. if ( lCompare != 0 ) { // first we need to lode the file,, reinit the globals TraceLineS( "Must Reparse", pchOperationName ); SysCloseFile( vVML_Subtask, g_lfHandle, 0 ); InitGlobalDataForParse( ); // reread the file/open it InitReadBuffer( vVML_Subtask, szSrcDirectory2, g_lParseSource ); // get position in the XPG and the source lRC = PositionAtOperationInSource( lZKey ); // delete the old one, actually this deletes all of // the statements, variables, and sets the operation // attributes to null so that the ZKeyt does not change // icase it was called locally lRC = DeleteOneOperForSource( g_lpPIView ); // we are going to recreate the operation entity g_lOperationFlag = 1; // create // see if we can get rid of these g_lParseAction = zPARSE_ACTION_FULL; g_lParseLimit = zPARSE_LIMIT_SIGNATURES; SaveTextLine( ); // this should create the OperationTextEntity ??? qqparse( vVML_Subtask ); SysCloseFile( vVML_Subtask, g_lfHandle, 0 ); InitGlobalDataForParse( ); g_lParseLimit = zPARSE_LIMIT_OPERATION; g_lParseAction = zPARSE_ACTION_FULL; InitReadBuffer( vVML_Subtask, szSrcDirectory2, g_lParseSource ); lRC = PositionAtOperationInSource( lZKey ); g_lOperationFlag = 3; // position qqparse( vVML_Subtask ); break; } break; } // full parse of the operation case zPARSE_ACTION_FULL: { lZKey = 0; // initialize to something DKS 2000.03.09? g_lOperationFlag = 1; // create lRC = PositionAtOperationInSource( lZKey ); lRC = DeleteOneOperForSource( g_lpPIView ); g_lOldParseLimit = g_lParseLimit = zPARSE_LIMIT_SIGNATURES; qqparse( vVML_Subtask ); SysCloseFile( vVML_Subtask, g_lfHandle, 0 ); InitGlobalDataForParse( ); g_lParseLimit = zPARSE_LIMIT_OPERATION; g_lParseAction = zPARSE_ACTION_FULL; InitReadBuffer( vVML_Subtask, szSrcDirectory2, g_lParseSource ); lRC = PositionAtOperationInSource( lZKey ); g_lOldParseLimit = zPARSE_LIMIT_OPERATION; g_lParseLimit = zPARSE_LIMIT_OPERATION; g_lOperationFlag = 3; // position qqparse( vVML_Subtask ); break; } } } case zPARSE_LIMIT_SOURCE: // parse the entire source code { switch( g_lParseAction ) { // Loop through all of the operations, delete the ones that have changed and fall through. case zPARSE_ACTION_INCREMENTAL : { // Position at the first operation. lRC = PositionAtOperationInSource( 0 ); do { lRC = GetIntegerFromAttribute( &lZKey, g_lpPIView, "OperationSource", "ZKey" ); lCompare = CompareFileToXPG( lZKey ); // zALL if ( lCompare != 0 ) { SysCloseFile( vVML_Subtask, g_lfHandle, 0 ); InitGlobalDataForParse( ); InitReadBuffer( vVML_Subtask, szSrcDirectory2, g_lParseSource ); lRC = PositionAtOperationInSource( lZKey ); lRC = DeleteOneOperForSource( g_lpPIView ); g_lOldParseLimit = zPARSE_LIMIT_OPERATION; g_lParseLimit = zPARSE_LIMIT_OPERATION; g_lParseAction = zPARSE_ACTION_FULL; g_lOperationFlag = 1; // create SaveTextLine( ); qqparse( vVML_Subtask ); SysCloseFile( vVML_Subtask, g_lfHandle, 0 ); InitGlobalDataForParse( ); g_lParseLimit = zPARSE_LIMIT_OPERATION; g_lParseAction = zPARSE_ACTION_FULL; InitReadBuffer( vVML_Subtask, szSrcDirectory2, g_lParseSource ); lRC = PositionAtOperationInSource( lZKey ); g_lOperationFlag = 3; // position qqparse( vVML_Subtask ); SysCloseFile( vVML_Subtask, g_lfHandle, 0 ); InitGlobalDataForParse( ); InitReadBuffer( vVML_Subtask, szSrcDirectory2, g_lParseSource ); } else { SysCloseFile( vVML_Subtask, g_lfHandle, 0 ); InitGlobalDataForParse( ); InitReadBuffer( vVML_Subtask, szSrcDirectory2, g_lParseSource ); } lRC = PositionAtOperationInSource( 1 ); } while ( lRC == zCURSOR_SET ); break; } case zPARSE_ACTION_FULL: { // Delete all of the operations that exist for this source. lRC = DeleteAllOpersForSource( g_lpPIView ); // Do operations only first ... then the full. g_lParseLimit = zPARSE_LIMIT_SIGNATURES; g_lOldParseLimit = g_lParseLimit; g_lOperationFlag = 1; // create GetTextLine( ); SaveTextLine( ); qqparse( vVML_Subtask ); g_lParseLimit = zPARSE_LIMIT_SOURCE; g_lOldParseLimit = g_lParseLimit; SysCloseFile( vVML_Subtask, g_lfHandle, 0 ); InitGlobalDataForParse( ); InitReadBuffer( vVML_Subtask, szSrcDirectory2, g_lParseSource ); lGlobalReadRetCode = GetTextLine( ); lRC = ResetView( g_lpPIView ); InitGlobalDataForParse( ); g_lOperationFlag = 3; // position qqlineno = 1; qqparse( vVML_Subtask ); break; } } } } //-------------------------------------- Step Nine -------------------------------------------// // Clean up. Commit what is necessary and drop instances no longer needed reset the View to the top. lRC = ResetView( g_lpPIView ); // if ( 0 ) // { // SetNameForView( g_lpPIView, "AfterParse", vVML_Subtask, zLEVEL_TASK ); // IssueError( vVML_Subtask, 0, 0, "AfterParse" ); // } // Don't write the XPG if the user doesn't want it. if ( (lControl & zPARSE_DONOTWRITEXPG) == 0 ) { // store the XPG File lRC = CommitOI_ToFile( g_lpPIView, szFullXPGPathName, zASCII ); // Give the XPG file the same timestamp as the VML file. This will give us a more accurate guide to when the VML file needs to be parsed. lOrigFile = SysOpenFile( vVML_Subtask, szSrcDirectory, COREFILE_READ ); SysGetFileDateTime( lOrigFile, szVML_DateTime, zsizeof( szVML_DateTime ) ); SysCloseFile( vVML_Subtask, lOrigFile, 0 ); SysSetFileTime( szFullXPGPathName, szVML_DateTime, 0 ); } // print xpg if triggered by zeidon.ini // dks { zCHAR szIni[ 16 ] = { 0 }; SysReadZeidonIni( -1, "[Zeidon]", "PrintXPG", szIni, zsizeof( szIni ) ); if ( szIni[ 0 ] == 'Y' || szIni[ 0 ] == 'y' || szIni[ 0 ] == '1' ) PrintXPG( g_lpPIView ); } } else // <========== CATCH fatal error exception { // Return from longjmp ... parse abborted due to fatal error. if ( g_lfHandle > 0 ) SysCloseFile( vVML_Subtask, g_lfHandle, 0 ); qq_reset(); // necessary for re-parse SysMessageBox( vVML_Subtask, "Parse aborted due to fatal error", g_szFatalErrorMsg, zBEEP ); } // Drop the views ... drop the XPG Views and instance. // DropMetaOI( vVML_Subtask, g_vSourceMeta ); DropView( g_lpSGView ); // If the user doesn't want the XPG written to a file, we'll name the view so that the // XPG OI can be retrieved by the caller. if ( lControl & zPARSE_DONOTWRITEXPG ) SetNameForView( g_lpPIView, "XPG", vVML_Subtask, zLEVEL_TASK ); else DropObjectInstance( g_lpPIView ); // Drop the Global Expression view. DropView( g_vGlobalView ); // Drop the Expression view. DropObjectInstance( g_lpExprView ); // Drop the Global operation list. if ( g_lpGOListView ) DropView( g_lpGOListView ); // Drop the LOD list view. DropView( g_vLODList ); DropView( g_vVORList ); // Drop the core operation list view. DropView( g_lpZOListView ); // Close the error file and source file. SysCloseFile( vVML_Subtask, g_lfHandle, 0 ); SysCloseFile( vVML_Subtask, g_lfErrorHandle, 0 ); // Return a return code based on the error object. lRC = GetViewByName( &vError, "TZVMEROO", vVML_Subtask, zLEVEL_TASK ); // If the error object exists, which it better. if ( lRC == zLEVEL_TASK ) { zLONG lCountErrors; // Count the number of entities. If there are any, then there were errors. lCountErrors = CountEntitiesForView( vError, "Error" ); // If none, say so. if ( lCountErrors == 0 ) { CreateEntity( vError, "Error", zPOS_AFTER ); SetAttributeFromString( vError, "Error", "String", "No errors" ); return( 0 ); } else return( -1 ); // more than one means there were errors } // If no view, just get out. return( 0 ); } // // OPERATION: PositionAtOperationInSource // // DESCRIPTION: This function is passed a ZKey, 1, or 0. Its function // is to position the PI View on an operation of that ZKey. To position // an operation in the PI view means to position both the operation // entity as well as the operation source entity. If a 0 is sent in for // the ZKey then position is set to the first operation. If a 1 is sent // then position is sent to the NEXT operation. This is okay since 0 and // 1 can never be ZKeys. // zOPER_EXPORT zLONG OPERATION PositionAtOperationInSource( zLONG lZKey ) { zLONG lLineNumber; zLONG lRC; if ( lZKey == 0 ) // position at first operation { lRC = SetCursorFirstEntity( g_lpPIView, "OperationSource", "" ); } else if ( lZKey == 1 ) // position at next operation { lRC = SetCursorNextEntity( g_lpPIView, "OperationSource", "" ); } else // position at specific operation via zkey { lRC = SetCursorFirstEntityByInteger( g_lpPIView, "OperationSource", "ZKey", lZKey, "" ); } // if it is not there return an error if ( lRC != zCURSOR_SET ) return( lRC ); // now position on the operation entity SetCursorFirstEntityByAttr( g_lpPIView, "Operation", "ZKey", g_lpPIView, "OperationSource", "ZKey", "" ); // position on the first text line SetCursorFirstEntity( g_lpPIView, "OperationText", "" ); // get the line number GetIntegerFromAttribute( &lLineNumber, g_lpPIView, "OperationSource", "LineNumber" ); // this section is to position on the correct line in the text file it re-reads // through the file to the correct line number lGlobalReadRetCode = GetTextLine( ); // fast forward in the file while( qqlineno < lLineNumber ) { lGlobalReadRetCode = GetTextLine( ); } return( 0 ); // success } // // OPERATION: DeleteAllOpersForSource // // DESCRIPTION: Since an XPG file can have multiple source members per, we need to delete // the operations by position from under the source entity. // zOPER_EXPORT zLONG OPERATION DeleteAllOpersForSource( zVIEW vXPGView ) { zLONG lRC; // Start with the first source file. lRC = SetCursorFirstEntity( vXPGView, "OperationSource", "SourceFile" ); // While source entities exist, position on the correct operation entity as well as operation source. while ( lRC >= 0 ) { // Now the operation lRC = SetCursorFirstEntityByAttr( vXPGView, "Operation", "ZKey", vXPGView, "OperationSource", "ZKey", "" ); if ( lRC >= 0 ) // if one is there, do excludes (they were included) { // exclude operation ExcludeEntity( vXPGView, "Operation", zREPOS_NONE ); // exclude operation source positioning at the next lRC = ExcludeEntity( vXPGView, "OperationSource", zREPOS_NEXT ); } else { // if not there go on. lRC = SetCursorNextEntity( vXPGView, "OperationSource", "SourceFile" ); } } // now exclude from the XPG ExcludeEntity( vXPGView, "SourceFile", zREPOS_NONE ); // now re-include it for the parse. IncludeSubobjectFromSubobject( vXPGView, "SourceFile", g_vSourceMeta, "SourceFile", zPOS_AFTER ); return( 0 ); } // // OPERATION: DeleteOneOperForSource // // DESCRIPTION: to delete one operation and any reference to it from the xpg file. What this // really does is EXCLUDE it from the XPG then re-include it. This is so the ZKey of the // operation does not change. If we deleted it and recreated it the ZKey would be no good, // thereby making local calls to this operation no good. // zOPER_EXPORT zLONG OPERATION DeleteOneOperForSource( zVIEW vXPGView ) { // We are already positioned on the correct operation in the XPG object so // key off of it to position in the source. SetCursorFirstEntityByAttr( g_vSourceMeta, "Operation", "ZKey", vXPGView, "Operation", "ZKey", "" ); // Now the source entity. SetCursorFirstEntityByAttr( vXPGView, "OperationSource", "ZKey", vXPGView, "Operation", "ZKey", "" ); // Exclude the operation. This is easier and quicker that deleting all of the statements and // variables, but it essentially does the same thing. ExcludeEntity( vXPGView, "Operation", zREPOS_NONE ); // Ditto here, deletes all of the text lines. ExcludeEntity( vXPGView, "OperationSource", zREPOS_NONE ); // Re-include it back from the Source meta. IncludeSubobjectFromSubobject( vXPGView, "OperationSource", g_vSourceMeta, "Operation", zPOS_AFTER ); return( 0 ); } // // OPERATION: InitReadBuffer // // DESCRIPTION: This function sets up the text buffer for the parser. yylex (actually qqlex) // requires that the string of text be named qqin, and the file handle be g_lfHandle (see qqlex). // Parsing can occur from either a file handle or a buffer. If the buffer parse is requested // then this function simply sets qqin to point to lpBuffer. If a file parse is requested, // then the lpBuffer contains the name (fully qualified) of the file. In that case, this // function opens the file for parsing. // zOPER_EXPORT zLONG OPERATION InitReadBuffer( zVIEW vSubtask, zPCHAR lpBuffer, // buffer or file name. zLONG lParseSource ) // PARSE_FROM_FILE or PARSE_FROM_BUFFER { // zVIEW lpTaskView = GetDefaultViewForActiveTask( ); // View to error object just in case. zVIEW vError; // Init the line number to 0. qqlineno = 0; // Get the error object GetViewByName( &vError, "TZVMEROO", vSubtask, zLEVEL_TASK ); // Do different things depending on what mode of parsing will be needed. switch ( lParseSource ) { case 1: // file // Open the file for reading. g_lfHandle = SysOpenFile( vSubtask, lpBuffer, COREFILE_READ ); // Generateerror if open failed. if ( g_lfHandle == -1 ) { if ( vError ) { CreateEntity( vError, "Error", zPOS_AFTER ); SetAttributeFromString( vError, "Error", "String", "File Open Error!" ); } return( -1 ); } break; case 2: // buffer qqin = lpBuffer; break; case 3: // xpg not implemented break; default: break; } return( 0 ); } // // OPERATION: InitGlobalDataForParse // // DESCRIPTION: Just Zero's out global stuff for parsing. // zOPER_EXPORT zLONG OPERATION InitGlobalDataForParse( void ) { g_lLastTypeDeclared = 0; g_lDeclaredStringLength = 0; g_lEntityNameLength = 18; g_lAttributeNameLength = 32; g_lNumber = 0; g_lSetFNPL = 0; g_lPriorityFudgeFactor = 0; g_nStackPtr = 0; g_nOperStack[ 0 ].lOffset = 0; g_nOperStack[ 0 ].lLevel = 0; g_szViewName[ 0 ] = 0; g_szEntityName[ 0 ] = 0; g_szAttributeName[ 0 ] = 0; g_szScopeEntityName[ 0 ] = 0; g_lViewID = 0; g_lEntityID = 0; g_lScopeEntityID = 0; g_lAttributeID = 0; g_lAddNextStatementBefore = 0; g_lLoopControlID = -1; g_lNeedExtraEnd = 0; g_lParmListIndex = 0; //g_lParmListIndex = 1; g_lLeftDataType = 0; g_lLeftDataClass = 0; g_lRelativeLineNumber = 1; // test g_lFlag = 0; g_lParseAction = 0; g_lSaveText = 0; g_lCount = 0; return( 0 ); } // // OPERATION: InitErrorObject // // DESCRIPTION: Sets up the error object so that SyntaxError // can set up messages. // zOPER_EXPORT zLONG OPERATION InitErrorObject( zVIEW vSubtask, zPCHAR pchErrorFile, // fully qualified file name zPCHAR pchSourceFile ) // name of source file { // zVIEW lpTaskView = GetDefaultViewForActiveTask( ); zVIEW vError; zSHORT nRC; // See if an error object already exists. nRC = GetViewByName( &vError, "TZVMEROO", vSubtask, zLEVEL_TASK ); // If there is, drop it. from last parse. if ( nRC == zLEVEL_TASK ) DropObjectInstance( vError ); // Activate an empty instance of the error object. nRC = ActivateEmptyObjectInstance( &vError, "TZVMEROO", lpGlobalSubtask, zSINGLE ); // If this could not be done, then give an error stating this. Notice we do not use the global error object since this is // what we are trying to load. if ( nRC == -1 ) { MessageSend( lpGlobalSubtask, "VM01007", "VML Parser", szMessageListParse[ 6 ], zMSGQ_OBJECT_CONSTRAINT_ERROR, zBEEP ); return( -1 ); } // Create the root entity. nRC = CreateEntity( vError, "Root", zPOS_AFTER ); // Name the view. nRC = SetNameForView( vError, "TZVMEROO", vSubtask, zLEVEL_TASK ); // Open the error file to write errors too. g_lfErrorHandle = SysOpenFile( vSubtask, pchErrorFile, COREFILE_CREATE ); // Put the name of the source file in the error list as a title. SysWriteLine( vSubtask, g_lfErrorHandle, pchSourceFile ); nRC = SetAttributeFromString( vError, "Root", "SourceFileName", pchSourceFile ); return( 0 ); } // // OPERATION: InitExpressionObject // // DESCRIPTION: This function initializes the expression object so that // it may be manipulated // zOPER_EXPORT zLONG OPERATION InitExpressionObject( zVOID ) { zSHORT nRC; // Activate it empty. nRC = ActivateEmptyObjectInstance( &g_lpExprView, "TZVSEXPO", lpGlobalSubtask, zSINGLE ); // If it could not be activated empty, give an error why. if ( nRC == -1 ) { MessageSend( lpGlobalSubtask, "VM01008", "VML Parser", szMessageListParse[ 1 ], zMSGQ_OBJECT_CONSTRAINT_ERROR, zBEEP ); return( -1 ); } // Create a root expression and a globally accessable view to it. CreateEntity( g_lpExprView, "Root", zPOS_AFTER ); CreateEntity( g_lpExprView, "Expression", zPOS_AFTER ); CreateViewFromViewForTask( &g_vGlobalView, g_lpExprView, 0 ); return( 0 ); } // // OPERATION: GetTextLine // // DESCRIPTION: Reads the next line from the file into qqin and increments the line // number for the next line. // zOPER_EXPORT zLONG OPERATION GetTextLine( ) { lGlobalReadRetCode = SysReadLine( g_lpPIView, &qqin, g_lfHandle ); qqlineno++; if ( lGlobalReadRetCode < 0 ) lGlobalReadRetCode = 0; return( lGlobalReadRetCode ); } // // OPERATION: SaveTextLine // // DESCRIPTION: creates an operation text entity and stores the actual line // // zOPER_EXPORT zLONG OPERATION SaveTextLine( void ) { zCHAR szWork[ LENWORK ]; zLONG lRC; // If we have already stored the entire text git out. if ( g_lOperationFlag > 1 ) // update or position return( 0 ); // This situation exists where we have read in some lines but. if ( g_lSaveText != 0 && (CheckExistenceOfEntity( g_lpPIView, "OperationSource" ) == zCURSOR_SET) ) { zLONG k; lRC = SetCursorLastEntity( g_lpPIView, "PreParseText", "" ); k = qqlineno - g_lRelativeLineNumber; while ( lRC == zCURSOR_SET && k > 0 ) { CreateEntity( g_lpPIView, "OperationText", zPOS_BEFORE ); SetMatchingAttributesByName( g_lpPIView, "OperationText", g_lpPIView, "PreParseText", zSET_ALL ); SetAttributeFromInteger( g_lpPIView, "OperationText", "RelativeLineNumber", k - 1 ); lRC = DeleteEntity( g_lpPIView, "PreParseText", zREPOS_PREV ); k--; } while ( lRC == zCURSOR_SET ) lRC = DeleteEntity( g_lpPIView, "PreParseText", zREPOS_PREV ); SetCursorLastEntity( g_lpPIView, "OperationText", "" ); CreateEntity( g_lpPIView, "OperationText", zPOS_AFTER ); SetAttributeFromInteger( g_lpPIView, "OperationText", "RelativeLineNumber", qqlineno - g_lRelativeLineNumber ); SetAttributeFromString( g_lpPIView, "OperationText", "Text", RemoveTabs( szWork, zsizeof( szWork ) ) ); } else { // Save line. CreateEntity( g_lpPIView, "PreParseText", zPOS_AFTER ); SetAttributeFromInteger( g_lpPIView, "PreParseText", "RelativeLineNumber", qqlineno - g_lRelativeLineNumber ); SetAttributeFromString( g_lpPIView, "PreParseText", "Text", RemoveTabs( szWork, zsizeof( szWork ) ) ); } return( 0 ); } zOPER_EXPORT zLONG OPERATION GetProfileData( zVIEW vSubtask, zPCHAR pchSrcDirectory, zLONG lMaxSrcDirectoryLth, zPCHAR pchSourceFileName, zLONG lMaxSourceFileNameLth, zPCHAR pchXPGFileName, zLONG lMaxXPGFileNameLth, zPCHAR pchOperationName, zLONG lMaxOperationNameLth ) { zVIEW vProfileView; zLONG lLth; zLONG lRC; lRC = oTZ__PRFO_GetViewToProfile( &vProfileView, "VML", vSubtask, zCURRENT_OI ); if ( lRC == 0 ) { GetIntegerFromAttribute( &g_lParseAction, vProfileView, "VML", "ParseAction" ); GetIntegerFromAttribute( &g_lParseLimit, vProfileView, "VML", "ParseLimit" ); GetIntegerFromAttribute( &g_lParseSource, vProfileView, "VML", "ParseSource" ); GetStringFromAttribute( pchSrcDirectory, lMaxSrcDirectoryLth, vProfileView, "VML", "Dir" ); lLth = zstrlen( pchSrcDirectory ); if ( pchSrcDirectory[ lLth ] != '\\' ) { pchSrcDirectory[ lLth ] = '\\'; pchSrcDirectory[ lLth + 1 ] = 0; } lLth = 0; GetStringFromAttribute( pchSourceFileName, lMaxSourceFileNameLth, vProfileView, "VML", "SourceFileName" ); GetStringFromAttribute( pchXPGFileName, lMaxXPGFileNameLth, vProfileView, "VML", "XPGFileName" ); // If the XPG file name is NULL then copy in the SourceFileName. if ( pchXPGFileName[ 0 ] == 0 ) { strcpy_s( pchXPGFileName, lMaxXPGFileNameLth, pchSourceFileName ); } GetStringFromAttribute( pchOperationName, lMaxOperationNameLth, vProfileView, "OP", "PassedName1" ); return( 0 ); } else return( -1 ); } zOPER_EXPORT zLONG OPERATION ReInitOperation( void ) { // Set the LINENUMBER attribute. SetAttributeFromInteger( g_lpPIView, "OperationSource", "LineNumber", -1 ); return( 0 ); } zOPER_EXPORT zLONG OPERATION CompareFileToXPG( zLONG lZKey ) { zLONG lCompare; zLONG lRC; SetCursorFirstEntityByInteger( g_lpPIView, "OperationSource", "ZKey", lZKey, ""); // Compare the current line to what was stored. lCompare = CompareAttributeToString( g_lpPIView, "OperationText", "Text", qqin ); // As long as the lines are equal and there are more text attributes, loop. lRC = zCURSOR_SET; while ( lCompare == 0 && lRC == zCURSOR_SET ) { // Last was good, get the next from the file. lRC = GetTextLine( ); if ( lRC < 0 ) return( -1 ); // Get the next from the XPG. lRC = SetCursorNextEntity( g_lpPIView, "OperationText", "" ); // If these was one there, compare. if ( lRC == zCURSOR_SET ) lCompare = CompareAttributeToString( g_lpPIView, "OperationText", "Text", qqin ); } return( lCompare ); } zOPER_EXPORT zLONG OPERATION SkipRemainingFile( ) { lGlobalReadRetCode = SysReadLine( g_lpPIView, &qqin, g_lfHandle ); while ( lGlobalReadRetCode > 0 ) { lGlobalReadRetCode = SysReadLine( g_lpPIView, &qqin, g_lfHandle ); qqlineno++; } return( lGlobalReadRetCode ); } zOPER_EXPORT zLONG OPERATION IncludeCoreHeader( zVIEW lpView, zPCHAR pchHeaderName ) { zLONG lZKey; zLONG lRC; lRC = SetCursorFirstEntityByString( g_lpZOListView, "HeaderFile", "Name", pchHeaderName, "" ); if ( lRC > zCURSOR_UNCHANGED ) { GetIntegerFromAttribute( &lZKey, g_lpZOListView, "HeaderFile", "ZKey" ); lRC = SetCursorFirstEntityByInteger( lpView, "ExternalHeaderFile", "ZKey", lZKey, "" ); if ( lRC < zCURSOR_SET ) { SetCursorLastEntity( lpView, "ExternalHeaderFile", "" ); IncludeSubobjectFromSubobject( lpView, "ExternalHeaderFile", g_lpZOListView, "HeaderFile", zPOS_AFTER ); } } return( 0 ); } static zPCHAR RemoveTabs( zPCHAR pchWork, zLONG lMaxLth ) { zPCHAR pch; zSHORT nTab = 0; zSHORT nLth = (zSHORT) zstrlen( qqin ); // Count the tabs. pch = qqin; while ( (pch = zstrchr( pch,'\t' )) != 0 ) { nTab++; pch++; } if ( nTab == 0 ) return( qqin ); // nothing to do // For each tab we need 2 more bytes in the workarea. if ( nLth + 2 * nTab >= LENWORK - 1 ) { // The workstring is not large enough, so we replace each tab in qqin by a blank and return qqin without using the workstring. pch = qqin; while ( (pch = zstrchr( pch, '\t' )) != 0 ) { *pch = ' '; pch++; } return( qqin ); } else { // There is enouch space in pchWork we substitute each tab by 3 blanks. zPCHAR pchSource = qqin; zPCHAR pchTarget = pchWork; zLONG k, n; while ( (pch = zstrchr( pchSource, '\t' ) ) != 0 ) { k = pch - pchSource; if ( k > 0 ) zmemcpy( pchTarget, pchSource, k ); pchTarget += k; for ( n = 0; n < 3; n++ ) *(pchTarget++) = ' '; pchSource = ++pch; } // Lastly, move the rest of the string or add a zero-Byte to target. if ( *pchSource ) strcpy_s( pchTarget, lMaxLth, pchSource ); else *pchTarget = 0; return( pchWork ); } } //////////////////////////////////////////////// // // >>>PrintXPG // // PURPOSE: Print XPG object to Engine Trace Window // // DESCRIPTION: // go Operations, Variables, Statements // resolve exprexions and print everything to Trace Window // // PARAMETER: // zVIEW vXPG = the object (based on LOD TZVSPOOO) to be printed // // RETURNS: zLONG // 0 ==> ok // otherwise ==> Error // //////////////////////////////////////////////// zOPER_EXPORT zLONG OPERATION PrintXPG( zVIEW vXPG ) { zSHORT nRC; // For Each Operation ... nRC = SetCursorFirstEntity( vXPG, "Operation", 0 ); while ( nRC >= zCURSOR_SET ) { zSHORT nRC2; // print operation detail fnPrintOperation( vXPG ); // loop over variables nRC2 = SetCursorFirstEntity( vXPG, "Variable", 0 ); while ( nRC2 >= zCURSOR_SET ) { // print variable detail fnPrintVariable( vXPG ); nRC2 = SetCursorNextEntity( vXPG, "Variable", 0 ); } // loop over statements nRC2 = SetCursorFirstEntity( vXPG, "Statement", 0 ); while ( nRC2 >= zCURSOR_SET ) { // print statement detail fnPrintStatement( vXPG, 1 ); nRC2 = SetCursorNextEntity( vXPG, "Statement", 0 ); } nRC = SetCursorNextEntity( vXPG, "Operation", 0 ); } return( 0 ); } //////////////////////////////////////////////// // // >>>fnPrintOperation // // Print XPG "Operation" to Engine Trace Window // //////////////////////////////////////////////// static zVOID fnPrintOperation( zVIEW vXPG ) { zCHAR szLine[ 256 ]; zCHAR szOperation[ 33 ] = { 0 }; zLONG lZKey = 0; zCHAR szType[ 2 ] = { 0 }; zCHAR szReturnDataType[ 2 ] = { 0 }; GetStringFromAttribute( szOperation, zsizeof( szOperation ), vXPG, "Operation", "Name" ); GetIntegerFromAttribute( &lZKey, vXPG, "Operation", "ZKey" ); // Description is skipped GetStringFromAttribute( szType, zsizeof( szType ), vXPG, "Operation", "Type" ); // ReturnDesc is skipped GetStringFromAttribute( szReturnDataType, zsizeof( szReturnDataType ), vXPG, "Operation", "ReturnDataType" ); // OrdinalValue is skipped // CurrentDebugFlag is skipped // C_GeneratedOperationName is skipped sprintf_s( szLine, zsizeof( szLine ), "Operation=%s ZKey=%ld Type=%s ReturnType=%s", szOperation, lZKey, szType, szReturnDataType ); TraceLineS( "", "" ); TraceLineS( szLine, "" ); } //////////////////////////////////////////////// // // >>>fnPrintVariable // // Print XPG "Variable" to Engine Trace Window // //////////////////////////////////////////////// static zVOID fnPrintVariable( zVIEW vXPG ) { zCHAR szLine[ 256 ]; zLONG lID = 0; zLONG lParameterFlag = 0; zLONG lVMLType = 0; zLONG lDataType = 0; zLONG lNElements = 0; zLONG lLineNumber = 0; zCHAR szName[ 33 ] = { 0 }; zCHAR szPFlag[ 2 ] = { 0 }; zCHAR szUFlag[ 2 ] = { 0 }; GetIntegerFromAttribute( &lID, vXPG, "Variable", "ID" ); GetIntegerFromAttribute( &lParameterFlag, vXPG, "Variable", "ParameterFlag" ); GetStringFromAttribute( szName, zsizeof( szName ), vXPG, "Variable", "Name" ); GetIntegerFromAttribute( &lVMLType, vXPG, "Variable", "VMLType" ); GetIntegerFromAttribute( &lDataType, vXPG, "Variable", "DataType" ); GetIntegerFromAttribute( &lNElements, vXPG, "Variable", "NElements" ); // Modify is skipped // Value is skipped GetIntegerFromAttribute( &lLineNumber, vXPG, "Variable", "LineNumber" ); GetStringFromAttribute( szPFlag, zsizeof( szPFlag ), vXPG, "Variable", "PFlag" ); GetStringFromAttribute( szUFlag, zsizeof( szUFlag ), vXPG, "Variable", "UFlag" ); sprintf_s( szLine, zsizeof( szLine ), " Variable=%s ID=%ld Parameter=%ld VMLType=%ld DataType=%ld NElements=%ld LineNumber=%ld PFlag=%s UFlag=%s", szName, lID, lParameterFlag, lVMLType, lDataType, lNElements, lLineNumber, szPFlag, szUFlag ); TraceLineS( szLine, "" ); } //////////////////////////////////////////////// // // >>>fnPrintStatement // // Print XPG "Statement" to Engine Trace Window // Print Substatements recursively // //////////////////////////////////////////////// static zVOID fnPrintStatement( zVIEW vXPG, zLONG lLevel ) { zCHAR szIndent[ 91 ] = { 0 }; zCHAR szClass[ 33 ] = { 0 }; zCHAR szLine[ 256 ]; zLONG lLineNumber = 0; zLONG lClass = 0; zCHAR szExprCode[ EXPRCODE_MAXSTRING ]; zCHAR szExprText[ EXPRTEXT_MAXSTRING ]; sQExprStruct sWorkExpr = { 0 }; zLONG lParameterFlag = 0; zLONG lVMLType = 0; zLONG lDataType = 0; zLONG lNElements = 0; zULONG uCodeLth; zULONG uTextLth; zULONG nExprIndex; int k; // indentation for ( k = 0; k < lLevel; k++ ) strcat_s( szIndent, zsizeof( szIndent ), " " ); GetIntegerFromAttribute( &lLineNumber, vXPG, "Statement", "LineNumber" ); GetIntegerFromAttribute( &lClass, vXPG, "Statement", "Class" ); switch ( lClass ) { case qEXPRESSION: strcpy_s( szClass, zsizeof( szClass ), "qEXPRESSION" ); break; case qWHILE: strcpy_s( szClass, zsizeof( szClass ), "qWHILE" ); break; case qEND: strcpy_s( szClass, zsizeof( szClass ), "qEND" ); break; case qRETURN: case qRETURNEND: strcpy_s( szClass, zsizeof( szClass ), "qRETURN" ); break; case qIF: strcpy_s( szClass, zsizeof( szClass ), "qIF" ); break; case qFOR: strcpy_s( szClass, zsizeof( szClass ), "qFOR" ); break; } sprintf_s( szLine, zsizeof( szLine ), "*STATEMENT* LineNumber=%ld Class=%s(%ld)", lLineNumber, szClass, lClass ); TraceLineS( "", "" ); TraceLineS( szIndent, szLine ); uCodeLth = EXPRCODE_MAXSTRING; GetBlobFromAttribute( szExprCode, &uCodeLth, vXPG, "Statement", "Expression" ); uTextLth = EXPRTEXT_MAXSTRING; GetBlobFromAttribute( szExprText, &uTextLth, vXPG, "Statement", "ExprText" ); // loop over expressions nExprIndex = 0; while ( nExprIndex < uCodeLth ) { zmemcpy( (zPCHAR) &sWorkExpr, (zPCHAR) &szExprCode[ nExprIndex ], sizeof( sQExprStruct ) - MAXSTRING ); fnPrintExpression( &sWorkExpr, lLevel ); nExprIndex += sizeof( sQExprStruct ) - MAXSTRING; } if ( uTextLth ) { for ( k = 0; k < (int) uTextLth - 1; k++ ) { if ( szExprText[ k ] == 0 ) szExprText[ k ] = ' '; } sprintf_s( szLine, zsizeof( szLine ), "%s ExpressionText=", szIndent ); TraceLineS( szLine, szExprText ); } // recursion to SubStatement if ( CheckExistenceOfEntity( vXPG, "Substatement" ) >= zCURSOR_SET ) { zSHORT nRC2; nRC2 = SetCursorFirstEntity( vXPG, "Substatement", 0 ); while ( nRC2 >= zCURSOR_SET ) { // recurse down SetViewToSubobject( vXPG, "Substatement" ); fnPrintStatement( vXPG, lLevel + 1 ); ResetViewFromSubobject( vXPG ); nRC2 = SetCursorNextEntity( vXPG, "Substatement", 0 ); } } } //////////////////////////////////////////////// // // >>>fnPrintExpression // // Print XPG Expressionto Engine Trace Window // //////////////////////////////////////////////// static zVOID fnPrintExpression( sQExprStruct *pWorkExpr, zLONG lLevel ) { zCHAR szIndent[ 91 ] = { 0 }; zCHAR szElementClass[ 33 ] = { 0 }; zCHAR szDataClass[ 33 ] = { 0 }; zCHAR szDataType[ 33 ] = { 0 }; zCHAR szLine[ 256 ] = { 0 }; int k; // indentation for ( k = 0; k < lLevel; k++ ) strcat_s( szIndent, zsizeof( szIndent ), " " ); switch( pWorkExpr->lElementClass ) { case qVARIABLE: strcpy_s( szElementClass, zsizeof( szElementClass ), "qVARIABLE" ); break; case qDEFINE: strcpy_s( szElementClass, zsizeof( szElementClass ), "qDEFINE" ); break; case qCONSTANT: strcpy_s( szElementClass, zsizeof( szElementClass ), "qCONSTANT" ); break; case qATTRIBUTEQUALIFIER: strcpy_s( szElementClass, zsizeof( szElementClass ), "qATTRIBUTEQUALIFIER" ); break; case qOPERATIONCALL: strcpy_s( szElementClass, zsizeof( szElementClass ), "qOPERATIONCALL" ); break; case qOPERATOR: fnPrintOperator( pWorkExpr, szIndent ); return; } switch( pWorkExpr->lDataClass ) { case qTEXT: strcpy_s( szDataClass, zsizeof( szDataClass ), "qTEXT" ); break; case qNUMERIC: strcpy_s( szDataClass, zsizeof( szDataClass ), "qNUMERIC" ); break; } switch( pWorkExpr->lDataType ) { case qTINTEGER: strcpy_s( szDataType, zsizeof( szDataType ), "qTINTEGER" ); break; case qTDECIMAL: strcpy_s( szDataType, zsizeof( szDataType ), "qTDECIMAL" ); break; case qTSHORT: strcpy_s( szDataType, zsizeof( szDataType ), "qTSHORT" ); break; case qTSTRING: strcpy_s( szDataType, zsizeof( szDataType ), "qTSTRING" ); break; case qTCHARACTER: strcpy_s( szDataType, zsizeof( szDataType ), "qTCHARACTER" ); break; case qTUNKNOWN: strcpy_s( szDataType, zsizeof( szDataType ), "qTUNKNOWN" ); break; } sprintf_s( szLine, zsizeof( szLine ), "%s DataClass=%s(%ld) DataType=%s(%ld) Offset=%ld Level=%ld Flags=%ld", szElementClass, szDataClass, pWorkExpr->lDataClass, szDataType, pWorkExpr->lDataType, pWorkExpr->lOffset, pWorkExpr->lLevel, pWorkExpr->lFlags ); TraceLineS( szIndent, szLine ); } //////////////////////////////////////////////// // // >>>fnPrintOperator // // Print XPG Operator to Engine Trace Window // //////////////////////////////////////////////// static zVOID fnPrintOperator( sQExprStruct *pWorkExpr, zCPCHAR szIndent ) { zCHAR szOffset[ 33 ] = { 0 }; zCHAR szLine[ 256 ] = { 0 }; switch ( pWorkExpr->lOffset ) { case qLPAREN: strcpy_s( szOffset, zsizeof( szOffset ), "qLPAREN" ); break; case qRPAREN: strcpy_s( szOffset, zsizeof( szOffset ), "qRPAREN" ); break; case qOPENOPER: strcpy_s( szOffset, zsizeof( szOffset ), "qOPENOPER" ); break; case qCLOSEOPER: strcpy_s( szOffset, zsizeof( szOffset ), "qCLOSEOPER" ); break; case qCOMMA: strcpy_s( szOffset, zsizeof(szOffset), "qCOMMA" ); break; case qPERIOD: strcpy_s( szOffset, zsizeof( szOffset ), "qPERIOD" ); break; case qEQUAL: strcpy_s( szOffset, zsizeof( szOffset ), "qEQUAL" ); break; case qMINUS: strcpy_s( szOffset, zsizeof( szOffset ), "qMINUS" ); break; case qADDITION: strcpy_s( szOffset, zsizeof( szOffset ), "qADDITION" ); break; case qMULTIPLICATION: strcpy_s( szOffset, zsizeof( szOffset ), "qMULTIPLICATION" ); break; case qDIVISION: strcpy_s( szOffset, zsizeof( szOffset ), "qDIVISION" ); break; case qCONDEQUAL: strcpy_s( szOffset, zsizeof( szOffset ), "qCONDEQUAL" ); break; case qLESSTHANEQUAL: strcpy_s( szOffset, zsizeof( szOffset ), "qLESSTHANEQUAL" ); break; case qLESSTHAN: strcpy_s( szOffset, zsizeof( szOffset ), "qLESSTHAN" ); break; case qGREATERTHANEQUAL: strcpy_s( szOffset, zsizeof( szOffset ), "qGREATERTHANEQUAL" ); break; case qGREATERTHAN: strcpy_s( szOffset, zsizeof( szOffset ), "qGREATERTHAN" ); break; case qNOTEQUAL: strcpy_s( szOffset, zsizeof( szOffset ), "qNOTEQUAL" ); break; case qNOT: strcpy_s( szOffset, zsizeof( szOffset ), "qNOT" ); break; case qAND: strcpy_s( szOffset, zsizeof( szOffset ), "qAND" ); break; case qOR: strcpy_s( szOffset, zsizeof( szOffset ), "qOR" ); break; } sprintf_s( szLine, zsizeof( szLine ), "qOPERATOR Offset=%s(%ld)", szOffset, pWorkExpr->lOffset ); TraceLineS( szIndent, szLine ); } // >>>fnDeleteGenerated // delete generated operations from source meta // static zVOID fnDeleteGenerated( zVIEW vSourceMeta ) { zSHORT nRC; zVIEW vSearchView; CreateViewFromViewForTask( &vSearchView, vSourceMeta, 0 ); nRC = SetCursorFirstEntity( vSearchView, "Operation", 0 ); while ( nRC >= zCURSOR_SET ) { zCHAR szOperName[ 33 ]; zLONG lClass = 0; GetStringFromAttribute( szOperName, zsizeof( szOperName ), vSearchView, "Operation", "Name" ); GetIntegerFromAttribute( &lClass, vSearchView, "Operation", "Class" ); if ( zstrlen( szOperName ) > 7 && memcmp( szOperName, "fnLocal", 7 ) == 0 && (lClass & 0x00000001) != 0 ) { DeleteEntity( vSearchView, "Operation", zREPOS_NONE ); } nRC = SetCursorNextEntity( vSearchView, "Operation", 0 ); } DropView( vSearchView ); }
[ "arksoft@comcast.net" ]
arksoft@comcast.net
b84d1c50074dd3d3f4d1127a529871b59c103336
f3c6c4c5a86466f66cf439f7dc08366222be4cb1
/src/boundary/fixed.c
d952d2d647a77a3820f2de3774deb4f4996574d2
[ "MIT" ]
permissive
sativa/hydro2d
5bb6793cfb9833c9f8625e05c4b557268c13f190
383b680bb5b8ffe2d9d436f926a6ba7b1220dff6
refs/heads/master
2021-01-18T15:16:25.311350
2016-06-14T02:23:17
2016-06-14T02:23:17
null
0
0
null
null
null
null
UTF-8
C
false
false
2,137
c
#include <stdlib.h> #include "../boundary.h" #include "../geom.h" #include "../grid.h" #include "../initial.h" #include "../par.h" // Fixed (dirichlet) boundary condition. void bc_1L_fixed(struct grid *g, struct parList *par) { int nq = g->nq; int nx2 = g->nx2; int d1 = g->d1; int d2 = g->d2; int ng11 = g->ng11; int i, j; for(i=0; i<ng11; i++) for(j=0; j<nx2; j++) { double xm[2] = {g->x1[i], g->x2[j]}; double xp[2] = {g->x1[i+1], g->x2[j+1]}; double x[2]; geom_CM(xm, xp, x); initial_value(&(g->prim[d1*i+d2*j]), x, nq, par); } } void bc_1R_fixed(struct grid *g, struct parList *par) { int nq = g->nq; int nx1 = g->nx1; int nx2 = g->nx2; int ng12 = g->ng12; int d1 = g->d1; int d2 = g->d2; int i, j; for(i=nx1-ng12; i<nx1; i++) for(j=0; j<nx2; j++) { double xm[2] = {g->x1[i], g->x2[j]}; double xp[2] = {g->x1[i+1], g->x2[j+1]}; double x[2]; geom_CM(xm, xp, x); initial_value(&(g->prim[d1*i+d2*j]), x, nq, par); } } void bc_2L_fixed(struct grid *g, struct parList *par) { int nq = g->nq; int nx1 = g->nx1; int ng21 = g->ng21; int d1 = g->d1; int d2 = g->d2; int i, j; for(i=0; i<nx1; i++) for(j=0; j<ng21; j++) { double xm[2] = {g->x1[i], g->x2[j]}; double xp[2] = {g->x1[i+1], g->x2[j+1]}; double x[2]; geom_CM(xm, xp, x); initial_value(&(g->prim[d1*i+d2*j]), x, nq, par); } } void bc_2R_fixed(struct grid *g, struct parList *par) { int nq = g->nq; int nx1 = g->nx1; int nx2 = g->nx2; int ng22 = g->ng22; int d1 = g->d1; int d2 = g->d2; int i, j; for(i=0; i<nx1; i++) for(j=nx2-ng22; j<nx2; j++) { double xm[2] = {g->x1[i], g->x2[j]}; double xp[2] = {g->x1[i+1], g->x2[j+1]}; double x[2]; geom_CM(xm, xp, x); initial_value(&(g->prim[d1*i+d2*j]), x, nq, par); } }
[ "geoffrey.s.ryan@gmail.com" ]
geoffrey.s.ryan@gmail.com
c87b336908e3348e25e05d97267c2b54f6104606
ac8a5cbd3996c03b45acaf3903015029cb8f65ae
/INF1301-Trab04-MRSFTL/Fontes/GENERICO.H
17103f05e67b25b395563e73fa0c73959b9682a0
[]
no_license
stephaniefay/INF1301
4ca3cc0cf580e07c5cc049d7b4aa33766edc62a3
032dd82d83967990e0e15501d47a1739e05376d3
refs/heads/master
2021-05-31T18:07:41.210099
2016-05-14T01:19:36
2016-05-14T01:19:36
null
0
0
null
null
null
null
ISO-8859-1
C
false
false
27,514
h
#if ! defined( GENERICO_ ) #define GENERICO_ /*************************************************************************** * * $MCD Modulo de definicao: TSTG Controlador de teste generico * * Arquivo gerado: GENERICO.h * Letras identificadoras: TST * * Nome da base de software: Arcabouco para a automacao de testes de programas redigidos em C * Arquivo da base de software: C:\AUTOTEST\PROJETOS\INSTRUM.BSW * * Projeto: INF 1301 / 1628 Automatizacao dos testes de modulos C * Gestor: LES/DI/PUC-Rio * Autores: avs * * $HA Historico de evolucao: * Versao Autor Data Observacoes * 4 avs 01/fev/2006 criar linguagem script simbolica * 3 avs 08/dez/2004 uniformizacao dos exemplos * 2 avs 07/jul/2003 unificacao de todos os modulos em um so projeto * 1 avs 16/abr/2003 inicio desenvolvimento * * $ED Descricao do modulo * O modulo de teste generico contem um conjunto de funcoes de * coordenacao, apoio e controle da execucao de testes de modulos * quaisquer. * * Embora na pratica a funcao de teste especifica seja uma extensao da * funcao de teste generica, a funcao de teste especifica encontra-se em * outro modulo. Desta forma as alteracoes necessarias para cada * modulo a testar concentram-se exclusivamente naquele modulo. * * $EIU Interface com o usuario pessoa * Os seguintes comandos genericos estao definidos: * * linha em branco - faz nada * * // - comentario, e impresso no LOG * * == - titulo de caso de teste, o titulo e impresso no LOG * * =recuperar * - Caso o comando imediatamente anterior ao comando * =recuperar retorne TST_CondRetOK, obviemanete o comando * executou corretamente, portanto o comando =recuperar * reportara uma falha no script de teste, uma vez que nao * foi encontrada a falha esperada ao executar o comando. * - Caso o comando antecessor retorne TST_CondRetErro, * ou TST_CondRetParm (erro de parâmetros do comando) * a falha reportada sera desconsiderada, uma vez que * era esperada. O comando =recuperar destina-se a * apoiar o teste da corretude dos validadores de * parâmetros dos comandos e das funcoes por eles * ativadas. * - caso o comando antecessor retorne outras condicoes, o * comando =recuperar sera tratado como falha. * * =bkpt - permite interagir com o depurador utilizado para * desenvolver os modulos sob teste. O comando =bkpt * executa um codigo "dummy" no qual pode ser inserido * um "breakpoint" do depurador. Desta forma o teste pode * prosseguir sem interrupcao ate o comando =bkpt. * Para isto * - apague ou desative todos os breakpoints do depurador * - insira o comando =bkpt no script pouco antes do ponto * de interrupcao desejado * - usando o depurador, estabeleca um breakpoint na linha de * codigo: "Dummy = 0 ;" contida no modulo de teste * generico. Esta linha pode ser encontrada * procurando por "BKPT_CMD" * - de partida no programa e espere ate chegar ao breakpoint * associado ao comando "dummy". Agora reative ou instale * os breakpoints requeridos pela a sessao de depuracao. * e continue depurando * * =cancelar * - termina a interpretacao dos comandos de teste. * Sempre sinaliza falha. * * =AceitaFalhasAcumuladas numFalhas * - caso o contador de falhas registre numFalhas, ele sera * tornado zero. Este comando e similar a =recuperar. * Difere deste por ser executado desde que o comando * anterior nao tenha reportado erro, tal como acontece * com todos os comandos, exceto =recuperar. * O comando permite recuperar falhas sinalizadas por * modulos de apoio, tais como, leitor de parâmetros, * contador de passagens e controle de espaco dinâmico. * Caso o contador de número de falhas contenha um valor * diferente de numFalhas, sera reportado um erro e * o contador e incrementado de 1. * * Os demais comandos sao passados para as funcoes de teste especifico. * Primeiro para as do arcabouco, depois para a especifica do modulo * a testar. A última funcao de teste especifico deve retornar a condicao * TST_CondRetNaoConhec caso nao consiga interpretar a diretiva. * * $EIM Interface com outros modulos * A primeira funcao do arcabouco ("framework") a ser chamada deve a * sempre ser TST_InicializarTeste. Caso nao o seja, ocorrerao erros * de execucao (assert). * * Apos abra o arquivo de script executando a funcao * TST_AbrirArquivoScript. Se for desejado gerar um log abra * o arquivo corresponente com a funcao TST_AbrirArquivoLog. * * Depois de abrir os arquivos, execute os testes chamando a funcao * TST_RealizarTeste. A funcao de teste generico lera todo o arquivo * de script, retornando apos concluir o teste. * * Apos, termine o teste atraves da funcao TST_TerminarTeste. * Esta funcao exibe as estatisticas do teste e, caso solicitado, * acumula essas estatisticas em um arquivo acumulador (ver * parâmetro /a do programa principal. * * As funcoes "TST_ObterXXX" podem ser utilizadas antes de fechar o * modulo de teste para exibir o resumo do teste no modulo cliente do * modulo de controle generico. * * O programa cliente do modulo controle de teste generico pode * efetuar as operacoes acima repetidas vezes, permitindo, assim o * teste envolvendo diversos arquivos scripts de teste. A saida * de cada teste deve ser dirigida para um log especifico, ou para * stdout, uma vez que, ao abrir um arquivo log, o seu conteúdo sera * sempre destruido. * * O modulo de teste generico tambem implementa diversas funcoes * de comparacao "TST_CompararXXX" use-as no modulo de controle de * teste especifico. Desta forma sera assegurado o tratamento uniforme * de todas as falhas possivelmente encontradas. * * O modulo disponibiliza ainda a funcao TST_ExibirPrefixo * que gera uma linha de saida obedecendo aos padroes de interface * estabelecidos. Sendo desejado pode-se adicionar textos à linha * usando a funcao fprintf( TST_pArqLog , ... ). Um exemplo disso * e quando se deseja imprimir informacao complementar ao interpretar * uma determinada diretiva. * * Finalmente, o modulo disponibiliza a funcao TST_NotificarFalha * que incrementa o contador de falhas alem de emitir uma mensagem * de erro. * ***************************************************************************/ #if defined( GENERICO_OWN ) #define GENERICO_EXT #else #define GENERICO_EXT extern #endif /***** Declaracoes exportadas pelo modulo *****/ #include "TST_Espc.h" /*********************************************************************** * * $TC Tipo de dados: TST Cond ret modulo de teste generico * * ***********************************************************************/ typedef enum { TST_CondOK , /* Generico executou correto */ TST_CondNaoAbriu /* Generico nao abriu arquivo */ } TST_tpCond ; /*********************************************************************** * * $FC Funcao: TSTG &Inicializar o modulo de teste * * $ED Descricao da funcao * Inicializa todas as variaveis globais exportadas e encapsuladas * do modulo de teste generico. * * Embora pouco recomendavel (ver descricao do modulo TesteSpc) * esta funcao pode ser alterada para assegurar o estabelecimento * do contexto inicial do modulo TesteSpc. Este deve conter uma * funcao de inicializacao a ser chamada pela presente funcao. * ***********************************************************************/ void TST_InicializarTeste( void ) ; /*********************************************************************** * * $FC Funcao: TSTG &Terminar a execucao do modulo de teste * * $ED Descricao da funcao * Fecha todos os arquivos e desaloca todos os espacos de dados * alocados sob controle do modulo de teste generico * ***********************************************************************/ void TST_TerminarTeste( void ) ; /*********************************************************************** * * $FC Funcao: TSTG &Obter origem do nome da extensao de arquivo * * $ED Descricao da funcao * Procura o inicio do nome da extensao contido no nome do arquivo * dado por parâmetro * * Evite o uso de nomes de arquivos com dois ou mais caracteres ".". * Isto pode confundir no caso de se desejar a adicao de algum nome * de extensao padrao. * * $EP Parâmetros * $P NomeArqParm - nome de arquivo a ser analisado * * $FV Valor retornado * Ponteiro para o caractere '.' que separa a extensao. * Sera NULL caso o nome do arquivo nao contenha extensao. * ***********************************************************************/ char * TST_ObterInicioExtensao( char * NomeArqParm ) ; /*********************************************************************** * * $FC Funcao: TSTG &Abrir arquivo log * * $ED Descricao da funcao * Abre o arquivo log a ser utilizado como saida durante os testes. * Todas as saidas geradas pelo modulo de teste sao dirigidos para * este arquivo. Caso nao tenha sido aberto, sera utilizado o * arquivo stdout. * * A extensao default do arquivo log e ".log" e sera acrescida ao nome * do arquivo caso este nao contenha nome de extensao. * * $EP Parâmetros * $P NomeArqParm - nome do arquivo. Pode (deve) ser um nome relativo * ao diretorio corrente. Caso o arquivo * exista, sera destruido sem perguntar se pode. * * $FV Valor retornado * TST_CondRetOK - abriu corretamente * TST_CondRetNaoAbriu - ocorreu algum problema ao tentar abrir. * O problema nao e descriminado. * O arquivo de saida do log volta a ser stdout * * $EIU Interface com usuario pessoa * Esta funcao deve ser chamada antes de iniciar a execucao dos testes. * ***********************************************************************/ TST_tpCondRet TST_AbrirArquivoLog( char * NomeArqParm ) ; /*********************************************************************** * * $FC Funcao: TSTG &Obter ponteiro para arquivo LOG * * $ED Descricao da funcao * Retorna o ponteiro para o FILE do log. * Sera stdout caso nao seja definido explicitamente por * TSTG_DefinirLog * * $FV Valor retornado * Ponteiro valido para um arquivo de texto de saida * ***********************************************************************/ FILE * TST_ObterArqLog( void ) ; /*********************************************************************** * * $FC Funcao: TSTG &Registrar nome do arquivo acumulador * * $ED Descricao da funcao * Registra o nome do arquivo acumulador. Este arquivo e utilizado * para acumular as estatisticas de um teste formado por um conjunto * de massas de teste. Cada massa de teste gera o seu conjunto de * estatisticas de execucao. O arquivo acumulador acumula estas * estatisticas permitindo ver o total de todas as massas de teste. * * $EIU Interface com usuario pessoa * O arquivo acumulador tem serventia somente se o teste e formado * por um conjunto de duas ou mais massas de teste. * Antes de executar a primeira deve ser apagado o arquivo acumulador. * Apos terminar a execucao da última massa de teste exiba o resultado * como o programa "ExbeEstat" que faz parte do arcabouco. * ***********************************************************************/ void TST_RegistrarArquivoAcumulador( char * pNomeArquivoAcumulador ) ; /*********************************************************************** * * $FC Funcao: TSTG &Interpretar toda a massa de teste * * $ED Descricao da funcao * Interpreta o arquivo de diretivas (script) de teste ja aberto * * A funcao de teste e dividida em tres classes de comandos: * * - os de teste generico, que coordenam e controlam a realizacao do * teste. Estes comandos sao interpretados por esta funcao. * - os de teste e controle de modulos componentes do arcabouco. * Estes comandos sao interpretados por funcoes de teste especificas * para cada um dos modulos componentes. * - os de teste especifico do modulo (ou modulos) a ser testado. * O modulo de teste especifico interpreta os comandos projetados * para realizar os testes do modulo a testar. * * A funcao de teste generico le um arquivo de diretivas de teste. * Cada linha deste arquivo e um comando de teste. * A funcao de teste le uma a uma as linhas do arquivo, limpa os * caracteres em branco no final da linha e procura interpretar o * comando. * * As funcoes de teste especificas comunicam os resultados da execucao * de cada comando por meio de uma condicao de retorno. * * Cada linha do arquivo script de teste corresponde a um comando de * teste. * * Caso seja encontrada uma falha nao esperada (ver comando =recuperar) * os restantes comandos do caso de teste serao ignorados e contados * como problemas. * * A sintaxe utilizada pelos comandos de teste e semelhante a assembler. * Esta sintaxe facilita a analise: * * =<cmd> <parâmetros> * * em que: * = - todos os comandos a serem interpretados iniciam * com este caractere * <cmd> - e o string que identifica o comando * <parâmetros> - sao zero ou mais itens a serem utilizados * pelo comando de teste. Os itens devem, de preferencia, * ser separados um do outro por um caractere "espaco" * * Deve ser adotado o seguinte padrao de uso: * * - procure sempre utlizar uma das funcoes TST_CompararXXX, na forma: * return TST_CompararXXX( valoresperado, funcao a testar , mensagem ) * * - as funcoes de comparacao fornecidas sempre geram as mensagens no * padrao estipulado * * - quando nao for possivel utilizar uma funcao de comparacao, reporte * a falha, esperadas ou nao, atraves da funcao * TST_ImprimirPrefixo( Mensagem ) * * - a seguir mostre o valor esperado e o obtido * * - Informacoes relativas a falhas dos testes sao sinalizadas por * uma mensagem iniciando com ">>>" o número da linha do comando de teste * e o número de falhas encontradas ate o momento. * * - Informacoes relativas à execucao dos testes sao sinalizadas por * uma mensagem iniciando com "!!!". * * $FV Valor retornado * TST_CondRetErro - caso tenha sido encontrado um ou mais problemas * TST_CondRetOK - caso o teste tenha terminado com zero problemas * nao esperados. * * $FGP Tipos e Variaveis globais externas do proprio modulo * pArqScript - deve referenciar o arquivo script aberto * pArqLog - deve referenciar o arquivo log aberto * ***********************************************************************/ TST_tpCondRet TST_RealizarTeste( char * Construto ) ; /*********************************************************************** * * $FC Funcao: TSTG &Obter número de casos de teste efetuados * * $ED Descricao da funcao * Retorna o número de casos de teste lidos. * Cada caso de teste inicia com o comando "== <nome do caso de teste>". * ***********************************************************************/ int TST_ObterNumCasosTeste( ) ; /*********************************************************************** * * $FC Funcao: TSTG &Obter número de comandos especificos corretamente interpretados * * $ED Descricao da funcao * Retorna o número de comandos de teste especificos lidos e * corretamente interpretados. Nao conta comandos que retornem nao OK * independentemento do motivo. Tambem nao conta comandos recuperar. * ***********************************************************************/ int ObterNumComandosExecutados( void ) ; /*********************************************************************** * * $FC Funcao: TSTG &Obter número de problemas encontrados * * $ED Descricao da funcao * Retorna o número de problemas encontrados. * O modulo de teste especifico sinaliza problemas atraves de * uma condicao de retorno diferente de TST_CondRetOK. * Sao tratados como problema tambem comandos de teste em erro, * e todos os comandos de teste de um dado caso de teste ignorados * em virtude de alguma falha encontrada. * Portanto, e possivel que o número de problemas venha a ser maior do * que o número de casos de teste existente no script. * ***********************************************************************/ int TST_ObterNumFalhas( void ) ; /*********************************************************************** * * $FC Funcao: TSTG &Incrementar contador de falhas * ***********************************************************************/ void TST_ContarFalhas( ) ; /*********************************************************************** * * $FC Funcao: TSTG &Comparar booleano * * $ED Descricao da funcao * Compara valor booleano esperado com valor booleano obtido, * reportamdo uma falha caso nao sejam iguais. * Note que "!= 0" corresponde a TRUE e "== 0" corresponde a FALSE * * $EP Parâmetros * ValorEsperado - e um valor fornecido como parâmetro do comando * de teste * ValorObtido - e o valor retornado pela funcao em teste * pMensagem - mensagem explanatoria da falha encontrada * * $FV Valor retornado * TST_CondRetErro se o valor esperado nao for consistente com o obtido * TST_CondRetOK se os valores forem consistentes * ***********************************************************************/ TST_tpCondRet TST_CompararBool( int ValorEsperado , int ValorObtido , char * pMensagem ) ; /*********************************************************************** * * $FC Funcao: TSTG &Comparar caractere * * $ED Descricao da funcao * Compara um caractere esperado com um caractere obtido, emitindo mensagem de * erro caso nao sejam iguais. * * $EP Parâmetros * ValorEsperado - e um valor fornecido como parâmetro do comando * de teste * ValorObtido - e o valor retornado pela funcao em teste * pMensagem - mensagem explanatoria da falha encontrada * * $FV Valor retornado * TST_CondRetErro se o valor esperado nao for igual ao obtido * TST_CondRetOK se os valores forem iguais * ***********************************************************************/ TST_tpCondRet TST_CompararChar( char ValorEsperado , char ValorObtido , char * pMensagem ) ; /*********************************************************************** * * $FC Funcao: TSTG &Comparar inteiro * * $ED Descricao da funcao * Compara valor inteiro long esperado com valor inteiro obtido, * reportamdo uma falha caso nao sejam iguais. * * $EP Parâmetros * ValorEsperado - e um valor fornecido como parâmetro do comando * de teste * ValorObtido - e o valor retornado pela funcao em teste * pMensagem - mensagem explanatoria da falha encontrada * * $FV Valor retornado * TST_CondRetErro se o valor esperado nao for igual ao obtido * TST_CondRetOK se os valores forem iguais * ***********************************************************************/ TST_tpCondRet TST_CompararInt( long ValorEsperado , long ValorObtido , char * pMensagem ) ; /*********************************************************************** * * $FC Funcao: TSTG &Comparar flutuante * * $ED Descricao da funcao * Compara valor flutuante esperado com valor flutuante obtido, * reportando uma falha caso * 1 - Tolerancia > esperado / obtido ou * 1 + Tolerancia < esperado / obtido * * $EP Parâmetros * ValorEsperado - e um valor fornecido como parâmetro do comando * de teste * ValorObtido - e o valor retornado pela funcao em teste * Tolerância - indica os limites da relacao entre esperado e obtido. * Deve ser um valor positivo, menor do que 1. * Use um valor do tipo 10 ** -n, no qual n e o * número de digitos significativos desejado. * pMensagem - mensagem explanatoria da falha encontrada * * $FV Valor retornado * TST_CondRetErro se o valor obtido nao estiver dentro do dominio da * tolerância em torno do valor esperado * TST_CondRetOK se os valores estiverem dentro da tolerância * ***********************************************************************/ TST_tpCondRet TST_CompararFloat( double ValorEsperado , double ValorObtido , double Tolerancia , char * pMensagem ) ; /*********************************************************************** * * $FC Funcao: TSTG &Comparar string * * $ED Descricao da funcao * Compara string esperado com string obtido, reportamdo uma falha * caso nao sejam iguais. Ambos os strings devem obedecer o * padrao C, terminando em zero. * * $EP Parâmetros * ValorEsperado - e um string fornecido como parâmetro do comando * de teste. * ValorObtido - e o string retornado pela funcao em teste * pMensagem - mensagem explanatoria da falha encontrada * * $FV Valor retornado * TST_CondRetErro se o valor esperado nao for igual ao obtido * TST_CondRetOK se os valores forem iguais * ***********************************************************************/ TST_tpCondRet TST_CompararString( char * ValorEsperado , char * ValorObtido , char * pMensagem ) ; /*********************************************************************** * * $FC Funcao: TSTG &Comparar espaco * * $ED Descricao da funcao * Compara espacos de dados, reportando uma falha caso nao sejam iguais. * Esta funcao pode ser utilizada para comparar qualquer coisa, * inclusive valores do tipo "struct" * O tipo do valor e indefinido e os valores serao exibidos em * formato hexadecimal, caso nao sejam iguais * * $EP Parâmetros * ValorEsperado - ponteiro para o espaco que contem o valor esperado * ValorObtido - ponteiro para o espaco que contem o valor obtido * TamEspaco - tamanho do espaco a ser comparado * pMensagem - mensagem explanatoria da falha encontrada * * $FV Valor retornado * TST_CondRetErro se o valor esperado nao for igual ao obtido * TST_CondRetOK se os valores forem iguais * ***********************************************************************/ TST_tpCondRet TST_CompararEspaco( void * ValorEsperado , void * ValorObtido , int TamEspaco , char * pMensagem ) ; /*********************************************************************** * * $FC Funcao: TSTG &Comparar ponteiro * * $ED Descricao da funcao * Compara dois ponteiros emitindo uma mensagem caso nao sejam iguais * * $FV Valor retornado * TST_CondRetErro se os dois ponteiros forem diferentes * TST_CondRetOK se forem iguais * ***********************************************************************/ TST_tpCondRet TST_CompararPonteiro( void * PonteiroEsperado , void * PonteiroObtido , char * pMensagem ) ; /*********************************************************************** * * $FC Funcao: TSTG &Comparar ponteiro nulo * * $ED Descricao da funcao * Verifica * - quando ModoEsperado e 0 se o ponteiro e nulo * - quando ModoEsperado nao e 0 se o ponteiro e nao nulo * * $FV Valor retornado * TST_CondRetErro se os dois ponteiros forem diferentes * TST_CondRetOK se forem iguais * ***********************************************************************/ TST_tpCondRet TST_CompararPonteiroNulo( int ModoEsperado , void * PonteiroObtido , char * pMensagem ) ; /*********************************************************************** * * $FC Funcao: TSTG &Assertiva controlada * * $ED Descricao da funcao * Esta funcao substitui a funcao assert de C. * e utilizada no contexto do arcabouco de teste. * Ela imprime mensagens mais visiveis tanto no log como na * janela de comando. * * Recomenda-se, no entanto, utilizar a funcao assert de C em aplicacoes. * * $FV Valor retornado * Termina a execucao do programa com codigo de retorno == 4 * ***********************************************************************/ #define TST_ASSERT( Expressao ) \ TST_Assert( Expressao , __LINE__ , __FILE__ ) void TST_Assert( int Expressao , int Linha , char * NomeArq ) ; /*********************************************************************** * * $FC Funcao: TSTG &Notificar falha * * $ED Descricao da funcao * Exibe uma mensagem de falha no formato padrao do arcabouco. * * $FV Valor retornado * TST_CondRetErro sempre * ***********************************************************************/ TST_tpCondRet TST_NotificarFalha( char * pMensagem ) ; /*********************************************************************** * * $FC Funcao: TSTG &Exibir prefixo da mensagem * * $ED Descricao da funcao * Imprime o prefixo de mensages de falha * * $EH Hipoteses assumidas pela funcao * O contador de falhas e incrementado somente pela funcao de teste * generica e apos à conclusao da interpretacao do comando. * ***********************************************************************/ void TST_ExibirPrefixo( char * Indicador , char * pMensagem ) ; /*********************************************************************** * * $FC Funcao: TSTG &Exibir um espaco qualquer em formato hexadecimal e char * * $EP Parâmetros * $P tamEspaco - tamanho em bytes do espaco a exibir * $P Ponteiro - ponteiro para o primeiro byte do espaco a exibir * ***********************************************************************/ void TST_ExibirEspacoHexa( int tamEspaco , void * Ponteiro ) ; #undef GENERICO_EXT /********** Fim do modulo de definicao: TSTG Controlador de teste generico **********/ #else #endif
[ "Stephanie Fay" ]
Stephanie Fay
961937ebd73af2e1b18157b05dc70f9f78d75119
53980c4c4ae09e5b83efb351493c92de2ce412b1
/Placement/programs/binary.c
ecbe88b381fad3841332b3b1c62c50004da5c1da
[]
no_license
daniellimzj/CS1010-1
78ead2a95c7ef8086cda4496bbb2ea0137e83f3e
af9480ad5371b99556c4f45995c91c88d8b3313c
refs/heads/master
2020-08-22T08:20:24.354126
2019-10-16T04:44:10
2019-10-16T04:44:10
null
0
0
null
null
null
null
UTF-8
C
false
false
382
c
#include <stdio.h> #include <string.h> #include <stdlib.h> void tata(long n, char str[], long k) { if (k == n-1) { str[k] = '0'; printf("%s\n", str); str[k] = '1'; printf("%s\n", str); return; } str[k]='0'; tata(n, str, k+1); str[k]='1'; tata(n, str, k+1); } int main(void) { char str[4]; tata(3, str, 0); }
[ "h1110050@github.com" ]
h1110050@github.com
8c06b246d33a4bb2f903b8d5303b4bc66a816e7c
634f568757f6b6e427da20b82b512163cf1157c3
/Herd/Pods/Headers/Public/SmartDeviceLink/SDLGetSystemCapabilityResponse.h
d4bb42f3ca3e21fc580facc802a40327b410d87b
[]
no_license
xyf199919/emily99
487c441535206caa75607faefa248f451cc80fe2
60fcc0ab9bd67e8df2cf43ef46d7334c35457aab
refs/heads/master
2020-04-14T23:51:10.226541
2019-01-05T15:07:45
2019-01-05T15:07:45
164,219,127
0
0
null
null
null
null
UTF-8
C
false
false
73
h
../../../SmartDeviceLink/SmartDeviceLink/SDLGetSystemCapabilityResponse.h
[ "emily@Yunfangs-MacBook-Pro.local" ]
emily@Yunfangs-MacBook-Pro.local
bc9c79988282d0261e487e1567ea8a6257d928e5
f6392d1406ee7acadb32a60255b22022a263ccd0
/code/src/btstack/src/classic/pbap_client.c
d32c2f3f48d80ac5a9265f17bca60a67122e3429
[]
no_license
mrjake2014/bt_stack
9b359ad3ac3024bb45060b0066ad4e1e954404b0
f27cd1de938c29be6664b8d49c1da8a3b2ef605a
refs/heads/master
2021-10-09T01:22:59.611590
2018-12-19T18:43:56
2018-12-19T18:43:56
null
0
0
null
null
null
null
UTF-8
C
false
false
13,875
c
/* * Copyright (C) 2014 BlueKitchen GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * 4. Any redistribution, use, or modification is done solely for * personal benefit and not for any commercial purpose or for * monetary gain. * * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH 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 MATTHIAS * RINGWALD 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. * * Please inquire about commercial licensing options at * contact@bluekitchen-gmbh.com * */ #define __BTSTACK_FILE__ "pbap_client.c" // ***************************************************************************** // #if 0 0x0000 = uint32(65542), // BLUETOOTH_SERVICE_CLASS_PHONEBOOK_ACCESS_PSE 0x0001 = { uuid16(11 2f) }, // BLUETOOTH_PROTOCOL_L2CAP, BLUETOOTH_PROTOCOL_RFCOMM, BLUETOOTH_PROTOCOL_OBEX 0x0004 = { { uuid16(01 00) }, { uuid16(00 03), uint8(19) }, { uuid16(00 08) } } 0x0005 = { uuid16(10 02) }, // BLUETOOTH_SERVICE_CLASS_PHONEBOOK_ACCESS, v1.01 = 0x101 0x0009 = { { uuid16(11 30), uint16(257) } }, 0x0100 = string(OBEX Phonebook Access Server // BLUETOOTH_ATTRIBUTE_SUPPORTED_FEATURES -- should be 0x317 BLUETOOTH_ATTRIBUTE_PBAP_SUPPORTED_FEATURES? 0x0311 = uint8(3), // BLUETOOTH_ATTRIBUTE_SUPPORTED_REPOSITORIES 0x0314 = uint8(1), #endif // // ***************************************************************************** #include "btstack_config.h" #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "hci_cmd.h" #include "btstack_run_loop.h" #include "btstack_debug.h" #include "hci.h" #include "btstack_memory.h" #include "hci_dump.h" #include "l2cap.h" #include "bluetooth_sdp.h" #include "classic/sdp_client_rfcomm.h" #include "btstack_event.h" #include "classic/obex.h" #include "classic/obex_iterator.h" #include "classic/goep_client.h" #include "classic/pbap_client.h" // 796135f0-f0c5-11d8-0966- 0800200c9a66 uint8_t pbap_uuid[] = { 0x79, 0x61, 0x35, 0xf0, 0xf0, 0xc5, 0x11, 0xd8, 0x09, 0x66, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66}; const char* pbap_type = "x-bt/phonebook"; const char* pbap_name = "pb.vcf"; typedef enum { PBAP_INIT = 0, PBAP_W4_GOEP_CONNECTION, PBAP_W2_SEND_CONNECT_REQUEST, PBAP_W4_CONNECT_RESPONSE, PBAP_CONNECT_RESPONSE_RECEIVED, PBAP_CONNECTED, // PBAP_W2_PULL_PHONE_BOOK, PBAP_W4_PHONE_BOOK, PBAP_W2_SET_PATH_ROOT, PBAP_W4_SET_PATH_ROOT_COMPLETE, PBAP_W2_SET_PATH_ELEMENT, PBAP_W4_SET_PATH_ELEMENT_COMPLETE, } pbap_state_t; typedef struct pbap_client { pbap_state_t state; uint16_t cid; bd_addr_t bd_addr; hci_con_handle_t con_handle; uint8_t incoming; uint16_t goep_cid; btstack_packet_handler_t client_handler; const char* current_folder; uint16_t set_path_offset; } pbap_client_t; static pbap_client_t _pbap_client; static pbap_client_t* pbap_client = &_pbap_client; static inline void pbap_client_emit_connected_event(pbap_client_t* context, uint8_t status) { uint8_t event[15]; int pos = 0; event[pos++] = HCI_EVENT_PBAP_META; pos++; // skip len event[pos++] = PBAP_SUBEVENT_CONNECTION_OPENED; little_endian_store_16(event,pos,context->cid); pos+=2; event[pos++] = status; memcpy(&event[pos], context->bd_addr, 6); pos += 6; little_endian_store_16(event,pos,context->con_handle); pos += 2; event[pos++] = context->incoming; event[1] = pos - 2; if (pos != sizeof(event)) { log_error("goep_client_emit_connected_event size %u", pos); } context->client_handler(HCI_EVENT_PACKET, context->cid, &event[0], pos); } static inline void pbap_client_emit_connection_closed_event(pbap_client_t* context) { uint8_t event[5]; int pos = 0; event[pos++] = HCI_EVENT_PBAP_META; pos++; // skip len event[pos++] = PBAP_SUBEVENT_CONNECTION_CLOSED; little_endian_store_16(event,pos,context->cid); pos+=2; event[1] = pos - 2; if (pos != sizeof(event)) { log_error("pbap_client_emit_connection_closed_event size %u", pos); } context->client_handler(HCI_EVENT_PACKET, context->cid, &event[0], pos); } static inline void pbap_client_emit_operation_complete_event(pbap_client_t* context, uint8_t status) { uint8_t event[6]; int pos = 0; event[pos++] = HCI_EVENT_PBAP_META; pos++; // skip len event[pos++] = PBAP_SUBEVENT_OPERATION_COMPLETED; little_endian_store_16(event,pos,context->cid); pos+=2; event[pos++]= status; event[1] = pos - 2; if (pos != sizeof(event)) { log_error("pbap_client_emit_can_send_now_event size %u", pos); } context->client_handler(HCI_EVENT_PACKET, context->cid, &event[0], pos); } static void pbap_handle_can_send_now(void) { uint8_t path_element[20]; uint16_t path_element_start; uint16_t path_element_len; switch (pbap_client->state) { case PBAP_W2_SEND_CONNECT_REQUEST: goep_client_create_connect_request(pbap_client->goep_cid, OBEX_VERSION, 0, OBEX_MAX_PACKETLEN_DEFAULT); goep_client_add_header_target(pbap_client->goep_cid, 16, pbap_uuid); // state pbap_client->state = PBAP_W4_CONNECT_RESPONSE; // send packet goep_client_execute(pbap_client->goep_cid); return; case PBAP_W2_PULL_PHONE_BOOK: goep_client_create_get_request(pbap_client->goep_cid); goep_client_add_header_type(pbap_client->goep_cid, pbap_type); goep_client_add_header_name(pbap_client->goep_cid, pbap_name); // state pbap_client->state = PBAP_W4_PHONE_BOOK; // send packet goep_client_execute(pbap_client->goep_cid); break; case PBAP_W2_SET_PATH_ROOT: goep_client_create_set_path_request(pbap_client->goep_cid, 1 << 1); // Don’t create directory // On Android 4.2 Cyanogenmod, using "" as path fails // goep_client_add_header_name(pbap_client->goep_cid, ""); // empty == / // state pbap_client->state = PBAP_W4_SET_PATH_ROOT_COMPLETE; // send packet goep_client_execute(pbap_client->goep_cid); break; case PBAP_W2_SET_PATH_ELEMENT: // find '/' or '\0' path_element_start = pbap_client->set_path_offset; while (pbap_client->current_folder[pbap_client->set_path_offset] != '\0' && pbap_client->current_folder[pbap_client->set_path_offset] != '/') { pbap_client->set_path_offset++; } // skip / if (pbap_client->current_folder[pbap_client->set_path_offset] == '/') { pbap_client->set_path_offset++; } path_element_len = pbap_client->set_path_offset-path_element_start; memcpy(path_element, &pbap_client->current_folder[path_element_start], path_element_len); path_element[path_element_len] = 0; goep_client_create_set_path_request(pbap_client->goep_cid, 1 << 1); // Don’t create directory goep_client_add_header_name(pbap_client->goep_cid, (const char*) path_element); // next element // state pbap_client->state = PBAP_W4_SET_PATH_ELEMENT_COMPLETE; // send packet goep_client_execute(pbap_client->goep_cid); break; default: break; } } static void pbap_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t* packet, uint16_t size) { UNUSED(channel); // ok: there is no channel UNUSED(size); // ok: handling own geop events obex_iterator_t it; uint8_t status; switch (packet_type) { case HCI_EVENT_PACKET: switch (hci_event_packet_get_type(packet)) { case HCI_EVENT_GOEP_META: switch (hci_event_goep_meta_get_subevent_code(packet)) { case GOEP_SUBEVENT_CONNECTION_OPENED: status = goep_subevent_connection_opened_get_status(packet); pbap_client->con_handle = goep_subevent_connection_opened_get_con_handle(packet); pbap_client->incoming = goep_subevent_connection_opened_get_incoming(packet); goep_subevent_connection_opened_get_bd_addr(packet, pbap_client->bd_addr); if (status) { log_info("pbap: connection failed %u", status); pbap_client->state = PBAP_INIT; pbap_client_emit_connected_event(pbap_client, status); } else { log_info("pbap: connection established"); pbap_client->goep_cid = goep_subevent_connection_opened_get_goep_cid(packet); pbap_client->state = PBAP_W2_SEND_CONNECT_REQUEST; goep_client_request_can_send_now(pbap_client->goep_cid); } break; case GOEP_SUBEVENT_CONNECTION_CLOSED: if (pbap_client->state != PBAP_CONNECTED) { pbap_client_emit_operation_complete_event(pbap_client, OBEX_DISCONNECTED); } pbap_client->state = PBAP_INIT; pbap_client_emit_connection_closed_event(pbap_client); break; case GOEP_SUBEVENT_CAN_SEND_NOW: pbap_handle_can_send_now(); break; } break; default: break; } break; case GOEP_DATA_PACKET: // TODO: handle chunked data #if 0 obex_dump_packet(goep_client_get_request_opcode(pbap_client->goep_cid), packet, size); #endif switch (pbap_client->state) { case PBAP_W4_CONNECT_RESPONSE: for (obex_iterator_init_with_response_packet(&it, goep_client_get_request_opcode(pbap_client->goep_cid), packet, size); obex_iterator_has_more(&it) ; obex_iterator_next(&it)) { uint8_t hi = obex_iterator_get_hi(&it); if (hi == OBEX_HEADER_CONNECTION_ID) { goep_client_set_connection_id(pbap_client->goep_cid, obex_iterator_get_data_32(&it)); } } if (packet[0] == OBEX_RESP_SUCCESS) { pbap_client->state = PBAP_CONNECTED; pbap_client_emit_connected_event(pbap_client, 0); } else { log_info("pbap: obex connect failed, result 0x%02x", packet[0]); pbap_client->state = PBAP_INIT; pbap_client_emit_connected_event(pbap_client, OBEX_CONNECT_FAILED); } break; case PBAP_W4_SET_PATH_ROOT_COMPLETE: case PBAP_W4_SET_PATH_ELEMENT_COMPLETE: if (packet[0] == OBEX_RESP_SUCCESS) { if (pbap_client->current_folder) { pbap_client->state = PBAP_W2_SET_PATH_ELEMENT; goep_client_request_can_send_now(pbap_client->goep_cid); } else { pbap_client_emit_operation_complete_event(pbap_client, 0); } } else if (packet[0] == OBEX_RESP_NOT_FOUND) { pbap_client->state = PBAP_CONNECTED; pbap_client_emit_operation_complete_event(pbap_client, OBEX_NOT_FOUND); } else { pbap_client->state = PBAP_CONNECTED; pbap_client_emit_operation_complete_event(pbap_client, OBEX_UNKNOWN_ERROR); } break; case PBAP_W4_PHONE_BOOK: for (obex_iterator_init_with_response_packet(&it, goep_client_get_request_opcode(pbap_client->goep_cid), packet, size); obex_iterator_has_more(&it) ; obex_iterator_next(&it)) { uint8_t hi = obex_iterator_get_hi(&it); if (hi == OBEX_HEADER_BODY || hi == OBEX_HEADER_END_OF_BODY) { uint16_t data_len = obex_iterator_get_data_len(&it); const uint8_t* data = obex_iterator_get_data(&it); pbap_client->client_handler(PBAP_DATA_PACKET, pbap_client->cid, (uint8_t*) data, data_len); } } if (packet[0] == OBEX_RESP_CONTINUE) { pbap_client->state = PBAP_W2_PULL_PHONE_BOOK; goep_client_request_can_send_now(pbap_client->goep_cid); } else if (packet[0] == OBEX_RESP_SUCCESS) { pbap_client->state = PBAP_CONNECTED; pbap_client_emit_operation_complete_event(pbap_client, 0); } else { pbap_client->state = PBAP_CONNECTED; pbap_client_emit_operation_complete_event(pbap_client, OBEX_UNKNOWN_ERROR); } break; default: break; } break; default: break; } } void pbap_client_init(void) { memset(pbap_client, 0, sizeof(pbap_client_t)); pbap_client->state = PBAP_INIT; pbap_client->cid = 1; } uint8_t pbap_connect(btstack_packet_handler_t handler, bd_addr_t addr, uint16_t* out_cid) { if (pbap_client->state != PBAP_INIT) { return BTSTACK_MEMORY_ALLOC_FAILED; } pbap_client->state = PBAP_W4_GOEP_CONNECTION; pbap_client->client_handler = handler; uint8_t err = goep_client_create_connection(&pbap_packet_handler, addr, BLUETOOTH_SERVICE_CLASS_PHONEBOOK_ACCESS_PSE, &pbap_client->goep_cid); *out_cid = pbap_client->cid; if (err) { return err; } return 0; } uint8_t pbap_disconnect(uint16_t pbap_cid) { UNUSED(pbap_cid); if (pbap_client->state != PBAP_CONNECTED) { return BTSTACK_BUSY; } goep_client_disconnect(pbap_client->goep_cid); return 0; } uint8_t pbap_pull_phonebook(uint16_t pbap_cid) { UNUSED(pbap_cid); if (pbap_client->state != PBAP_CONNECTED) { return BTSTACK_BUSY; } pbap_client->state = PBAP_W2_PULL_PHONE_BOOK; goep_client_request_can_send_now(pbap_client->goep_cid); return 0; } uint8_t pbap_set_phonebook(uint16_t pbap_cid, const char* path) { UNUSED(pbap_cid); if (pbap_client->state != PBAP_CONNECTED) { return BTSTACK_BUSY; } pbap_client->state = PBAP_W2_SET_PATH_ROOT; pbap_client->current_folder = path; pbap_client->set_path_offset = 0; goep_client_request_can_send_now(pbap_client->goep_cid); return 0; }
[ "1016771083@qq.com" ]
1016771083@qq.com
2414a2dff52d08262b8e87998402d80ea92db67c
6b990e1470c29765d2ca27da396be7d971c3e7e2
/ch10/10_20.c
a8d68fc675c9ebb633cef86d580554ade181908a
[]
no_license
wobushiludahai/apue
8774c351cd7d84e4b8ca458b2876b787b82bdab3
c6bb7ef78b08020e61841885ebbbd01256065bb4
refs/heads/master
2020-12-15T09:45:25.000585
2020-01-31T06:37:25
2020-01-31T06:37:25
235,064,079
0
0
null
null
null
null
UTF-8
C
false
false
2,321
c
/* * @Author: land sea * @Date: 2020-01-27 19:55:54 * @LastEditTime : 2020-01-27 20:56:56 * @LastEditors : Please set LastEditors * @Description: sigsetjmp/siglongjmp函数示例 * @FilePath: /apue/ch10/10_20.c */ #include "apue.h" #include <setjmp.h> #include <time.h> #include <errno.h> #include <signal.h> static void sig_usrl(int); static void sig_alrm(int); static sigjmp_buf jmpbuf; static volatile sig_atomic_t canjump; // #define SIGBAD(signo) ((signo) <= 0 || (signo) >= NSIG) // int sigismember(const sigset_t *set, int signo) // { // if(SIGBAD(signo)) // { // errno = EINVAL; // return (-1); // } // return((*set & (1 << (signo - 1))) != 0); // } // void pr_mask(const char *str) // { // sigset_t sigset; // int errno_save; // errno_save = errno; // if(sigprocmask(0, NULL, &sigset) < 0) // { // err_ret("sigprocmask error"); // } // else // { // printf("%s", str); // if(sigismember(&sigset, SIGINT)) // { // printf(" SIGNET"); // } // if(sigismember(&sigset, SIGQUIT)) // { // printf(" SIGQUIT"); // } // if(sigismember(&sigset, SIGUSR1)) // { // printf(" SIGUSR1"); // } // if(sigismember(&sigset, SIGALRM)) // { // printf(" SIGALRM"); // } // printf("\n"); // } // errno = errno_save; // } int main(void) { if(signal(SIGUSR1, sig_usrl) == SIG_ERR) { err_sys("signal(SIGUSR1) error"); } if(signal(SIGALRM, sig_alrm) == SIG_ERR) { err_sys("signal(SIGALRM) error"); } pr_mask("starting main: "); if(sigsetjmp(jmpbuf, 1)) { pr_mask("ending main: "); exit(0); } canjump = 1; for(;;) { pause(); } } static void sig_usrl(int signo) { time_t starttime; if(canjump == 0) { return; } pr_mask("starting sig_usrl: "); alarm(3); starttime = time(NULL); for(;;) { if(time(NULL) > starttime + 5) { break; } } pr_mask("finish sig_usrl: "); canjump = 0; siglongjmp(jmpbuf, 1); } static void sig_alrm(int signo) { pr_mask("in sig_alrm: "); }
[ "wobushiludahai@163.com" ]
wobushiludahai@163.com
eb6f52e42b14aa85b7c91f88ba6bd3dd0e24b6a0
e683a0b8dbb87c7ceb99e0d06896174a559d2c67
/CInclude/JS/jsemem.h
d0b2fb21912929b10082e152714477cee1f7f84a
[ "Apache-2.0" ]
permissive
bluewaysw/pcgeos
f093d79567d977d992f47065056d14d5a04b9f14
c6ae4c8e77b54b9ff654c3916f2191f8b1a1b65d
refs/heads/master
2023-08-31T00:17:54.481175
2023-08-29T19:00:49
2023-08-29T19:00:49
157,968,410
603
88
Apache-2.0
2023-09-13T07:44:06
2018-11-17T09:09:55
Assembly
UTF-8
C
false
false
5,934
h
/* jsemem.h */ /* (c) COPYRIGHT 1993-98 NOMBAS, INC. * 64 SALEM ST. * MEDFORD, MA 02155 USA * * ALL RIGHTS RESERVED * * This software is the property of Nombas, Inc. and is furnished under * license by Nombas, Inc.; this software may be used only in accordance * with the terms of said license. This copyright notice may not be removed, * modified or obliterated without the prior written permission of Nombas, Inc. * * This software is a Trade Secret of Nombas, Inc. * * This software may not be copied, transmitted, provided to or otherwise made * available to any other person, company, corporation or other entity except * as specified in the terms of said license. * * No right, title, ownership or other interest in the software is hereby * granted or transferred. * * The information contained herein is subject to change without notice and * should not be construed as a commitment by Nombas, Inc. */ #ifndef _MEMDEBUG_H #define _MEMDEBUG_H #include "jsetypes.h" #include "jselib.h" #ifdef __cplusplus extern "C" { #endif /* common stuff for production version */ void jseInsufficientMemory(void); #ifdef HUGE_MEMORY void _HUGE_ *jseMustHugeMalloc(ulong size); #else # define jseMustHugeMalloc(SIZE) jseMustMalloc(void,SIZE) #endif #if defined(JSE_MEM_DEBUG) && (0!=JSE_MEM_DEBUG) void * jseUtilMalloc(uint size, ulong line, const char* file); /* If cannot malloc then return NULL. */ void * jseUtilReMalloc(void *PrevMalloc,uint size, ulong line, const char* file); /* return NULL if failed; old memory is not freed */ void * jseUtilMustMalloc(uint size, ulong line, const char* file); /* If cannot malloc then Fatal() and so * will not return. */ /*void * jseUtilMustCalloc(uint num,uint size, ulong line, const char* file);*/ /* If cannot malloc then Fatal() and so * will not return. */ void * jseUtilMustReMalloc(void *PrevMalloc,uint size, ulong line, const char* file); /* fatal abort if failure */ # define jseMalloc(TYPE,SIZE) (TYPE *)jseUtilMalloc(SIZE,__LINE__,__FILE__) # define jseReMalloc(TYPE,PTR,SIZE) \ (TYPE *)jseUtilReMalloc(PTR,SIZE,__LINE__,__FILE__) # define jseMustMalloc(TYPE,SIZE) \ (TYPE *)jseUtilMustMalloc(SIZE,__LINE__,__FILE__) # define jseMustReMalloc(TYPE,PTR,SIZE) \ (TYPE *)jseUtilMustReMalloc(PTR,SIZE,__LINE__,__FILE__) # define jseMustCalloc(TYPE,NUM,SIZE) \ (TYPE *)jseUtilMustCalloc(NUM,SIZE,__LINE__,__FILE__) void jseUtilMustFree(void *ptr); # define jseMustFree(PTR) jseUtilMustFree(PTR) # if !defined(JSE_ENFORCE_MEMCHECK) || (0!=JSE_ENFORCE_MEMCHECK) /* make sure no one tries to use these. The preceding #if statement * will allow ISDK users to selectively not enforce use of our * own memory checking, and yet still allow memory-allocation calls * on their own objects. */ # define free(P) use jseMustFree # define malloc(S) use jseMustMalloc or jseMalloc # define realloc(P,S) use jseMustReMalloc or jseReMalloc # define calloc(N,S) use jseMustMalloc or jseMalloc # endif void jseInitializeMallocDebugging(void); void jseTerminateMallocDebugging(void); ulong jseMemReport(jsebool Verboseness); /* if verboseness then write it all to DebugPrintf() */ void jseMemVerbose(jsebool SetVerbose); jsebool jseMemValid(void *ptr,uint offset); void jseMemDisplay(void); #else void * jseUtilMalloc(uint size); void * jseUtilReMalloc(void *PrevMalloc,uint size); void * jseUtilMustMalloc(uint size); /* If cannot malloc then Fatal() and so will not return. */ /*void * jseUtilMustCalloc(uint num,uint size);*/ /* If cannot malloc then Fatal() and so will not return. */ void * jseUtilMustReMalloc(void *PrevMalloc,uint size); /* fatal abort if failure */ # define jseMalloc(TYPE,SIZE) (TYPE *)jseUtilMalloc(SIZE) # define jseReMalloc(TYPE,PTR,SIZE) (TYPE *)jseUtilReMalloc(PTR,SIZE) # define jseMustMalloc(TYPE,SIZE) (TYPE *)jseUtilMustMalloc(SIZE) # define jseMustCalloc(TYPE,NUM,SIZE) (TYPE *)jseUtilMustCalloc(NUM,SIZE) #ifdef GEOS_MAPPED_MALLOC # define jseMustReMalloc(TYPE,PTR,SIZE) (TYPE *)jseMappedRealloc(PTR,SIZE) #else # define jseMustReMalloc(TYPE,PTR,SIZE) \ (TYPE *)jseUtilMustReMalloc(PTR,SIZE) #endif #ifdef GEOS_MAPPED_MALLOC # define jseMustFree(P) jseMappedFree(P) # define jseUtilMalloc(SIZE) jseMappedMalloc(SIZE) # define jseUtilReMalloc(PTR,SIZE) jseMappedRealloc(PTR,SIZE) #else # define jseMustFree(P) free(P) # define jseUtilMalloc(SIZE) malloc(SIZE) # if defined(__JSE_PALMOS__) # define jseUtilReMalloc(PTR,SIZE) jseUtilMustReMalloc(PTR,SIZE) # else # define jseUtilReMalloc(PTR,SIZE) realloc(PTR,SIZE) # endif #endif #endif /* these exist in non-GEOS_MAPPED_MALLOC version, as they're exported */ JSECALLSEQ_CFUNC(void) jseEnter(void); JSECALLSEQ_CFUNC(void) jseLeave(void); JSECALLSEQ_CFUNC(void) jseAssert(void); JSECALLSEQ_CFUNC(void *) jseMappedMalloc(word blockSize); JSECALLSEQ_CFUNC(void) jseMappedFree(void *blockPtr); JSECALLSEQ_CFUNC(void *) jseMappedRealloc(void *blockPtr, word newSize); typedef struct { dword mappedSize; dword maxMappedSize; dword nonMappedSize; dword maxNonMappedSize; dword handleMemSize; dword maxHandleMemSize; } jseMemInfoStruct; JSECALLSEQ_CFUNC(void) jseMemInfo(jseMemInfoStruct *memInfo); #ifdef MEM_TRACKING /* this is useful (internal only) */ extern dword jseChunkSize(void *ptr); #endif #ifdef __cplusplus } #endif #endif
[ "frehwagen@bluewaysw.de" ]
frehwagen@bluewaysw.de
36a6025a86b170a5765a4186e7a6aef90bcaf500
4e38aaf21898427d27511e498e00871af29aeaf7
/week04/ex2.c
f3a62842a99752070ea5258e2137572a6baa6e62
[]
no_license
h0henz0llern/OS19
f3c3f666444f7105ff85734aeefabb357c46d8f4
14e24dab259e4d77f12c90723c30b7f16f18acad
refs/heads/master
2020-07-08T05:20:44.216758
2019-10-10T20:42:53
2019-10-10T20:42:53
203,576,990
0
0
null
null
null
null
UTF-8
C
false
false
122
c
#include <stdio.h> #include <stdlib.h> int main() { for (int i = 0; i < 5; ++i) { fork(); sleep(5); } return 0; }
[ "noreply@github.com" ]
h0henz0llern.noreply@github.com
1e233e998c845910de7e4fd83cff940a1e44f3d1
6a1ac443aa41ba28df96cd9ae068bdd4230d96e5
/src/raster.h
bb7b92881b4311642059cb43666a0f80bee7b642
[]
no_license
porglezomp/piraster
b2105e130cfa1597555871d0c0d48a81c09f45ff
5b83bba3ae32d70633fca44ad5ffdd5779cf33a4
refs/heads/master
2021-01-23T14:47:26.683748
2014-01-12T02:40:11
2014-01-12T02:40:11
null
0
0
null
null
null
null
UTF-8
C
false
false
518
h
#ifndef PIRASTER_RASTER_H #define PIRASTER_RASTER_H #include "pixelmethods.h" #include "triangle.h" #include "line.h" #include "point.h" struct SDL_Surface; struct vec2; void pr_setsurface(SDL_Surface *); void pr_point(const vec2&); void pr_line(const vec2&, const vec2&); void pr_tri(const vec2&, const vec2&, const vec2&); void pr_pointcolor(float, float, float); void pr_linecolor(float, float, float); void pr_tricolor(float, float, float); void pr_color(float, float, float); void pr_pointsize(int); #endif
[ "bionicle.dragon@gmail.com" ]
bionicle.dragon@gmail.com
675e3a74a7de48f0d21fad7166cb521ee2a453aa
433acd5140a397787aeb1f87f472514484667f6c
/src/utils.h
f9c366ada22bb8de67b5bdcd2772969cae51d356
[]
no_license
agds93/cellular_automata
919dd8d7884ae9c1a11cb6e3e041a81be03d1df9
bc71bfdfdf2b6c6f0860f290eb1b4236f9bdd4e4
refs/heads/master
2020-06-23T01:43:17.236198
2019-11-06T19:45:03
2019-11-06T19:45:03
198,463,816
0
0
null
null
null
null
UTF-8
C
false
false
252
h
#ifndef CELLULAR_AUTOMATA_UTILS_H #define CELLULAR_AUTOMATA_UTILS_H 1 #define N_FIGURE 2 #define MAX_POINTS 10 int** def_matrix(int M,int N); void free_matrix(int **matrix,int M); int cas_int(int min,int max); #endif //CELLULAR_AUTOMATA_UTILS_H
[ "53229638+agds93@users.noreply.github.com" ]
53229638+agds93@users.noreply.github.com
ea7a8f0683fff31401637eea5a40d82918fedef2
740b9bb41ea64307c5f7c85cff818b9190d7a02c
/components/libraries/balloc/nrf_balloc.h
af40abe9a922be5d65ada869db49168795f17d1c
[]
no_license
thumb2/nrf51sdk12_3
4fefe074ef34b69054613ff8ab3faba18f6aa8d1
d6956d24ae6ada32db9139ca5da4885377003bf8
refs/heads/master
2020-04-26T07:26:49.519306
2018-01-12T02:08:34
2018-01-12T02:08:34
173,394,420
0
1
null
null
null
null
UTF-8
C
false
false
15,096
h
/** * Copyright (c) 2016 - 2017, Nordic Semiconductor ASA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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. * */ /** * @defgroup nrf_balloc Block memory allocator * @{ * @ingroup app_common * @brief This module handles block memory allocator features. */ #ifndef NRF_BALLOC_H__ #define NRF_BALLOC_H__ #ifdef __cplusplus extern "C" { #endif #include "sdk_errors.h" #include "sdk_config.h" #include "app_util_platform.h" /**@defgroup NRF_BALLOC_DEBUG Macros for preparing debug flags for block allocator module. * @{ */ #define NRF_BALLOC_DEBUG_HEAD_GUARD_WORDS_SET(words) (((words) & 0xFF) << 0) #define NRF_BALLOC_DEBUG_HEAD_GUARD_WORDS_GET(flags) (((flags) >> 0) & 0xFF) #define NRF_BALLOC_DEBUG_TAIL_GUARD_WORDS_SET(words) (((words) & 0xFF) << 8) #define NRF_BALLOC_DEBUG_TAIL_GUARD_WORDS_GET(flags) (((flags) >> 8) & 0xFF) #define NRF_BALLOC_DEBUG_BASIC_CHECKS_SET(enable) (!!(enable) << 16) #define NRF_BALLOC_DEBUG_BASIC_CHECKS_GET(flags) (flags & (1 << 16)) #define NRF_BALLOC_DEBUG_DOUBLE_FREE_CHECK_SET(enable) (!!(enable) << 17) #define NRF_BALLOC_DEBUG_DOUBLE_FREE_CHECK_GET(flags) (flags & (1 << 17)) #define NRF_BALLOC_DEBUG_DATA_TRASHING_CHECK_SET(enable) (!!(enable) << 18) #define NRF_BALLOC_DEBUG_DATA_TRASHING_CHECK_GET(flags) (flags & (1 << 18)) /**@} */ /**@brief Default debug flags for @ref nrf_balloc. This is used by the @ref NRF_BALLOC_DEF macro. * Flags can be changed in @ref sdk_config. */ #if NRF_BALLOC_CONFIG_DEBUG_ENABLED #define NRF_BALLOC_DEFAULT_DEBUG_FLAGS \ ( \ NRF_BALLOC_DEBUG_HEAD_GUARD_WORDS_SET(NRF_BALLOC_CONFIG_HEAD_GUARD_WORDS) | \ NRF_BALLOC_DEBUG_TAIL_GUARD_WORDS_SET(NRF_BALLOC_CONFIG_TAIL_WORDS) | \ NRF_BALLOC_DEBUG_BASIC_CHECKS_SET(NRF_BALLOC_CONFIG_BASIC_CHECKS_ENABLED) | \ NRF_BALLOC_DEBUG_DOUBLE_FREE_CHECK_SET(NRF_BALLOC_CONFIG_DOUBLE_FREE_CHECK_ENABLED) | \ NRF_BALLOC_DEBUG_DATA_TRASHING_CHECK_SET(NRF_BALLOC_CONFIG_DATA_TRASHING_CHECK_ENABLED) \ ) #else #define NRF_BALLOC_DEFAULT_DEBUG_FLAGS 0 #endif // NRF_BALLOC_CONFIG_DEBUG_ENABLED /**@brief Block memory allocator control block.*/ typedef struct { uint8_t * p_stack_pointer; //!< Current allocation stack pointer. uint8_t max_utilization; //!< Maximum utilization of the memory pool. } nrf_balloc_cb_t; /**@brief Block memory allocator pool instance. The pool is made of elements of the same size. */ typedef struct { nrf_balloc_cb_t * p_cb; //!< Pointer to the instance control block. uint8_t * p_stack_base; //!< Base of the allocation stack. /**< * Stack is used to store handlers to not allocated elements. */ uint8_t * p_stack_limit; //!< Maximum possible value of the allocation stack pointer. void * p_memory_begin; //!< Pointer to the start of the memory pool. /**< * Memory is used as a heap for blocks. */ #if NRF_BALLOC_CONFIG_DEBUG_ENABLED void * p_memory_end; //!< Pointer to the end of the memory pool. uint32_t debug_flags; //!< Debugging settings. /**< * Debug flag should be created by @ref NRF_BALLOC_DEBUG. */ #endif // NRF_BALLOC_CONFIG_DEBUG_ENABLED uint16_t block_size; //!< Size of the allocated block (including debug overhead). /**< * Single block contains user element with header and tail * words. */ } nrf_balloc_t; /**@brief Get total memory consumed by single block (element size with overhead caused by debug * flags). * * @param[in] _element_size Size of an element. * @param[in] _debug_flags Debug flags. */ #if NRF_BALLOC_CONFIG_DEBUG_ENABLED #define NRF_BALLOC_BLOCK_SIZE(_element_size, _debug_flags) \ ( \ (sizeof(uint32_t) * NRF_BALLOC_DEBUG_HEAD_GUARD_WORDS_GET(_debug_flags)) + \ ALIGN_NUM(sizeof(uint32_t), (_element_size)) + \ (sizeof(uint32_t) * NRF_BALLOC_DEBUG_TAIL_GUARD_WORDS_GET(_debug_flags)) \ ) #else #define NRF_BALLOC_BLOCK_SIZE(_element_size, _debug_flags) \ ALIGN_NUM(sizeof(uint32_t), (_element_size)) #endif // NRF_BALLOC_CONFIG_DEBUG_ENABLED /**@brief Create a block allocator instance with custom debug flags. * * @note This macro reserves memory for the given block allocator instance. * * @param[in] _name Name of the allocator. * @param[in] _element_size Size of one element. * @param[in] _pool_size Size of the pool. * @param[in] _debug_flags Debug flags (@ref NRF_BALLOC_DEBUG). */ #if NRF_BALLOC_CONFIG_DEBUG_ENABLED #define NRF_BALLOC_DBG_DEF(_name, _element_size, _pool_size, _debug_flags) \ STATIC_ASSERT((_pool_size) <= UINT8_MAX); \ static uint8_t _name##_nrf_balloc_pool_stack[(_pool_size)]; \ static uint32_t _name##_nrf_balloc_pool_mem \ [NRF_BALLOC_BLOCK_SIZE(_element_size, _debug_flags) * (_pool_size) / sizeof(uint32_t)]; \ static nrf_balloc_cb_t _name##_nrf_balloc_cb; \ static const nrf_balloc_t _name = \ { \ .p_cb = &_name##_nrf_balloc_cb, \ .p_stack_base = _name##_nrf_balloc_pool_stack, \ .p_stack_limit = _name##_nrf_balloc_pool_stack + (_pool_size), \ .p_memory_begin = _name##_nrf_balloc_pool_mem, \ .block_size = NRF_BALLOC_BLOCK_SIZE(_element_size, _debug_flags), \ .p_memory_end = (uint8_t *)_name##_nrf_balloc_pool_mem \ + NRF_BALLOC_BLOCK_SIZE(_element_size, _debug_flags) * (_pool_size),\ .debug_flags = (_debug_flags), \ } #else #define NRF_BALLOC_DBG_DEF(_name, _element_size, _pool_size, _debug_flags) \ STATIC_ASSERT((_pool_size) <= UINT8_MAX); \ static uint8_t _name##_nrf_balloc_pool_stack[(_pool_size)]; \ static uint32_t _name##_nrf_balloc_pool_mem \ [NRF_BALLOC_BLOCK_SIZE(_element_size, _debug_flags) * (_pool_size) / sizeof(uint32_t)]; \ static nrf_balloc_cb_t _name##_nrf_balloc_cb; \ static const nrf_balloc_t _name = \ { \ .p_cb = &_name##_nrf_balloc_cb, \ .p_stack_base = _name##_nrf_balloc_pool_stack, \ .p_stack_limit = _name##_nrf_balloc_pool_stack + (_pool_size), \ .p_memory_begin = _name##_nrf_balloc_pool_mem, \ .block_size = NRF_BALLOC_BLOCK_SIZE(_element_size, _debug_flags), \ } #endif // NRF_BALLOC_CONFIG_DEBUG_ENABLED /**@brief Create a block allocator instance. * * @note This macro reserves memory for the given block allocator instance. * * @param[in] _name Name of the allocator. * @param[in] _element_size Size of one element. * @param[in] _pool_size Size of the pool. */ #define NRF_BALLOC_DEF(_name, _element_size, _pool_size) \ NRF_BALLOC_DBG_DEF(_name, _element_size, _pool_size, NRF_BALLOC_DEFAULT_DEBUG_FLAGS) /**@brief Create a block allocator interface. * * @param[in] _type Type which is allocated. * @param[in] _name Name of the allocator. */ #define NRF_BALLOC_INTERFACE_DEC(_type, _name) \ _type * _name##_alloc(void); \ void _name##_free(_type * p_element); \ uint8_t _name##_max_utilization_get(void) /**@brief Define a custom block allocator interface. * * @param[in] _attr Function attribute that will be added to allocator function definition. * @param[in] _type Type which is allocated. * @param[in] _name Name of the allocator. * @param[in] _p_pool Pool from which data will be allocated. */ #define NRF_BALLOC_INTERFACE_CUSTOM_DEF(_attr, _type, _name, _p_pool) \ _attr _type * _name##_alloc(void) \ { \ ASSERT((_p_pool) != NULL); \ ASSERT((_p_pool)->block_size >= \ NRF_BALLOC_BLOCK_SIZE(sizeof(_type), (_p_pool)->debug_flags)); \ return (_type *)(nrf_balloc_alloc(_p_pool)); \ } \ \ _attr void _name##_free(_type * p_element) \ { \ ASSERT((_p_pool) != NULL); \ ASSERT((_p_pool)->block_size >= \ NRF_BALLOC_BLOCK_SIZE(sizeof(_type), (_p_pool)->debug_flags)); \ nrf_balloc_free((_p_pool), p_element); \ } \ \ _attr uint8_t _name##_max_utilization_get(void) \ { \ ASSERT((_p_pool) != NULL); \ return nrf_balloc_max_utilization_get((_p_pool)); \ } /**@brief Define block allocator interface. * * @param[in] _type Type which is allocated. * @param[in] _name Name of the allocator. * @param[in] _p_pool Pool from which data will be allocated. */ #define NRF_BALLOC_INTERFACE_DEF(_type, _name, _p_pool) \ NRF_BALLOC_INTERFACE_CUSTOM_DEF(/* empty */, _type, _name, _p_pool) /**@brief Define a local block allocator interface. * * @param[in] _type Type which is allocated. * @param[in] _name Name of the allocator. * @param[in] _p_pool Pool from which data will be allocated. */ #define NRF_BALLOC_INTERFACE_LOCAL_DEF(_type, _name, _p_pool) \ NRF_BALLOC_INTERFACE_CUSTOM_DEF(static, _type, _name, _p_pool) /**@brief Function for initializing a block memory allocator pool. * * @param[out] p_pool Pointer to the pool that is to be initialized. * * @return NRF_SUCCESS on success, otherwise error code. */ ret_code_t nrf_balloc_init(nrf_balloc_t const * p_pool); /**@brief Function for allocating an element from the pool. * * @note This module guarantees that the returned memory is aligned to 4. * * @param[in] p_pool Pointer to the memory pool from which the element will be allocated. * * @return Allocated element or NULL if the specified pool is empty. */ void * nrf_balloc_alloc(nrf_balloc_t const * p_pool); /**@brief Function for freeing an element back to the pool. * * @param[in] p_pool Pointer to the memory pool. * @param[in] p_element Element to be freed. */ void nrf_balloc_free(nrf_balloc_t const * p_pool, void * p_element); /**@brief Function for getting maximum memory pool utilization. * * @param[in] p_pool Pointer to the memory pool instance. * * @return Maximum number of elements allocated from the pool. */ __STATIC_INLINE uint8_t nrf_balloc_max_utilization_get(nrf_balloc_t const * p_pool) { ASSERT(p_pool != NULL); return p_pool->p_cb->max_utilization; } #ifdef __cplusplus } #endif #endif // NRF_BALLOC_H__ /** @} */
[ "johnson@btsmartshield.com" ]
johnson@btsmartshield.com
b2c4a92238b8e2d0ee45e0661f4e86241cdfd2ce
30bc4beea0df3011d18fafd0fc57fefc41864268
/src/router/php8/ext/reflection/php_reflection.c
64c5355fc83657fbdb3d10c6f6f170f17c630259
[ "PHP-3.01", "GD", "IJG", "Zlib", "LicenseRef-scancode-other-permissive", "TCL", "BSD-3-Clause", "BSD-4-Clause-UC", "OLDAP-2.8", "ISC", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
bialanjoni/dd-wrt
ad490f4bea1f0196bfb08a1ebc01a1c4f2977d5a
67eebe196548d49d96aa941c83699d8b5c446e8e
refs/heads/master
2023-06-26T03:55:18.811888
2021-07-30T10:07:50
2021-07-30T10:07:50
null
0
0
null
null
null
null
UTF-8
C
false
false
184,946
c
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Timm Friebe <thekid@thekid.de> | | George Schlossnagle <george@omniti.com> | | Andrei Zmievski <andrei@gravitonic.com> | | Marcus Boerger <helly@php.net> | | Johannes Schlueter <johannes@php.net> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "php_reflection.h" #include "ext/standard/info.h" #include "ext/standard/sha1.h" #include "ext/standard/php_random.h" #include "zend.h" #include "zend_API.h" #include "zend_ast.h" #include "zend_attributes.h" #include "zend_exceptions.h" #include "zend_operators.h" #include "zend_constants.h" #include "zend_ini.h" #include "zend_interfaces.h" #include "zend_closures.h" #include "zend_generators.h" #include "zend_extensions.h" #include "zend_builtin_functions.h" #include "zend_smart_str.h" #include "php_reflection_arginfo.h" /* Key used to avoid leaking addresses in ReflectionProperty::getId() */ #define REFLECTION_KEY_LEN 16 ZEND_BEGIN_MODULE_GLOBALS(reflection) zend_bool key_initialized; unsigned char key[REFLECTION_KEY_LEN]; ZEND_END_MODULE_GLOBALS(reflection) ZEND_DECLARE_MODULE_GLOBALS(reflection) #define REFLECTION_G(v) ZEND_MODULE_GLOBALS_ACCESSOR(reflection, v) static zend_always_inline zval *reflection_prop_name(zval *object) { /* $name is always in the first property slot. */ ZEND_ASSERT(Z_OBJCE_P(object)->default_properties_count >= 1); return &Z_OBJ_P(object)->properties_table[0]; } static zend_always_inline zval *reflection_prop_class(zval *object) { /* $class is always in the second property slot. */ ZEND_ASSERT(Z_OBJCE_P(object)->default_properties_count >= 2); return &Z_OBJ_P(object)->properties_table[1]; } /* Class entry pointers */ PHPAPI zend_class_entry *reflector_ptr; PHPAPI zend_class_entry *reflection_exception_ptr; PHPAPI zend_class_entry *reflection_ptr; PHPAPI zend_class_entry *reflection_function_abstract_ptr; PHPAPI zend_class_entry *reflection_function_ptr; PHPAPI zend_class_entry *reflection_generator_ptr; PHPAPI zend_class_entry *reflection_parameter_ptr; PHPAPI zend_class_entry *reflection_type_ptr; PHPAPI zend_class_entry *reflection_named_type_ptr; PHPAPI zend_class_entry *reflection_union_type_ptr; PHPAPI zend_class_entry *reflection_class_ptr; PHPAPI zend_class_entry *reflection_object_ptr; PHPAPI zend_class_entry *reflection_method_ptr; PHPAPI zend_class_entry *reflection_property_ptr; PHPAPI zend_class_entry *reflection_class_constant_ptr; PHPAPI zend_class_entry *reflection_extension_ptr; PHPAPI zend_class_entry *reflection_zend_extension_ptr; PHPAPI zend_class_entry *reflection_reference_ptr; PHPAPI zend_class_entry *reflection_attribute_ptr; /* Exception throwing macro */ #define _DO_THROW(msg) \ zend_throw_exception(reflection_exception_ptr, msg, 0); #define GET_REFLECTION_OBJECT() do { \ intern = Z_REFLECTION_P(ZEND_THIS); \ if (intern->ptr == NULL) { \ if (EG(exception) && EG(exception)->ce == reflection_exception_ptr) { \ RETURN_THROWS(); \ } \ zend_throw_error(NULL, "Internal error: Failed to retrieve the reflection object"); \ RETURN_THROWS(); \ } \ } while (0) #define GET_REFLECTION_OBJECT_PTR(target) do { \ GET_REFLECTION_OBJECT(); \ target = intern->ptr; \ } while (0) /* Class constants */ #define REGISTER_REFLECTION_CLASS_CONST_LONG(class_name, const_name, value) \ zend_declare_class_constant_long(reflection_ ## class_name ## _ptr, const_name, sizeof(const_name)-1, (zend_long)value); #define REFLECTION_ATTRIBUTE_IS_INSTANCEOF (1 << 1) /* {{{ Object structure */ /* Struct for properties */ typedef struct _property_reference { zend_property_info *prop; zend_string *unmangled_name; } property_reference; /* Struct for parameters */ typedef struct _parameter_reference { uint32_t offset; zend_bool required; struct _zend_arg_info *arg_info; zend_function *fptr; } parameter_reference; /* Struct for type hints */ typedef struct _type_reference { zend_type type; /* Whether to use backwards compatible null representation */ zend_bool legacy_behavior; } type_reference; /* Struct for attributes */ typedef struct _attribute_reference { HashTable *attributes; zend_attribute *data; zend_class_entry *scope; zend_string *filename; uint32_t target; } attribute_reference; typedef enum { REF_TYPE_OTHER, /* Must be 0 */ REF_TYPE_FUNCTION, REF_TYPE_GENERATOR, REF_TYPE_PARAMETER, REF_TYPE_TYPE, REF_TYPE_PROPERTY, REF_TYPE_CLASS_CONSTANT, REF_TYPE_ATTRIBUTE } reflection_type_t; /* Struct for reflection objects */ typedef struct { zval obj; void *ptr; zend_class_entry *ce; reflection_type_t ref_type; unsigned int ignore_visibility:1; zend_object zo; } reflection_object; static inline reflection_object *reflection_object_from_obj(zend_object *obj) { return (reflection_object*)((char*)(obj) - XtOffsetOf(reflection_object, zo)); } #define Z_REFLECTION_P(zv) reflection_object_from_obj(Z_OBJ_P((zv))) /* }}} */ static zend_object_handlers reflection_object_handlers; static zend_always_inline uint32_t prop_get_flags(property_reference *ref) { return ref->prop ? ref->prop->flags : ZEND_ACC_PUBLIC; } static inline zend_bool is_closure_invoke(zend_class_entry *ce, zend_string *lcname) { return ce == zend_ce_closure && zend_string_equals_literal(lcname, ZEND_INVOKE_FUNC_NAME); } static void _default_get_name(zval *object, zval *return_value) /* {{{ */ { zval *name = reflection_prop_name(object); if (Z_ISUNDEF_P(name)) { RETURN_FALSE; } ZVAL_COPY(return_value, name); } /* }}} */ static zend_function *_copy_function(zend_function *fptr) /* {{{ */ { if (fptr && (fptr->internal_function.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) { zend_function *copy_fptr; copy_fptr = emalloc(sizeof(zend_function)); memcpy(copy_fptr, fptr, sizeof(zend_function)); copy_fptr->internal_function.function_name = zend_string_copy(fptr->internal_function.function_name); return copy_fptr; } else { /* no copy needed */ return fptr; } } /* }}} */ static void _free_function(zend_function *fptr) /* {{{ */ { if (fptr && (fptr->internal_function.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) { zend_string_release_ex(fptr->internal_function.function_name, 0); zend_free_trampoline(fptr); } } /* }}} */ static void reflection_free_objects_storage(zend_object *object) /* {{{ */ { reflection_object *intern = reflection_object_from_obj(object); parameter_reference *reference; property_reference *prop_reference; if (intern->ptr) { switch (intern->ref_type) { case REF_TYPE_PARAMETER: reference = (parameter_reference*)intern->ptr; _free_function(reference->fptr); efree(intern->ptr); break; case REF_TYPE_TYPE: { type_reference *type_ref = intern->ptr; if (ZEND_TYPE_HAS_NAME(type_ref->type)) { zend_string_release(ZEND_TYPE_NAME(type_ref->type)); } efree(type_ref); break; } case REF_TYPE_FUNCTION: _free_function(intern->ptr); break; case REF_TYPE_PROPERTY: prop_reference = (property_reference*)intern->ptr; zend_string_release_ex(prop_reference->unmangled_name, 0); efree(intern->ptr); break; case REF_TYPE_ATTRIBUTE: { attribute_reference *attr_ref = intern->ptr; if (attr_ref->filename) { zend_string_release(attr_ref->filename); } efree(intern->ptr); break; } case REF_TYPE_GENERATOR: case REF_TYPE_CLASS_CONSTANT: case REF_TYPE_OTHER: break; } } intern->ptr = NULL; zval_ptr_dtor(&intern->obj); zend_object_std_dtor(object); } /* }}} */ static HashTable *reflection_get_gc(zend_object *obj, zval **gc_data, int *gc_data_count) /* {{{ */ { reflection_object *intern = reflection_object_from_obj(obj); *gc_data = &intern->obj; *gc_data_count = 1; return zend_std_get_properties(obj); } /* }}} */ static zend_object *reflection_objects_new(zend_class_entry *class_type) /* {{{ */ { reflection_object *intern = zend_object_alloc(sizeof(reflection_object), class_type); zend_object_std_init(&intern->zo, class_type); object_properties_init(&intern->zo, class_type); intern->zo.handlers = &reflection_object_handlers; return &intern->zo; } /* }}} */ static zval *reflection_instantiate(zend_class_entry *pce, zval *object) /* {{{ */ { object_init_ex(object, pce); return object; } /* }}} */ static void _const_string(smart_str *str, char *name, zval *value, char *indent); static void _function_string(smart_str *str, zend_function *fptr, zend_class_entry *scope, char* indent); static void _property_string(smart_str *str, zend_property_info *prop, const char *prop_name, char* indent); static void _class_const_string(smart_str *str, char *name, zend_class_constant *c, char* indent); static void _class_string(smart_str *str, zend_class_entry *ce, zval *obj, char *indent); static void _extension_string(smart_str *str, zend_module_entry *module, char *indent); static void _zend_extension_string(smart_str *str, zend_extension *extension, char *indent); /* {{{ _class_string */ static void _class_string(smart_str *str, zend_class_entry *ce, zval *obj, char *indent) { int count, count_static_props = 0, count_static_funcs = 0, count_shadow_props = 0; zend_string *sub_indent = strpprintf(0, "%s ", indent); /* TBD: Repair indenting of doc comment (or is this to be done in the parser?) */ if (ce->type == ZEND_USER_CLASS && ce->info.user.doc_comment) { smart_str_append_printf(str, "%s%s", indent, ZSTR_VAL(ce->info.user.doc_comment)); smart_str_appendc(str, '\n'); } if (obj && Z_TYPE_P(obj) == IS_OBJECT) { smart_str_append_printf(str, "%sObject of class [ ", indent); } else { char *kind = "Class"; if (ce->ce_flags & ZEND_ACC_INTERFACE) { kind = "Interface"; } else if (ce->ce_flags & ZEND_ACC_TRAIT) { kind = "Trait"; } smart_str_append_printf(str, "%s%s [ ", indent, kind); } smart_str_append_printf(str, (ce->type == ZEND_USER_CLASS) ? "<user" : "<internal"); if (ce->type == ZEND_INTERNAL_CLASS && ce->info.internal.module) { smart_str_append_printf(str, ":%s", ce->info.internal.module->name); } smart_str_append_printf(str, "> "); if (ce->get_iterator != NULL) { smart_str_append_printf(str, "<iterateable> "); } if (ce->ce_flags & ZEND_ACC_INTERFACE) { smart_str_append_printf(str, "interface "); } else if (ce->ce_flags & ZEND_ACC_TRAIT) { smart_str_append_printf(str, "trait "); } else { if (ce->ce_flags & (ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { smart_str_append_printf(str, "abstract "); } if (ce->ce_flags & ZEND_ACC_FINAL) { smart_str_append_printf(str, "final "); } smart_str_append_printf(str, "class "); } smart_str_append_printf(str, "%s", ZSTR_VAL(ce->name)); if (ce->parent) { smart_str_append_printf(str, " extends %s", ZSTR_VAL(ce->parent->name)); } if (ce->num_interfaces) { uint32_t i; ZEND_ASSERT(ce->ce_flags & ZEND_ACC_LINKED); if (ce->ce_flags & ZEND_ACC_INTERFACE) { smart_str_append_printf(str, " extends %s", ZSTR_VAL(ce->interfaces[0]->name)); } else { smart_str_append_printf(str, " implements %s", ZSTR_VAL(ce->interfaces[0]->name)); } for (i = 1; i < ce->num_interfaces; ++i) { smart_str_append_printf(str, ", %s", ZSTR_VAL(ce->interfaces[i]->name)); } } smart_str_append_printf(str, " ] {\n"); /* The information where a class is declared is only available for user classes */ if (ce->type == ZEND_USER_CLASS) { smart_str_append_printf(str, "%s @@ %s %d-%d\n", indent, ZSTR_VAL(ce->info.user.filename), ce->info.user.line_start, ce->info.user.line_end); } /* Constants */ smart_str_append_printf(str, "\n"); count = zend_hash_num_elements(&ce->constants_table); smart_str_append_printf(str, "%s - Constants [%d] {\n", indent, count); if (count > 0) { zend_string *key; zend_class_constant *c; ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->constants_table, key, c) { _class_const_string(str, ZSTR_VAL(key), c, ZSTR_VAL(sub_indent)); if (UNEXPECTED(EG(exception))) { zend_string_release(sub_indent); return; } } ZEND_HASH_FOREACH_END(); } smart_str_append_printf(str, "%s }\n", indent); /* Static properties */ /* counting static properties */ count = zend_hash_num_elements(&ce->properties_info); if (count > 0) { zend_property_info *prop; ZEND_HASH_FOREACH_PTR(&ce->properties_info, prop) { if ((prop->flags & ZEND_ACC_PRIVATE) && prop->ce != ce) { count_shadow_props++; } else if (prop->flags & ZEND_ACC_STATIC) { count_static_props++; } } ZEND_HASH_FOREACH_END(); } /* static properties */ smart_str_append_printf(str, "\n%s - Static properties [%d] {\n", indent, count_static_props); if (count_static_props > 0) { zend_property_info *prop; ZEND_HASH_FOREACH_PTR(&ce->properties_info, prop) { if ((prop->flags & ZEND_ACC_STATIC) && (!(prop->flags & ZEND_ACC_PRIVATE) || prop->ce == ce)) { _property_string(str, prop, NULL, ZSTR_VAL(sub_indent)); } } ZEND_HASH_FOREACH_END(); } smart_str_append_printf(str, "%s }\n", indent); /* Static methods */ /* counting static methods */ count = zend_hash_num_elements(&ce->function_table); if (count > 0) { zend_function *mptr; ZEND_HASH_FOREACH_PTR(&ce->function_table, mptr) { if ((mptr->common.fn_flags & ZEND_ACC_STATIC) && ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) == 0 || mptr->common.scope == ce)) { count_static_funcs++; } } ZEND_HASH_FOREACH_END(); } /* static methods */ smart_str_append_printf(str, "\n%s - Static methods [%d] {", indent, count_static_funcs); if (count_static_funcs > 0) { zend_function *mptr; ZEND_HASH_FOREACH_PTR(&ce->function_table, mptr) { if ((mptr->common.fn_flags & ZEND_ACC_STATIC) && ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) == 0 || mptr->common.scope == ce)) { smart_str_append_printf(str, "\n"); _function_string(str, mptr, ce, ZSTR_VAL(sub_indent)); } } ZEND_HASH_FOREACH_END(); } else { smart_str_append_printf(str, "\n"); } smart_str_append_printf(str, "%s }\n", indent); /* Default/Implicit properties */ count = zend_hash_num_elements(&ce->properties_info) - count_static_props - count_shadow_props; smart_str_append_printf(str, "\n%s - Properties [%d] {\n", indent, count); if (count > 0) { zend_property_info *prop; ZEND_HASH_FOREACH_PTR(&ce->properties_info, prop) { if (!(prop->flags & ZEND_ACC_STATIC) && (!(prop->flags & ZEND_ACC_PRIVATE) || prop->ce == ce)) { _property_string(str, prop, NULL, ZSTR_VAL(sub_indent)); } } ZEND_HASH_FOREACH_END(); } smart_str_append_printf(str, "%s }\n", indent); if (obj && Z_TYPE_P(obj) == IS_OBJECT) { HashTable *properties = Z_OBJ_HT_P(obj)->get_properties(Z_OBJ_P(obj)); zend_string *prop_name; smart_str prop_str = {0}; count = 0; if (properties && zend_hash_num_elements(properties)) { ZEND_HASH_FOREACH_STR_KEY(properties, prop_name) { if (prop_name && ZSTR_LEN(prop_name) && ZSTR_VAL(prop_name)[0]) { /* skip all private and protected properties */ if (!zend_hash_exists(&ce->properties_info, prop_name)) { count++; _property_string(&prop_str, NULL, ZSTR_VAL(prop_name), ZSTR_VAL(sub_indent)); } } } ZEND_HASH_FOREACH_END(); } smart_str_append_printf(str, "\n%s - Dynamic properties [%d] {\n", indent, count); smart_str_append_smart_str(str, &prop_str); smart_str_append_printf(str, "%s }\n", indent); smart_str_free(&prop_str); } /* Non static methods */ count = zend_hash_num_elements(&ce->function_table) - count_static_funcs; if (count > 0) { zend_function *mptr; smart_str method_str = {0}; count = 0; ZEND_HASH_FOREACH_PTR(&ce->function_table, mptr) { if ((mptr->common.fn_flags & ZEND_ACC_STATIC) == 0 && ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) == 0 || mptr->common.scope == ce)) { zend_function *closure; /* see if this is a closure */ if (obj && is_closure_invoke(ce, mptr->common.function_name) && (closure = zend_get_closure_invoke_method(Z_OBJ_P(obj))) != NULL) { mptr = closure; } else { closure = NULL; } smart_str_appendc(&method_str, '\n'); _function_string(&method_str, mptr, ce, ZSTR_VAL(sub_indent)); count++; _free_function(closure); } } ZEND_HASH_FOREACH_END(); smart_str_append_printf(str, "\n%s - Methods [%d] {", indent, count); smart_str_append_smart_str(str, &method_str); if (!count) { smart_str_append_printf(str, "\n"); } smart_str_free(&method_str); } else { smart_str_append_printf(str, "\n%s - Methods [0] {\n", indent); } smart_str_append_printf(str, "%s }\n", indent); smart_str_append_printf(str, "%s}\n", indent); zend_string_release_ex(sub_indent, 0); } /* }}} */ /* {{{ _const_string */ static void _const_string(smart_str *str, char *name, zval *value, char *indent) { const char *type = zend_zval_type_name(value); if (Z_TYPE_P(value) == IS_ARRAY) { smart_str_append_printf(str, "%s Constant [ %s %s ] { Array }\n", indent, type, name); } else if (Z_TYPE_P(value) == IS_STRING) { smart_str_append_printf(str, "%s Constant [ %s %s ] { %s }\n", indent, type, name, Z_STRVAL_P(value)); } else { zend_string *tmp_value_str; zend_string *value_str = zval_get_tmp_string(value, &tmp_value_str); smart_str_append_printf(str, "%s Constant [ %s %s ] { %s }\n", indent, type, name, ZSTR_VAL(value_str)); zend_tmp_string_release(tmp_value_str); } } /* }}} */ /* {{{ _class_const_string */ static void _class_const_string(smart_str *str, char *name, zend_class_constant *c, char *indent) { char *visibility = zend_visibility_string(Z_ACCESS_FLAGS(c->value)); const char *type; if (zval_update_constant_ex(&c->value, c->ce) == FAILURE) { return; } type = zend_zval_type_name(&c->value); if (Z_TYPE(c->value) == IS_ARRAY) { smart_str_append_printf(str, "%sConstant [ %s %s %s ] { Array }\n", indent, visibility, type, name); } else { zend_string *tmp_value_str; zend_string *value_str = zval_get_tmp_string(&c->value, &tmp_value_str); smart_str_append_printf(str, "%sConstant [ %s %s %s ] { %s }\n", indent, visibility, type, name, ZSTR_VAL(value_str)); zend_tmp_string_release(tmp_value_str); } } /* }}} */ static zend_op *get_recv_op(zend_op_array *op_array, uint32_t offset) { zend_op *op = op_array->opcodes; zend_op *end = op + op_array->last; ++offset; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT || op->opcode == ZEND_RECV_VARIADIC) && op->op1.num == offset) { return op; } ++op; } ZEND_ASSERT(0 && "Failed to find op"); return NULL; } static zval *get_default_from_recv(zend_op_array *op_array, uint32_t offset) { zend_op *recv = get_recv_op(op_array, offset); if (!recv || recv->opcode != ZEND_RECV_INIT) { return NULL; } return RT_CONSTANT(recv, recv->op2); } static int format_default_value(smart_str *str, zval *value, zend_class_entry *scope) { zval zv; ZVAL_COPY(&zv, value); if (UNEXPECTED(zval_update_constant_ex(&zv, scope) == FAILURE)) { zval_ptr_dtor(&zv); return FAILURE; } if (Z_TYPE(zv) == IS_TRUE) { smart_str_appends(str, "true"); } else if (Z_TYPE(zv) == IS_FALSE) { smart_str_appends(str, "false"); } else if (Z_TYPE(zv) == IS_NULL) { smart_str_appends(str, "NULL"); } else if (Z_TYPE(zv) == IS_STRING) { smart_str_appendc(str, '\''); smart_str_appendl(str, Z_STRVAL(zv), MIN(Z_STRLEN(zv), 15)); if (Z_STRLEN(zv) > 15) { smart_str_appends(str, "..."); } smart_str_appendc(str, '\''); } else if (Z_TYPE(zv) == IS_ARRAY) { smart_str_appends(str, "Array"); } else { zend_string *tmp_zv_str; zend_string *zv_str = zval_get_tmp_string(&zv, &tmp_zv_str); smart_str_append(str, zv_str); zend_tmp_string_release(tmp_zv_str); } zval_ptr_dtor(&zv); return SUCCESS; } static inline zend_bool has_internal_arg_info(const zend_function *fptr) { return fptr->type == ZEND_INTERNAL_FUNCTION && !(fptr->common.fn_flags & ZEND_ACC_USER_ARG_INFO); } /* {{{ _parameter_string */ static void _parameter_string(smart_str *str, zend_function *fptr, struct _zend_arg_info *arg_info, uint32_t offset, zend_bool required, char* indent) { smart_str_append_printf(str, "Parameter #%d [ ", offset); if (!required) { smart_str_append_printf(str, "<optional> "); } else { smart_str_append_printf(str, "<required> "); } if (ZEND_TYPE_IS_SET(arg_info->type)) { zend_string *type_str = zend_type_to_string(arg_info->type); smart_str_append(str, type_str); smart_str_appendc(str, ' '); zend_string_release(type_str); } if (ZEND_ARG_SEND_MODE(arg_info)) { smart_str_appendc(str, '&'); } if (ZEND_ARG_IS_VARIADIC(arg_info)) { smart_str_appends(str, "..."); } smart_str_append_printf(str, "$%s", has_internal_arg_info(fptr) ? ((zend_internal_arg_info*)arg_info)->name : ZSTR_VAL(arg_info->name)); if (!required && !ZEND_ARG_IS_VARIADIC(arg_info)) { if (fptr->type == ZEND_INTERNAL_FUNCTION) { smart_str_appends(str, " = "); /* TODO: We don't have a way to fetch the default value for an internal function * with userland arg info. */ if (has_internal_arg_info(fptr) && ((zend_internal_arg_info*)arg_info)->default_value) { smart_str_appends(str, ((zend_internal_arg_info*)arg_info)->default_value); } else { smart_str_appends(str, "<default>"); } } else { zval *default_value = get_default_from_recv((zend_op_array*)fptr, offset); if (default_value) { smart_str_appends(str, " = "); if (format_default_value(str, default_value, fptr->common.scope) == FAILURE) { return; } } } } smart_str_appends(str, " ]"); } /* }}} */ /* {{{ _function_parameter_string */ static void _function_parameter_string(smart_str *str, zend_function *fptr, char* indent) { struct _zend_arg_info *arg_info = fptr->common.arg_info; uint32_t i, num_args, num_required = fptr->common.required_num_args; if (!arg_info) { return; } num_args = fptr->common.num_args; if (fptr->common.fn_flags & ZEND_ACC_VARIADIC) { num_args++; } smart_str_appendc(str, '\n'); smart_str_append_printf(str, "%s- Parameters [%d] {\n", indent, num_args); for (i = 0; i < num_args; i++) { smart_str_append_printf(str, "%s ", indent); _parameter_string(str, fptr, arg_info, i, i < num_required, indent); smart_str_appendc(str, '\n'); arg_info++; } smart_str_append_printf(str, "%s}\n", indent); } /* }}} */ /* {{{ _function_closure_string */ static void _function_closure_string(smart_str *str, zend_function *fptr, char* indent) { uint32_t i, count; zend_string *key; HashTable *static_variables; if (fptr->type != ZEND_USER_FUNCTION || !fptr->op_array.static_variables) { return; } static_variables = ZEND_MAP_PTR_GET(fptr->op_array.static_variables_ptr); count = zend_hash_num_elements(static_variables); if (!count) { return; } smart_str_append_printf(str, "\n"); smart_str_append_printf(str, "%s- Bound Variables [%d] {\n", indent, zend_hash_num_elements(static_variables)); i = 0; ZEND_HASH_FOREACH_STR_KEY(static_variables, key) { smart_str_append_printf(str, "%s Variable #%d [ $%s ]\n", indent, i++, ZSTR_VAL(key)); } ZEND_HASH_FOREACH_END(); smart_str_append_printf(str, "%s}\n", indent); } /* }}} */ /* {{{ _function_string */ static void _function_string(smart_str *str, zend_function *fptr, zend_class_entry *scope, char* indent) { smart_str param_indent = {0}; zend_function *overwrites; zend_string *lc_name; /* TBD: Repair indenting of doc comment (or is this to be done in the parser?) * What's "wrong" is that any whitespace before the doc comment start is * swallowed, leading to an unaligned comment. */ if (fptr->type == ZEND_USER_FUNCTION && fptr->op_array.doc_comment) { smart_str_append_printf(str, "%s%s\n", indent, ZSTR_VAL(fptr->op_array.doc_comment)); } smart_str_appendl(str, indent, strlen(indent)); smart_str_append_printf(str, fptr->common.fn_flags & ZEND_ACC_CLOSURE ? "Closure [ " : (fptr->common.scope ? "Method [ " : "Function [ ")); smart_str_append_printf(str, (fptr->type == ZEND_USER_FUNCTION) ? "<user" : "<internal"); if (fptr->common.fn_flags & ZEND_ACC_DEPRECATED) { smart_str_appends(str, ", deprecated"); } if (fptr->type == ZEND_INTERNAL_FUNCTION && ((zend_internal_function*)fptr)->module) { smart_str_append_printf(str, ":%s", ((zend_internal_function*)fptr)->module->name); } if (scope && fptr->common.scope) { if (fptr->common.scope != scope) { smart_str_append_printf(str, ", inherits %s", ZSTR_VAL(fptr->common.scope->name)); } else if (fptr->common.scope->parent) { lc_name = zend_string_tolower(fptr->common.function_name); if ((overwrites = zend_hash_find_ptr(&fptr->common.scope->parent->function_table, lc_name)) != NULL) { if (fptr->common.scope != overwrites->common.scope) { smart_str_append_printf(str, ", overwrites %s", ZSTR_VAL(overwrites->common.scope->name)); } } zend_string_release_ex(lc_name, 0); } } if (fptr->common.prototype && fptr->common.prototype->common.scope) { smart_str_append_printf(str, ", prototype %s", ZSTR_VAL(fptr->common.prototype->common.scope->name)); } if (fptr->common.fn_flags & ZEND_ACC_CTOR) { smart_str_appends(str, ", ctor"); } smart_str_appends(str, "> "); if (fptr->common.fn_flags & ZEND_ACC_ABSTRACT) { smart_str_appends(str, "abstract "); } if (fptr->common.fn_flags & ZEND_ACC_FINAL) { smart_str_appends(str, "final "); } if (fptr->common.fn_flags & ZEND_ACC_STATIC) { smart_str_appends(str, "static "); } if (fptr->common.scope) { /* These are mutually exclusive */ switch (fptr->common.fn_flags & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PUBLIC: smart_str_appends(str, "public "); break; case ZEND_ACC_PRIVATE: smart_str_appends(str, "private "); break; case ZEND_ACC_PROTECTED: smart_str_appends(str, "protected "); break; default: smart_str_appends(str, "<visibility error> "); break; } smart_str_appends(str, "method "); } else { smart_str_appends(str, "function "); } if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { smart_str_appendc(str, '&'); } smart_str_append_printf(str, "%s ] {\n", ZSTR_VAL(fptr->common.function_name)); /* The information where a function is declared is only available for user classes */ if (fptr->type == ZEND_USER_FUNCTION) { smart_str_append_printf(str, "%s @@ %s %d - %d\n", indent, ZSTR_VAL(fptr->op_array.filename), fptr->op_array.line_start, fptr->op_array.line_end); } smart_str_append_printf(&param_indent, "%s ", indent); smart_str_0(&param_indent); if (fptr->common.fn_flags & ZEND_ACC_CLOSURE) { _function_closure_string(str, fptr, ZSTR_VAL(param_indent.s)); } _function_parameter_string(str, fptr, ZSTR_VAL(param_indent.s)); smart_str_free(&param_indent); if (fptr->op_array.fn_flags & ZEND_ACC_HAS_RETURN_TYPE) { smart_str_append_printf(str, " %s- Return [ ", indent); if (ZEND_TYPE_IS_SET(fptr->common.arg_info[-1].type)) { zend_string *type_str = zend_type_to_string(fptr->common.arg_info[-1].type); smart_str_append_printf(str, "%s ", ZSTR_VAL(type_str)); zend_string_release(type_str); } smart_str_appends(str, "]\n"); } smart_str_append_printf(str, "%s}\n", indent); } /* }}} */ static zval *property_get_default(zend_property_info *prop_info) { zend_class_entry *ce = prop_info->ce; if (prop_info->flags & ZEND_ACC_STATIC) { zval *prop = &ce->default_static_members_table[prop_info->offset]; ZVAL_DEINDIRECT(prop); return prop; } else { return &ce->default_properties_table[OBJ_PROP_TO_NUM(prop_info->offset)]; } } /* {{{ _property_string */ static void _property_string(smart_str *str, zend_property_info *prop, const char *prop_name, char* indent) { smart_str_append_printf(str, "%sProperty [ ", indent); if (!prop) { smart_str_append_printf(str, "<dynamic> public $%s", prop_name); } else { /* These are mutually exclusive */ switch (prop->flags & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PUBLIC: smart_str_appends(str, "public "); break; case ZEND_ACC_PRIVATE: smart_str_appends(str, "private "); break; case ZEND_ACC_PROTECTED: smart_str_appends(str, "protected "); break; } if (prop->flags & ZEND_ACC_STATIC) { smart_str_appends(str, "static "); } if (ZEND_TYPE_IS_SET(prop->type)) { zend_string *type_str = zend_type_to_string(prop->type); smart_str_append(str, type_str); smart_str_appendc(str, ' '); zend_string_release(type_str); } if (!prop_name) { const char *class_name; zend_unmangle_property_name(prop->name, &class_name, &prop_name); } smart_str_append_printf(str, "$%s", prop_name); zval *default_value = property_get_default(prop); if (!Z_ISUNDEF_P(default_value)) { smart_str_appends(str, " = "); if (format_default_value(str, default_value, prop->ce) == FAILURE) { return; } } } smart_str_appends(str, " ]\n"); } /* }}} */ static void _extension_ini_string(zend_ini_entry *ini_entry, smart_str *str, char *indent, int number) /* {{{ */ { char *comma = ""; if (number == ini_entry->module_number) { smart_str_append_printf(str, " %sEntry [ %s <", indent, ZSTR_VAL(ini_entry->name)); if (ini_entry->modifiable == ZEND_INI_ALL) { smart_str_appends(str, "ALL"); } else { if (ini_entry->modifiable & ZEND_INI_USER) { smart_str_appends(str, "USER"); comma = ","; } if (ini_entry->modifiable & ZEND_INI_PERDIR) { smart_str_append_printf(str, "%sPERDIR", comma); comma = ","; } if (ini_entry->modifiable & ZEND_INI_SYSTEM) { smart_str_append_printf(str, "%sSYSTEM", comma); } } smart_str_appends(str, "> ]\n"); smart_str_append_printf(str, " %s Current = '%s'\n", indent, ini_entry->value ? ZSTR_VAL(ini_entry->value) : ""); if (ini_entry->modified) { smart_str_append_printf(str, " %s Default = '%s'\n", indent, ini_entry->orig_value ? ZSTR_VAL(ini_entry->orig_value) : ""); } smart_str_append_printf(str, " %s}\n", indent); } } /* }}} */ static void _extension_class_string(zend_class_entry *ce, zend_string *key, smart_str *str, char *indent, zend_module_entry *module, int *num_classes) /* {{{ */ { if (ce->type == ZEND_INTERNAL_CLASS && ce->info.internal.module && !strcasecmp(ce->info.internal.module->name, module->name)) { /* dump class if it is not an alias */ if (zend_string_equals_ci(ce->name, key)) { smart_str_append_printf(str, "\n"); _class_string(str, ce, NULL, indent); (*num_classes)++; } } } /* }}} */ static void _extension_string(smart_str *str, zend_module_entry *module, char *indent) /* {{{ */ { smart_str_append_printf(str, "%sExtension [ ", indent); if (module->type == MODULE_PERSISTENT) { smart_str_appends(str, "<persistent>"); } if (module->type == MODULE_TEMPORARY) { smart_str_appends(str, "<temporary>" ); } smart_str_append_printf(str, " extension #%d %s version %s ] {\n", module->module_number, module->name, (module->version == NO_VERSION_YET) ? "<no_version>" : module->version); if (module->deps) { const zend_module_dep* dep = module->deps; smart_str_appends(str, "\n - Dependencies {\n"); while(dep->name) { smart_str_append_printf(str, "%s Dependency [ %s (", indent, dep->name); switch(dep->type) { case MODULE_DEP_REQUIRED: smart_str_appends(str, "Required"); break; case MODULE_DEP_CONFLICTS: smart_str_appends(str, "Conflicts"); break; case MODULE_DEP_OPTIONAL: smart_str_appends(str, "Optional"); break; default: smart_str_appends(str, "Error"); /* shouldn't happen */ break; } if (dep->rel) { smart_str_append_printf(str, " %s", dep->rel); } if (dep->version) { smart_str_append_printf(str, " %s", dep->version); } smart_str_appends(str, ") ]\n"); dep++; } smart_str_append_printf(str, "%s }\n", indent); } { smart_str str_ini = {0}; zend_ini_entry *ini_entry; ZEND_HASH_FOREACH_PTR(EG(ini_directives), ini_entry) { _extension_ini_string(ini_entry, &str_ini, indent, module->module_number); } ZEND_HASH_FOREACH_END(); if (smart_str_get_len(&str_ini) > 0) { smart_str_append_printf(str, "\n - INI {\n"); smart_str_append_smart_str(str, &str_ini); smart_str_append_printf(str, "%s }\n", indent); } smart_str_free(&str_ini); } { smart_str str_constants = {0}; zend_constant *constant; int num_constants = 0; ZEND_HASH_FOREACH_PTR(EG(zend_constants), constant) { if (ZEND_CONSTANT_MODULE_NUMBER(constant) == module->module_number) { _const_string(&str_constants, ZSTR_VAL(constant->name), &constant->value, indent); num_constants++; } } ZEND_HASH_FOREACH_END(); if (num_constants) { smart_str_append_printf(str, "\n - Constants [%d] {\n", num_constants); smart_str_append_smart_str(str, &str_constants); smart_str_append_printf(str, "%s }\n", indent); } smart_str_free(&str_constants); } { zend_function *fptr; int first = 1; ZEND_HASH_FOREACH_PTR(CG(function_table), fptr) { if (fptr->common.type==ZEND_INTERNAL_FUNCTION && fptr->internal_function.module == module) { if (first) { smart_str_append_printf(str, "\n - Functions {\n"); first = 0; } _function_string(str, fptr, NULL, " "); } } ZEND_HASH_FOREACH_END(); if (!first) { smart_str_append_printf(str, "%s }\n", indent); } } { zend_string *sub_indent = strpprintf(0, "%s ", indent); smart_str str_classes = {0}; zend_string *key; zend_class_entry *ce; int num_classes = 0; ZEND_HASH_FOREACH_STR_KEY_PTR(EG(class_table), key, ce) { _extension_class_string(ce, key, &str_classes, ZSTR_VAL(sub_indent), module, &num_classes); } ZEND_HASH_FOREACH_END(); if (num_classes) { smart_str_append_printf(str, "\n - Classes [%d] {", num_classes); smart_str_append_smart_str(str, &str_classes); smart_str_append_printf(str, "%s }\n", indent); } smart_str_free(&str_classes); zend_string_release_ex(sub_indent, 0); } smart_str_append_printf(str, "%s}\n", indent); } /* }}} */ /* {{{ reflection_attribute_factory */ static void reflection_attribute_factory(zval *object, HashTable *attributes, zend_attribute *data, zend_class_entry *scope, uint32_t target, zend_string *filename) { reflection_object *intern; attribute_reference *reference; reflection_instantiate(reflection_attribute_ptr, object); intern = Z_REFLECTION_P(object); reference = (attribute_reference*) emalloc(sizeof(attribute_reference)); reference->attributes = attributes; reference->data = data; reference->scope = scope; reference->filename = filename ? zend_string_copy(filename) : NULL; reference->target = target; intern->ptr = reference; intern->ref_type = REF_TYPE_ATTRIBUTE; } /* }}} */ static int read_attributes(zval *ret, HashTable *attributes, zend_class_entry *scope, uint32_t offset, uint32_t target, zend_string *name, zend_class_entry *base, zend_string *filename) /* {{{ */ { ZEND_ASSERT(attributes != NULL); zend_attribute *attr; zval tmp; if (name) { // Name based filtering using lowercased key. zend_string *filter = zend_string_tolower(name); ZEND_HASH_FOREACH_PTR(attributes, attr) { if (attr->offset == offset && zend_string_equals(attr->lcname, filter)) { reflection_attribute_factory(&tmp, attributes, attr, scope, target, filename); add_next_index_zval(ret, &tmp); } } ZEND_HASH_FOREACH_END(); zend_string_release(filter); return SUCCESS; } ZEND_HASH_FOREACH_PTR(attributes, attr) { if (attr->offset != offset) { continue; } if (base) { // Base type filtering. zend_class_entry *ce = zend_lookup_class_ex(attr->name, attr->lcname, 0); if (ce == NULL) { // Bailout on error, otherwise ignore unavailable class. if (EG(exception)) { return FAILURE; } continue; } if (!instanceof_function(ce, base)) { continue; } } reflection_attribute_factory(&tmp, attributes, attr, scope, target, filename); add_next_index_zval(ret, &tmp); } ZEND_HASH_FOREACH_END(); return SUCCESS; } /* }}} */ static void reflect_attributes(INTERNAL_FUNCTION_PARAMETERS, HashTable *attributes, uint32_t offset, zend_class_entry *scope, uint32_t target, zend_string *filename) /* {{{ */ { zend_string *name = NULL; zend_long flags = 0; zend_class_entry *base = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!l", &name, &flags) == FAILURE) { RETURN_THROWS(); } if (flags & ~REFLECTION_ATTRIBUTE_IS_INSTANCEOF) { zend_argument_value_error(2, "must be a valid attribute filter flag"); RETURN_THROWS(); } if (name && (flags & REFLECTION_ATTRIBUTE_IS_INSTANCEOF)) { if (NULL == (base = zend_lookup_class(name))) { if (!EG(exception)) { zend_throw_error(NULL, "Class \"%s\" not found", ZSTR_VAL(name)); } RETURN_THROWS(); } name = NULL; } if (!attributes) { RETURN_EMPTY_ARRAY(); } array_init(return_value); if (FAILURE == read_attributes(return_value, attributes, scope, offset, target, name, base, filename)) { RETURN_THROWS(); } } /* }}} */ static void _zend_extension_string(smart_str *str, zend_extension *extension, char *indent) /* {{{ */ { smart_str_append_printf(str, "%sZend Extension [ %s ", indent, extension->name); if (extension->version) { smart_str_append_printf(str, "%s ", extension->version); } if (extension->copyright) { smart_str_append_printf(str, "%s ", extension->copyright); } if (extension->author) { smart_str_append_printf(str, "by %s ", extension->author); } if (extension->URL) { smart_str_append_printf(str, "<%s> ", extension->URL); } smart_str_appends(str, "]\n"); } /* }}} */ /* {{{ _function_check_flag */ static void _function_check_flag(INTERNAL_FUNCTION_PARAMETERS, int mask) { reflection_object *intern; zend_function *mptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(mptr); RETURN_BOOL(mptr->common.fn_flags & mask); } /* }}} */ /* {{{ zend_reflection_class_factory */ PHPAPI void zend_reflection_class_factory(zend_class_entry *ce, zval *object) { reflection_object *intern; reflection_instantiate(reflection_class_ptr, object); intern = Z_REFLECTION_P(object); intern->ptr = ce; intern->ref_type = REF_TYPE_OTHER; intern->ce = ce; ZVAL_STR_COPY(reflection_prop_name(object), ce->name); } /* }}} */ /* {{{ reflection_extension_factory */ static void reflection_extension_factory(zval *object, const char *name_str) { reflection_object *intern; size_t name_len = strlen(name_str); zend_string *lcname; struct _zend_module_entry *module; lcname = zend_string_alloc(name_len, 0); zend_str_tolower_copy(ZSTR_VAL(lcname), name_str, name_len); module = zend_hash_find_ptr(&module_registry, lcname); zend_string_efree(lcname); if (!module) { return; } reflection_instantiate(reflection_extension_ptr, object); intern = Z_REFLECTION_P(object); intern->ptr = module; intern->ref_type = REF_TYPE_OTHER; intern->ce = NULL; ZVAL_STRINGL(reflection_prop_name(object), module->name, name_len); } /* }}} */ /* {{{ reflection_parameter_factory */ static void reflection_parameter_factory(zend_function *fptr, zval *closure_object, struct _zend_arg_info *arg_info, uint32_t offset, zend_bool required, zval *object) { reflection_object *intern; parameter_reference *reference; zval *prop_name; reflection_instantiate(reflection_parameter_ptr, object); intern = Z_REFLECTION_P(object); reference = (parameter_reference*) emalloc(sizeof(parameter_reference)); reference->arg_info = arg_info; reference->offset = offset; reference->required = required; reference->fptr = fptr; intern->ptr = reference; intern->ref_type = REF_TYPE_PARAMETER; intern->ce = fptr->common.scope; if (closure_object) { ZVAL_OBJ_COPY(&intern->obj, Z_OBJ_P(closure_object)); } prop_name = reflection_prop_name(object); if (has_internal_arg_info(fptr)) { ZVAL_STRING(prop_name, ((zend_internal_arg_info*)arg_info)->name); } else { ZVAL_STR_COPY(prop_name, arg_info->name); } } /* }}} */ /* For backwards compatibility reasons, we need to return T|null style unions * as a ReflectionNamedType. Here we determine what counts as a union type and * what doesn't. */ static zend_bool is_union_type(zend_type type) { if (ZEND_TYPE_HAS_LIST(type)) { return 1; } uint32_t type_mask_without_null = ZEND_TYPE_PURE_MASK_WITHOUT_NULL(type); if (ZEND_TYPE_HAS_CLASS(type)) { return type_mask_without_null != 0; } if (type_mask_without_null == MAY_BE_BOOL) { return 0; } /* Check that only one bit is set. */ return (type_mask_without_null & (type_mask_without_null - 1)) != 0; } /* {{{ reflection_type_factory */ static void reflection_type_factory(zend_type type, zval *object, zend_bool legacy_behavior) { reflection_object *intern; type_reference *reference; zend_bool is_union = is_union_type(type); zend_bool is_mixed = ZEND_TYPE_PURE_MASK(type) == MAY_BE_ANY; reflection_instantiate(is_union && !is_mixed ? reflection_union_type_ptr : reflection_named_type_ptr, object); intern = Z_REFLECTION_P(object); reference = (type_reference*) emalloc(sizeof(type_reference)); reference->type = type; reference->legacy_behavior = legacy_behavior && !is_union && !is_mixed; intern->ptr = reference; intern->ref_type = REF_TYPE_TYPE; /* Property types may be resolved during the lifetime of the ReflectionType. * If we reference a string, make sure it doesn't get released. However, only * do this for the top-level type, as resolutions inside type lists will be * fully visible to us (we'd have to do a fully copy of the type if we wanted * to prevent that). */ if (ZEND_TYPE_HAS_NAME(type)) { zend_string_addref(ZEND_TYPE_NAME(type)); } } /* }}} */ /* {{{ reflection_function_factory */ static void reflection_function_factory(zend_function *function, zval *closure_object, zval *object) { reflection_object *intern; reflection_instantiate(reflection_function_ptr, object); intern = Z_REFLECTION_P(object); intern->ptr = function; intern->ref_type = REF_TYPE_FUNCTION; intern->ce = NULL; if (closure_object) { ZVAL_OBJ_COPY(&intern->obj, Z_OBJ_P(closure_object)); } ZVAL_STR_COPY(reflection_prop_name(object), function->common.function_name); } /* }}} */ /* {{{ reflection_method_factory */ static void reflection_method_factory(zend_class_entry *ce, zend_function *method, zval *closure_object, zval *object) { reflection_object *intern; reflection_instantiate(reflection_method_ptr, object); intern = Z_REFLECTION_P(object); intern->ptr = method; intern->ref_type = REF_TYPE_FUNCTION; intern->ce = ce; if (closure_object) { ZVAL_OBJ_COPY(&intern->obj, Z_OBJ_P(closure_object)); } ZVAL_STR_COPY(reflection_prop_name(object), method->common.function_name); ZVAL_STR_COPY(reflection_prop_class(object), method->common.scope->name); } /* }}} */ /* {{{ reflection_property_factory */ static void reflection_property_factory(zend_class_entry *ce, zend_string *name, zend_property_info *prop, zval *object) { reflection_object *intern; property_reference *reference; reflection_instantiate(reflection_property_ptr, object); intern = Z_REFLECTION_P(object); reference = (property_reference*) emalloc(sizeof(property_reference)); reference->prop = prop; reference->unmangled_name = zend_string_copy(name); intern->ptr = reference; intern->ref_type = REF_TYPE_PROPERTY; intern->ce = ce; intern->ignore_visibility = 0; ZVAL_STR_COPY(reflection_prop_name(object), name); ZVAL_STR_COPY(reflection_prop_class(object), prop ? prop->ce->name : ce->name); } /* }}} */ static void reflection_property_factory_str(zend_class_entry *ce, const char *name_str, size_t name_len, zend_property_info *prop, zval *object) { zend_string *name = zend_string_init(name_str, name_len, 0); reflection_property_factory(ce, name, prop, object); zend_string_release(name); } /* {{{ reflection_class_constant_factory */ static void reflection_class_constant_factory(zend_string *name_str, zend_class_constant *constant, zval *object) { reflection_object *intern; reflection_instantiate(reflection_class_constant_ptr, object); intern = Z_REFLECTION_P(object); intern->ptr = constant; intern->ref_type = REF_TYPE_CLASS_CONSTANT; intern->ce = constant->ce; intern->ignore_visibility = 0; ZVAL_STR_COPY(reflection_prop_name(object), name_str); ZVAL_STR_COPY(reflection_prop_class(object), constant->ce->name); } /* }}} */ static int get_parameter_default(zval *result, parameter_reference *param) { if (param->fptr->type == ZEND_INTERNAL_FUNCTION) { if (param->fptr->common.fn_flags & ZEND_ACC_USER_ARG_INFO) { /* We don't have a way to determine the default value for this case right now. */ return FAILURE; } return zend_get_default_from_internal_arg_info( result, (zend_internal_arg_info *) param->arg_info); } else { zval *default_value = get_default_from_recv((zend_op_array *) param->fptr, param->offset); if (!default_value) { return FAILURE; } ZVAL_COPY(result, default_value); return SUCCESS; } } /* {{{ Preventing __clone from being called */ ZEND_METHOD(ReflectionClass, __clone) { /* Should never be executable */ _DO_THROW("Cannot clone object using __clone()"); } /* }}} */ /* {{{ Returns an array of modifier names */ ZEND_METHOD(Reflection, getModifierNames) { zend_long modifiers; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &modifiers) == FAILURE) { RETURN_THROWS(); } array_init(return_value); if (modifiers & (ZEND_ACC_ABSTRACT | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { add_next_index_stringl(return_value, "abstract", sizeof("abstract")-1); } if (modifiers & ZEND_ACC_FINAL) { add_next_index_stringl(return_value, "final", sizeof("final")-1); } /* These are mutually exclusive */ switch (modifiers & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PUBLIC: add_next_index_stringl(return_value, "public", sizeof("public")-1); break; case ZEND_ACC_PRIVATE: add_next_index_stringl(return_value, "private", sizeof("private")-1); break; case ZEND_ACC_PROTECTED: add_next_index_stringl(return_value, "protected", sizeof("protected")-1); break; } if (modifiers & ZEND_ACC_STATIC) { add_next_index_stringl(return_value, "static", sizeof("static")-1); } } /* }}} */ /* {{{ Constructor. Throws an Exception in case the given function does not exist */ ZEND_METHOD(ReflectionFunction, __construct) { zval *object; zend_object *closure_obj = NULL; reflection_object *intern; zend_function *fptr; zend_string *fname, *lcname; object = ZEND_THIS; intern = Z_REFLECTION_P(object); ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_OBJ_OF_CLASS_OR_STR(closure_obj, zend_ce_closure, fname) ZEND_PARSE_PARAMETERS_END(); if (closure_obj) { fptr = (zend_function*)zend_get_closure_method_def(closure_obj); } else { if (UNEXPECTED(ZSTR_VAL(fname)[0] == '\\')) { /* Ignore leading "\" */ ALLOCA_FLAG(use_heap) ZSTR_ALLOCA_ALLOC(lcname, ZSTR_LEN(fname) - 1, use_heap); zend_str_tolower_copy(ZSTR_VAL(lcname), ZSTR_VAL(fname) + 1, ZSTR_LEN(fname) - 1); fptr = zend_fetch_function(lcname); ZSTR_ALLOCA_FREE(lcname, use_heap); } else { lcname = zend_string_tolower(fname); fptr = zend_fetch_function(lcname); zend_string_release(lcname); } if (fptr == NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Function %s() does not exist", ZSTR_VAL(fname)); RETURN_THROWS(); } } if (intern->ptr) { zval_ptr_dtor(&intern->obj); zval_ptr_dtor(reflection_prop_name(object)); } ZVAL_STR_COPY(reflection_prop_name(object), fptr->common.function_name); intern->ptr = fptr; intern->ref_type = REF_TYPE_FUNCTION; if (closure_obj) { ZVAL_OBJ_COPY(&intern->obj, closure_obj); } else { ZVAL_UNDEF(&intern->obj); } intern->ce = NULL; } /* }}} */ /* {{{ Returns a string representation */ ZEND_METHOD(ReflectionFunction, __toString) { reflection_object *intern; zend_function *fptr; smart_str str = {0}; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); _function_string(&str, fptr, intern->ce, ""); RETURN_STR(smart_str_extract(&str)); } /* }}} */ /* {{{ Returns this function's name */ ZEND_METHOD(ReflectionFunctionAbstract, getName) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); RETURN_STR_COPY(fptr->common.function_name); } /* }}} */ /* {{{ Returns whether this is a closure */ ZEND_METHOD(ReflectionFunctionAbstract, isClosure) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL(fptr->common.fn_flags & ZEND_ACC_CLOSURE); } /* }}} */ /* {{{ Returns this pointer bound to closure */ ZEND_METHOD(ReflectionFunctionAbstract, getClosureThis) { reflection_object *intern; zval* closure_this; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT(); if (!Z_ISUNDEF(intern->obj)) { closure_this = zend_get_closure_this_ptr(&intern->obj); if (!Z_ISUNDEF_P(closure_this)) { RETURN_OBJ_COPY(Z_OBJ_P(closure_this)); } } } /* }}} */ /* {{{ Returns the scope associated to the closure */ ZEND_METHOD(ReflectionFunctionAbstract, getClosureScopeClass) { reflection_object *intern; const zend_function *closure_func; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT(); if (!Z_ISUNDEF(intern->obj)) { closure_func = zend_get_closure_method_def(Z_OBJ(intern->obj)); if (closure_func && closure_func->common.scope) { zend_reflection_class_factory(closure_func->common.scope, return_value); } } } /* }}} */ /* {{{ Returns a dynamically created closure for the function */ ZEND_METHOD(ReflectionFunction, getClosure) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); if (!Z_ISUNDEF(intern->obj)) { /* Closures are immutable objects */ RETURN_OBJ_COPY(Z_OBJ(intern->obj)); } else { zend_create_fake_closure(return_value, fptr, NULL, NULL, NULL); } } /* }}} */ /* {{{ Returns whether this is an internal function */ ZEND_METHOD(ReflectionFunctionAbstract, isInternal) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL(fptr->type == ZEND_INTERNAL_FUNCTION); } /* }}} */ /* {{{ Returns whether this is a user-defined function */ ZEND_METHOD(ReflectionFunctionAbstract, isUserDefined) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL(fptr->type == ZEND_USER_FUNCTION); } /* }}} */ /* {{{ Returns whether this function has been disabled or not */ ZEND_METHOD(ReflectionFunction, isDisabled) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } /* A disabled function cannot be queried using Reflection. */ RETURN_FALSE; } /* }}} */ /* {{{ Returns the filename of the file this function was declared in */ ZEND_METHOD(ReflectionFunctionAbstract, getFileName) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION) { RETURN_STR_COPY(fptr->op_array.filename); } RETURN_FALSE; } /* }}} */ /* {{{ Returns the line this function's declaration starts at */ ZEND_METHOD(ReflectionFunctionAbstract, getStartLine) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION) { RETURN_LONG(fptr->op_array.line_start); } RETURN_FALSE; } /* }}} */ /* {{{ Returns the line this function's declaration ends at */ ZEND_METHOD(ReflectionFunctionAbstract, getEndLine) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION) { RETURN_LONG(fptr->op_array.line_end); } RETURN_FALSE; } /* }}} */ /* {{{ Returns the doc comment for this function */ ZEND_METHOD(ReflectionFunctionAbstract, getDocComment) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION && fptr->op_array.doc_comment) { RETURN_STR_COPY(fptr->op_array.doc_comment); } RETURN_FALSE; } /* }}} */ /* {{{ Returns the attributes of this function */ ZEND_METHOD(ReflectionFunctionAbstract, getAttributes) { reflection_object *intern; zend_function *fptr; uint32_t target; GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->common.scope) { target = ZEND_ATTRIBUTE_TARGET_METHOD; } else { target = ZEND_ATTRIBUTE_TARGET_FUNCTION; } reflect_attributes(INTERNAL_FUNCTION_PARAM_PASSTHRU, fptr->common.attributes, 0, fptr->common.scope, target, fptr->type == ZEND_USER_FUNCTION ? fptr->op_array.filename : NULL); } /* }}} */ /* {{{ Returns an associative array containing this function's static variables and their values */ ZEND_METHOD(ReflectionFunctionAbstract, getStaticVariables) { reflection_object *intern; zend_function *fptr; zval *val; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); /* Return an empty array in case no static variables exist */ if (fptr->type == ZEND_USER_FUNCTION && fptr->op_array.static_variables != NULL) { HashTable *ht; array_init(return_value); ht = ZEND_MAP_PTR_GET(fptr->op_array.static_variables_ptr); if (!ht) { ZEND_ASSERT(fptr->op_array.fn_flags & ZEND_ACC_IMMUTABLE); ht = zend_array_dup(fptr->op_array.static_variables); ZEND_MAP_PTR_SET(fptr->op_array.static_variables_ptr, ht); } ZEND_HASH_FOREACH_VAL(ht, val) { if (UNEXPECTED(zval_update_constant_ex(val, fptr->common.scope) != SUCCESS)) { RETURN_THROWS(); } } ZEND_HASH_FOREACH_END(); zend_hash_copy(Z_ARRVAL_P(return_value), ht, zval_add_ref); } else { RETURN_EMPTY_ARRAY(); } } /* }}} */ /* {{{ Invokes the function */ ZEND_METHOD(ReflectionFunction, invoke) { zval retval; zval *params; int result, num_args; HashTable *named_params; zend_fcall_info fci; zend_fcall_info_cache fcc; reflection_object *intern; zend_function *fptr; ZEND_PARSE_PARAMETERS_START(0, -1) Z_PARAM_VARIADIC_WITH_NAMED(params, num_args, named_params) ZEND_PARSE_PARAMETERS_END(); GET_REFLECTION_OBJECT_PTR(fptr); fci.size = sizeof(fci); ZVAL_UNDEF(&fci.function_name); fci.object = NULL; fci.retval = &retval; fci.param_count = num_args; fci.params = params; fci.named_params = named_params; fcc.function_handler = fptr; fcc.called_scope = NULL; fcc.object = NULL; if (!Z_ISUNDEF(intern->obj)) { Z_OBJ_HT(intern->obj)->get_closure( Z_OBJ(intern->obj), &fcc.called_scope, &fcc.function_handler, &fcc.object, 0); } result = zend_call_function(&fci, &fcc); if (result == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Invocation of function %s() failed", ZSTR_VAL(fptr->common.function_name)); RETURN_THROWS(); } if (Z_TYPE(retval) != IS_UNDEF) { if (Z_ISREF(retval)) { zend_unwrap_reference(&retval); } ZVAL_COPY_VALUE(return_value, &retval); } } /* }}} */ /* {{{ Invokes the function and pass its arguments as array. */ ZEND_METHOD(ReflectionFunction, invokeArgs) { zval retval; int result; zend_fcall_info fci; zend_fcall_info_cache fcc; reflection_object *intern; zend_function *fptr; HashTable *params; GET_REFLECTION_OBJECT_PTR(fptr); if (zend_parse_parameters(ZEND_NUM_ARGS(), "h", &params) == FAILURE) { RETURN_THROWS(); } fci.size = sizeof(fci); ZVAL_UNDEF(&fci.function_name); fci.object = NULL; fci.retval = &retval; fci.param_count = 0; fci.params = NULL; fci.named_params = params; fcc.function_handler = fptr; fcc.called_scope = NULL; fcc.object = NULL; if (!Z_ISUNDEF(intern->obj)) { Z_OBJ_HT(intern->obj)->get_closure( Z_OBJ(intern->obj), &fcc.called_scope, &fcc.function_handler, &fcc.object, 0); } result = zend_call_function(&fci, &fcc); if (result == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Invocation of function %s() failed", ZSTR_VAL(fptr->common.function_name)); RETURN_THROWS(); } if (Z_TYPE(retval) != IS_UNDEF) { if (Z_ISREF(retval)) { zend_unwrap_reference(&retval); } ZVAL_COPY_VALUE(return_value, &retval); } } /* }}} */ /* {{{ Gets whether this function returns a reference */ ZEND_METHOD(ReflectionFunctionAbstract, returnsReference) { reflection_object *intern; zend_function *fptr; GET_REFLECTION_OBJECT_PTR(fptr); if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } RETURN_BOOL((fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) != 0); } /* }}} */ /* {{{ Gets the number of parameters */ ZEND_METHOD(ReflectionFunctionAbstract, getNumberOfParameters) { reflection_object *intern; zend_function *fptr; uint32_t num_args; GET_REFLECTION_OBJECT_PTR(fptr); if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } num_args = fptr->common.num_args; if (fptr->common.fn_flags & ZEND_ACC_VARIADIC) { num_args++; } RETURN_LONG(num_args); } /* }}} */ /* {{{ Gets the number of required parameters */ ZEND_METHOD(ReflectionFunctionAbstract, getNumberOfRequiredParameters) { reflection_object *intern; zend_function *fptr; GET_REFLECTION_OBJECT_PTR(fptr); if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } RETURN_LONG(fptr->common.required_num_args); } /* }}} */ /* {{{ Returns an array of parameter objects for this function */ ZEND_METHOD(ReflectionFunctionAbstract, getParameters) { reflection_object *intern; zend_function *fptr; uint32_t i, num_args; struct _zend_arg_info *arg_info; GET_REFLECTION_OBJECT_PTR(fptr); if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } arg_info= fptr->common.arg_info; num_args = fptr->common.num_args; if (fptr->common.fn_flags & ZEND_ACC_VARIADIC) { num_args++; } if (!num_args) { RETURN_EMPTY_ARRAY(); } array_init(return_value); for (i = 0; i < num_args; i++) { zval parameter; reflection_parameter_factory( _copy_function(fptr), Z_ISUNDEF(intern->obj) ? NULL : &intern->obj, arg_info, i, i < fptr->common.required_num_args, &parameter ); add_next_index_zval(return_value, &parameter); arg_info++; } } /* }}} */ /* {{{ Returns NULL or the extension the function belongs to */ ZEND_METHOD(ReflectionFunctionAbstract, getExtension) { reflection_object *intern; zend_function *fptr; zend_internal_function *internal; GET_REFLECTION_OBJECT_PTR(fptr); if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } if (fptr->type != ZEND_INTERNAL_FUNCTION) { RETURN_NULL(); } internal = (zend_internal_function *)fptr; if (internal->module) { reflection_extension_factory(return_value, internal->module->name); } else { RETURN_NULL(); } } /* }}} */ /* {{{ Returns false or the name of the extension the function belongs to */ ZEND_METHOD(ReflectionFunctionAbstract, getExtensionName) { reflection_object *intern; zend_function *fptr; zend_internal_function *internal; GET_REFLECTION_OBJECT_PTR(fptr); if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } if (fptr->type != ZEND_INTERNAL_FUNCTION) { RETURN_FALSE; } internal = (zend_internal_function *)fptr; if (internal->module) { RETURN_STRING(internal->module->name); } else { RETURN_FALSE; } } /* }}} */ /* {{{ */ ZEND_METHOD(ReflectionGenerator, __construct) { zval *generator, *object; reflection_object *intern; zend_execute_data *ex; object = ZEND_THIS; intern = Z_REFLECTION_P(object); if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &generator, zend_ce_generator) == FAILURE) { RETURN_THROWS(); } ex = ((zend_generator *) Z_OBJ_P(generator))->execute_data; if (!ex) { _DO_THROW("Cannot create ReflectionGenerator based on a terminated Generator"); RETURN_THROWS(); } if (intern->ce) { zval_ptr_dtor(&intern->obj); } intern->ref_type = REF_TYPE_GENERATOR; ZVAL_OBJ_COPY(&intern->obj, Z_OBJ_P(generator)); intern->ce = zend_ce_generator; } /* }}} */ #define REFLECTION_CHECK_VALID_GENERATOR(ex) \ if (!ex) { \ _DO_THROW("Cannot fetch information from a terminated Generator"); \ RETURN_THROWS(); \ } /* {{{ */ ZEND_METHOD(ReflectionGenerator, getTrace) { zend_long options = DEBUG_BACKTRACE_PROVIDE_OBJECT; zend_generator *generator = (zend_generator *) Z_OBJ(Z_REFLECTION_P(ZEND_THIS)->obj); zend_generator *root_generator; zend_execute_data *ex_backup = EG(current_execute_data); zend_execute_data *ex = generator->execute_data; zend_execute_data *root_prev = NULL, *cur_prev; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &options) == FAILURE) { RETURN_THROWS(); } REFLECTION_CHECK_VALID_GENERATOR(ex) root_generator = zend_generator_get_current(generator); cur_prev = generator->execute_data->prev_execute_data; if (generator == root_generator) { generator->execute_data->prev_execute_data = NULL; } else { root_prev = root_generator->execute_data->prev_execute_data; generator->execute_fake.prev_execute_data = NULL; root_generator->execute_data->prev_execute_data = &generator->execute_fake; } EG(current_execute_data) = root_generator->execute_data; zend_fetch_debug_backtrace(return_value, 0, options, 0); EG(current_execute_data) = ex_backup; root_generator->execute_data->prev_execute_data = root_prev; generator->execute_data->prev_execute_data = cur_prev; } /* }}} */ /* {{{ */ ZEND_METHOD(ReflectionGenerator, getExecutingLine) { zend_generator *generator = (zend_generator *) Z_OBJ(Z_REFLECTION_P(ZEND_THIS)->obj); zend_execute_data *ex = generator->execute_data; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } REFLECTION_CHECK_VALID_GENERATOR(ex) ZVAL_LONG(return_value, ex->opline->lineno); } /* }}} */ /* {{{ */ ZEND_METHOD(ReflectionGenerator, getExecutingFile) { zend_generator *generator = (zend_generator *) Z_OBJ(Z_REFLECTION_P(ZEND_THIS)->obj); zend_execute_data *ex = generator->execute_data; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } REFLECTION_CHECK_VALID_GENERATOR(ex) ZVAL_STR_COPY(return_value, ex->func->op_array.filename); } /* }}} */ /* {{{ */ ZEND_METHOD(ReflectionGenerator, getFunction) { zend_generator *generator = (zend_generator *) Z_OBJ(Z_REFLECTION_P(ZEND_THIS)->obj); zend_execute_data *ex = generator->execute_data; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } REFLECTION_CHECK_VALID_GENERATOR(ex) if (ex->func->common.fn_flags & ZEND_ACC_CLOSURE) { zval closure; ZVAL_OBJ(&closure, ZEND_CLOSURE_OBJECT(ex->func)); reflection_function_factory(ex->func, &closure, return_value); } else if (ex->func->op_array.scope) { reflection_method_factory(ex->func->op_array.scope, ex->func, NULL, return_value); } else { reflection_function_factory(ex->func, NULL, return_value); } } /* }}} */ /* {{{ */ ZEND_METHOD(ReflectionGenerator, getThis) { zend_generator *generator = (zend_generator *) Z_OBJ(Z_REFLECTION_P(ZEND_THIS)->obj); zend_execute_data *ex = generator->execute_data; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } REFLECTION_CHECK_VALID_GENERATOR(ex) if (Z_TYPE(ex->This) == IS_OBJECT) { RETURN_OBJ_COPY(Z_OBJ(ex->This)); } else { RETURN_NULL(); } } /* }}} */ /* {{{ */ ZEND_METHOD(ReflectionGenerator, getExecutingGenerator) { zend_generator *generator = (zend_generator *) Z_OBJ(Z_REFLECTION_P(ZEND_THIS)->obj); zend_execute_data *ex = generator->execute_data; zend_generator *current; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } REFLECTION_CHECK_VALID_GENERATOR(ex) current = zend_generator_get_current(generator); RETURN_OBJ_COPY(&current->std); } /* }}} */ /* {{{ Constructor. Throws an Exception in case the given method does not exist */ ZEND_METHOD(ReflectionParameter, __construct) { parameter_reference *ref; zval *reference; zend_string *arg_name = NULL; zend_long position; zval *object; zval *prop_name; reflection_object *intern; zend_function *fptr; struct _zend_arg_info *arg_info; uint32_t num_args; zend_class_entry *ce = NULL; zend_bool is_closure = 0; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_ZVAL(reference) Z_PARAM_STR_OR_LONG(arg_name, position) ZEND_PARSE_PARAMETERS_END(); object = ZEND_THIS; intern = Z_REFLECTION_P(object); /* First, find the function */ switch (Z_TYPE_P(reference)) { case IS_STRING: { zend_string *lcname = zend_string_tolower(Z_STR_P(reference)); fptr = zend_hash_find_ptr(EG(function_table), lcname); zend_string_release(lcname); if (!fptr) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Function %s() does not exist", Z_STRVAL_P(reference)); RETURN_THROWS(); } ce = fptr->common.scope; } break; case IS_ARRAY: { zval *classref; zval *method; zend_string *name, *lcname; if (((classref = zend_hash_index_find(Z_ARRVAL_P(reference), 0)) == NULL) || ((method = zend_hash_index_find(Z_ARRVAL_P(reference), 1)) == NULL)) { _DO_THROW("Expected array($object, $method) or array($classname, $method)"); RETURN_THROWS(); } if (Z_TYPE_P(classref) == IS_OBJECT) { ce = Z_OBJCE_P(classref); } else { name = zval_try_get_string(classref); if (UNEXPECTED(!name)) { return; } if ((ce = zend_lookup_class(name)) == NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Class \"%s\" does not exist", ZSTR_VAL(name)); zend_string_release(name); RETURN_THROWS(); } zend_string_release(name); } name = zval_try_get_string(method); if (UNEXPECTED(!name)) { return; } lcname = zend_string_tolower(name); if (Z_TYPE_P(classref) == IS_OBJECT && is_closure_invoke(ce, lcname) && (fptr = zend_get_closure_invoke_method(Z_OBJ_P(classref))) != NULL) { /* nothing to do. don't set is_closure since is the invoke handler, not the closure itself */ } else if ((fptr = zend_hash_find_ptr(&ce->function_table, lcname)) == NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Method %s::%s() does not exist", ZSTR_VAL(ce->name), ZSTR_VAL(name)); zend_string_release(name); zend_string_release(lcname); RETURN_THROWS(); } zend_string_release(name); zend_string_release(lcname); } break; case IS_OBJECT: { ce = Z_OBJCE_P(reference); if (instanceof_function(ce, zend_ce_closure)) { fptr = (zend_function *)zend_get_closure_method_def(Z_OBJ_P(reference)); Z_ADDREF_P(reference); is_closure = 1; } else if ((fptr = zend_hash_find_ptr(&ce->function_table, ZSTR_KNOWN(ZEND_STR_MAGIC_INVOKE))) == NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Method %s::%s() does not exist", ZSTR_VAL(ce->name), ZEND_INVOKE_FUNC_NAME); RETURN_THROWS(); } } break; default: zend_argument_error(reflection_exception_ptr, 1, "must be a string, an array(class, method), or a callable object, %s given", zend_zval_type_name(reference)); RETURN_THROWS(); } /* Now, search for the parameter */ arg_info = fptr->common.arg_info; num_args = fptr->common.num_args; if (fptr->common.fn_flags & ZEND_ACC_VARIADIC) { num_args++; } if (arg_name != NULL) { uint32_t i; position = -1; if (has_internal_arg_info(fptr)) { for (i = 0; i < num_args; i++) { if (arg_info[i].name) { if (strcmp(((zend_internal_arg_info*)arg_info)[i].name, ZSTR_VAL(arg_name)) == 0) { position = i; break; } } } } else { for (i = 0; i < num_args; i++) { if (arg_info[i].name) { if (zend_string_equals(arg_name, arg_info[i].name)) { position = i; break; } } } } if (position == -1) { _DO_THROW("The parameter specified by its name could not be found"); goto failure; } } else { if (position < 0) { zend_argument_value_error(2, "must be greater than or equal to 0"); goto failure; } if (position >= num_args) { _DO_THROW("The parameter specified by its offset could not be found"); goto failure; } } ref = (parameter_reference*) emalloc(sizeof(parameter_reference)); ref->arg_info = &arg_info[position]; ref->offset = (uint32_t)position; ref->required = (uint32_t)position < fptr->common.required_num_args; ref->fptr = fptr; /* TODO: copy fptr */ intern->ptr = ref; intern->ref_type = REF_TYPE_PARAMETER; intern->ce = ce; if (reference && is_closure) { ZVAL_COPY_VALUE(&intern->obj, reference); } prop_name = reflection_prop_name(object); if (has_internal_arg_info(fptr)) { ZVAL_STRING(prop_name, ((zend_internal_arg_info*)arg_info)[position].name); } else { ZVAL_STR_COPY(prop_name, arg_info[position].name); } return; failure: if (fptr->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) { zend_string_release_ex(fptr->common.function_name, 0); zend_free_trampoline(fptr); } if (is_closure) { zval_ptr_dtor(reference); } RETURN_THROWS(); } /* }}} */ /* {{{ Returns a string representation */ ZEND_METHOD(ReflectionParameter, __toString) { reflection_object *intern; parameter_reference *param; smart_str str = {0}; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); _parameter_string(&str, param->fptr, param->arg_info, param->offset, param->required, ""); RETURN_STR(smart_str_extract(&str)); } /* }}} */ /* {{{ Returns this parameters's name */ ZEND_METHOD(ReflectionParameter, getName) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); if (has_internal_arg_info(param->fptr)) { RETURN_STRING(((zend_internal_arg_info *) param->arg_info)->name); } else { RETURN_STR_COPY(param->arg_info->name); } } /* }}} */ /* {{{ Returns the ReflectionFunction for the function of this parameter */ ZEND_METHOD(ReflectionParameter, getDeclaringFunction) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); if (!param->fptr->common.scope) { reflection_function_factory(_copy_function(param->fptr), Z_ISUNDEF(intern->obj)? NULL : &intern->obj, return_value); } else { reflection_method_factory(param->fptr->common.scope, _copy_function(param->fptr), Z_ISUNDEF(intern->obj)? NULL : &intern->obj, return_value); } } /* }}} */ /* {{{ Returns in which class this parameter is defined (not the type of the parameter) */ ZEND_METHOD(ReflectionParameter, getDeclaringClass) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); if (param->fptr->common.scope) { zend_reflection_class_factory(param->fptr->common.scope, return_value); } } /* }}} */ /* {{{ Returns this parameters's class hint or NULL if there is none */ ZEND_METHOD(ReflectionParameter, getClass) { reflection_object *intern; parameter_reference *param; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); // TODO: This is going to return null for union types, which is rather odd. if (ZEND_TYPE_HAS_NAME(param->arg_info->type)) { /* Class name is stored as a string, we might also get "self" or "parent" * - For "self", simply use the function scope. If scope is NULL then * the function is global and thus self does not make any sense * * - For "parent", use the function scope's parent. If scope is NULL then * the function is global and thus parent does not make any sense. * If the parent is NULL then the class does not extend anything and * thus parent does not make any sense, either. * * TODO: Think about moving these checks to the compiler or some sort of * lint-mode. */ zend_string *class_name; class_name = ZEND_TYPE_NAME(param->arg_info->type); if (0 == zend_binary_strcasecmp(ZSTR_VAL(class_name), ZSTR_LEN(class_name), "self", sizeof("self")- 1)) { ce = param->fptr->common.scope; if (!ce) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Parameter uses \"self\" as type but function is not a class member"); RETURN_THROWS(); } } else if (0 == zend_binary_strcasecmp(ZSTR_VAL(class_name), ZSTR_LEN(class_name), "parent", sizeof("parent")- 1)) { ce = param->fptr->common.scope; if (!ce) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Parameter uses \"parent\" as type but function is not a class member"); RETURN_THROWS(); } if (!ce->parent) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Parameter uses \"parent\" as type although class does not have a parent"); RETURN_THROWS(); } ce = ce->parent; } else { ce = zend_lookup_class(class_name); if (!ce) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Class \"%s\" does not exist", ZSTR_VAL(class_name)); RETURN_THROWS(); } } zend_reflection_class_factory(ce, return_value); } } /* }}} */ /* {{{ Returns whether parameter has a type */ ZEND_METHOD(ReflectionParameter, hasType) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(ZEND_TYPE_IS_SET(param->arg_info->type)); } /* }}} */ /* {{{ Returns the type associated with the parameter */ ZEND_METHOD(ReflectionParameter, getType) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); if (!ZEND_TYPE_IS_SET(param->arg_info->type)) { RETURN_NULL(); } reflection_type_factory(param->arg_info->type, return_value, 1); } /* }}} */ /* {{{ Returns whether parameter MUST be an array */ ZEND_METHOD(ReflectionParameter, isArray) { reflection_object *intern; parameter_reference *param; uint32_t type_mask; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); type_mask = ZEND_TYPE_PURE_MASK_WITHOUT_NULL(param->arg_info->type); RETVAL_BOOL(type_mask == MAY_BE_ARRAY); } /* }}} */ /* {{{ Returns whether parameter MUST be callable */ ZEND_METHOD(ReflectionParameter, isCallable) { reflection_object *intern; parameter_reference *param; uint32_t type_mask; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); type_mask = ZEND_TYPE_PURE_MASK_WITHOUT_NULL(param->arg_info->type); RETVAL_BOOL(type_mask == MAY_BE_CALLABLE); } /* }}} */ /* {{{ Returns whether NULL is allowed as this parameters's value */ ZEND_METHOD(ReflectionParameter, allowsNull) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(!ZEND_TYPE_IS_SET(param->arg_info->type) || ZEND_TYPE_ALLOW_NULL(param->arg_info->type)); } /* }}} */ /* {{{ Returns whether this parameters is passed to by reference */ ZEND_METHOD(ReflectionParameter, isPassedByReference) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(ZEND_ARG_SEND_MODE(param->arg_info)); } /* }}} */ /* {{{ Returns whether this parameter can be passed by value */ ZEND_METHOD(ReflectionParameter, canBePassedByValue) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); /* true if it's ZEND_SEND_BY_VAL or ZEND_SEND_PREFER_REF */ RETVAL_BOOL(ZEND_ARG_SEND_MODE(param->arg_info) != ZEND_SEND_BY_REF); } /* }}} */ /* {{{ Get parameter attributes. */ ZEND_METHOD(ReflectionParameter, getAttributes) { reflection_object *intern; parameter_reference *param; GET_REFLECTION_OBJECT_PTR(param); HashTable *attributes = param->fptr->common.attributes; zend_class_entry *scope = param->fptr->common.scope; reflect_attributes(INTERNAL_FUNCTION_PARAM_PASSTHRU, attributes, param->offset + 1, scope, ZEND_ATTRIBUTE_TARGET_PARAMETER, param->fptr->type == ZEND_USER_FUNCTION ? param->fptr->op_array.filename : NULL); } /* {{{ Returns whether this parameter is an optional parameter */ ZEND_METHOD(ReflectionParameter, getPosition) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); RETVAL_LONG(param->offset); } /* }}} */ /* {{{ Returns whether this parameter is an optional parameter */ ZEND_METHOD(ReflectionParameter, isOptional) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(!param->required); } /* }}} */ /* {{{ Returns whether the default value of this parameter is available */ ZEND_METHOD(ReflectionParameter, isDefaultValueAvailable) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); if (param->fptr->type == ZEND_INTERNAL_FUNCTION) { RETURN_BOOL(!(param->fptr->common.fn_flags & ZEND_ACC_USER_ARG_INFO) && ((zend_internal_arg_info*) (param->arg_info))->default_value); } else { zval *default_value = get_default_from_recv((zend_op_array *)param->fptr, param->offset); RETURN_BOOL(default_value != NULL); } } /* }}} */ /* {{{ Returns the default value of this parameter or throws an exception */ ZEND_METHOD(ReflectionParameter, getDefaultValue) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); if (get_parameter_default(return_value, param) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Internal error: Failed to retrieve the default value"); RETURN_THROWS(); } if (Z_TYPE_P(return_value) == IS_CONSTANT_AST) { zval_update_constant_ex(return_value, param->fptr->common.scope); } } /* }}} */ /* {{{ Returns whether the default value of this parameter is constant */ ZEND_METHOD(ReflectionParameter, isDefaultValueConstant) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); zval default_value; if (get_parameter_default(&default_value, param) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Internal error: Failed to retrieve the default value"); RETURN_THROWS(); } if (Z_TYPE(default_value) == IS_CONSTANT_AST) { zend_ast *ast = Z_ASTVAL(default_value); RETVAL_BOOL(ast->kind == ZEND_AST_CONSTANT || ast->kind == ZEND_AST_CONSTANT_CLASS); } else { RETVAL_FALSE; } zval_ptr_dtor_nogc(&default_value); } /* }}} */ /* {{{ Returns the default value's constant name if default value is constant or null */ ZEND_METHOD(ReflectionParameter, getDefaultValueConstantName) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); zval default_value; if (get_parameter_default(&default_value, param) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Internal error: Failed to retrieve the default value"); RETURN_THROWS(); } if (Z_TYPE(default_value) != IS_CONSTANT_AST) { zval_ptr_dtor_nogc(&default_value); RETURN_NULL(); } zend_ast *ast = Z_ASTVAL(default_value); if (ast->kind == ZEND_AST_CONSTANT) { RETVAL_STR_COPY(zend_ast_get_constant_name(ast)); } else if (ast->kind == ZEND_AST_CONSTANT_CLASS) { RETVAL_STRINGL("__CLASS__", sizeof("__CLASS__")-1); } else { RETVAL_NULL(); } zval_ptr_dtor_nogc(&default_value); } /* {{{ Returns whether this parameter is a variadic parameter */ ZEND_METHOD(ReflectionParameter, isVariadic) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(ZEND_ARG_IS_VARIADIC(param->arg_info)); } /* }}} */ /* {{{ Returns this constructor parameter has been promoted to a property */ ZEND_METHOD(ReflectionParameter, isPromoted) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(ZEND_ARG_IS_PROMOTED(param->arg_info)); } /* }}} */ /* {{{ Returns whether parameter MAY be null */ ZEND_METHOD(ReflectionType, allowsNull) { reflection_object *intern; type_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(ZEND_TYPE_ALLOW_NULL(param->type)); } /* }}} */ static zend_string *zend_type_to_string_without_null(zend_type type) { ZEND_TYPE_FULL_MASK(type) &= ~MAY_BE_NULL; return zend_type_to_string(type); } /* {{{ Return the text of the type hint */ ZEND_METHOD(ReflectionType, __toString) { reflection_object *intern; type_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); RETURN_STR(zend_type_to_string(param->type)); } /* }}} */ /* {{{ Return the name of the type */ ZEND_METHOD(ReflectionNamedType, getName) { reflection_object *intern; type_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); if (param->legacy_behavior) { RETURN_STR(zend_type_to_string_without_null(param->type)); } RETURN_STR(zend_type_to_string(param->type)); } /* }}} */ /* {{{ Returns whether type is a builtin type */ ZEND_METHOD(ReflectionNamedType, isBuiltin) { reflection_object *intern; type_reference *param; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); /* Treat "static" as a class type for the purposes of reflection. */ RETVAL_BOOL(ZEND_TYPE_IS_ONLY_MASK(param->type) && !(ZEND_TYPE_FULL_MASK(param->type) & MAY_BE_STATIC)); } /* }}} */ static void append_type(zval *return_value, zend_type type) { zval reflection_type; reflection_type_factory(type, &reflection_type, 0); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &reflection_type); } static void append_type_mask(zval *return_value, uint32_t type_mask) { append_type(return_value, (zend_type) ZEND_TYPE_INIT_MASK(type_mask)); } /* {{{ Returns the types that are part of this union type */ ZEND_METHOD(ReflectionUnionType, getTypes) { reflection_object *intern; type_reference *param; uint32_t type_mask; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(param); array_init(return_value); if (ZEND_TYPE_HAS_LIST(param->type)) { zend_type *list_type; ZEND_TYPE_LIST_FOREACH(ZEND_TYPE_LIST(param->type), list_type) { append_type(return_value, *list_type); } ZEND_TYPE_LIST_FOREACH_END(); } else if (ZEND_TYPE_HAS_NAME(param->type)) { append_type(return_value, (zend_type) ZEND_TYPE_INIT_CLASS(ZEND_TYPE_NAME(param->type), 0, 0)); } else if (ZEND_TYPE_HAS_CE(param->type)) { append_type(return_value, (zend_type) ZEND_TYPE_INIT_CE(ZEND_TYPE_CE(param->type), 0, 0)); } type_mask = ZEND_TYPE_PURE_MASK(param->type); ZEND_ASSERT(!(type_mask & MAY_BE_VOID)); if (type_mask & MAY_BE_STATIC) { append_type_mask(return_value, MAY_BE_STATIC); } if (type_mask & MAY_BE_CALLABLE) { append_type_mask(return_value, MAY_BE_CALLABLE); } if (type_mask & MAY_BE_ITERABLE) { append_type_mask(return_value, MAY_BE_ITERABLE); } if (type_mask & MAY_BE_OBJECT) { append_type_mask(return_value, MAY_BE_OBJECT); } if (type_mask & MAY_BE_ARRAY) { append_type_mask(return_value, MAY_BE_ARRAY); } if (type_mask & MAY_BE_STRING) { append_type_mask(return_value, MAY_BE_STRING); } if (type_mask & MAY_BE_LONG) { append_type_mask(return_value, MAY_BE_LONG); } if (type_mask & MAY_BE_DOUBLE) { append_type_mask(return_value, MAY_BE_DOUBLE); } if ((type_mask & MAY_BE_BOOL) == MAY_BE_BOOL) { append_type_mask(return_value, MAY_BE_BOOL); } else if (type_mask & MAY_BE_FALSE) { append_type_mask(return_value, MAY_BE_FALSE); } if (type_mask & MAY_BE_NULL) { append_type_mask(return_value, MAY_BE_NULL); } } /* }}} */ /* {{{ Constructor. Throws an Exception in case the given method does not exist */ ZEND_METHOD(ReflectionMethod, __construct) { zend_object *arg1_obj; zend_string *arg1_str; zend_string *arg2_str = NULL; zend_object *orig_obj = NULL; zend_class_entry *ce = NULL; zend_string *class_name = NULL; char *method_name; size_t method_name_len; char *lcname; zval *object; reflection_object *intern; zend_function *mptr; ZEND_PARSE_PARAMETERS_START(1, 2) Z_PARAM_OBJ_OR_STR(arg1_obj, arg1_str) Z_PARAM_OPTIONAL Z_PARAM_STR_OR_NULL(arg2_str) ZEND_PARSE_PARAMETERS_END(); if (arg1_obj) { if (!arg2_str) { zend_argument_value_error(2, "cannot be null when argument #1 ($objectOrMethod) is an object"); RETURN_THROWS(); } orig_obj = arg1_obj; ce = arg1_obj->ce; method_name = ZSTR_VAL(arg2_str); method_name_len = ZSTR_LEN(arg2_str); } else if (arg2_str) { class_name = zend_string_copy(arg1_str); method_name = ZSTR_VAL(arg2_str); method_name_len = ZSTR_LEN(arg2_str); } else { char *tmp; size_t tmp_len; char *name = ZSTR_VAL(arg1_str); if ((tmp = strstr(name, "::")) == NULL) { zend_argument_error(reflection_exception_ptr, 1, "must be a valid method name"); RETURN_THROWS(); } tmp_len = tmp - name; class_name = zend_string_init(name, tmp_len, 0); method_name = tmp + 2; method_name_len = ZSTR_LEN(arg1_str) - tmp_len - 2; } if (class_name) { if ((ce = zend_lookup_class(class_name)) == NULL) { if (!EG(exception)) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Class \"%s\" does not exist", ZSTR_VAL(class_name)); } zend_string_release(class_name); RETURN_THROWS(); } zend_string_release(class_name); } object = ZEND_THIS; intern = Z_REFLECTION_P(object); lcname = zend_str_tolower_dup(method_name, method_name_len); if (ce == zend_ce_closure && orig_obj && (method_name_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lcname, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && (mptr = zend_get_closure_invoke_method(orig_obj)) != NULL) { /* do nothing, mptr already set */ } else if ((mptr = zend_hash_str_find_ptr(&ce->function_table, lcname, method_name_len)) == NULL) { efree(lcname); zend_throw_exception_ex(reflection_exception_ptr, 0, "Method %s::%s() does not exist", ZSTR_VAL(ce->name), method_name); RETURN_THROWS(); } efree(lcname); ZVAL_STR_COPY(reflection_prop_name(object), mptr->common.function_name); ZVAL_STR_COPY(reflection_prop_class(object), mptr->common.scope->name); intern->ptr = mptr; intern->ref_type = REF_TYPE_FUNCTION; intern->ce = ce; } /* }}} */ /* {{{ Returns a string representation */ ZEND_METHOD(ReflectionMethod, __toString) { reflection_object *intern; zend_function *mptr; smart_str str = {0}; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(mptr); _function_string(&str, mptr, intern->ce, ""); RETURN_STR(smart_str_extract(&str)); } /* }}} */ /* {{{ Invokes the function */ ZEND_METHOD(ReflectionMethod, getClosure) { reflection_object *intern; zval *obj = NULL; zend_function *mptr; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|o!", &obj) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(mptr); if (mptr->common.fn_flags & ZEND_ACC_STATIC) { zend_create_fake_closure(return_value, mptr, mptr->common.scope, mptr->common.scope, NULL); } else { if (!obj) { zend_argument_value_error(1, "cannot be null for non-static methods"); RETURN_THROWS(); } if (!instanceof_function(Z_OBJCE_P(obj), mptr->common.scope)) { _DO_THROW("Given object is not an instance of the class this method was declared in"); RETURN_THROWS(); } /* This is an original closure object and __invoke is to be called. */ if (Z_OBJCE_P(obj) == zend_ce_closure && (mptr->internal_function.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) { RETURN_OBJ_COPY(Z_OBJ_P(obj)); } else { zend_create_fake_closure(return_value, mptr, mptr->common.scope, Z_OBJCE_P(obj), obj); } } } /* }}} */ /* {{{ reflection_method_invoke */ static void reflection_method_invoke(INTERNAL_FUNCTION_PARAMETERS, int variadic) { zval retval; zval *params = NULL, *object; HashTable *named_params = NULL; reflection_object *intern; zend_function *mptr; int argc = 0, result; zend_fcall_info fci; zend_fcall_info_cache fcc; zend_class_entry *obj_ce; GET_REFLECTION_OBJECT_PTR(mptr); if (mptr->common.fn_flags & ZEND_ACC_ABSTRACT) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Trying to invoke abstract method %s::%s()", ZSTR_VAL(mptr->common.scope->name), ZSTR_VAL(mptr->common.function_name)); RETURN_THROWS(); } if (!(mptr->common.fn_flags & ZEND_ACC_PUBLIC) && intern->ignore_visibility == 0) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Trying to invoke %s method %s::%s() from scope %s", mptr->common.fn_flags & ZEND_ACC_PROTECTED ? "protected" : "private", ZSTR_VAL(mptr->common.scope->name), ZSTR_VAL(mptr->common.function_name), ZSTR_VAL(Z_OBJCE_P(ZEND_THIS)->name)); RETURN_THROWS(); } if (variadic) { ZEND_PARSE_PARAMETERS_START(1, -1) Z_PARAM_OBJECT_OR_NULL(object) Z_PARAM_VARIADIC_WITH_NAMED(params, argc, named_params) ZEND_PARSE_PARAMETERS_END(); } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), "o!h", &object, &named_params) == FAILURE) { RETURN_THROWS(); } } /* In case this is a static method, we shouldn't pass an object_ptr * (which is used as calling context aka $this). We can thus ignore the * first parameter. * * Else, we verify that the given object is an instance of the class. */ if (mptr->common.fn_flags & ZEND_ACC_STATIC) { object = NULL; obj_ce = mptr->common.scope; } else { if (!object) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Trying to invoke non static method %s::%s() without an object", ZSTR_VAL(mptr->common.scope->name), ZSTR_VAL(mptr->common.function_name)); RETURN_THROWS(); } obj_ce = Z_OBJCE_P(object); if (!instanceof_function(obj_ce, mptr->common.scope)) { if (!variadic) { efree(params); } _DO_THROW("Given object is not an instance of the class this method was declared in"); RETURN_THROWS(); } } fci.size = sizeof(fci); ZVAL_UNDEF(&fci.function_name); fci.object = object ? Z_OBJ_P(object) : NULL; fci.retval = &retval; fci.param_count = argc; fci.params = params; fci.named_params = named_params; fcc.function_handler = mptr; fcc.called_scope = intern->ce; fcc.object = object ? Z_OBJ_P(object) : NULL; /* * Copy the zend_function when calling via handler (e.g. Closure::__invoke()) */ if ((mptr->internal_function.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) { fcc.function_handler = _copy_function(mptr); } result = zend_call_function(&fci, &fcc); if (result == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Invocation of method %s::%s() failed", ZSTR_VAL(mptr->common.scope->name), ZSTR_VAL(mptr->common.function_name)); RETURN_THROWS(); } if (Z_TYPE(retval) != IS_UNDEF) { if (Z_ISREF(retval)) { zend_unwrap_reference(&retval); } ZVAL_COPY_VALUE(return_value, &retval); } } /* }}} */ /* {{{ Invokes the method. */ ZEND_METHOD(ReflectionMethod, invoke) { reflection_method_invoke(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ Invokes the function and pass its arguments as array. */ ZEND_METHOD(ReflectionMethod, invokeArgs) { reflection_method_invoke(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ Returns whether this method is final */ ZEND_METHOD(ReflectionMethod, isFinal) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_FINAL); } /* }}} */ /* {{{ Returns whether this method is abstract */ ZEND_METHOD(ReflectionMethod, isAbstract) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_ABSTRACT); } /* }}} */ /* {{{ Returns whether this method is public */ ZEND_METHOD(ReflectionMethod, isPublic) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PUBLIC); } /* }}} */ /* {{{ Returns whether this method is private */ ZEND_METHOD(ReflectionMethod, isPrivate) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PRIVATE); } /* }}} */ /* {{{ Returns whether this method is protected */ ZEND_METHOD(ReflectionMethod, isProtected) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PROTECTED); } /* }}} */ /* {{{ Returns whether this method is static */ ZEND_METHOD(ReflectionMethod, isStatic) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_STATIC); } /* }}} */ /* {{{ Returns whether this function is deprecated */ ZEND_METHOD(ReflectionFunctionAbstract, isDeprecated) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_DEPRECATED); } /* }}} */ /* {{{ Returns whether this function is a generator */ ZEND_METHOD(ReflectionFunctionAbstract, isGenerator) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_GENERATOR); } /* }}} */ /* {{{ Returns whether this function is variadic */ ZEND_METHOD(ReflectionFunctionAbstract, isVariadic) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_VARIADIC); } /* }}} */ /* {{{ Returns whether this function is defined in namespace */ ZEND_METHOD(ReflectionFunctionAbstract, inNamespace) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); zend_string *name = fptr->common.function_name; const char *backslash = zend_memrchr(ZSTR_VAL(name), '\\', ZSTR_LEN(name)); RETURN_BOOL(backslash && backslash > ZSTR_VAL(name)); } /* }}} */ /* {{{ Returns the name of namespace where this function is defined */ ZEND_METHOD(ReflectionFunctionAbstract, getNamespaceName) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); zend_string *name = fptr->common.function_name; const char *backslash = zend_memrchr(ZSTR_VAL(name), '\\', ZSTR_LEN(name)); if (backslash && backslash > ZSTR_VAL(name)) { RETURN_STRINGL(ZSTR_VAL(name), backslash - ZSTR_VAL(name)); } RETURN_EMPTY_STRING(); } /* }}} */ /* {{{ Returns the short name of the function (without namespace part) */ ZEND_METHOD(ReflectionFunctionAbstract, getShortName) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); zend_string *name = fptr->common.function_name; const char *backslash = zend_memrchr(ZSTR_VAL(name), '\\', ZSTR_LEN(name)); if (backslash && backslash > ZSTR_VAL(name)) { RETURN_STRINGL(backslash + 1, ZSTR_LEN(name) - (backslash - ZSTR_VAL(name) + 1)); } RETURN_STR_COPY(name); } /* }}} */ /* {{{ Return whether the function has a return type */ ZEND_METHOD(ReflectionFunctionAbstract, hasReturnType) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); RETVAL_BOOL(fptr->op_array.fn_flags & ZEND_ACC_HAS_RETURN_TYPE); } /* }}} */ /* {{{ Returns the return type associated with the function */ ZEND_METHOD(ReflectionFunctionAbstract, getReturnType) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(fptr); if (!(fptr->op_array.fn_flags & ZEND_ACC_HAS_RETURN_TYPE)) { RETURN_NULL(); } reflection_type_factory(fptr->common.arg_info[-1].type, return_value, 1); } /* }}} */ /* {{{ Returns whether this method is the constructor */ ZEND_METHOD(ReflectionMethod, isConstructor) { reflection_object *intern; zend_function *mptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(mptr); /* we need to check if the ctor is the ctor of the class level we we * looking at since we might be looking at an inherited old style ctor * defined in base class. */ RETURN_BOOL((mptr->common.fn_flags & ZEND_ACC_CTOR) && intern->ce->constructor && intern->ce->constructor->common.scope == mptr->common.scope); } /* }}} */ /* {{{ Returns whether this method is a destructor */ ZEND_METHOD(ReflectionMethod, isDestructor) { reflection_object *intern; zend_function *mptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(mptr); RETURN_BOOL(zend_string_equals_literal_ci( mptr->common.function_name, ZEND_DESTRUCTOR_FUNC_NAME)); } /* }}} */ /* {{{ Returns a bitfield of the access modifiers for this method */ ZEND_METHOD(ReflectionMethod, getModifiers) { reflection_object *intern; zend_function *mptr; uint32_t keep_flags = ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC | ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(mptr); RETURN_LONG((mptr->common.fn_flags & keep_flags)); } /* }}} */ /* {{{ Get the declaring class */ ZEND_METHOD(ReflectionMethod, getDeclaringClass) { reflection_object *intern; zend_function *mptr; GET_REFLECTION_OBJECT_PTR(mptr); if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } zend_reflection_class_factory(mptr->common.scope, return_value); } /* }}} */ /* {{{ Get the prototype */ ZEND_METHOD(ReflectionMethod, getPrototype) { reflection_object *intern; zend_function *mptr; GET_REFLECTION_OBJECT_PTR(mptr); if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } if (!mptr->common.prototype) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Method %s::%s does not have a prototype", ZSTR_VAL(intern->ce->name), ZSTR_VAL(mptr->common.function_name)); RETURN_THROWS(); } reflection_method_factory(mptr->common.prototype->common.scope, mptr->common.prototype, NULL, return_value); } /* }}} */ /* {{{ Sets whether non-public methods can be invoked */ ZEND_METHOD(ReflectionMethod, setAccessible) { reflection_object *intern; zend_bool visible; if (zend_parse_parameters(ZEND_NUM_ARGS(), "b", &visible) == FAILURE) { RETURN_THROWS(); } intern = Z_REFLECTION_P(ZEND_THIS); intern->ignore_visibility = visible; } /* }}} */ /* {{{ Constructor. Throws an Exception in case the given class constant does not exist */ ZEND_METHOD(ReflectionClassConstant, __construct) { zval *object; zend_string *classname_str; zend_object *classname_obj; zend_string *constname; reflection_object *intern; zend_class_entry *ce; zend_class_constant *constant = NULL; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_OBJ_OR_STR(classname_obj, classname_str) Z_PARAM_STR(constname) ZEND_PARSE_PARAMETERS_END(); if (classname_obj) { ce = classname_obj->ce; } else { if ((ce = zend_lookup_class(classname_str)) == NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Class \"%s\" does not exist", ZSTR_VAL(classname_str)); RETURN_THROWS(); } } object = ZEND_THIS; intern = Z_REFLECTION_P(object); if ((constant = zend_hash_find_ptr(&ce->constants_table, constname)) == NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Constant %s::%s does not exist", ZSTR_VAL(ce->name), ZSTR_VAL(constname)); RETURN_THROWS(); } intern->ptr = constant; intern->ref_type = REF_TYPE_CLASS_CONSTANT; intern->ce = constant->ce; intern->ignore_visibility = 0; ZVAL_STR_COPY(reflection_prop_name(object), constname); ZVAL_STR_COPY(reflection_prop_class(object), constant->ce->name); } /* }}} */ /* {{{ Returns a string representation */ ZEND_METHOD(ReflectionClassConstant, __toString) { reflection_object *intern; zend_class_constant *ref; smart_str str = {0}; zval name; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); _default_get_name(ZEND_THIS, &name); _class_const_string(&str, Z_STRVAL(name), ref, ""); zval_ptr_dtor(&name); RETURN_STR(smart_str_extract(&str)); } /* }}} */ /* {{{ Returns the constant' name */ ZEND_METHOD(ReflectionClassConstant, getName) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } _default_get_name(ZEND_THIS, return_value); } /* }}} */ static void _class_constant_check_flag(INTERNAL_FUNCTION_PARAMETERS, int mask) /* {{{ */ { reflection_object *intern; zend_class_constant *ref; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); RETURN_BOOL(Z_ACCESS_FLAGS(ref->value) & mask); } /* }}} */ /* {{{ Returns whether this constant is public */ ZEND_METHOD(ReflectionClassConstant, isPublic) { _class_constant_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PUBLIC); } /* }}} */ /* {{{ Returns whether this constant is private */ ZEND_METHOD(ReflectionClassConstant, isPrivate) { _class_constant_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PRIVATE); } /* }}} */ /* {{{ Returns whether this constant is protected */ ZEND_METHOD(ReflectionClassConstant, isProtected) { _class_constant_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PROTECTED); } /* }}} */ /* {{{ Returns a bitfield of the access modifiers for this constant */ ZEND_METHOD(ReflectionClassConstant, getModifiers) { reflection_object *intern; zend_class_constant *ref; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); RETURN_LONG(Z_ACCESS_FLAGS(ref->value)); } /* }}} */ /* {{{ Returns this constant's value */ ZEND_METHOD(ReflectionClassConstant, getValue) { reflection_object *intern; zend_class_constant *ref; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); ZVAL_COPY_OR_DUP(return_value, &ref->value); if (Z_TYPE_P(return_value) == IS_CONSTANT_AST) { zval_update_constant_ex(return_value, ref->ce); } } /* }}} */ /* {{{ Get the declaring class */ ZEND_METHOD(ReflectionClassConstant, getDeclaringClass) { reflection_object *intern; zend_class_constant *ref; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); zend_reflection_class_factory(ref->ce, return_value); } /* }}} */ /* {{{ Returns the doc comment for this constant */ ZEND_METHOD(ReflectionClassConstant, getDocComment) { reflection_object *intern; zend_class_constant *ref; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); if (ref->doc_comment) { RETURN_STR_COPY(ref->doc_comment); } RETURN_FALSE; } /* }}} */ /* {{{ Returns the attributes of this constant */ ZEND_METHOD(ReflectionClassConstant, getAttributes) { reflection_object *intern; zend_class_constant *ref; GET_REFLECTION_OBJECT_PTR(ref); reflect_attributes(INTERNAL_FUNCTION_PARAM_PASSTHRU, ref->attributes, 0, ref->ce, ZEND_ATTRIBUTE_TARGET_CLASS_CONST, ref->ce->type == ZEND_USER_CLASS ? ref->ce->info.user.filename : NULL); } /* }}} */ /* {{{ reflection_class_object_ctor */ static void reflection_class_object_ctor(INTERNAL_FUNCTION_PARAMETERS, int is_object) { zval *object; zend_string *arg_class = NULL; zend_object *arg_obj; reflection_object *intern; zend_class_entry *ce; if (is_object) { ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_OBJ(arg_obj) ZEND_PARSE_PARAMETERS_END(); } else { ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_OBJ_OR_STR(arg_obj, arg_class) ZEND_PARSE_PARAMETERS_END(); } object = ZEND_THIS; intern = Z_REFLECTION_P(object); if (arg_obj) { ZVAL_STR_COPY(reflection_prop_name(object), arg_obj->ce->name); intern->ptr = arg_obj->ce; if (is_object) { ZVAL_OBJ_COPY(&intern->obj, arg_obj); } } else { if ((ce = zend_lookup_class(arg_class)) == NULL) { if (!EG(exception)) { zend_throw_exception_ex(reflection_exception_ptr, -1, "Class \"%s\" does not exist", ZSTR_VAL(arg_class)); } RETURN_THROWS(); } ZVAL_STR_COPY(reflection_prop_name(object), ce->name); intern->ptr = ce; } intern->ref_type = REF_TYPE_OTHER; } /* }}} */ /* {{{ Constructor. Takes a string or an instance as an argument */ ZEND_METHOD(ReflectionClass, __construct) { reflection_class_object_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ add_class_vars */ static void add_class_vars(zend_class_entry *ce, zend_bool statics, zval *return_value) { zend_property_info *prop_info; zval *prop, prop_copy; zend_string *key; ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->properties_info, key, prop_info) { if (((prop_info->flags & ZEND_ACC_PRIVATE) && prop_info->ce != ce)) { continue; } zend_bool is_static = (prop_info->flags & ZEND_ACC_STATIC) != 0; if (statics != is_static) { continue; } prop = property_get_default(prop_info); if (Z_ISUNDEF_P(prop)) { continue; } /* copy: enforce read only access */ ZVAL_DEREF(prop); ZVAL_COPY_OR_DUP(&prop_copy, prop); /* this is necessary to make it able to work with default array * properties, returned to user */ if (Z_TYPE(prop_copy) == IS_CONSTANT_AST) { if (UNEXPECTED(zval_update_constant_ex(&prop_copy, ce) != SUCCESS)) { return; } } zend_hash_update(Z_ARRVAL_P(return_value), key, &prop_copy); } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ Returns an associative array containing all static property values of the class */ ZEND_METHOD(ReflectionClass, getStaticProperties) { reflection_object *intern; zend_class_entry *ce; zend_property_info *prop_info; zval *prop; zend_string *key; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (UNEXPECTED(zend_update_class_constants(ce) != SUCCESS)) { RETURN_THROWS(); } if (ce->default_static_members_count && !CE_STATIC_MEMBERS(ce)) { zend_class_init_statics(ce); } array_init(return_value); ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->properties_info, key, prop_info) { if (((prop_info->flags & ZEND_ACC_PRIVATE) && prop_info->ce != ce)) { continue; } if ((prop_info->flags & ZEND_ACC_STATIC) == 0) { continue; } prop = &CE_STATIC_MEMBERS(ce)[prop_info->offset]; ZVAL_DEINDIRECT(prop); if (ZEND_TYPE_IS_SET(prop_info->type) && Z_ISUNDEF_P(prop)) { continue; } /* enforce read only access */ ZVAL_DEREF(prop); Z_TRY_ADDREF_P(prop); zend_hash_update(Z_ARRVAL_P(return_value), key, prop); } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ Returns the value of a static property */ ZEND_METHOD(ReflectionClass, getStaticPropertyValue) { reflection_object *intern; zend_class_entry *ce, *old_scope; zend_string *name; zval *prop, *def_value = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "S|z", &name, &def_value) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (UNEXPECTED(zend_update_class_constants(ce) != SUCCESS)) { RETURN_THROWS(); } old_scope = EG(fake_scope); EG(fake_scope) = ce; prop = zend_std_get_static_property(ce, name, BP_VAR_IS); EG(fake_scope) = old_scope; if (!prop) { if (def_value) { ZVAL_COPY(return_value, def_value); } else { zend_throw_exception_ex(reflection_exception_ptr, 0, "Property %s::$%s does not exist", ZSTR_VAL(ce->name), ZSTR_VAL(name)); } return; } else { ZVAL_COPY_DEREF(return_value, prop); } } /* }}} */ /* {{{ Sets the value of a static property */ ZEND_METHOD(ReflectionClass, setStaticPropertyValue) { reflection_object *intern; zend_class_entry *ce, *old_scope; zend_property_info *prop_info; zend_string *name; zval *variable_ptr, *value; if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sz", &name, &value) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (UNEXPECTED(zend_update_class_constants(ce) != SUCCESS)) { RETURN_THROWS(); } old_scope = EG(fake_scope); EG(fake_scope) = ce; variable_ptr = zend_std_get_static_property_with_info(ce, name, BP_VAR_W, &prop_info); EG(fake_scope) = old_scope; if (!variable_ptr) { zend_clear_exception(); zend_throw_exception_ex(reflection_exception_ptr, 0, "Class %s does not have a property named %s", ZSTR_VAL(ce->name), ZSTR_VAL(name)); RETURN_THROWS(); } if (Z_ISREF_P(variable_ptr)) { zend_reference *ref = Z_REF_P(variable_ptr); variable_ptr = Z_REFVAL_P(variable_ptr); if (!zend_verify_ref_assignable_zval(ref, value, 0)) { return; } } if (ZEND_TYPE_IS_SET(prop_info->type) && !zend_verify_property_type(prop_info, value, 0)) { return; } zval_ptr_dtor(variable_ptr); ZVAL_COPY(variable_ptr, value); } /* }}} */ /* {{{ Returns an associative array containing copies of all default property values of the class */ ZEND_METHOD(ReflectionClass, getDefaultProperties) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); if (UNEXPECTED(zend_update_class_constants(ce) != SUCCESS)) { RETURN_THROWS(); } add_class_vars(ce, 1, return_value); add_class_vars(ce, 0, return_value); } /* }}} */ /* {{{ Returns a string representation */ ZEND_METHOD(ReflectionClass, __toString) { reflection_object *intern; zend_class_entry *ce; smart_str str = {0}; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); _class_string(&str, ce, &intern->obj, ""); RETURN_STR(smart_str_extract(&str)); } /* }}} */ /* {{{ Returns the class' name */ ZEND_METHOD(ReflectionClass, getName) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); RETURN_STR_COPY(ce->name); } /* }}} */ /* {{{ Returns whether this class is an internal class */ ZEND_METHOD(ReflectionClass, isInternal) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(ce->type == ZEND_INTERNAL_CLASS); } /* }}} */ /* {{{ Returns whether this class is user-defined */ ZEND_METHOD(ReflectionClass, isUserDefined) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(ce->type == ZEND_USER_CLASS); } /* }}} */ /* {{{ Returns whether this class is anonymous */ ZEND_METHOD(ReflectionClass, isAnonymous) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(ce->ce_flags & ZEND_ACC_ANON_CLASS); } /* }}} */ /* {{{ Returns the filename of the file this class was declared in */ ZEND_METHOD(ReflectionClass, getFileName) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_CLASS) { RETURN_STR_COPY(ce->info.user.filename); } RETURN_FALSE; } /* }}} */ /* {{{ Returns the line this class' declaration starts at */ ZEND_METHOD(ReflectionClass, getStartLine) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_CLASS) { RETURN_LONG(ce->info.user.line_start); } RETURN_FALSE; } /* }}} */ /* {{{ Returns the line this class' declaration ends at */ ZEND_METHOD(ReflectionClass, getEndLine) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_CLASS) { RETURN_LONG(ce->info.user.line_end); } RETURN_FALSE; } /* }}} */ /* {{{ Returns the doc comment for this class */ ZEND_METHOD(ReflectionClass, getDocComment) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_CLASS && ce->info.user.doc_comment) { RETURN_STR_COPY(ce->info.user.doc_comment); } RETURN_FALSE; } /* }}} */ /* {{{ Returns the attributes for this class */ ZEND_METHOD(ReflectionClass, getAttributes) { reflection_object *intern; zend_class_entry *ce; GET_REFLECTION_OBJECT_PTR(ce); reflect_attributes(INTERNAL_FUNCTION_PARAM_PASSTHRU, ce->attributes, 0, ce, ZEND_ATTRIBUTE_TARGET_CLASS, ce->type == ZEND_USER_CLASS ? ce->info.user.filename : NULL); } /* }}} */ /* {{{ Returns the class' constructor if there is one, NULL otherwise */ ZEND_METHOD(ReflectionClass, getConstructor) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (ce->constructor) { reflection_method_factory(ce, ce->constructor, NULL, return_value); } else { RETURN_NULL(); } } /* }}} */ /* {{{ Returns whether a method exists or not */ ZEND_METHOD(ReflectionClass, hasMethod) { reflection_object *intern; zend_class_entry *ce; zend_string *name, *lc_name; if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &name) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); lc_name = zend_string_tolower(name); RETVAL_BOOL(zend_hash_exists(&ce->function_table, lc_name) || is_closure_invoke(ce, lc_name)); zend_string_release(lc_name); } /* }}} */ /* {{{ Returns the class' method specified by its name */ ZEND_METHOD(ReflectionClass, getMethod) { reflection_object *intern; zend_class_entry *ce; zend_function *mptr; zval obj_tmp; zend_string *name, *lc_name; if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &name) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); lc_name = zend_string_tolower(name); if (!Z_ISUNDEF(intern->obj) && is_closure_invoke(ce, lc_name) && (mptr = zend_get_closure_invoke_method(Z_OBJ(intern->obj))) != NULL) { /* don't assign closure_object since we only reflect the invoke handler method and not the closure definition itself */ reflection_method_factory(ce, mptr, NULL, return_value); } else if (Z_ISUNDEF(intern->obj) && is_closure_invoke(ce, lc_name) && object_init_ex(&obj_tmp, ce) == SUCCESS && (mptr = zend_get_closure_invoke_method(Z_OBJ(obj_tmp))) != NULL) { /* don't assign closure_object since we only reflect the invoke handler method and not the closure definition itself */ reflection_method_factory(ce, mptr, NULL, return_value); zval_ptr_dtor(&obj_tmp); } else if ((mptr = zend_hash_find_ptr(&ce->function_table, lc_name)) != NULL) { reflection_method_factory(ce, mptr, NULL, return_value); } else { zend_throw_exception_ex(reflection_exception_ptr, 0, "Method %s::%s() does not exist", ZSTR_VAL(ce->name), ZSTR_VAL(name)); } zend_string_release(lc_name); } /* }}} */ /* {{{ _addmethod */ static void _addmethod(zend_function *mptr, zend_class_entry *ce, zval *retval, zend_long filter) { if ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) && mptr->common.scope != ce) { return; } if (mptr->common.fn_flags & filter) { zval method; reflection_method_factory(ce, mptr, NULL, &method); add_next_index_zval(retval, &method); } } /* }}} */ /* {{{ Returns an array of this class' methods */ ZEND_METHOD(ReflectionClass, getMethods) { reflection_object *intern; zend_class_entry *ce; zend_function *mptr; zend_long filter; zend_bool filter_is_null = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!", &filter, &filter_is_null) == FAILURE) { RETURN_THROWS(); } if (filter_is_null) { filter = ZEND_ACC_PPP_MASK | ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL | ZEND_ACC_STATIC; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); ZEND_HASH_FOREACH_PTR(&ce->function_table, mptr) { _addmethod(mptr, ce, return_value, filter); } ZEND_HASH_FOREACH_END(); if (instanceof_function(ce, zend_ce_closure)) { zend_bool has_obj = Z_TYPE(intern->obj) != IS_UNDEF; zval obj_tmp; zend_object *obj; if (!has_obj) { object_init_ex(&obj_tmp, ce); obj = Z_OBJ(obj_tmp); } else { obj = Z_OBJ(intern->obj); } zend_function *closure = zend_get_closure_invoke_method(obj); if (closure) { _addmethod(closure, ce, return_value, filter); } if (!has_obj) { zval_ptr_dtor(&obj_tmp); } } } /* }}} */ /* {{{ Returns whether a property exists or not */ ZEND_METHOD(ReflectionClass, hasProperty) { reflection_object *intern; zend_property_info *property_info; zend_class_entry *ce; zend_string *name; if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &name) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if ((property_info = zend_hash_find_ptr(&ce->properties_info, name)) != NULL) { if ((property_info->flags & ZEND_ACC_PRIVATE) && property_info->ce != ce) { RETURN_FALSE; } RETURN_TRUE; } else { if (Z_TYPE(intern->obj) != IS_UNDEF) { if (Z_OBJ_HANDLER(intern->obj, has_property)(Z_OBJ(intern->obj), name, 2, NULL)) { RETURN_TRUE; } } RETURN_FALSE; } } /* }}} */ /* {{{ Returns the class' property specified by its name */ ZEND_METHOD(ReflectionClass, getProperty) { reflection_object *intern; zend_class_entry *ce, *ce2; zend_property_info *property_info; zend_string *name, *classname; char *tmp, *str_name; size_t classname_len, str_name_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &name) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if ((property_info = zend_hash_find_ptr(&ce->properties_info, name)) != NULL) { if (!(property_info->flags & ZEND_ACC_PRIVATE) || property_info->ce == ce) { reflection_property_factory(ce, name, property_info, return_value); return; } } else if (Z_TYPE(intern->obj) != IS_UNDEF) { /* Check for dynamic properties */ if (zend_hash_exists(Z_OBJ_HT(intern->obj)->get_properties(Z_OBJ(intern->obj)), name)) { reflection_property_factory(ce, name, NULL, return_value); return; } } str_name = ZSTR_VAL(name); if ((tmp = strstr(ZSTR_VAL(name), "::")) != NULL) { classname_len = tmp - ZSTR_VAL(name); classname = zend_string_alloc(classname_len, 0); zend_str_tolower_copy(ZSTR_VAL(classname), ZSTR_VAL(name), classname_len); ZSTR_VAL(classname)[classname_len] = '\0'; str_name_len = ZSTR_LEN(name) - (classname_len + 2); str_name = tmp + 2; ce2 = zend_lookup_class(classname); if (!ce2) { if (!EG(exception)) { zend_throw_exception_ex(reflection_exception_ptr, -1, "Class \"%s\" does not exist", ZSTR_VAL(classname)); } zend_string_release_ex(classname, 0); RETURN_THROWS(); } zend_string_release_ex(classname, 0); if (!instanceof_function(ce, ce2)) { zend_throw_exception_ex(reflection_exception_ptr, -1, "Fully qualified property name %s::$%s does not specify a base class of %s", ZSTR_VAL(ce2->name), str_name, ZSTR_VAL(ce->name)); RETURN_THROWS(); } ce = ce2; property_info = zend_hash_str_find_ptr(&ce->properties_info, str_name, str_name_len); if (property_info != NULL && (!(property_info->flags & ZEND_ACC_PRIVATE) || property_info->ce == ce)) { reflection_property_factory_str(ce, str_name, str_name_len, property_info, return_value); return; } } zend_throw_exception_ex(reflection_exception_ptr, 0, "Property %s::$%s does not exist", ZSTR_VAL(ce->name), str_name); } /* }}} */ /* {{{ _addproperty */ static void _addproperty(zend_property_info *pptr, zend_string *key, zend_class_entry *ce, zval *retval, long filter) { if ((pptr->flags & ZEND_ACC_PRIVATE) && pptr->ce != ce) { return; } if (pptr->flags & filter) { zval property; reflection_property_factory(ce, key, pptr, &property); add_next_index_zval(retval, &property); } } /* }}} */ /* {{{ _adddynproperty */ static void _adddynproperty(zval *ptr, zend_string *key, zend_class_entry *ce, zval *retval) { zval property; /* under some circumstances, the properties hash table may contain numeric * properties (e.g. when casting from array). This is a WON'T FIX bug, at * least for the moment. Ignore these */ if (key == NULL) { return; } /* Not a dynamic property */ if (Z_TYPE_P(ptr) == IS_INDIRECT) { return; } reflection_property_factory(ce, key, NULL, &property); add_next_index_zval(retval, &property); } /* }}} */ /* {{{ Returns an array of this class' properties */ ZEND_METHOD(ReflectionClass, getProperties) { reflection_object *intern; zend_class_entry *ce; zend_string *key; zend_property_info *prop_info; zend_long filter; zend_bool filter_is_null = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!", &filter, &filter_is_null) == FAILURE) { RETURN_THROWS(); } if (filter_is_null) { filter = ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->properties_info, key, prop_info) { _addproperty(prop_info, key, ce, return_value, filter); } ZEND_HASH_FOREACH_END(); if (Z_TYPE(intern->obj) != IS_UNDEF && (filter & ZEND_ACC_PUBLIC) != 0) { HashTable *properties = Z_OBJ_HT(intern->obj)->get_properties(Z_OBJ(intern->obj)); zval *prop; ZEND_HASH_FOREACH_STR_KEY_VAL(properties, key, prop) { _adddynproperty(prop, key, ce, return_value); } ZEND_HASH_FOREACH_END(); } } /* }}} */ /* {{{ Returns whether a constant exists or not */ ZEND_METHOD(ReflectionClass, hasConstant) { reflection_object *intern; zend_class_entry *ce; zend_string *name; if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &name) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (zend_hash_exists(&ce->constants_table, name)) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ Returns an associative array containing this class' constants and their values */ ZEND_METHOD(ReflectionClass, getConstants) { reflection_object *intern; zend_class_entry *ce; zend_string *key; zend_class_constant *constant; zval val; zend_long filter; zend_bool filter_is_null = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!", &filter, &filter_is_null) == FAILURE) { RETURN_THROWS(); } if (filter_is_null) { filter = ZEND_ACC_PPP_MASK; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->constants_table, key, constant) { if (UNEXPECTED(zval_update_constant_ex(&constant->value, ce) != SUCCESS)) { RETURN_THROWS(); } if (Z_ACCESS_FLAGS(constant->value) & filter) { ZVAL_COPY_OR_DUP(&val, &constant->value); zend_hash_add_new(Z_ARRVAL_P(return_value), key, &val); } } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ Returns an associative array containing this class' constants as ReflectionClassConstant objects */ ZEND_METHOD(ReflectionClass, getReflectionConstants) { reflection_object *intern; zend_class_entry *ce; zend_string *name; zend_class_constant *constant; zend_long filter; zend_bool filter_is_null = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!", &filter, &filter_is_null) == FAILURE) { RETURN_THROWS(); } if (filter_is_null) { filter = ZEND_ACC_PPP_MASK; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->constants_table, name, constant) { if (Z_ACCESS_FLAGS(constant->value) & filter) { zval class_const; reflection_class_constant_factory(name, constant, &class_const); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &class_const); } } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ Returns the class' constant specified by its name */ ZEND_METHOD(ReflectionClass, getConstant) { reflection_object *intern; zend_class_entry *ce; zend_class_constant *c; zend_string *name; if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &name) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); ZEND_HASH_FOREACH_PTR(&ce->constants_table, c) { if (UNEXPECTED(zval_update_constant_ex(&c->value, ce) != SUCCESS)) { RETURN_THROWS(); } } ZEND_HASH_FOREACH_END(); if ((c = zend_hash_find_ptr(&ce->constants_table, name)) == NULL) { RETURN_FALSE; } ZVAL_COPY_OR_DUP(return_value, &c->value); } /* }}} */ /* {{{ Returns the class' constant as ReflectionClassConstant objects */ ZEND_METHOD(ReflectionClass, getReflectionConstant) { reflection_object *intern; zend_class_entry *ce; zend_class_constant *constant; zend_string *name; GET_REFLECTION_OBJECT_PTR(ce); if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &name) == FAILURE) { RETURN_THROWS(); } if ((constant = zend_hash_find_ptr(&ce->constants_table, name)) == NULL) { RETURN_FALSE; } reflection_class_constant_factory(name, constant, return_value); } /* }}} */ /* {{{ _class_check_flag */ static void _class_check_flag(INTERNAL_FUNCTION_PARAMETERS, int mask) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); RETVAL_BOOL(ce->ce_flags & mask); } /* }}} */ /* {{{ Returns whether this class is instantiable */ ZEND_METHOD(ReflectionClass, isInstantiable) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (ce->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS | ZEND_ACC_IMPLICIT_ABSTRACT_CLASS)) { RETURN_FALSE; } /* Basically, the class is instantiable. Though, if there is a constructor * and it is not publicly accessible, it isn't! */ if (!ce->constructor) { RETURN_TRUE; } RETURN_BOOL(ce->constructor->common.fn_flags & ZEND_ACC_PUBLIC); } /* }}} */ /* {{{ Returns whether this class is cloneable */ ZEND_METHOD(ReflectionClass, isCloneable) { reflection_object *intern; zend_class_entry *ce; zval obj; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (ce->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS | ZEND_ACC_IMPLICIT_ABSTRACT_CLASS)) { RETURN_FALSE; } if (!Z_ISUNDEF(intern->obj)) { if (ce->clone) { RETURN_BOOL(ce->clone->common.fn_flags & ZEND_ACC_PUBLIC); } else { RETURN_BOOL(Z_OBJ_HANDLER(intern->obj, clone_obj) != NULL); } } else { if (ce->clone) { RETURN_BOOL(ce->clone->common.fn_flags & ZEND_ACC_PUBLIC); } else { if (UNEXPECTED(object_init_ex(&obj, ce) != SUCCESS)) { return; } /* We're not calling the constructor, so don't call the destructor either. */ zend_object_store_ctor_failed(Z_OBJ(obj)); RETVAL_BOOL(Z_OBJ_HANDLER(obj, clone_obj) != NULL); zval_ptr_dtor(&obj); } } } /* }}} */ /* {{{ Returns whether this is an interface or a class */ ZEND_METHOD(ReflectionClass, isInterface) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_INTERFACE); } /* }}} */ /* {{{ Returns whether this is a trait */ ZEND_METHOD(ReflectionClass, isTrait) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_TRAIT); } /* }}} */ /* {{{ Returns whether this class is final */ ZEND_METHOD(ReflectionClass, isFinal) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_FINAL); } /* }}} */ /* {{{ Returns whether this class is abstract */ ZEND_METHOD(ReflectionClass, isAbstract) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); } /* }}} */ /* {{{ Returns a bitfield of the access modifiers for this class */ ZEND_METHOD(ReflectionClass, getModifiers) { reflection_object *intern; zend_class_entry *ce; uint32_t keep_flags = ZEND_ACC_FINAL | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); RETURN_LONG((ce->ce_flags & keep_flags)); } /* }}} */ /* {{{ Returns whether the given object is an instance of this class */ ZEND_METHOD(ReflectionClass, isInstance) { reflection_object *intern; zend_class_entry *ce; zval *object; if (zend_parse_parameters(ZEND_NUM_ARGS(), "o", &object) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(instanceof_function(Z_OBJCE_P(object), ce)); } /* }}} */ /* {{{ Returns an instance of this class */ ZEND_METHOD(ReflectionClass, newInstance) { reflection_object *intern; zend_class_entry *ce, *old_scope; zend_function *constructor; GET_REFLECTION_OBJECT_PTR(ce); if (UNEXPECTED(object_init_ex(return_value, ce) != SUCCESS)) { return; } old_scope = EG(fake_scope); EG(fake_scope) = ce; constructor = Z_OBJ_HT_P(return_value)->get_constructor(Z_OBJ_P(return_value)); EG(fake_scope) = old_scope; /* Run the constructor if there is one */ if (constructor) { zval *params; int num_args; HashTable *named_params; if (!(constructor->common.fn_flags & ZEND_ACC_PUBLIC)) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Access to non-public constructor of class %s", ZSTR_VAL(ce->name)); zval_ptr_dtor(return_value); RETURN_NULL(); } ZEND_PARSE_PARAMETERS_START(0, -1) Z_PARAM_VARIADIC_WITH_NAMED(params, num_args, named_params) ZEND_PARSE_PARAMETERS_END(); zend_call_known_function( constructor, Z_OBJ_P(return_value), Z_OBJCE_P(return_value), NULL, num_args, params, named_params); if (EG(exception)) { zend_object_store_ctor_failed(Z_OBJ_P(return_value)); } } else if (ZEND_NUM_ARGS()) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Class %s does not have a constructor, so you cannot pass any constructor arguments", ZSTR_VAL(ce->name)); } } /* }}} */ /* {{{ Returns an instance of this class without invoking its constructor */ ZEND_METHOD(ReflectionClass, newInstanceWithoutConstructor) { reflection_object *intern; zend_class_entry *ce; GET_REFLECTION_OBJECT_PTR(ce); if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } if (ce->type == ZEND_INTERNAL_CLASS && ce->create_object != NULL && (ce->ce_flags & ZEND_ACC_FINAL)) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Class %s is an internal class marked as final that cannot be instantiated without invoking its constructor", ZSTR_VAL(ce->name)); RETURN_THROWS(); } object_init_ex(return_value, ce); } /* }}} */ /* {{{ Returns an instance of this class */ ZEND_METHOD(ReflectionClass, newInstanceArgs) { reflection_object *intern; zend_class_entry *ce, *old_scope; int argc = 0; HashTable *args = NULL; zend_function *constructor; GET_REFLECTION_OBJECT_PTR(ce); if (zend_parse_parameters(ZEND_NUM_ARGS(), "|h", &args) == FAILURE) { RETURN_THROWS(); } if (args) { argc = zend_hash_num_elements(args); } if (UNEXPECTED(object_init_ex(return_value, ce) != SUCCESS)) { return; } old_scope = EG(fake_scope); EG(fake_scope) = ce; constructor = Z_OBJ_HT_P(return_value)->get_constructor(Z_OBJ_P(return_value)); EG(fake_scope) = old_scope; /* Run the constructor if there is one */ if (constructor) { if (!(constructor->common.fn_flags & ZEND_ACC_PUBLIC)) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Access to non-public constructor of class %s", ZSTR_VAL(ce->name)); zval_ptr_dtor(return_value); RETURN_NULL(); } zend_call_known_function( constructor, Z_OBJ_P(return_value), Z_OBJCE_P(return_value), NULL, 0, NULL, args); if (EG(exception)) { zend_object_store_ctor_failed(Z_OBJ_P(return_value)); } } else if (argc) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Class %s does not have a constructor, so you cannot pass any constructor arguments", ZSTR_VAL(ce->name)); } } /* }}} */ /* {{{ Returns an array of interfaces this class implements */ ZEND_METHOD(ReflectionClass, getInterfaces) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (ce->num_interfaces) { uint32_t i; ZEND_ASSERT(ce->ce_flags & ZEND_ACC_LINKED); array_init(return_value); for (i=0; i < ce->num_interfaces; i++) { zval interface; zend_reflection_class_factory(ce->interfaces[i], &interface); zend_hash_update(Z_ARRVAL_P(return_value), ce->interfaces[i]->name, &interface); } } else { RETURN_EMPTY_ARRAY(); } } /* }}} */ /* {{{ Returns an array of names of interfaces this class implements */ ZEND_METHOD(ReflectionClass, getInterfaceNames) { reflection_object *intern; zend_class_entry *ce; uint32_t i; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (!ce->num_interfaces) { /* Return an empty array if this class implements no interfaces */ RETURN_EMPTY_ARRAY(); } ZEND_ASSERT(ce->ce_flags & ZEND_ACC_LINKED); array_init(return_value); for (i=0; i < ce->num_interfaces; i++) { add_next_index_str(return_value, zend_string_copy(ce->interfaces[i]->name)); } } /* }}} */ /* {{{ Returns an array of traits used by this class */ ZEND_METHOD(ReflectionClass, getTraits) { reflection_object *intern; zend_class_entry *ce; uint32_t i; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (!ce->num_traits) { RETURN_EMPTY_ARRAY(); } array_init(return_value); for (i=0; i < ce->num_traits; i++) { zval trait; zend_class_entry *trait_ce; trait_ce = zend_fetch_class_by_name(ce->trait_names[i].name, ce->trait_names[i].lc_name, ZEND_FETCH_CLASS_TRAIT); ZEND_ASSERT(trait_ce); zend_reflection_class_factory(trait_ce, &trait); zend_hash_update(Z_ARRVAL_P(return_value), ce->trait_names[i].name, &trait); } } /* }}} */ /* {{{ Returns an array of names of traits used by this class */ ZEND_METHOD(ReflectionClass, getTraitNames) { reflection_object *intern; zend_class_entry *ce; uint32_t i; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (!ce->num_traits) { RETURN_EMPTY_ARRAY(); } array_init(return_value); for (i=0; i < ce->num_traits; i++) { add_next_index_str(return_value, zend_string_copy(ce->trait_names[i].name)); } } /* }}} */ /* {{{ Returns an array of trait aliases */ ZEND_METHOD(ReflectionClass, getTraitAliases) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (ce->trait_aliases) { uint32_t i = 0; array_init(return_value); while (ce->trait_aliases[i]) { zend_string *mname; zend_trait_method_reference *cur_ref = &ce->trait_aliases[i]->trait_method; if (ce->trait_aliases[i]->alias) { mname = zend_string_alloc(ZSTR_LEN(cur_ref->class_name) + ZSTR_LEN(cur_ref->method_name) + 2, 0); snprintf(ZSTR_VAL(mname), ZSTR_LEN(mname) + 1, "%s::%s", ZSTR_VAL(cur_ref->class_name), ZSTR_VAL(cur_ref->method_name)); add_assoc_str_ex(return_value, ZSTR_VAL(ce->trait_aliases[i]->alias), ZSTR_LEN(ce->trait_aliases[i]->alias), mname); } i++; } } else { RETURN_EMPTY_ARRAY(); } } /* }}} */ /* {{{ Returns the class' parent class, or, if none exists, FALSE */ ZEND_METHOD(ReflectionClass, getParentClass) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (ce->parent) { zend_reflection_class_factory(ce->parent, return_value); } else { RETURN_FALSE; } } /* }}} */ /* {{{ Returns whether this class is a subclass of another class */ ZEND_METHOD(ReflectionClass, isSubclassOf) { reflection_object *intern, *argument; zend_class_entry *ce, *class_ce; zend_string *class_str; zend_object *class_obj; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_OBJ_OF_CLASS_OR_STR(class_obj, reflection_class_ptr, class_str) ZEND_PARSE_PARAMETERS_END(); if (class_obj) { argument = reflection_object_from_obj(class_obj); if (argument->ptr == NULL) { zend_throw_error(NULL, "Internal error: Failed to retrieve the argument's reflection object"); RETURN_THROWS(); } class_ce = argument->ptr; } else { if ((class_ce = zend_lookup_class(class_str)) == NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Class \"%s\" does not exist", ZSTR_VAL(class_str)); RETURN_THROWS(); } } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL((ce != class_ce && instanceof_function(ce, class_ce))); } /* }}} */ /* {{{ Returns whether this class is a subclass of another class */ ZEND_METHOD(ReflectionClass, implementsInterface) { reflection_object *intern, *argument; zend_string *interface_str; zend_class_entry *ce, *interface_ce; zend_object *interface_obj; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_OBJ_OF_CLASS_OR_STR(interface_obj, reflection_class_ptr, interface_str) ZEND_PARSE_PARAMETERS_END(); if (interface_obj) { argument = reflection_object_from_obj(interface_obj); if (argument->ptr == NULL) { zend_throw_error(NULL, "Internal error: Failed to retrieve the argument's reflection object"); RETURN_THROWS(); } interface_ce = argument->ptr; } else { if ((interface_ce = zend_lookup_class(interface_str)) == NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Interface \"%s\" does not exist", ZSTR_VAL(interface_str)); RETURN_THROWS(); } } if (!(interface_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_throw_exception_ex(reflection_exception_ptr, 0, "%s is not an interface", ZSTR_VAL(interface_ce->name)); RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(instanceof_function(ce, interface_ce)); } /* }}} */ /* {{{ Returns whether this class is iterable (can be used inside foreach) */ ZEND_METHOD(ReflectionClass, isIterable) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if (ce->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_IMPLICIT_ABSTRACT_CLASS | ZEND_ACC_TRAIT | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { RETURN_FALSE; } RETURN_BOOL(ce->get_iterator || instanceof_function(ce, zend_ce_traversable)); } /* }}} */ /* {{{ Returns NULL or the extension the class belongs to */ ZEND_METHOD(ReflectionClass, getExtension) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if ((ce->type == ZEND_INTERNAL_CLASS) && ce->info.internal.module) { reflection_extension_factory(return_value, ce->info.internal.module->name); } } /* }}} */ /* {{{ Returns false or the name of the extension the class belongs to */ ZEND_METHOD(ReflectionClass, getExtensionName) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); if ((ce->type == ZEND_INTERNAL_CLASS) && ce->info.internal.module) { RETURN_STRING(ce->info.internal.module->name); } else { RETURN_FALSE; } } /* }}} */ /* {{{ Returns whether this class is defined in namespace */ ZEND_METHOD(ReflectionClass, inNamespace) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); zend_string *name = ce->name; const char *backslash = zend_memrchr(ZSTR_VAL(name), '\\', ZSTR_LEN(name)); RETURN_BOOL(backslash && backslash > ZSTR_VAL(name)); } /* }}} */ /* {{{ Returns the name of namespace where this class is defined */ ZEND_METHOD(ReflectionClass, getNamespaceName) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); zend_string *name = ce->name; const char *backslash = zend_memrchr(ZSTR_VAL(name), '\\', ZSTR_LEN(name)); if (backslash && backslash > ZSTR_VAL(name)) { RETURN_STRINGL(ZSTR_VAL(name), backslash - ZSTR_VAL(name)); } RETURN_EMPTY_STRING(); } /* }}} */ /* {{{ Returns the short name of the class (without namespace part) */ ZEND_METHOD(ReflectionClass, getShortName) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ce); zend_string *name = ce->name; const char *backslash = zend_memrchr(ZSTR_VAL(name), '\\', ZSTR_LEN(name)); if (backslash && backslash > ZSTR_VAL(name)) { RETURN_STRINGL(backslash + 1, ZSTR_LEN(name) - (backslash - ZSTR_VAL(name) + 1)); } RETURN_STR_COPY(name); } /* }}} */ /* {{{ Constructor. Takes an instance as an argument */ ZEND_METHOD(ReflectionObject, __construct) { reflection_class_object_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ Constructor. Throws an Exception in case the given property does not exist */ ZEND_METHOD(ReflectionProperty, __construct) { zend_string *classname_str; zend_object *classname_obj; zend_string *name; int dynam_prop = 0; zval *object; reflection_object *intern; zend_class_entry *ce; zend_property_info *property_info = NULL; property_reference *reference; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_OBJ_OR_STR(classname_obj, classname_str) Z_PARAM_STR(name) ZEND_PARSE_PARAMETERS_END(); object = ZEND_THIS; intern = Z_REFLECTION_P(object); if (classname_obj) { ce = classname_obj->ce; } else { if ((ce = zend_lookup_class(classname_str)) == NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Class \"%s\" does not exist", ZSTR_VAL(classname_str)); RETURN_THROWS(); } } property_info = zend_hash_find_ptr(&ce->properties_info, name); if (property_info == NULL || ((property_info->flags & ZEND_ACC_PRIVATE) && property_info->ce != ce)) { /* Check for dynamic properties */ if (property_info == NULL && classname_obj) { if (zend_hash_exists(classname_obj->handlers->get_properties(classname_obj), name)) { dynam_prop = 1; } } if (dynam_prop == 0) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Property %s::$%s does not exist", ZSTR_VAL(ce->name), ZSTR_VAL(name)); RETURN_THROWS(); } } ZVAL_STR_COPY(reflection_prop_name(object), name); if (dynam_prop == 0) { ZVAL_STR_COPY(reflection_prop_class(object), property_info->ce->name); } else { ZVAL_STR_COPY(reflection_prop_class(object), ce->name); } reference = (property_reference*) emalloc(sizeof(property_reference)); reference->prop = dynam_prop ? NULL : property_info; reference->unmangled_name = zend_string_copy(name); intern->ptr = reference; intern->ref_type = REF_TYPE_PROPERTY; intern->ce = ce; intern->ignore_visibility = 0; } /* }}} */ /* {{{ Returns a string representation */ ZEND_METHOD(ReflectionProperty, __toString) { reflection_object *intern; property_reference *ref; smart_str str = {0}; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); _property_string(&str, ref->prop, ZSTR_VAL(ref->unmangled_name), ""); RETURN_STR(smart_str_extract(&str)); } /* }}} */ /* {{{ Returns the class' name */ ZEND_METHOD(ReflectionProperty, getName) { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); RETURN_STR_COPY(ref->unmangled_name); } /* }}} */ static void _property_check_flag(INTERNAL_FUNCTION_PARAMETERS, int mask) /* {{{ */ { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); RETURN_BOOL(prop_get_flags(ref) & mask); } /* }}} */ /* {{{ Returns whether this property is public */ ZEND_METHOD(ReflectionProperty, isPublic) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PUBLIC); } /* }}} */ /* {{{ Returns whether this property is private */ ZEND_METHOD(ReflectionProperty, isPrivate) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PRIVATE); } /* }}} */ /* {{{ Returns whether this property is protected */ ZEND_METHOD(ReflectionProperty, isProtected) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PROTECTED); } /* }}} */ /* {{{ Returns whether this property is static */ ZEND_METHOD(ReflectionProperty, isStatic) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_STATIC); } /* }}} */ /* {{{ Returns whether this property is default (declared at compilation time). */ ZEND_METHOD(ReflectionProperty, isDefault) { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); RETURN_BOOL(ref->prop != NULL); } /* }}} */ /* {{{ Returns whether this property has been promoted from a constructor */ ZEND_METHOD(ReflectionProperty, isPromoted) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PROMOTED); } /* }}} */ /* {{{ Returns a bitfield of the access modifiers for this property */ ZEND_METHOD(ReflectionProperty, getModifiers) { reflection_object *intern; property_reference *ref; uint32_t keep_flags = ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); RETURN_LONG(prop_get_flags(ref) & keep_flags); } /* }}} */ /* {{{ Returns this property's value */ ZEND_METHOD(ReflectionProperty, getValue) { reflection_object *intern; property_reference *ref; zval *object = NULL; zval *member_p = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|o!", &object) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); if (!(prop_get_flags(ref) & ZEND_ACC_PUBLIC) && intern->ignore_visibility == 0) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Cannot access non-public property %s::$%s", ZSTR_VAL(intern->ce->name), ZSTR_VAL(ref->unmangled_name)); RETURN_THROWS(); } if (prop_get_flags(ref) & ZEND_ACC_STATIC) { member_p = zend_read_static_property_ex(intern->ce, ref->unmangled_name, 0); if (member_p) { ZVAL_COPY_DEREF(return_value, member_p); } } else { zval rv; if (!object) { zend_argument_type_error(1, "must be provided for instance properties"); RETURN_THROWS(); } /* TODO: Should this always use intern->ce? */ if (!instanceof_function(Z_OBJCE_P(object), ref->prop ? ref->prop->ce : intern->ce)) { _DO_THROW("Given object is not an instance of the class this property was declared in"); RETURN_THROWS(); } member_p = zend_read_property_ex(intern->ce, Z_OBJ_P(object), ref->unmangled_name, 0, &rv); if (member_p != &rv) { ZVAL_COPY_DEREF(return_value, member_p); } else { if (Z_ISREF_P(member_p)) { zend_unwrap_reference(member_p); } ZVAL_COPY_VALUE(return_value, member_p); } } } /* }}} */ /* {{{ Sets this property's value */ ZEND_METHOD(ReflectionProperty, setValue) { reflection_object *intern; property_reference *ref; zval *object; zval *value; zval *tmp; GET_REFLECTION_OBJECT_PTR(ref); if (!(prop_get_flags(ref) & ZEND_ACC_PUBLIC) && intern->ignore_visibility == 0) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Cannot access non-public property %s::$%s", ZSTR_VAL(intern->ce->name), ZSTR_VAL(ref->unmangled_name)); RETURN_THROWS(); } if (prop_get_flags(ref) & ZEND_ACC_STATIC) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "z", &value) == FAILURE) { if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &tmp, &value) == FAILURE) { RETURN_THROWS(); } } zend_update_static_property_ex(intern->ce, ref->unmangled_name, value); } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), "oz", &object, &value) == FAILURE) { RETURN_THROWS(); } zend_update_property_ex(intern->ce, Z_OBJ_P(object), ref->unmangled_name, value); } } /* }}} */ /* {{{ Returns this property's value */ ZEND_METHOD(ReflectionProperty, isInitialized) { reflection_object *intern; property_reference *ref; zval *object = NULL; zval *member_p = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|o!", &object) == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); if (!(prop_get_flags(ref) & ZEND_ACC_PUBLIC) && intern->ignore_visibility == 0) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Cannot access non-public property %s::$%s", ZSTR_VAL(intern->ce->name), ZSTR_VAL(ref->unmangled_name)); RETURN_THROWS(); } if (prop_get_flags(ref) & ZEND_ACC_STATIC) { member_p = zend_read_static_property_ex(intern->ce, ref->unmangled_name, 1); if (member_p) { RETURN_BOOL(!Z_ISUNDEF_P(member_p)); } RETURN_FALSE; } else { zend_class_entry *old_scope; int retval; if (!object) { zend_argument_type_error(1, "must be provided for instance properties"); RETURN_THROWS(); } /* TODO: Should this always use intern->ce? */ if (!instanceof_function(Z_OBJCE_P(object), ref->prop ? ref->prop->ce : intern->ce)) { _DO_THROW("Given object is not an instance of the class this property was declared in"); RETURN_THROWS(); } old_scope = EG(fake_scope); EG(fake_scope) = intern->ce; retval = Z_OBJ_HT_P(object)->has_property(Z_OBJ_P(object), ref->unmangled_name, ZEND_PROPERTY_EXISTS, NULL); EG(fake_scope) = old_scope; RETVAL_BOOL(retval); } } /* }}} */ /* {{{ Get the declaring class */ ZEND_METHOD(ReflectionProperty, getDeclaringClass) { reflection_object *intern; property_reference *ref; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); ce = ref->prop ? ref->prop->ce : intern->ce; zend_reflection_class_factory(ce, return_value); } /* }}} */ /* {{{ Returns the doc comment for this property */ ZEND_METHOD(ReflectionProperty, getDocComment) { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); if (ref->prop && ref->prop->doc_comment) { RETURN_STR_COPY(ref->prop->doc_comment); } RETURN_FALSE; } /* }}} */ /* {{{ Returns the attributes of this property */ ZEND_METHOD(ReflectionProperty, getAttributes) { reflection_object *intern; property_reference *ref; GET_REFLECTION_OBJECT_PTR(ref); if (ref->prop == NULL) { RETURN_EMPTY_ARRAY(); } reflect_attributes(INTERNAL_FUNCTION_PARAM_PASSTHRU, ref->prop->attributes, 0, ref->prop->ce, ZEND_ATTRIBUTE_TARGET_PROPERTY, ref->prop->ce->type == ZEND_USER_CLASS ? ref->prop->ce->info.user.filename : NULL); } /* }}} */ /* {{{ Sets whether non-public properties can be requested */ ZEND_METHOD(ReflectionProperty, setAccessible) { reflection_object *intern; zend_bool visible; if (zend_parse_parameters(ZEND_NUM_ARGS(), "b", &visible) == FAILURE) { RETURN_THROWS(); } intern = Z_REFLECTION_P(ZEND_THIS); intern->ignore_visibility = visible; } /* }}} */ /* {{{ Returns the type associated with the property */ ZEND_METHOD(ReflectionProperty, getType) { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); if (!ref->prop || !ZEND_TYPE_IS_SET(ref->prop->type)) { RETURN_NULL(); } reflection_type_factory(ref->prop->type, return_value, 1); } /* }}} */ /* {{{ Returns whether property has a type */ ZEND_METHOD(ReflectionProperty, hasType) { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); RETVAL_BOOL(ref->prop && ZEND_TYPE_IS_SET(ref->prop->type)); } /* }}} */ /* {{{ Returns whether property has a default value */ ZEND_METHOD(ReflectionProperty, hasDefaultValue) { reflection_object *intern; property_reference *ref; zend_property_info *prop_info; zval *prop; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); prop_info = ref->prop; if (prop_info == NULL) { RETURN_FALSE; } prop = property_get_default(prop_info); RETURN_BOOL(!Z_ISUNDEF_P(prop)); } /* }}} */ /* {{{ Returns the default value of a property */ ZEND_METHOD(ReflectionProperty, getDefaultValue) { reflection_object *intern; property_reference *ref; zend_property_info *prop_info; zval *prop; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(ref); prop_info = ref->prop; if (prop_info == NULL) { return; // throw exception? } prop = property_get_default(prop_info); if (Z_ISUNDEF_P(prop)) { return; } /* copy: enforce read only access */ ZVAL_DEREF(prop); ZVAL_COPY_OR_DUP(return_value, prop); /* this is necessary to make it able to work with default array * properties, returned to user */ if (Z_TYPE_P(return_value) == IS_CONSTANT_AST) { if (UNEXPECTED(zval_update_constant_ex(return_value, prop_info->ce) != SUCCESS)) { RETURN_THROWS(); } } } /* }}} */ /* {{{ Constructor. Throws an Exception in case the given extension does not exist */ ZEND_METHOD(ReflectionExtension, __construct) { zval *object; char *lcname; reflection_object *intern; zend_module_entry *module; char *name_str; size_t name_len; ALLOCA_FLAG(use_heap) if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name_str, &name_len) == FAILURE) { RETURN_THROWS(); } object = ZEND_THIS; intern = Z_REFLECTION_P(object); lcname = do_alloca(name_len + 1, use_heap); zend_str_tolower_copy(lcname, name_str, name_len); if ((module = zend_hash_str_find_ptr(&module_registry, lcname, name_len)) == NULL) { free_alloca(lcname, use_heap); zend_throw_exception_ex(reflection_exception_ptr, 0, "Extension \"%s\" does not exist", name_str); RETURN_THROWS(); } free_alloca(lcname, use_heap); ZVAL_STRING(reflection_prop_name(object), module->name); intern->ptr = module; intern->ref_type = REF_TYPE_OTHER; intern->ce = NULL; } /* }}} */ /* {{{ Returns a string representation */ ZEND_METHOD(ReflectionExtension, __toString) { reflection_object *intern; zend_module_entry *module; smart_str str = {0}; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); _extension_string(&str, module, ""); RETURN_STR(smart_str_extract(&str)); } /* }}} */ /* {{{ Returns this extension's name */ ZEND_METHOD(ReflectionExtension, getName) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); RETURN_STRING(module->name); } /* }}} */ /* {{{ Returns this extension's version */ ZEND_METHOD(ReflectionExtension, getVersion) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); /* An extension does not necessarily have a version number */ if (module->version == NO_VERSION_YET) { RETURN_NULL(); } else { RETURN_STRING(module->version); } } /* }}} */ /* {{{ Returns an array of this extension's functions */ ZEND_METHOD(ReflectionExtension, getFunctions) { reflection_object *intern; zend_module_entry *module; zval function; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); ZEND_HASH_FOREACH_PTR(CG(function_table), fptr) { if (fptr->common.type==ZEND_INTERNAL_FUNCTION && fptr->internal_function.module == module) { reflection_function_factory(fptr, NULL, &function); zend_hash_update(Z_ARRVAL_P(return_value), fptr->common.function_name, &function); } } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ Returns an associative array containing this extension's constants and their values */ ZEND_METHOD(ReflectionExtension, getConstants) { reflection_object *intern; zend_module_entry *module; zend_constant *constant; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); ZEND_HASH_FOREACH_PTR(EG(zend_constants), constant) { if (module->module_number == ZEND_CONSTANT_MODULE_NUMBER(constant)) { zval const_val; ZVAL_COPY_OR_DUP(&const_val, &constant->value); zend_hash_update(Z_ARRVAL_P(return_value), constant->name, &const_val); } } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ _addinientry */ static void _addinientry(zend_ini_entry *ini_entry, zval *retval, int number) { if (number == ini_entry->module_number) { zval zv; if (ini_entry->value) { ZVAL_STR_COPY(&zv, ini_entry->value); } else { ZVAL_NULL(&zv); } zend_symtable_update(Z_ARRVAL_P(retval), ini_entry->name, &zv); } } /* }}} */ /* {{{ Returns an associative array containing this extension's INI entries and their values */ ZEND_METHOD(ReflectionExtension, getINIEntries) { reflection_object *intern; zend_module_entry *module; zend_ini_entry *ini_entry; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); ZEND_HASH_FOREACH_PTR(EG(ini_directives), ini_entry) { _addinientry(ini_entry, return_value, module->module_number); } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ add_extension_class */ static void add_extension_class(zend_class_entry *ce, zend_string *key, zval *class_array, zend_module_entry *module, zend_bool add_reflection_class) { if (ce->type == ZEND_INTERNAL_CLASS && ce->info.internal.module && !strcasecmp(ce->info.internal.module->name, module->name)) { zend_string *name; if (!zend_string_equals_ci(ce->name, key)) { /* This is a class alias, use alias name */ name = key; } else { /* Use class name */ name = ce->name; } if (add_reflection_class) { zval zclass; zend_reflection_class_factory(ce, &zclass); zend_hash_update(Z_ARRVAL_P(class_array), name, &zclass); } else { add_next_index_str(class_array, zend_string_copy(name)); } } } /* }}} */ /* {{{ Returns an array containing ReflectionClass objects for all classes of this extension */ ZEND_METHOD(ReflectionExtension, getClasses) { reflection_object *intern; zend_module_entry *module; zend_string *key; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); ZEND_HASH_FOREACH_STR_KEY_PTR(EG(class_table), key, ce) { add_extension_class(ce, key, return_value, module, 1); } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ Returns an array containing all names of all classes of this extension */ ZEND_METHOD(ReflectionExtension, getClassNames) { reflection_object *intern; zend_module_entry *module; zend_string *key; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); ZEND_HASH_FOREACH_STR_KEY_PTR(EG(class_table), key, ce) { add_extension_class(ce, key, return_value, module, 0); } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ Returns an array containing all names of all extensions this extension depends on */ ZEND_METHOD(ReflectionExtension, getDependencies) { reflection_object *intern; zend_module_entry *module; const zend_module_dep *dep; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); dep = module->deps; if (!dep) { RETURN_EMPTY_ARRAY(); } array_init(return_value); while(dep->name) { zend_string *relation; char *rel_type; size_t len = 0; switch(dep->type) { case MODULE_DEP_REQUIRED: rel_type = "Required"; len += sizeof("Required") - 1; break; case MODULE_DEP_CONFLICTS: rel_type = "Conflicts"; len += sizeof("Conflicts") - 1; break; case MODULE_DEP_OPTIONAL: rel_type = "Optional"; len += sizeof("Optional") - 1; break; default: rel_type = "Error"; /* shouldn't happen */ len += sizeof("Error") - 1; break; } if (dep->rel) { len += strlen(dep->rel) + 1; } if (dep->version) { len += strlen(dep->version) + 1; } relation = zend_string_alloc(len, 0); snprintf(ZSTR_VAL(relation), ZSTR_LEN(relation) + 1, "%s%s%s%s%s", rel_type, dep->rel ? " " : "", dep->rel ? dep->rel : "", dep->version ? " " : "", dep->version ? dep->version : ""); add_assoc_str(return_value, dep->name, relation); dep++; } } /* }}} */ /* {{{ Prints phpinfo block for the extension */ ZEND_METHOD(ReflectionExtension, info) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); php_info_print_module(module); } /* }}} */ /* {{{ Returns whether this extension is persistent */ ZEND_METHOD(ReflectionExtension, isPersistent) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); RETURN_BOOL(module->type == MODULE_PERSISTENT); } /* }}} */ /* {{{ Returns whether this extension is temporary */ ZEND_METHOD(ReflectionExtension, isTemporary) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(module); RETURN_BOOL(module->type == MODULE_TEMPORARY); } /* }}} */ /* {{{ Constructor. Throws an Exception in case the given Zend extension does not exist */ ZEND_METHOD(ReflectionZendExtension, __construct) { zval *object; reflection_object *intern; zend_extension *extension; char *name_str; size_t name_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name_str, &name_len) == FAILURE) { RETURN_THROWS(); } object = ZEND_THIS; intern = Z_REFLECTION_P(object); extension = zend_get_extension(name_str); if (!extension) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Zend Extension \"%s\" does not exist", name_str); RETURN_THROWS(); } ZVAL_STRING(reflection_prop_name(object), extension->name); intern->ptr = extension; intern->ref_type = REF_TYPE_OTHER; intern->ce = NULL; } /* }}} */ /* {{{ Returns a string representation */ ZEND_METHOD(ReflectionZendExtension, __toString) { reflection_object *intern; zend_extension *extension; smart_str str = {0}; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(extension); _zend_extension_string(&str, extension, ""); RETURN_STR(smart_str_extract(&str)); } /* }}} */ /* {{{ Returns the name of this Zend extension */ ZEND_METHOD(ReflectionZendExtension, getName) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(extension); RETURN_STRING(extension->name); } /* }}} */ /* {{{ Returns the version information of this Zend extension */ ZEND_METHOD(ReflectionZendExtension, getVersion) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(extension); if (extension->version) { RETURN_STRING(extension->version); } else { RETURN_EMPTY_STRING(); } } /* }}} */ /* {{{ Returns the name of this Zend extension's author */ ZEND_METHOD(ReflectionZendExtension, getAuthor) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(extension); if (extension->author) { RETURN_STRING(extension->author); } else { RETURN_EMPTY_STRING(); } } /* }}} */ /* {{{ Returns this Zend extension's URL*/ ZEND_METHOD(ReflectionZendExtension, getURL) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(extension); if (extension->URL) { RETURN_STRING(extension->URL); } else { RETURN_EMPTY_STRING(); } } /* }}} */ /* {{{ Returns this Zend extension's copyright information */ ZEND_METHOD(ReflectionZendExtension, getCopyright) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(extension); if (extension->copyright) { RETURN_STRING(extension->copyright); } else { RETURN_EMPTY_STRING(); } } /* }}} */ /* {{{ Dummy constructor -- always throws ReflectionExceptions. */ ZEND_METHOD(ReflectionReference, __construct) { _DO_THROW( "Cannot directly instantiate ReflectionReference. " "Use ReflectionReference::fromArrayElement() instead" ); } /* }}} */ static zend_bool is_ignorable_reference(HashTable *ht, zval *ref) { if (Z_REFCOUNT_P(ref) != 1) { return 0; } /* Directly self-referential arrays are treated as proper references * in zend_array_dup() despite rc=1. */ return Z_TYPE_P(Z_REFVAL_P(ref)) != IS_ARRAY || Z_ARRVAL_P(Z_REFVAL_P(ref)) != ht; } /* {{{ Create ReflectionReference for array item. Returns null if not a reference. */ ZEND_METHOD(ReflectionReference, fromArrayElement) { HashTable *ht; zval *item; zend_string *string_key = NULL; zend_long int_key = 0; reflection_object *intern; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_ARRAY_HT(ht) Z_PARAM_STR_OR_LONG(string_key, int_key) ZEND_PARSE_PARAMETERS_END(); if (string_key) { item = zend_hash_find(ht, string_key); } else { item = zend_hash_index_find(ht, int_key); } if (!item) { _DO_THROW("Array key not found"); RETURN_THROWS(); } if (Z_TYPE_P(item) != IS_REFERENCE || is_ignorable_reference(ht, item)) { RETURN_NULL(); } object_init_ex(return_value, reflection_reference_ptr); intern = Z_REFLECTION_P(return_value); ZVAL_COPY(&intern->obj, item); intern->ref_type = REF_TYPE_OTHER; } /* }}} */ /* {{{ Returns a unique identifier for the reference. * The format of the return value is unspecified and may change. */ ZEND_METHOD(ReflectionReference, getId) { reflection_object *intern; unsigned char digest[20]; PHP_SHA1_CTX context; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } intern = Z_REFLECTION_P(getThis()); if (Z_TYPE(intern->obj) != IS_REFERENCE) { _DO_THROW("Corrupted ReflectionReference object"); RETURN_THROWS(); } if (!REFLECTION_G(key_initialized)) { if (php_random_bytes_throw(&REFLECTION_G(key_initialized), 16) == FAILURE) { RETURN_THROWS(); } REFLECTION_G(key_initialized) = 1; } /* SHA1(ref || key) to avoid directly exposing memory addresses. */ PHP_SHA1Init(&context); PHP_SHA1Update(&context, (unsigned char *) &Z_REF(intern->obj), sizeof(zend_reference *)); PHP_SHA1Update(&context, REFLECTION_G(key), REFLECTION_KEY_LEN); PHP_SHA1Final(digest, &context); RETURN_STRINGL((char *) digest, sizeof(digest)); } /* }}} */ ZEND_METHOD(ReflectionAttribute, __construct) { } ZEND_METHOD(ReflectionAttribute, __clone) { /* Should never be executable */ _DO_THROW("Cannot clone object using __clone()"); } /* {{{ * Returns the name of the attribute */ ZEND_METHOD(ReflectionAttribute, getName) { reflection_object *intern; attribute_reference *attr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(attr); RETURN_STR_COPY(attr->data->name); } /* }}} */ /* {{{ * Returns the target of the attribute */ ZEND_METHOD(ReflectionAttribute, getTarget) { reflection_object *intern; attribute_reference *attr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(attr); RETURN_LONG(attr->target); } /* }}} */ /* {{{ * Returns true if the attribute is repeated */ ZEND_METHOD(ReflectionAttribute, isRepeated) { reflection_object *intern; attribute_reference *attr; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(attr); RETURN_BOOL(zend_is_attribute_repeated(attr->attributes, attr->data)); } /* }}} */ /* {{{ * Returns the arguments passed to the attribute */ ZEND_METHOD(ReflectionAttribute, getArguments) { reflection_object *intern; attribute_reference *attr; zval tmp; uint32_t i; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(attr); array_init(return_value); for (i = 0; i < attr->data->argc; i++) { if (FAILURE == zend_get_attribute_value(&tmp, attr->data, i, attr->scope)) { RETURN_THROWS(); } if (attr->data->args[i].name) { /* We ensured at compile-time that there are no duplicate parameter names. */ zend_hash_add_new(Z_ARRVAL_P(return_value), attr->data->args[i].name, &tmp); } else { add_next_index_zval(return_value, &tmp); } } } /* }}} */ static int call_attribute_constructor( zend_attribute *attr, zend_class_entry *ce, zend_object *obj, zval *args, uint32_t argc, HashTable *named_params, zend_string *filename) { zend_function *ctor = ce->constructor; zend_execute_data *prev_execute_data, dummy_frame; zend_function dummy_func; zend_op dummy_opline; ZEND_ASSERT(ctor != NULL); if (!(ctor->common.fn_flags & ZEND_ACC_PUBLIC)) { zend_throw_error(NULL, "Attribute constructor of class %s must be public", ZSTR_VAL(ce->name)); return FAILURE; } if (filename) { /* Set up dummy call frame that makes it look like the attribute was invoked * from where it occurs in the code. */ memset(&dummy_frame, 0, sizeof(zend_execute_data)); memset(&dummy_func, 0, sizeof(zend_function)); memset(&dummy_opline, 0, sizeof(zend_op)); prev_execute_data = EG(current_execute_data); dummy_frame.prev_execute_data = prev_execute_data; dummy_frame.func = &dummy_func; dummy_frame.opline = &dummy_opline; dummy_func.type = ZEND_USER_FUNCTION; dummy_func.common.fn_flags = attr->flags & ZEND_ATTRIBUTE_STRICT_TYPES ? ZEND_ACC_STRICT_TYPES : 0; dummy_func.op_array.filename = filename; dummy_opline.opcode = ZEND_DO_FCALL; dummy_opline.lineno = attr->lineno; EG(current_execute_data) = &dummy_frame; } zend_call_known_function(ctor, obj, obj->ce, NULL, argc, args, named_params); if (filename) { EG(current_execute_data) = prev_execute_data; } if (EG(exception)) { zend_object_store_ctor_failed(obj); return FAILURE; } return SUCCESS; } static void attribute_ctor_cleanup( zval *obj, zval *args, uint32_t argc, HashTable *named_params) /* {{{ */ { if (obj) { zval_ptr_dtor(obj); } if (args) { uint32_t i; for (i = 0; i < argc; i++) { zval_ptr_dtor(&args[i]); } efree(args); } if (named_params) { zend_array_destroy(named_params); } } /* }}} */ /* {{{ * Returns the attribute as an object */ ZEND_METHOD(ReflectionAttribute, newInstance) { reflection_object *intern; attribute_reference *attr; zend_attribute *marker; zend_class_entry *ce; zval obj; zval *args = NULL; HashTable *named_params = NULL; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } GET_REFLECTION_OBJECT_PTR(attr); if (NULL == (ce = zend_lookup_class(attr->data->name))) { zend_throw_error(NULL, "Attribute class \"%s\" not found", ZSTR_VAL(attr->data->name)); RETURN_THROWS(); } if (NULL == (marker = zend_get_attribute_str(ce->attributes, ZEND_STRL("attribute")))) { zend_throw_error(NULL, "Attempting to use non-attribute class \"%s\" as attribute", ZSTR_VAL(attr->data->name)); RETURN_THROWS(); } if (ce->type == ZEND_USER_CLASS) { uint32_t flags = ZEND_ATTRIBUTE_TARGET_ALL; if (marker->argc > 0) { zval tmp; if (FAILURE == zend_get_attribute_value(&tmp, marker, 0, ce)) { RETURN_THROWS(); } flags = (uint32_t) Z_LVAL(tmp); } if (!(attr->target & flags)) { zend_string *location = zend_get_attribute_target_names(attr->target); zend_string *allowed = zend_get_attribute_target_names(flags); zend_throw_error(NULL, "Attribute \"%s\" cannot target %s (allowed targets: %s)", ZSTR_VAL(attr->data->name), ZSTR_VAL(location), ZSTR_VAL(allowed) ); zend_string_release(location); zend_string_release(allowed); RETURN_THROWS(); } if (!(flags & ZEND_ATTRIBUTE_IS_REPEATABLE)) { if (zend_is_attribute_repeated(attr->attributes, attr->data)) { zend_throw_error(NULL, "Attribute \"%s\" must not be repeated", ZSTR_VAL(attr->data->name)); RETURN_THROWS(); } } } if (SUCCESS != object_init_ex(&obj, ce)) { RETURN_THROWS(); } uint32_t argc = 0; if (attr->data->argc) { args = emalloc(attr->data->argc * sizeof(zval)); for (uint32_t i = 0; i < attr->data->argc; i++) { zval val; if (FAILURE == zend_get_attribute_value(&val, attr->data, i, attr->scope)) { attribute_ctor_cleanup(&obj, args, i, named_params); RETURN_THROWS(); } if (attr->data->args[i].name) { if (!named_params) { named_params = zend_new_array(0); } zend_hash_add_new(named_params, attr->data->args[i].name, &val); } else { ZVAL_COPY_VALUE(&args[i], &val); argc++; } } } if (ce->constructor) { if (FAILURE == call_attribute_constructor(attr->data, ce, Z_OBJ(obj), args, argc, named_params, attr->filename)) { attribute_ctor_cleanup(&obj, args, argc, named_params); RETURN_THROWS(); } } else if (argc || named_params) { attribute_ctor_cleanup(&obj, args, argc, named_params); zend_throw_error(NULL, "Attribute class %s does not have a constructor, cannot pass arguments", ZSTR_VAL(ce->name)); RETURN_THROWS(); } attribute_ctor_cleanup(NULL, args, argc, named_params); RETURN_COPY_VALUE(&obj); } /* {{{ _reflection_write_property */ static zval *_reflection_write_property(zend_object *object, zend_string *name, zval *value, void **cache_slot) { if (zend_hash_exists(&object->ce->properties_info, name) && (zend_string_equals_literal(name, "name") || zend_string_equals_literal(name, "class"))) { zend_throw_exception_ex(reflection_exception_ptr, 0, "Cannot set read-only property %s::$%s", ZSTR_VAL(object->ce->name), ZSTR_VAL(name)); return &EG(uninitialized_zval); } else { return zend_std_write_property(object, name, value, cache_slot); } } /* }}} */ static void reflection_init_class_handlers(zend_class_entry *ce) { ce->create_object = reflection_objects_new; ce->serialize = zend_class_serialize_deny; ce->unserialize = zend_class_unserialize_deny; } PHP_MINIT_FUNCTION(reflection) /* {{{ */ { zend_class_entry _reflection_entry; memcpy(&reflection_object_handlers, &std_object_handlers, sizeof(zend_object_handlers)); reflection_object_handlers.offset = XtOffsetOf(reflection_object, zo); reflection_object_handlers.free_obj = reflection_free_objects_storage; reflection_object_handlers.clone_obj = NULL; reflection_object_handlers.write_property = _reflection_write_property; reflection_object_handlers.get_gc = reflection_get_gc; INIT_CLASS_ENTRY(_reflection_entry, "ReflectionException", class_ReflectionException_methods); reflection_exception_ptr = zend_register_internal_class_ex(&_reflection_entry, zend_ce_exception); INIT_CLASS_ENTRY(_reflection_entry, "Reflection", class_Reflection_methods); reflection_ptr = zend_register_internal_class(&_reflection_entry); INIT_CLASS_ENTRY(_reflection_entry, "Reflector", class_Reflector_methods); reflector_ptr = zend_register_internal_interface(&_reflection_entry); zend_class_implements(reflector_ptr, 1, zend_ce_stringable); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionFunctionAbstract", class_ReflectionFunctionAbstract_methods); reflection_init_class_handlers(&_reflection_entry); reflection_function_abstract_ptr = zend_register_internal_class(&_reflection_entry); zend_class_implements(reflection_function_abstract_ptr, 1, reflector_ptr); zend_declare_property_string(reflection_function_abstract_ptr, "name", sizeof("name")-1, "", ZEND_ACC_ABSTRACT); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionFunction", class_ReflectionFunction_methods); reflection_init_class_handlers(&_reflection_entry); reflection_function_ptr = zend_register_internal_class_ex(&_reflection_entry, reflection_function_abstract_ptr); zend_declare_property_string(reflection_function_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC); REGISTER_REFLECTION_CLASS_CONST_LONG(function, "IS_DEPRECATED", ZEND_ACC_DEPRECATED); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionGenerator", class_ReflectionGenerator_methods); reflection_init_class_handlers(&_reflection_entry); reflection_generator_ptr = zend_register_internal_class(&_reflection_entry); reflection_generator_ptr->ce_flags |= ZEND_ACC_FINAL; INIT_CLASS_ENTRY(_reflection_entry, "ReflectionParameter", class_ReflectionParameter_methods); reflection_init_class_handlers(&_reflection_entry); reflection_parameter_ptr = zend_register_internal_class(&_reflection_entry); zend_class_implements(reflection_parameter_ptr, 1, reflector_ptr); zend_declare_property_string(reflection_parameter_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionType", class_ReflectionType_methods); reflection_init_class_handlers(&_reflection_entry); reflection_type_ptr = zend_register_internal_class(&_reflection_entry); reflection_type_ptr->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; zend_class_implements(reflection_type_ptr, 1, zend_ce_stringable); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionNamedType", class_ReflectionNamedType_methods); reflection_init_class_handlers(&_reflection_entry); reflection_named_type_ptr = zend_register_internal_class_ex(&_reflection_entry, reflection_type_ptr); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionUnionType", class_ReflectionUnionType_methods); reflection_init_class_handlers(&_reflection_entry); reflection_union_type_ptr = zend_register_internal_class_ex(&_reflection_entry, reflection_type_ptr); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionMethod", class_ReflectionMethod_methods); reflection_init_class_handlers(&_reflection_entry); reflection_method_ptr = zend_register_internal_class_ex(&_reflection_entry, reflection_function_abstract_ptr); zend_declare_property_string(reflection_method_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC); zend_declare_property_string(reflection_method_ptr, "class", sizeof("class")-1, "", ZEND_ACC_PUBLIC); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_STATIC", ZEND_ACC_STATIC); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_PUBLIC", ZEND_ACC_PUBLIC); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_PROTECTED", ZEND_ACC_PROTECTED); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_PRIVATE", ZEND_ACC_PRIVATE); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_ABSTRACT", ZEND_ACC_ABSTRACT); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_FINAL", ZEND_ACC_FINAL); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionClass", class_ReflectionClass_methods); reflection_init_class_handlers(&_reflection_entry); reflection_class_ptr = zend_register_internal_class(&_reflection_entry); zend_class_implements(reflection_class_ptr, 1, reflector_ptr); zend_declare_property_string(reflection_class_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC); /* IS_IMPLICIT_ABSTRACT is not longer used */ REGISTER_REFLECTION_CLASS_CONST_LONG(class, "IS_IMPLICIT_ABSTRACT", ZEND_ACC_IMPLICIT_ABSTRACT_CLASS); REGISTER_REFLECTION_CLASS_CONST_LONG(class, "IS_EXPLICIT_ABSTRACT", ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); REGISTER_REFLECTION_CLASS_CONST_LONG(class, "IS_FINAL", ZEND_ACC_FINAL); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionObject", class_ReflectionObject_methods); reflection_init_class_handlers(&_reflection_entry); reflection_object_ptr = zend_register_internal_class_ex(&_reflection_entry, reflection_class_ptr); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionProperty", class_ReflectionProperty_methods); reflection_init_class_handlers(&_reflection_entry); reflection_property_ptr = zend_register_internal_class(&_reflection_entry); zend_class_implements(reflection_property_ptr, 1, reflector_ptr); zend_declare_property_string(reflection_property_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC); zend_declare_property_string(reflection_property_ptr, "class", sizeof("class")-1, "", ZEND_ACC_PUBLIC); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_STATIC", ZEND_ACC_STATIC); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_PUBLIC", ZEND_ACC_PUBLIC); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_PROTECTED", ZEND_ACC_PROTECTED); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_PRIVATE", ZEND_ACC_PRIVATE); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionClassConstant", class_ReflectionClassConstant_methods); reflection_init_class_handlers(&_reflection_entry); reflection_class_constant_ptr = zend_register_internal_class(&_reflection_entry); zend_class_implements(reflection_class_constant_ptr, 1, reflector_ptr); zend_declare_property_string(reflection_class_constant_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC); zend_declare_property_string(reflection_class_constant_ptr, "class", sizeof("class")-1, "", ZEND_ACC_PUBLIC); REGISTER_REFLECTION_CLASS_CONST_LONG(class_constant, "IS_PUBLIC", ZEND_ACC_PUBLIC); REGISTER_REFLECTION_CLASS_CONST_LONG(class_constant, "IS_PROTECTED", ZEND_ACC_PROTECTED); REGISTER_REFLECTION_CLASS_CONST_LONG(class_constant, "IS_PRIVATE", ZEND_ACC_PRIVATE); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionExtension", class_ReflectionExtension_methods); reflection_init_class_handlers(&_reflection_entry); reflection_extension_ptr = zend_register_internal_class(&_reflection_entry); zend_class_implements(reflection_extension_ptr, 1, reflector_ptr); zend_declare_property_string(reflection_extension_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionZendExtension", class_ReflectionZendExtension_methods); reflection_init_class_handlers(&_reflection_entry); reflection_zend_extension_ptr = zend_register_internal_class(&_reflection_entry); zend_class_implements(reflection_zend_extension_ptr, 1, reflector_ptr); zend_declare_property_string(reflection_zend_extension_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionReference", class_ReflectionReference_methods); reflection_init_class_handlers(&_reflection_entry); _reflection_entry.ce_flags |= ZEND_ACC_FINAL; reflection_reference_ptr = zend_register_internal_class(&_reflection_entry); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionAttribute", class_ReflectionAttribute_methods); reflection_init_class_handlers(&_reflection_entry); _reflection_entry.ce_flags |= ZEND_ACC_FINAL; reflection_attribute_ptr = zend_register_internal_class(&_reflection_entry); REGISTER_REFLECTION_CLASS_CONST_LONG(attribute, "IS_INSTANCEOF", REFLECTION_ATTRIBUTE_IS_INSTANCEOF); REFLECTION_G(key_initialized) = 0; return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(reflection) /* {{{ */ { php_info_print_table_start(); php_info_print_table_row(2, "Reflection", "enabled"); php_info_print_table_end(); } /* }}} */ zend_module_entry reflection_module_entry = { /* {{{ */ STANDARD_MODULE_HEADER, "Reflection", NULL, PHP_MINIT(reflection), NULL, NULL, NULL, PHP_MINFO(reflection), PHP_REFLECTION_VERSION, ZEND_MODULE_GLOBALS(reflection), NULL, NULL, NULL, STANDARD_MODULE_PROPERTIES_EX }; /* }}} */
[ "s.gottschall@dd-wrt.com" ]
s.gottschall@dd-wrt.com
c74e593753a01e69296537fde8a30ca263e6eff5
02e2e33a71a35a26fc936a3401c7ac0dfa9387b8
/permutations_II.c
e25bf6466bab945296ce4dea41f6035d3dc25227
[]
no_license
April01xxx/LeetCode
71d83bf06fe8dd449e31d3a0e961985a4e50c849
d506672137e19dae41aa7a7275e1bb469829d6c6
refs/heads/master
2021-07-10T14:13:38.517065
2019-04-04T11:03:32
2019-04-04T11:03:32
140,214,971
0
0
null
null
null
null
UTF-8
C
false
false
1,870
c
/** * Given a collection of numbers that might contain duplicates, return all * possible unique permutations. * * Example: * Input: [1,1,2] * Output: * [ * [1,1,2], * [1,2,1], * [2,1,1] * ] * * 这道题相比上一道难度增加了点,因为给定的数组中有重复的元素,返回的结果集中 * 需要去重,不过其实类似的题做多了都一个套路,先排序,然后查找时跳过已经处理 * 过的元素. */ void dfs(int *nums, int start, int size, int **ans, int *temp, int *curr, int *visited) { int i; if (start == size) { ans[*curr] = (int *)malloc(size * sizeof(int)); memcpy(ans[*curr], temp, size * sizeof(int)); ++*curr; return; } for (i = 0; i < size; ++i) { /** * 此处不能再像之前那道题中那样采用交换的方式,因为交换会破坏有序性. * 所以额外用一个数组来记录元素是否被访问过.每次都从头开始扫描. */ if (visited[i] == 0) { temp[start] = nums[i]; visited[i] = 1; dfs(nums, start + 1, size, ans, temp, curr, visited); visited[i] = 0; /** * 跳过相同元素. */ while (i < size - 1 && nums[i + 1] == nums[i]) ++i; } } } int compare(const void *a, const void *b) { return *(int *)a - *(int *)b; } int ** permuteUnique(int *nums, int numsSize, int *returnSize) { int **ans, *temp, *visited, i; if (numsSize == 0) return NULL; *returnSize = 1; for (i = 2; i <= numsSize; ++i) *returnSize *= i; ans = (int **)malloc(*returnSize * sizeof(int *)); temp = (int *)malloc(numsSize * sizeof(int)); visited = (int *)calloc(numsSize, sizeof(int)); qsort(nums, numsSize, sizeof(int), compare); i = 0; dfs(nums, 0, numsSize, ans, temp, &i, visited); free(temp); free(visited); *returnSize = i; return ans; }
[ "april01xxx@gmail.com" ]
april01xxx@gmail.com
45a0fc5373196c36f728a9835e75cc874e06d19c
a91924302898297409aa65d3f17cc1992a54cf66
/Module/CLayoutKB9Number.h
c61562c4cf61a4212b1e7f209effcd9af28a56f9
[]
no_license
CodeWorlds/GBIME
8bd68202cccd4bd5f836ef1fe824a641f9ae0b4c
89acf1e97e4d3fb97d88298e24ff0385827d87cd
refs/heads/master
2023-03-15T21:53:44.426568
2016-07-18T03:45:43
2016-07-18T03:45:43
null
0
0
null
null
null
null
GB18030
C
false
false
1,603
h
/*************************************************************************** * File Name : CLayoutKB9Number.h * Corporation : Guobi Technology Ltd. GuangZhou China * Copyright : Copyright Guobi Technology Ltd. And Subject to Confidentiality * Restrictions. This document is the confidential and proprietary * property of Guobi Technology Ltd.It is neither the document * itself nor any part of it can be shared with any party without * the written permission. * Author : ZhaoKun * Date : 2010-10-15 * Purpose : 物理九键数字Layout * Version : V1.0 * Last Changed List * Name | date | Discription ****************************************************************************/ #if defined(__GBIME_KB__) // 国笔物理键盘 #ifndef __CLASS_LAYOUT_KB9_NUMBER__ #define __CLASS_LAYOUT_KB9_NUMBER__ #include "CLayoutKB.h" /*! * \Layout this指针和Layout 基类指针转换 */ #undef CLASE_THIS_POITER #define CLASE_THIS_POITER(CLASS_NAME, pltObj) \ CLASS_NAME * pltThis = (CLASS_NAME *)pltObj; \ PCLayoutKB pltBase = &pltThis->m_ltParent; \ PCLayoutAbstract pltRoot = &pltThis->m_ltParent.m_ltParent; typedef struct _tag_CLayoutKB9Number { CLayoutKB m_ltParent; } CLayoutKB9Number, * PCLayoutKB9Number; CLayoutAbstract * CLayoutKB9Number__Construct(PCLayoutKB9Number pltKB, GBLPCVOID pltUIData, GBLPCVOID pltIMData, GBLPCVOID pltConfigData); #endif //__CLASS_LAYOUT_KB9_Number__ #endif // 国笔物理键盘
[ "gitlab.anydian.com" ]
gitlab.anydian.com
f4b36c35ebc5fd40f60023c7954ea8dec6498932
976f5e0b583c3f3a87a142187b9a2b2a5ae9cf6f
/source/linux/drivers/media/i2c/extr_max2175.c_max2175_set_rf_freq_non_am_bands.c
7bc9dda15915293c446a2795c9838bb4512812a3
[]
no_license
isabella232/AnghaBench
7ba90823cf8c0dd25a803d1688500eec91d1cf4e
9a5f60cdc907a0475090eef45e5be43392c25132
refs/heads/master
2023-04-20T09:05:33.024569
2021-05-07T18:36:26
2021-05-07T18:36:26
null
0
0
null
null
null
null
UTF-8
C
false
false
1,462
c
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int u64 ; typedef scalar_t__ u32 ; struct max2175 {int dummy; } ; typedef int s64 ; /* Variables and functions */ int MAX2175_IS_BAND_VHF (struct max2175*) ; scalar_t__ MAX2175_IS_FMHD_MODE (struct max2175*) ; scalar_t__ MAX2175_IS_FM_MODE (struct max2175*) ; scalar_t__ MAX2175_LO_ABOVE_DESIRED ; int max2175_set_lo_freq (struct max2175*,int) ; int max2175_set_nco_freq (struct max2175*,int) ; int /*<<< orphan*/ mxm_dbg (struct max2175*,char*) ; __attribute__((used)) static int max2175_set_rf_freq_non_am_bands(struct max2175 *ctx, u64 freq, u32 lo_pos) { s64 adj_freq, low_if_freq; int ret; mxm_dbg(ctx, "rf_freq: non AM bands\n"); if (MAX2175_IS_FM_MODE(ctx)) low_if_freq = 128000; else if (MAX2175_IS_FMHD_MODE(ctx)) low_if_freq = 228000; else return max2175_set_lo_freq(ctx, freq); if (MAX2175_IS_BAND_VHF(ctx) == (lo_pos == MAX2175_LO_ABOVE_DESIRED)) adj_freq = freq + low_if_freq; else adj_freq = freq - low_if_freq; ret = max2175_set_lo_freq(ctx, adj_freq); if (ret) return ret; return max2175_set_nco_freq(ctx, -low_if_freq); }
[ "brenocfg@gmail.com" ]
brenocfg@gmail.com
f8d5596091bf094b7da4ef65376e57b2f2eb1835
4ae17e009a2dcd620aaa26ab3c9ac2c130f02853
/client.c
7f9638c77426230daa08c3521e4d87404c71edc1
[]
no_license
bleuflares/EE209-assignment1
7881c13235b0688f894883344638dbc652591d39
437701baa38ebf0db03aacfff91db16cbcb0fd12
refs/heads/master
2021-07-04T02:23:45.479833
2017-09-25T14:03:35
2017-09-25T14:03:35
104,757,113
0
0
null
null
null
null
UTF-8
C
false
false
21,665
c
/********************** * EE209 Assignment 1 * **********************/ /*20130242*/ /*박기성 Ki Sung Park*/ /* client.c */ #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <assert.h> #define MAX_NUM_NAME_CHARS 63 #define MAX_NUM_ID_CHARS 63 #define MAX_NUM_DIGITS 10 /*--------------------------------------------------------------------*/ /* Pre-defined error messages */ #define ERR_UNDEF_CMD "ERROR: Undefined Command\n" #define ERR_UNDEF_OPT "ERROR: Undefined Option\n" #define ERR_NEED_OPT "ERROR: Need More Option\n" #define ERR_SAME_OPT "ERROR: Multiple Same Options\n" #define ERR_AMBIG_ARG "ERROR: Ambiguous Argument\n" #define ERR_INVALID_ARG "ERROR: Invalid Option Argument\n" /*--------------------------------------------------------------------*/ enum { FALSE = 0, TRUE }; typedef enum { C_EXIT, /* exit */ C_REG, /* register */ C_UNREG, /* unregister */ C_FIND, /* find */ C_FAIL, /* failure */ C_EOF /* end of file */ } Command_T; /*--------------------------------------------------------------------*/ /* Check whether an exit command valid. */ /* Input: no argument */ /* Return value: TRUE(valid) or FALSE(invalid) */ /*--------------------------------------------------------------------*/ static int ValidateExitCommand(void) { int c; /* only blank command is allowed */ while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; if (c == EOF) exit(0); if (c != '\n' && c != EOF) { fprintf(stderr, "%s", ERR_UNDEF_OPT); /* eat the line */ while ((c = getchar()) != EOF && c != '\n') ; if (c == EOF) exit(0); return FALSE; } return TRUE; } /*--------------------------------------------------------------------*/ /* Check whether a reg(register) command valid. */ /* Input: no argument */ /* Return value: TRUE(valid) or FALSE(invalid) */ /*--------------------------------------------------------------------*/ static int ValidateRegisterCommand(void) { typedef enum { TF, NPI, N, P, I }DFAState; DFAState state = TF; int c;//instant variable for input character int NF = 0;//instnat variable set when Name option is get int PF = 0;//instant variable set when Purchase option is get int IF = 0;//instant variable set when ID option is get int count = 0;//instant variable counting the number of characters int quote = 0;//instant variable set when more than one quote is get int end = 0;//instant variable set when the input reaches \n or EOF int instate = 1;//Instant variable set when the user is currently in the state while (instate){ switch (state){ //State TF checking whether the input is valid //moves to state NPI when more option is added //otherwise, determine whether there is an error or not case TF: instate = 0; if (end == 1){ //all options valid if (NF == 1 && PF == 1 && IF == 1){ if (c == EOF) exit(0); return TRUE; } // lack of option else{ fprintf(stderr, "%s", ERR_NEED_OPT); if (c == EOF) exit(0); return FALSE; } } while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; if (c == EOF || c == '\n'){ //all options valid if (NF == 1 && PF == 1 && IF == 1){ if (c == EOF) exit(0); return TRUE; } //lack of option else fprintf(stderr, "%s", ERR_NEED_OPT); } //get a new input else if (c == '-'){ state = NPI; instate = 1; } //other inappropriate input for option else fprintf(stderr, "%s", ERR_UNDEF_OPT); break; //state NPI determines the option //it directs to the state N when option n and at least one space is input //it directs to the state I when option i and at least one space is input //it directs to the state P when option p and at least one space is input //if other values are input, it returns error case NPI: instate = 0; c = getchar(); if (c == 'n'){ if (NF == 1){ while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; //option n not finished if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //option n already got else fprintf(stderr, "%s", ERR_SAME_OPT); } // space exists after the option move to state N else if ((c = getchar()) != EOF && c != '\n' && isspace(c)){ state = N; instate = 1; } //undefined option n else fprintf(stderr, "%s", ERR_UNDEF_OPT); } else if (c == 'p'){ if (PF == 1){ while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; //option n not finished if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //option n already got else fprintf(stderr, "%s", ERR_SAME_OPT); } //space exists after the option move to state P else if ((c = getchar()) != EOF && c != '\n' && isspace(c)){ state = P; instate = 1; } //undefined option p else fprintf(stderr, "%s", ERR_UNDEF_OPT); } else if (c == 'i'){ if (IF == 1){ while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; //option i not finished if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //option i already exists else fprintf(stderr, "%s", ERR_SAME_OPT); } //space after option i move to state I else if ((c = getchar()) != EOF && c != '\n' && isspace(c)){ state = I; instate = 1; } //undefined option p else fprintf(stderr, "%s", ERR_UNDEF_OPT); } //other undefined option else fprintf(stderr, "%s", ERR_UNDEF_OPT); break; //state N checks whether the input value for name is valid case N: instate = 0; count = 0; while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; if (isalpha(c) || c == '-' || c == '_' || c == '.'){ count++; while(isalpha(c)||c=='-'||c=='_'||c=='.'||c=='\''||c=='\\'){ if (c == '\\'){ c = getchar(); //argument not allowed for name as an input if(!(isalpha(c)||c=='-'||c=='_'||c=='.'||c=='\''||c==' ')) fprintf(stderr, "%s", ERR_INVALID_ARG); } c = getchar(); count++; } //more than the Max input allowed if (--count > MAX_NUM_NAME_CHARS) fprintf(stderr, "%s", ERR_INVALID_ARG); //valid argument as an input move to state TF else if (isspace(c) || c == EOF){ NF = 1; state = TF; instate = 1; if (c == EOF || c == '\n') end = 1; } else fprintf(stderr, "%s", ERR_INVALID_ARG); } else if (c == '\''){ c = getchar(); if ( (c == EOF|| c == '\n')){ //quote not finished fprintf(stderr, "%s", ERR_INVALID_ARG); if (c == EOF) exit(0); return FALSE; } while(isalpha(c)||c=='-'||c=='_'||c=='.'||c==' '||c=='\''||c== '\\'){ if (c == '\''){ c = getchar(); count--; quote++; break; } else if (c == '\\'){ c = getchar(); if (!(isalpha(c)||c=='-'||c=='_'||c=='.'||c=='\''||c==' ')) //argument not allowed for the name as an input fprintf(stderr, "%s", ERR_INVALID_ARG); } c = getchar(); count++; } //length of argument longer than the max number allowed if (count > MAX_NUM_NAME_CHARS || count<0) fprintf(stderr, "%s", ERR_INVALID_ARG); //valid argument as an input more to state TF else if ((isspace(c) || c == EOF)&&quote==1){ NF = 1; state = TF; instate = 1; if (c == EOF || c == '\n') end = 1; } //invalid argument else fprintf(stderr, "%s", ERR_INVALID_ARG); } else if (c == '\\'){ c = getchar(); //argument not allowed for the name as an input if(!(isalpha(c)||c=='-'||c=='_'||c=='.'||c=='\''||c==' ')) fprintf(stderr, "%s", ERR_INVALID_ARG); else{ c = getchar(); //valid argument as an input move to state TF if (isspace(c) || c == EOF){ NF = 1; state = TF; instate = 1; if (c == EOF || c == '\n') end = 1; } else{ if (c == '\'') quote = 1; count++; state = N; instate = 1; ungetc(c, stdin); } } } //no argument after the option else if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //invalid argument else fprintf(stderr, "%s", ERR_INVALID_ARG); break; //state I checks whether the input value for ID is valid case I: instate = 0; count = 0; while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; if (isalpha(c) || isdigit(c) || c == '-' || c == '_' || c == '.'){ while (isalpha(c)||isdigit(c)||c=='-'||c=='_'||c=='.'){ c = getchar(); count++; } //the length of argument longer than the max length if (count > MAX_NUM_ID_CHARS) fprintf(stderr, "%s", ERR_INVALID_ARG); //valid argument as an input move to TF state else if (isspace(c)||c==EOF){ IF = 1; state = TF; instate = 1; if (c == EOF || c == '\n') end = 1; } else fprintf(stderr, "%s", ERR_INVALID_ARG); } //option finished without an argument else if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //other invalid argument else fprintf(stderr, "%s", ERR_INVALID_ARG); break; //state P checks whether the input value for Purchase is valid case P: instate = 0; count = 0; while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; if (isdigit(c) && c != '0'){ while (isdigit(c)){ c = getchar(); count++; } //argument long than the max length if (count > MAX_NUM_DIGITS) fprintf(stderr, "%s", ERR_INVALID_ARG); //valid argument input move to state TF else if (isspace(c)||c==EOF){ PF = 1; state = TF; instate = 1; if (c == EOF || c == '\n') end = 1; } //invalid input argument else fprintf(stderr, "%s", ERR_INVALID_ARG); } else if (c == '0'){ c = getchar(); //valid input argument 0 if (isspace(c)||c==EOF){ PF = 1; state = TF; instate = 1; if (c == EOF || c == '\n') end = 1; } //invalid argument as more argument after 0 else fprintf(stderr, "%s", ERR_INVALID_ARG); } //no argument input else if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //other invalid arguments else fprintf(stderr, "%s", ERR_INVALID_ARG); break; } } //no more input for the line if (c == EOF || c == '\n'){ if (c == EOF) exit(0); return FALSE; } //Eat the line and return while ((c = getchar()) != EOF && c != '\n') ; if (c == EOF) exit(0); return FALSE; } /*--------------------------------------------------------------------*/ /* Check whether an unreg(unregister) or a find(search) command valid.*/ /* Input: no argument */ /* Return value: TRUE(valid) or FALSE(invalid) */ /*--------------------------------------------------------------------*/ static int ValidateUnregisterOrFindCommand(void) { typedef enum { TF, NI, N, I }DFAState; DFAState state = TF; int c; int NF = 0; int IF = 0; int count = 0; int end = 0; int instate = 1; int quote = 0; while (instate){ switch (state){ //State TF checking whether the input is valid //moves to state NPI when more option is added //otherwise, determine whether there is an error or not case TF: instate = 0; if (end == 1){ //all option valid if ((NF == 1) ^ (IF == 1)){ if (c == EOF) exit(0); return TRUE; } //too much option else if (NF == 1 && IF == 1) fprintf(stderr, "%s", ERR_AMBIG_ARG); //lack of option else fprintf(stderr, "%s", ERR_NEED_OPT); if (c == EOF) exit(0); return FALSE; } while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; if (c == EOF || c == '\n'){ //all option valid if ((NF == 1) ^ (IF == 1)){ if (c == EOF) exit(0); return TRUE; } //too much option else if (NF == 1 && IF == 1) fprintf(stderr, "%s", ERR_AMBIG_ARG); //lack of option else if (NF == 0 && IF == 0) fprintf(stderr, "%s", ERR_NEED_OPT); if (c == EOF) exit(0); return FALSE; } //too much option else if (NF == 1 && IF == 1) fprintf(stderr, "%s", ERR_AMBIG_ARG); //input - move to state NI else if (c == '-'){ state = NI; instate = 1; } //undefined option input else fprintf(stderr, "%s", ERR_UNDEF_OPT); break; //state NI determines the option //it directs to the state N when option n and at least one space is input //it directs to the state I when option i and at least one space is input //if other values are input, it returns error case NI: instate = 0; c = getchar(); if (c == 'n'){ if (NF == 1){ while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; //option n not finished if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //option n already got else fprintf(stderr, "%s", ERR_SAME_OPT); } else if (IF ==1) { while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; //option n not finished if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //option i already got else fprintf(stderr, "%s", ERR_AMBIG_ARG); } // space exists after the option move to state N else if ((c = getchar()) != EOF && c != '\n' && isspace(c)){ state = N; instate = 1; } //undefined option n else fprintf(stderr, "%s", ERR_UNDEF_OPT); } else if (c == 'i'){ if (IF == 1){ while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; //option i not finished if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //option i already exists else fprintf(stderr, "%s", ERR_SAME_OPT); } else if (NF==1) { while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; //option i not finished if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //option n already exists else fprintf(stderr, "%s", ERR_AMBIG_ARG); } //space after option i move to state I else if ((c = getchar()) != EOF && c != '\n' && isspace(c)){ state = I; instate = 1; } //undefined option i else fprintf(stderr, "%s", ERR_UNDEF_OPT); } //other undefined option else fprintf(stderr, "%s", ERR_UNDEF_OPT); break; //state N checks whether the input value for name is valid case N: instate = 0; count = 0; while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; if (isalpha(c) || c == '-' || c == '_' || c == '.'){ count++; while(isalpha(c)||c=='-'||c=='_'||c=='.'||c=='\''||c=='\\'){ if (c == '\\'){ c = getchar(); //argument not allowed for name as an input if(!(isalpha(c)||c=='-'||c=='_'||c=='.'||c=='\''||c==' ')) fprintf(stderr, "%s", ERR_INVALID_ARG); } c = getchar(); count++; } //argument longer than the max length if (--count > MAX_NUM_NAME_CHARS) fprintf(stderr, "%s", ERR_INVALID_ARG); //valid argument as an input move to state TF else if (isspace(c) || c == EOF){ NF = 1; state = TF; instate = 1; if (c == EOF || c == '\n') end = 1; } else fprintf(stderr, "%s", ERR_INVALID_ARG); } else if (c == '\''){ c = getchar(); if (quote == 0 && (c == EOF || c == '\n')){ //quote not finished fprintf(stderr, "%s", ERR_INVALID_ARG); if (c == EOF) exit(0); return FALSE; } while(isalpha(c)||c=='-'||c =='_'||c=='.'||c==' '||c=='\''||c=='\\'){ if (c == '\''){ c = getchar(); count--; quote++; break; } else if (c == '\\'){ c = getchar(); //argument not allowed for the name as an input if(!(isalpha(c)||c=='-'||c=='_'||c=='.'||c=='\''||c==' ')) fprintf(stderr, "%s", ERR_INVALID_ARG); } c = getchar(); count++; } //length of argument longer than the max number allowed if (count > MAX_NUM_NAME_CHARS || count<0) fprintf(stderr, "%s", ERR_INVALID_ARG); //valid argument as an input more to state TF else if ((isspace(c) || c == EOF) && quote == 1){ NF = 1; state = TF; instate = 1; if (c == EOF || c == '\n') end = 1; } //argument not allowed as an input else fprintf(stderr, "%s", ERR_INVALID_ARG); } else if (c == '\\'){ c = getchar(); //argument not allowed for the name as an input if (!(isalpha(c)||c=='-'||c=='_'||c=='.'||c=='\''||c==' ')) fprintf(stderr, "%s", ERR_INVALID_ARG); else{ c = getchar(); //valid argument as an input move to state TF if (isspace(c) || c == EOF){ NF = 1; state = TF; instate = 1; if (c == EOF || c == '\n') end = 1; } else{ if (c == '\'') quote = 1; count++; state = N; instate = 1; ungetc(c, stdin); } } } //no argument after the option else if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //argument not allowed as an input else fprintf(stderr, "%s", ERR_INVALID_ARG); break; //state I checks whether the input value for ID is valid case I: instate = 0; count = 0; while((c=getchar()) != EOF && c != '\n' && isspace(c)) ; if (isalpha(c) || isdigit(c) || c == '-' || c == '_' || c == '.'){ while (isalpha(c) || isdigit(c) || c == '-' || c == '_' || c == '.'){ c = getchar(); count++; } //the length of argument longer than the max length if (count > MAX_NUM_ID_CHARS) fprintf(stderr, "%s", ERR_INVALID_ARG); //valid argument as an input move to TF state else if (isspace(c) || c == EOF){ IF = 1; state = TF; instate = 1; if (c == EOF || c == '\n') end = 1; } //argument not allowed as an input else fprintf(stderr, "%s", ERR_INVALID_ARG); } //option finished without an argument else if (c == EOF || c == '\n') fprintf(stderr, "%s", ERR_UNDEF_OPT); //argument not allowed as an input else fprintf(stderr, "%s", ERR_INVALID_ARG); break; } } //no more input for the line if (c == EOF || c == '\n'){ if (c == EOF) exit(0); return FALSE; } //Eat the line and return while ((c = getchar()) != EOF && c != '\n') ; if (c == EOF) exit(0); return FALSE; /* TODO: Implement this function. */ } /*--------------------------------------------------------------------*/ /* Read the first word, and figure out and return the command type. */ /* Input: no argument */ /* Return value: Command_T value */ /* - In case of an error, it eats the entire line and returns C_FAIL */ /* - In case there's no more input (EOF), it returns C_EOF */ /*--------------------------------------------------------------------*/ static Command_T GetCommandType(void) { Command_T type = C_FAIL; const char *cmds[] = { "exit", /* exit */ "reg", /* reg */ "unreg", /* unreg */ "find", /* find */ }; int i, len; int c; /* eat space */ while ((c = getchar()) != EOF && c != '\n' && isspace(c)) ; switch (c) { case '\n':return C_FAIL; /* no command */ case EOF: return C_EOF; /* no more input */ case 'e': type = C_EXIT; break; case 'r': type = C_REG; break; case 'u': type = C_UNREG; break; case 'f': type = C_FIND; break; default: fprintf(stderr, "%s", ERR_UNDEF_CMD); goto EatLineAndReturn; } /* see the rest of the command chars actually match */ len = strlen(cmds[type]); for (i = 1; i < len; i++) { c = getchar(); if (c == '\n' || c == EOF) { /* line finished too early */ fprintf(stderr, "%s", ERR_UNDEF_CMD); return (c == EOF) ? C_EOF : C_FAIL; } if (c != cmds[type][i]) { /* wrong command */ fprintf(stderr, "%s", ERR_UNDEF_CMD); goto EatLineAndReturn; } } /* check the following character of a command */ c = getchar(); if (c != '\n' && isspace(c)) { return type; } else if (c == '\n' || c == EOF) { /* only exit can be followed by '\n' */ if (type != C_EXIT) fprintf(stderr, "%s", ERR_NEED_OPT); if (c == EOF) return C_EOF; else ungetc(c, stdin); if (type == C_EXIT) return type; } else { fprintf(stderr, "%s", ERR_UNDEF_CMD); } EatLineAndReturn: while ((c = getchar()) != EOF && (c != '\n')) ; return (c == EOF) ? C_EOF : C_FAIL; } /*--------------------------------------------------------------------*/ int main(int argc, const char *argv[]) { Command_T command; int res; printf("======================================\n" \ " Customer Manager Program\n" \ "======================================\n\n"); /* start prompt */ while (TRUE) { printf("\n> "); /* check command type */ command = GetCommandType(); /* command validation */ switch (command) { case C_EOF: return 0; case C_FAIL: res = FALSE; break; case C_EXIT: res = ValidateExitCommand(); break; case C_REG: res = ValidateRegisterCommand(); break; case C_FIND: res = ValidateUnregisterOrFindCommand(); break; case C_UNREG: res = ValidateUnregisterOrFindCommand(); break; default: assert(0); /* can't reach here */ break; } if (res == FALSE) { /* validation fail */ continue; } /* command functionalities */ switch (command) { case C_EXIT: exit(0); return 0; default: /* This will be expanded in assignment 3. */ break; } } assert(0); /* can't reach here */ return 0; }
[ "bleuflares@gmail.com" ]
bleuflares@gmail.com
9081fd6759edb313818bcb99852de0c4ccbe5a66
405b4813995180c449503662e145e2b4494b3371
/hello.c
2e0d41fa5da392d9d0b147b06be39b37c64208d6
[]
no_license
matty9210455/prova
66393a1497ee73c1871ef780393025bb0d741184
fba971094e5e33ad6241d9eafe28f8deb4decf76
refs/heads/master
2021-01-10T07:29:03.691955
2015-12-29T12:30:13
2015-12-29T12:30:13
48,640,925
0
0
null
2015-12-27T11:49:15
2015-12-27T10:17:36
C
UTF-8
C
false
false
168
c
#include<stdio.h> int main(int argc, char* argv[]){ printf("hello\n"); printf("i got %d args!\n",argc); printf("trallalero\n"); print("change"\n); int bah; return 0; }
[ "mattia.soprano@gmail.com" ]
mattia.soprano@gmail.com
fddd5dee5b45405c63d5df1eff0f1ee7dabaaa56
3db023edb0af1dcf8a1da83434d219c3a96362ba
/windows_nt_3_5_source_code/NT-782/PRIVATE/MAILPLUS/BULLET2/SRC/STORE/ITP/_ITPRC.H
08b88370a11b13e038969de50409547c6f78b5e9
[]
no_license
xiaoqgao/windows_nt_3_5_source_code
de30e9b95856bc09469d4008d76191f94379c884
d2894c9125ff1c14028435ed1b21164f6b2b871a
refs/heads/master
2022-12-23T17:58:33.768209
2020-09-28T20:20:18
2020-09-28T20:20:18
null
0
0
null
null
null
null
UTF-8
C
false
false
1,589
h
// Menu items #define RESFAIL 90 #define RESINC 91 // file menu #define IDM_MIN 100 #define IDM_FILE 100 #define IDM_OPEN 101 #define IDM_CREATE 102 #define IDM_CLOSE 103 #define IDM_EXIT 104 // test menu #define IDM_TEST 104 #define IDM_TEST_MIN 105 #define IDM_TEST_FILL_HIER 105 #define IDM_TEST_FILL_FLDRS 106 #define IDM_TEST_AMC 107 #define IDM_TEST_MOVE_COPY 108 #define IDM_TEST_FOLDER_OPS 109 #define IDM_TEST_PHAS 110 #define IDM_TEST_ATTACHMENTS 111 #define IDM_TEST_SUBMISSION 112 #define IDM_TEST_REGISTER 113 #define IDM_TEST_MOVE 114 #define IDM_TEST_CLONE 115 #define IDM_TEST_MANY_FLDRS 116 #define IDM_TEST_DB_LOCKING 117 #define IDM_TEST_FILL_FOLDER 118 #define IDM_TEST_MAX 119 #ifdef DEBUG #define IDM_DEBUG 200 #define IDM_DEBUG_BREAK 201 #define IDM_TRACE_POINTS 202 #define IDM_ASSERTS 203 #define IDM_RES_FAIL 204 #define IDM_RES_INC 205 #endif // DEBUG #define TMCPVALLOCRESET 220 #define TMCPVALLOC 221 #define TMCHVALLOCRESET 222 #define TMCHVALLOC 223 #define TMCDISKRESET 224 #define TMCDISK 225 #define TMCPVALLOCSET 226 #define TMCPVFAILAT 227 #define TMCHVALLOCSET 228 #define TMCHVFAILAT 229 #define TMCDISKSET 230 #define TMCDISKFAILAT 231 #define TMCPVSTART 232 #define TMCPVEND 233 #define TMCHVSTART 234 #define TMCHVEND 235 #define TMCDISKSTART 236 #define TMCDISKEND 237 #define TMCOK 238 #define TMCCANCEL 239 #define TMCAUTOFIND 240 #define TMCRESET 241
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
86582f17cf56fd66e00bc15d1fb60327976b99fb
8f40b673e3551c206ebff07cbb312aa9a794091c
/package/libnetwork/src/libnetwork.c
e8a82af8f7230c42f02acb992264add7dff232ef
[]
no_license
jkretzmer/piksi_buildroot
38b88422aca7380c31c871ffa598dd0482e3d275
dafbd7ef349193317acbdb3f6086ac5d60f869e5
refs/heads/v1.1.0-release
2021-01-02T08:41:48.762523
2017-07-26T20:31:27
2017-07-26T20:31:27
99,045,374
0
0
null
2017-08-01T21:40:00
2017-08-01T21:40:00
null
UTF-8
C
false
false
8,080
c
/* * Copyright (C) 2017 Swift Navigation Inc. * Contact: Swift Navigation <dev@swiftnav.com> * * This source is subject to the license found in the file 'LICENSE' which must * be be distributed together with this source. All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. */ #include <unistd.h> #include <curl/curl.h> #include <libpiksi/logging.h> #include <libpiksi/util.h> #include "libnetwork.h" typedef struct { int fd; bool debug; } network_transfer_t; typedef struct { curl_off_t bytes; curl_off_t count; bool debug; } network_progress_t; static size_t network_download_write(char *buf, size_t size, size_t n, void *data) { const network_transfer_t *transfer = data; while (true) { ssize_t ret = write(transfer->fd, buf, size * n); if (ret < 0 && errno == EINTR) { continue; } if (transfer->debug) { piksi_log(LOG_DEBUG, "write bytes (%d) %d", size * n, ret); } return ret; } return -1; } static size_t network_upload_read(char *buf, size_t size, size_t n, void *data) { const network_transfer_t *transfer = data; while (true) { ssize_t ret = read(transfer->fd, buf, size * n); if (ret < 0 && errno == EINTR) { continue; } if (transfer->debug) { piksi_log(LOG_DEBUG, "read bytes %d", ret); } if (ret < 0) { return CURL_READFUNC_ABORT; } return ret; } return -1; } static int network_progress(network_progress_t *progress, curl_off_t bytes) { if (progress->bytes == bytes && progress->count++ > 30) { return -1; } progress->bytes = bytes; progress->count = 0; return 0; } static int network_download_progress(void *data, curl_off_t dltot, curl_off_t dlnow, curl_off_t ultot, curl_off_t ulnow) { (void)dltot; (void)ultot; (void)ulnow; network_progress_t *progress = data; if (progress->debug) { piksi_log(LOG_DEBUG, "down bytes (%lld) %lld count %lld", dlnow, progress->bytes, progress->count); } return network_progress(progress, dlnow); } static int network_upload_progress(void *data, curl_off_t dltot, curl_off_t dlnow, curl_off_t ultot, curl_off_t ulnow) { (void)dltot; (void)dlnow; (void)ultot; network_progress_t *progress = data; if (progress->debug) { piksi_log(LOG_DEBUG, "up bytes (%lld) %lld count %lld", ulnow, progress->bytes, progress->count); } return network_progress(progress, ulnow); } static int network_sockopt(void *data, curl_socket_t fd, curlsocktype purpose) { (void)data; if (purpose == CURLSOCKTYPE_IPCXN) { unsigned int timeout = 20000; int ret = setsockopt(fd, SOL_TCP, TCP_USER_TIMEOUT, &timeout, sizeof(timeout)); if (ret < 0) { piksi_log(LOG_ERR, "setsockopt error %d", errno); return CURL_SOCKOPT_ERROR; } } return CURL_SOCKOPT_OK; } static CURL *network_setup(void) { CURLcode code = curl_global_init(CURL_GLOBAL_ALL); if (code != CURLE_OK) { piksi_log(LOG_ERR, "global init %d", code); return NULL; } CURL *curl = curl_easy_init(); if (curl == NULL) { piksi_log(LOG_ERR, "init"); curl_global_cleanup(); return NULL; } return curl; } static void network_teardown(CURL *curl) { curl_easy_cleanup(curl); curl_global_cleanup(); } static void network_request(CURL *curl) { char error_buf[CURL_ERROR_SIZE]; curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buf); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, 15000L); curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 0L); curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1L); curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1L); curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L); curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, 5L); curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, 20L); curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, network_sockopt); while (true) { CURLcode code = curl_easy_perform(curl); if (code != CURLE_OK) { piksi_log(LOG_ERR, "curl request (%d) \"%s\"", code, error_buf); } else { long response; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response); piksi_log(LOG_INFO, "curl request code %d", response); } usleep(1000000); } } static struct curl_slist *ntrip_init(CURL *curl) { struct curl_slist *chunk = NULL; chunk = curl_slist_append(chunk, "Transfer-Encoding: chunked"); chunk = curl_slist_append(chunk, "Ntrip-Version: Ntrip/2.0"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); curl_easy_setopt(curl, CURLOPT_USERAGENT, "NTRIP ntrip-client/1.0"); return chunk; } static struct curl_slist *skylark_init(CURL *curl) { char uuid_buf[256]; device_uuid_get(uuid_buf, sizeof(uuid_buf)); char device_buf[256]; snprintf(device_buf, sizeof(device_buf), "Device-Uid: %s", uuid_buf); struct curl_slist *chunk = NULL; chunk = curl_slist_append(chunk, device_buf); chunk = curl_slist_append(chunk, "Transfer-Encoding: chunked"); chunk = curl_slist_append(chunk, "Accept: application/vnd.swiftnav.broker.v1+sbp2"); chunk = curl_slist_append(chunk, "Content-Type: application/vnd.swiftnav.broker.v1+sbp2"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); curl_easy_setopt(curl, CURLOPT_USERAGENT, "skylark-agent/1.0"); return chunk; } void ntrip_download(const network_config_t *config) { network_transfer_t transfer = { .fd = config->fd, .debug = config->debug, }; network_progress_t progress = { .bytes = 0, .count = 0, .debug = config->debug, }; CURL *curl = network_setup(); if (curl == NULL) { return; } struct curl_slist *chunk = ntrip_init(curl); curl_easy_setopt(curl, CURLOPT_URL, config->url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, network_download_write); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &transfer); curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, network_download_progress); curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &progress); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); network_request(curl); curl_slist_free_all(chunk); network_teardown(curl); } void skylark_download(const network_config_t *config) { network_transfer_t transfer = { .fd = config->fd, .debug = config->debug, }; network_progress_t progress = { .bytes = 0, .count = 0, .debug = config->debug, }; CURL *curl = network_setup(); if (curl == NULL) { return; } struct curl_slist *chunk = skylark_init(curl); curl_easy_setopt(curl, CURLOPT_URL, config->url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, network_download_write); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &transfer); curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, network_download_progress); curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &progress); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); network_request(curl); curl_slist_free_all(chunk); network_teardown(curl); } void skylark_upload(const network_config_t *config) { network_transfer_t transfer = { .fd = config->fd, .debug = config->debug, }; network_progress_t progress = { .bytes = 0, .count = 0, .debug = config->debug, }; CURL *curl = network_setup(); if (curl == NULL) { return; } struct curl_slist *chunk = skylark_init(curl); curl_easy_setopt(curl, CURLOPT_PUT, 1L); curl_easy_setopt(curl, CURLOPT_URL, config->url); curl_easy_setopt(curl, CURLOPT_READFUNCTION, network_upload_read); curl_easy_setopt(curl, CURLOPT_READDATA, &transfer); curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, network_upload_progress); curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &progress); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); network_request(curl); curl_slist_free_all(chunk); network_teardown(curl); }
[ "mark.fine@gmail.com" ]
mark.fine@gmail.com
034139429fd21f6a77452eadafbb69aa1096aad5
06cc925a6a1aa30ab239b398705d23895aac9bd4
/NVIC_driver/NVIC_interface.h
21d7cb0a9f7a5203700d5f7d9a0024f6bf89aaa6
[]
no_license
shaimaa-77/STM32_drivers
9d34096fa91729d991e74074c733e3883be9a793
55eb7840de6a9b5c3aa69f26b73d91f3d76a63d2
refs/heads/main
2023-08-30T21:40:18.895025
2021-10-02T15:51:45
2021-10-02T15:51:45
310,468,421
0
0
null
null
null
null
UTF-8
C
false
false
767
h
/****************************************************************************************/ /* Author : Shaimaa Mahmoud */ /* Date : 24/8/2020 */ /* version : v01 */ /****************************************************************************************/ #ifndef NVIC_INTERFACE_H #define NVIC_INTERFACE_H void MNVIC_voidEnableInterrupt (u8 ); void MNVIC_voidDisableInterrupt (u8 ); void MNVIC_voidEnableInterruptPending (u8 ); void MNVIC_voidDisableInterruptPending (u8 ); u8 MNVIC_u8GetActiveFlag (u8 ); void MNVIC_voidInit (void); void NVIC_voidSetPriority (u8 copy_u8preipheralIdx , u8 copy_u8Piriorty); #endif
[ "noreply@github.com" ]
shaimaa-77.noreply@github.com
4b31c1391a7c29ce9ac766844022b08547b42cc3
a25a741f590e86fef685c20d05f0c60d0bd7a6fc
/201902/myAtoi/myAtoi.c
2f8af3059e5d5b965f0ded049c17746b76e40371
[ "MIT" ]
permissive
anotherNight/MathWS
85dae4a134083b8eacd5046c377aa2fa24edde03
9f82f9e3bd7bf8e3bec9ac56dff8aa521516a102
refs/heads/master
2021-07-04T02:16:15.361684
2020-09-08T10:51:02
2020-09-08T10:51:02
164,804,011
0
0
null
null
null
null
UTF-8
C
false
false
701
c
#include <stdio.h> #include <limits.h> int myAtoi(char* str) { if (*str == '\0') { return 0; } long long llnum = 0; int sign = 1; while (*str != '\0' && (*str == ' ') ) { printf("%c\n", *str); str++; } if (*str == '-') { sign = -1; str++; }else if(*str == '+'){ str++; } while (*str >= '0' && *str <= '9') { int i = *str - '0'; llnum = llnum*10+i; if (llnum*sign > INT_MAX) { llnum = INT_MAX; break; }else if(llnum*sign < INT_MIN){ llnum = INT_MIN; break; } str++; } return (int)(sign*llnum); } int main(){ char* a = "asb 987"; int result = myAtoi(a); printf("%d\n", result); return 0; }
[ "whanis123@21cn.com" ]
whanis123@21cn.com
f5ce73e0d7b2110833577caf70f8e7b832d7e9a2
9a20af7099d21201148a317c8078dd7fd09ef00a
/TestClipingNode/proj.win32/resource.h
b62a0d0de989d1abd058c05a90739c75a26b8aaf
[ "MIT" ]
permissive
Zhangzhiyi/cocos2d-x
49949485abfbd77d2ce4ad3f8956b36fe42d9b73
69623e970b6a0e71346d7a77def19a9d46d6e933
refs/heads/master
2021-01-21T00:05:53.929994
2013-08-06T04:23:22
2013-08-06T04:23:22
null
0
0
null
null
null
null
UTF-8
C
false
false
510
h
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by TestClipingNode.RC // #define IDS_PROJNAME 100 #define IDR_TESTCLIPINGNODE 100 #define ID_FILE_NEW_WINDOW 32771 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 201 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 32775 #endif #endif
[ "qq361119908@gmail.com" ]
qq361119908@gmail.com
9548827d40b919b01a060dc6dda5d9f003a61e66
dc315276a8e23f6a1bf009391b95aeafaead9ade
/mymalloc.c
597648bee4b2e76aa1fc514045e7a022f37485cc
[]
no_license
andrewpagano/MyMalloc
e61ccb6cd1dd4a3a79b61f16966d023a704d7f82
322ad8eb124957825a4da09730db94137fcb08ec
refs/heads/master
2021-01-20T02:41:58.714631
2017-04-26T05:14:47
2017-04-26T05:14:47
89,440,683
0
0
null
null
null
null
UTF-8
C
false
false
3,097
c
#include <stdio.h> #include <stdlib.h> #include <stddef.h> #include "mymalloc.h" /** *CS 214 Systems Programming *Assignment 1: Memory Allocation++ *due 2/26/2017 * *@author Thurgood Kilper *@author Andrew Pagano */ block *head = (void*)myBlock; /** *MALLOC implementation *@param s: size of the memory to be allocated */ void *mallocPlus(size_t s) { block *curr, *prev; /**initialize the head memory block*/ if(!(head->size)){ head->size=5000-sizeof(block); head->isFree=1; head->next=NULL; } curr=head; /**iterate through blocks that are too small*/ while((((curr->size)<s)||((curr->isFree)==0))&&(curr->next!=NULL)){ prev=curr; curr=curr->next; } /**found a memory block of the requested size -> no split needed*/ if((curr->size) == s){ curr->isFree=0; printf("Memory allocated (%s, line: %d)\n", __FILE__, __LINE__); return (void*)(++curr); } /**found a memory block larger than requested -> split the block*/ if((curr->size) > (s+sizeof(block))){ splitBlock(curr, s); printf("Memory allocated by split (%s, line: %d)\n", __FILE__, __LINE__); return (void*)(++curr); } /**requested memory is not available*/ printf("requested memory not available (%s, line: %d)\n", __FILE__, __LINE__); return NULL; } /** *Turn leftover block space into a new free block *@param bigBlock: The block to be split *@param s: amount of memory requested */ void splitBlock(block *bigBlock, size_t s) { /**create a new block that holds the leftover free memory*/ block * newBlock=(void*)((void*)bigBlock + s + sizeof(block)); newBlock->size=(bigBlock->size) - s - sizeof(block); newBlock->isFree=1; newBlock->next=bigBlock->next; bigBlock->size=s; bigBlock->next=newBlock; bigBlock->isFree=0; } /** *FREE implentation *sets pointer block to free and then calls for merging of free memory *@param ptr: the pointer to be freed */ void *freePlus(void* ptr) { /**check that pointer is within memory bounds*/ if((ptr>=(void*)myBlock)&&(ptr<=(void*)(myBlock+5000))){ block * curr=ptr; --curr; if(curr->isFree == 1){ printf("invalid mallocPlus pointer (%s, line: %d)\n", __FILE__, __LINE__); return NULL; } curr->isFree=1; combineFreeBlocks(); printf("memory freed successfully (%s, line: %d)\n", __FILE__, __LINE__); return NULL; } else printf("invalid mallocPlus pointer (%s, line: %d)\n", __FILE__, __LINE__); return NULL; } /** *iterate through block list and combine neighboring free blocks */ void combineFreeBlocks() { block *curr, *next; curr=head; next=head->next; while(curr != NULL && next != NULL){ if((curr->isFree==1) && (next->isFree==1)){ curr->size+=(next->size)+sizeof(block); curr->next=next->next; } curr=next; next=curr->next; } }
[ "andrewpagano95@gmail.com" ]
andrewpagano95@gmail.com
be738ba5f57db7ddba14798f57e0996424b968c4
bef88bc876f810b62ca729af95541d8dfdec2121
/source/main.c
b0d17fb961f338a113b08c7cb996e1d874bc7201
[]
no_license
dyg540/rt1050_emWin_demo
207d1dfe35b2362daccb2f4e9fea445e0ad57d4b
25c4b8e76b532f7b401ca01a1dc58efe71e71c94
refs/heads/master
2022-01-08T12:48:58.828109
2018-12-27T07:11:59
2018-12-27T07:11:59
null
0
0
null
null
null
null
UTF-8
C
false
false
2,283
c
/* * The Clear BSD License * Copyright (c) 2016, Freescale Semiconductor, Inc. * Copyright 2016-2017 NXP * All rights reserved. * * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided * that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /******************************************************************************* * Includes ******************************************************************************/ #include "bsp_init.h" #include "GUI.h" #include "AppTask.h" #include "stdio.h" /*! * @简介 主函数 */ int main(void) { bsp_init(); /* 硬件初始化 */ MainTask(); /* 绘制界面 */ printf("======== Tristana demo start! \r\n"); AppTask_Start(); /* 启动 FreeRTOS 的各个任务 */ while(1); }
[ "castellan@yeah.net" ]
castellan@yeah.net
06f4002a533866a2dd54e6016a0cdffb03265893
7f26cda249da3814a7b23fca951d048d7c502b25
/asfjsk.c
ac3aa2ab78307454df147704b244e9a147e14b35
[]
no_license
Tomistong/UvaProblemSolution
30b751e8b3ad658fe37f02e345dc9f9165f67ed2
caba3cb55d487b2bbbefdbd8a1d9441e6ab0c395
refs/heads/master
2023-03-25T08:59:35.101813
2018-08-15T11:11:26
2018-08-15T11:11:26
null
0
0
null
null
null
null
UTF-8
C
false
false
214
c
#include <stdio.h> #include <string.h> int main() { char num[100]; int dec = 0, i, j, len; printf("Enter a number: "); gets(num); len = strlen(num); for(i=1; i<=5; i++){ printf("%c",a[i]); } return 0; }
[ "formankhan2014@gmail.com" ]
formankhan2014@gmail.com
c96d580e14a682a5b4fbe98152cba5f3597e5fe7
1441c230b6f22e5979c2d279c27105f928cc8e40
/experimental_results/init-partial-3-u/init-partial-3-u.c
9b7395add5c776c9f27182c0bfa02fff59d81b11
[]
no_license
VerifierIntegerAssignment/VIAP-ARRAY
f567b02b30d86044a2f311cb6e7008816d8aa27a
c19eec24e1256974ee97d8b5a46586cdb6893130
refs/heads/master
2020-12-30T15:54:20.887769
2017-05-26T03:19:28
2017-05-26T03:19:28
91,181,002
0
0
null
null
null
null
UTF-8
C
false
false
683
c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } int __VERIFIER_nondet_int(); int main() { int i,j,k; int n; int p; int A [n][n][n]; int C; i=0; j=0; k=0; __VERIFIER_assume(p<n); while(i < p){ j=0; k=0; while(j < p){ k=0; while(k < p){ A[i][j][k]=C; k=k+1; } j=j+1; } i=i+1; } i=0; j=0; k=0; while(i < n){ j=0; k=0; while(j < n){ k=0; while(k < n){ __VERIFIER_assert(A[i][j][k]==C); k=k+1; } j=j+1; } i=i+1; } }
[ "pritom.rajkhowa@gmail.com" ]
pritom.rajkhowa@gmail.com
df030c96df6ce7558c65dabf636f1e8908b25810
c38d45d315ccb20c3656029c41081ef6a40f1f35
/cookie/cookie.c
6769938bad0e4178ffb14e878fcc7782226fe1aa
[]
no_license
petronny/aur3-mirror
3e12eed4901a807354a46399bdfd82763ec9f1b3
4279d4dcfcd6585fabd8b52d40d78d7db06c97ad
refs/heads/master
2020-06-30T06:47:24.836321
2019-07-29T09:45:08
2019-07-29T09:45:08
74,439,663
1
0
null
2016-11-22T06:00:49
2016-11-22T06:00:49
null
UTF-8
C
false
false
3,231
c
#include <stdio.h> #include <stdlib.h> #include <aitools.h> #define MEM_SIZE 4096 char *CCC_REM_NEW[] = {"reminder", "new", NULL}; char *CCC_REM_SHOW[] = {"reminders", "show", NULL}; char *CCC_NOTE_QUERY[] = {"edit", "note", NULL}; char *CCC_NOTE_VIEW[] = {"view", "note", NULL}; char *CCC_HELP[] = {"show", "help", NULL}; int main(int argc, char *argv[]) { opt_color = 1; char *buf = (char *)malloc(128*sizeof(char)); char *sbuf; char *ibuf; /* run standard init procedure */ at_std_init(1); ga_init(); pa_init(); dates_clean(); while(1) { col_red(); printf(">>> "); col_default(); fgets(buf, 128, stdin); *(strchr(buf, '\n')) = 0; if (strcmp(buf, "/exit") == 0) { clan_write(ga_clan, NCLAN, ga_clan_fh); cmem_write(ga_cmem, NCMEM, ga_cmem_fh); fhandle_close(ga_clan_fh); fhandle_close(ga_cmem_fh); return 0; } sbuf = ga_process(buf); if (strcontains(buf, CCC_REM_NEW)) { printf("Example: every thursday i go to the Cafe\n"); col_red(); printf("new reminder> "); col_default(); char *rem = (char *)malloc(128*sizeof(char)); fgets(rem, 128, stdin); date_new(rem); } else if (strcontains(buf, CCC_REM_SHOW)) { for (int i = 0; i < NDATES; i++) if (dates[i]) { if (date_check(dates[i]) == 0) col_green(); if (dates[i]->rep) printf("Every "); else printf("On "); switch(dates[i]->day) { case 0: printf("Monday"); break; case 1: printf("Tuesday"); break; case 2: printf("Wednesday"); break; case 3: printf("Thursday"); break; case 4: printf("Friday"); break; case 5: printf("Saturday"); break; case 6: printf("Sunday"); break; default: err_out("main", "unknown day", 0, 0); } if (strchr(dates[i]->name, '\n')) printf(" %s", dates[i]->name); else printf(" %s\n", dates[i]->name); col_default(); } } else if (strcontains(buf, CCC_NOTE_QUERY)) { printf("What is the name of the note you want to edit?\n"); col_red(); printf("note title> "); col_default(); char *n = (char *)malloc(128*sizeof(char)); fgets(n, 128, stdin); *(strchr(n, '\n')) = 0; pa_note_query(n); } else if (strcontains(buf, CCC_NOTE_VIEW)) { printf("What is the name of the note you want to view?\n"); col_red(); printf("note title> "); col_default(); char *n = (char *)malloc(128*sizeof(char)); fgets(n, 128, stdin); *(strchr(n, '\n')) = 0; col_blue(); printf("[PROCESSED]\n"); col_default(); pa_note_process(n); col_blue(); printf("[ORIGINAL]\n"); col_default(); pa_note_view(n); } else if (strcontains(buf, CCC_HELP)) { info_troubleshoot(1, 1, 1, 1, 1); } else { sbuf = ga_strip(buf); ibuf = cmem_query(ga_cmem, NCMEM, sbuf); if (!ibuf) { printf("I don't know what to reply to that.\nWhat would you say?\n"); col_red(); printf("responce> "); col_default(); char *r = (char *)malloc(1024*sizeof(char)); fgets(r, 1024, stdin); *(strchr(r, '\n')) = 0; cmem_add(ga_cmem, NCMEM, sbuf, r); } else printf("%% %s\n", ibuf); } } }
[ "gostrc@gmail.com" ]
gostrc@gmail.com
c2a5a58610a12994e82bfb4f5d17a6bf24b92d02
9ba41ac91aefc73bcc50a272da877bb98c7e8041
/pulp-os/include/rt/rt_periph.h
e653a08eb3a62c3198bc473d8d11726be52ce666
[ "Apache-2.0" ]
permissive
ccravens/gap_sdk
595af512dc1c4525f19f246130bf84a2bb497e91
d5d010a4e0be6f0539d87c4daf50af3d69d63e94
refs/heads/master
2020-03-27T19:58:03.858215
2018-08-31T08:53:09
2018-08-31T08:53:09
147,025,985
0
0
null
2018-09-01T19:17:40
2018-09-01T19:17:39
null
UTF-8
C
false
false
5,091
h
/* * Copyright (C) 2018 ETH Zurich and University of Bologna * * 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. */ /* * Copyright (C) 2018 GreenWaves Technologies * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __RT_RT_PERIPH_H__ #define __RT_RT_PERIPH_H__ /// @cond IMPLEM extern volatile unsigned int __rt_socevents_status[2]; #define RT_PERIPH_COPY_L2 0 static inline void rt_periph_copy_init(rt_periph_copy_t *copy, int flags); void rt_periph_copy(rt_periph_copy_t *copy, int channel, unsigned int addr, int size, unsigned int cfg, rt_event_t *event); void rt_periph_single_copy(rt_periph_copy_t *copy, int channel, unsigned int addr, int size, unsigned int cfg, rt_event_t *event); void rt_periph_dual_copy_safe(rt_periph_copy_t *copy, int rx_channel_id, unsigned int tx_addr, int tx_size, unsigned int rx_addr, int rx_size, unsigned int cfg); static inline void rt_periph_dual_copy(rt_periph_copy_t *copy, int rx_channel_id, unsigned int tx_addr, int tx_size, unsigned int rx_addr, int rx_size, unsigned int cfg, rt_event_t *event) { copy->event = event; int irq = rt_irq_disable(); rt_periph_dual_copy_safe(copy, rx_channel_id, tx_addr, tx_size, rx_addr, rx_size, cfg); rt_irq_restore(irq); } void __rt_periph_dual_copy_noshadow_safe(rt_periph_copy_t *copy, int rx_channel_id, unsigned int tx_addr, int tx_size, unsigned int rx_addr, int rx_size, unsigned int cfg); static inline void rt_periph_dual_copy_noshadow_safe(rt_periph_copy_t *copy, int rx_channel_id, unsigned int tx_addr, int tx_size, unsigned int rx_addr, int rx_size, unsigned int cfg, rt_event_t *event) { copy->event = event; __rt_periph_dual_copy_noshadow_safe(copy, rx_channel_id, tx_addr, tx_size, rx_addr, rx_size, cfg); } static inline void rt_periph_dual_copy_noshadow(rt_periph_copy_t *copy, int rx_channel_id, unsigned int tx_addr, int tx_size, unsigned int rx_addr, int rx_size, unsigned int cfg, rt_event_t *event) { int irq = rt_irq_disable(); rt_periph_dual_copy_noshadow_safe(copy, rx_channel_id, tx_addr, tx_size, rx_addr, rx_size, cfg, event); rt_irq_restore(irq); } static inline __attribute__((always_inline)) void __rt_channel_push(rt_periph_channel_t *channel, rt_periph_copy_t *copy) { copy->next = NULL; if (likely(channel->first == NULL)) { channel->first = copy; } else { channel->last->next = copy; } channel->last = copy; } static inline __attribute__((always_inline)) void __rt_channel_enqueue(rt_periph_channel_t *channel, rt_periph_copy_t *copy, int addr, int size, int cfg) { copy->addr = addr; copy->size = size; copy->cfg = cfg; if (channel->firstToEnqueue == NULL) channel->firstToEnqueue = copy; } static inline void rt_periph_copy_init(rt_periph_copy_t *copy, int flags) { copy->ctrl = 0; copy->repeat = 0; #if defined(UDMA_VERSION) && UDMA_VERSION == 1 copy->end_callback = 0; #endif } static inline void rt_periph_copy_init_callback(rt_periph_copy_t *copy, unsigned int callback) { copy->ctrl = 0; copy->repeat = 0; copy->enqueue_callback = callback; } static inline void rt_periph_copy_init_ctrl(rt_periph_copy_t *copy, int ctrl) { copy->ctrl = ctrl; copy->repeat = 0; } extern rt_periph_channel_t periph_channels[]; static inline rt_periph_channel_t *__rt_periph_channel(int channel) { return &periph_channels[channel]; } int __rt_periph_get_event(int event); void __rt_periph_wait_event(int event, int clear); void __rt_periph_clear_event(int event); static inline void __rt_periph_clear_event_safe(int event) { int index = 0; if (event >= 32) { index = 1; event -= 32; } __rt_socevents_status[index] &= ~(1<<event); } #if defined(UDMA_VERSION) && UDMA_VERSION == 1 void rt_periph_copy_i2c(rt_periph_copy_t *copy, int channel_id, unsigned int addr, int size, unsigned int cfg, int div, rt_event_t *event); void rt_periph_copy_spi(rt_periph_copy_t *copy, int channel_id, unsigned int addr, int size, int len, unsigned int cfg, unsigned int spi_status, rt_event_t *event); #endif /// @endcond #endif
[ "yao.zhang@greenwaves-technologies.com" ]
yao.zhang@greenwaves-technologies.com
3223b3f83abfddb986f7c726008312d9b84ed08c
46adba1fe06298743f018abd0096c753256ac03a
/src/raytracer/json-c/json_more_utils.c
c91087250ae7b4b401b5c650e4f8ea36496d407a
[]
no_license
ajaycharan/vehicles
9e0f21a2550c56e83303329c1bdf8c40bde5c0eb
2cfe467422160f90bc76800216ac42c0f13f2c4d
refs/heads/master
2021-05-28T21:03:35.466743
2013-07-19T06:59:51
2013-07-19T06:59:51
null
0
0
null
null
null
null
UTF-8
C
false
false
7,563
c
#include <string.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <math.h> #include "debug.h" #include "bits.h" #include "json_object.h" #include "json_more_utils.h" #include "json_tokener.h" #include "JSON_checker.h" #include "linkhash.h" double convert_to_double(JO jo); #ifndef NAN #define NAN strtod("NaN",0) #endif int json_stream_skip(FILE*f) { int count = 0; JSON_checker_init(); while(1) { char c; if(1 != fread(&c,1,1,f)) { if(feof(f)) { if(count==0) return 0; mc_error("EOF after %d bytes were read.\n", count); return 0; } mc_error("Reading error: %s\n", strerror(errno)); return 0; } else { if(!JSON_checker_push(c)) { mc_error("Malformed JSON object. (read %d bytes).\n", count); return 0; } if(JSON_checker_finished()) return 1; } count++; } } JO json_read_stream(FILE*f) { size_t buf_size = 100000; char * buf = (char*) malloc(buf_size); int count = 0; JSON_checker_init(); while(1) { if( ((size_t)count) > buf_size - 2) { buf_size *= 2; char * new_buf = realloc(buf, buf_size); if(!new_buf) { mc_error("Having read %d bytes, cannot allocate a block of size %d.", count, buf_size); free(buf); return 0; } buf = new_buf; } char c; if(1 != fread(&c,1,1,f)) { if(feof(f)) { if(count==0) { free(buf); return 0; } mc_error("EOF while %d were read: \n\t'%.*s'. \n", count, count, buf); free(buf); return 0; } mc_error("Reading error: %s\n", strerror(errno)); return 0; } else { if(count==0 && isspace(c)) continue; buf[count] = c; count++; if(!JSON_checker_push(c)) { mc_error("Malformed JSON object: \n'%.*s'\n", count, buf); free(buf); return 0; } if(JSON_checker_finished()) { /* sm_de("Found object.\n"); */ JO jo = json_tokener_parse_len(buf, count); free(buf); return jo; } } } } struct json_object* json_tokener_parse_len(const char *str, int len) { struct json_tokener* tok; struct json_object* obj; tok = json_tokener_new(); obj = json_tokener_parse_ex(tok, str, len); if(tok->err != json_tokener_success) { /*obj = error_ptr(-tok->err);*/ json_tokener_free(tok); mc_error("Malformed JSON object: \n'%.*s'\n", len, str); return 0; } json_tokener_free(tok); return obj; } int jo_has_field(JO s, const char*name) { return json_object_object_get(s, name) != 0; } int jo_read_double_array(JO s, const char*name, double*p, int n, double when_null) { JO jo = json_object_object_get(s, name); if(!jo) { /* mc_error("Field '%s' not found.\n", name); */ return 0; } return jo_read_from_double_array (jo, p, n, when_null); } /* Returns 0 if jo is not a double array, or its length is not n */ int jo_read_from_double_array (JO jo, double *p, int n, double when_null) { if(!json_object_is_type(jo, (enum json_type) json_type_array)) { mc_error("This is not an array: '%s'\n",json_object_to_json_string(jo)); return 0; } { int size = json_object_array_length(jo); if(size < n) { mc_error("I expected at least %d elements, got %d. \nArray: '%s'\n", n, size, json_object_to_json_string(jo)); return 0; } } { int i; for(i=0;i<n;i++) { JO v = json_object_array_get_idx(jo, i); if(!v) p[i] = when_null; else if(json_object_is_type(v, (enum json_type) json_type_double)) { p[i] = json_object_get_double(v); } else if(json_object_is_type(v, (enum json_type) json_type_int)) { p[i] = json_object_get_int(v); } else p[i] = when_null; } } return 1; } int jo_read_int_array(JO s, const char*name, int*p, int n, int when_null) { int size, i; JO jo = json_object_object_get(s, name); if(!jo) { /* mc_error("Field '%s' not found.\n", name); */ return 0; } if(!json_object_is_type(jo, (enum json_type) json_type_array)) { mc_error("This is not an array: '%s'\n",json_object_to_json_string(jo)); return 0; } size = json_object_array_length(jo); if(size < n) { mc_error("I expected at least %d elements, got %d. \nArray: '%s'\n", n, size, json_object_to_json_string(jo)); return 0; } for(i=0;i<n;i++) { JO v = json_object_array_get_idx(jo, i); if(!v || !json_object_is_type(v, (enum json_type) json_type_int)) p[i] = when_null; else p[i] = json_object_get_int(v); } return 1; /** XXX should we thro error? */ } JO jo_double_or_null(double v) { return (v == v) ? /* NAN is null */ json_object_new_double(v) : jo_new_null() ; } JO jo_new_double_array(const double *v, int n) { JO array = json_object_new_array(); int i; for(i=0;i<n;i++) { json_object_array_add(array, jo_double_or_null(v[i])); } return array; } JO jo_new_int_array(const int *v, int n) { JO array = json_object_new_array(); int i; for(i=0;i<n;i++) { json_object_array_add(array, json_object_new_int(v[i])); } return array; } /** XXX forse ho fatto casino */ int json_to_int(JO jo, int*ptr) { if(!jo) { /* mc_error("Field '%s' not found.\n", name); */ return 0; } if(!json_object_is_type(jo, (enum json_type) json_type_int)) { mc_error("I was looking for a int, instead got '%s'.\n", json_object_to_json_string(jo)); return 0; } *ptr = json_object_get_int(jo); return 1; } int json_to_double(JO jo, double*ptr) { if(json_object_is_type(jo, (enum json_type) json_type_double)) { *ptr = json_object_get_double(jo); return 1; } else if(json_object_is_type(jo, (enum json_type) json_type_int)) { *ptr = json_object_get_int(jo); return 1; } else{ *ptr = NAN; return 0; } } int jo_read_int(JO jo, const char*name, int*p) { JO v = json_object_object_get(jo, name); if(!v) { return 0; } return json_to_int(v, p); } double convert_to_double(JO jo) { if(json_object_is_type(jo, (enum json_type) json_type_double)) return json_object_get_double(jo); else if(json_object_is_type(jo, (enum json_type) json_type_int)) { return json_object_get_int(jo); } else return NAN; } int jo_read_double(JO jo, const char*name, double*p) { JO v = json_object_object_get(jo, name); if(!v) { /* mc_error("Field '%s' not found.\n", name); */ return 0; } *p = convert_to_double(v); return 1; } int jo_read_string(JO jo, const char*name, char*dest_string, size_t max_len) { JO v = json_object_object_get(jo, name); if(!v) return 0; if(json_object_is_type(v, (enum json_type) json_type_string)) { strncpy(dest_string, json_object_get_string(v), max_len); return 1; } else { strncpy(dest_string, "<string not found>", max_len); return 0; } } void jo_add_string(JO root, const char*name, const char*v) { jo_add(root, name, jo_new_string(v)); } void jo_add_double_array(JO root, const char*name, const double*v, int n) { jo_add(root, name, jo_new_double_array(v, n)); } void jo_add_int_array(JO root, const char*name, const int*v, int n) { jo_add(root, name, jo_new_int_array(v, n)); } void jo_add_int(JO root, const char*name, int v) { jo_add(root, name, jo_new_int(v)); } void jo_add_double(JO root, const char*name, double v) { jo_add(root, name, jo_double_or_null(v)); } JO json_parse(const char*str) { return json_tokener_parse_len(str, (int)strlen(str)); } const char* json_write(JO jo) { return json_object_to_json_string(jo); } /* JO find_object_with_name(JO root, const char*name) { json_object_object_foreach(root, key, val) { if(!strcmp(key, name)) return root; if(json_object_is_type(val, json_type_object)) { JO jo = find_object_with_name(val, name); if(jo) return jo; } } return 0; }*/
[ "andrea@cds.caltech.edu" ]
andrea@cds.caltech.edu
1cc6dad4917975c04ca1dd5e36eaef4f0b04e18e
a1446c3f95df2dfe097a9bd6b463767b00f18140
/usr.bin/aucat/listen.h
8b156d619250c4484bf1c6180cd4b60cbc903e6e
[]
no_license
chrissicool/l4openbsd
e2fb756debc1c3bdc1c2da509fa228c25a3185e8
077177814444e08500e47bc2488502f11469bc60
refs/heads/master
2021-04-09T17:12:53.122136
2011-08-22T16:52:58
2011-08-22T16:52:58
1,706,491
18
4
null
2017-04-06T19:17:29
2011-05-05T14:08:03
C
UTF-8
C
false
false
1,312
h
/* $OpenBSD: listen.h,v 1.5 2009/07/25 10:52:19 ratchov Exp $ */ /* * Copyright (c) 2008 Alexandre Ratchov <alex@caoua.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef LISTEN_H #define LISTEN_H #include <sys/types.h> #include "aparams.h" #include "file.h" struct listen { struct file file; char *path; int fd; }; struct listen *listen_new(struct fileops *, char *); int listen_nfds(struct file *); int listen_pollfd(struct file *, struct pollfd *, int); int listen_revents(struct file *, struct pollfd *); void listen_close(struct file *); extern struct fileops listen_ops; #endif /* !defined(LISTEN_H) */
[ "cludwig@net.t-labs.tu-berlin.de" ]
cludwig@net.t-labs.tu-berlin.de
304583000c5c2c426ccb975ba2ef299359d39925
ba34893ac115da1b22f2b6d0c3cca65e9200e053
/miner_gate/real_time_queue.h
8544df3e62afd3dc3ccdac75b8f410fe5bbd78eb
[]
no_license
jameshilliard/miner_gate
cdbf31d63c1bde9c4c14f0155ffef2e62b590281
fecaf2f109c1541751fb2842cd7d126b19211f82
refs/heads/master
2021-01-20T15:59:19.607212
2014-08-04T10:42:18
2014-08-04T10:42:18
null
0
0
null
null
null
null
UTF-8
C
false
false
651
h
/* * Copyright 2014 Zvi (Zvisha) Shteingart - Spondoolies-tech.com * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. See COPYING for more details. * * Note that changing this SW will void your miners guaranty */ #ifndef _REAAL_TIME_QUEUE_H_ #define _REAAL_TIME_QUEUE_H_ #include <stdio.h> #include <stdlib.h> #include "hammer.h" int one_done_sw_rt_queue(RT_JOB *work); void push_work_rsp(RT_JOB *work); void reset_sw_rt_queue(); #endif
[ "zvisha@gmail.com" ]
zvisha@gmail.com
aec8cbfed5d17649d6fdc520b50ee3c83e1a8af8
23a24a14e73d623e149f59ebe861f97b0e831473
/CameraHal00_Develop/SiliconImage/isi/drv/NT99252/include_priv/NT99252_priv.h
0d58f1c085f5cd8b9120155d3f4ff22abd3154bb
[]
no_license
dfyuan/work_test_lib
1d70a68403247a4177e1c0e0e6a40766f39f4401
27efa97907e7ebcf578683604a1c16105eb12f4b
refs/heads/master
2021-07-04T11:40:53.714700
2020-08-14T01:46:24
2020-08-14T01:46:24
137,144,596
2
0
null
null
null
null
UTF-8
C
false
false
3,781
h
#ifndef __NT99252_PRIV_H__ #define __NT99252_PRIV_H__ #include <ebase/types.h> #include <common/return_codes.h> #include <hal/hal_api.h> #ifdef __cplusplus extern "C" { #endif /*v0.1.0: * 1).add senosr drv version in get sensor i2c info func *v0.2.0: * 1). support for isi v0.5.0 *v0.3.0 * 1). support for isi v0.6.0 *v0.4.0 * 1). support for isi v0.7.0 *v0.5.0 * 1). update init svga and 2M setting *v0.6.0 * 1). fix bugs *v0.7.0 * 1). disable no-need debug *v0.8.0 * 1). merge from hixin setting *v0.9.0 * 1). support for isi v0.0xc.0 * 2). change VPol from ISI_VPOL_NEG to ISI_VPOL_POS *v0.a.0 * 1). support isi v0.0xd.0 */ #define CONFIG_SENSOR_DRV_VERSION KERNEL_VERSION(0, 0xa, 0) #define NT99252_DELAY_5MS (0x0000) //delay 5 ms #define NT99252_MODE_SELECT (0x0100) // rw - Bit[7:1]not used Bit[0]Streaming set 0: software_standby 1: streaming #define NT99252_SOFTWARE_RST (0x3021) //(0x0103) // rw - Bit[7:1]not used Bit[0]software_reset #define NT99252_SOFTWARE_RST_VALUE (0x61) #define NT99252_CHIP_ID_HIGH_BYTE_DEFAULT (0x25) // r - #define NT99252_CHIP_ID_MIDDLE_BYTE_DEFAULT (0x20) // r - #define NT99252_CHIP_ID_LOW_BYTE_DEFAULT (0x25) // r - #define NT99252_CHIP_ID_HIGH_BYTE (0x3000) // r - #define NT99252_CHIP_ID_MIDDLE_BYTE (0x3001) // r - #define NT99252_CHIP_ID_LOW_BYTE (0x3000) // r - /***************************************************************************** * Further defines for driver management *****************************************************************************/ #define NT99252_DRIVER_INIT (0x00000001) /***************************************************************************** * ov14825 context structure *****************************************************************************/ typedef struct NT99252_Context_s { IsiSensorContext_t IsiCtx; /**< common context of ISI and ISI driver layer; @note: MUST BE FIRST IN DRIVER CONTEXT */ //// modify below here //// IsiSensorConfig_t Config; /**< sensor configuration */ bool_t Configured; /**< flags that config was applied to sensor */ bool_t Streaming; /**< flags that sensor is streaming data */ bool_t TestPattern; /**< flags that sensor is streaming test-pattern */ bool_t isAfpsRun; /**< if true, just do anything required for Afps parameter calculation, but DON'T access SensorHW! */ bool_t GroupHold; float VtPixClkFreq; /**< pixel clock */ uint16_t LineLengthPck; /**< line length with blanking */ uint16_t FrameLengthLines; /**< frame line length */ float AecMaxGain; float AecMinGain; float AecMaxIntegrationTime; float AecMinIntegrationTime; float AecIntegrationTimeIncrement; /**< _smallest_ increment the sensor/driver can handle (e.g. used for sliders in the application) */ float AecGainIncrement; /**< _smallest_ increment the sensor/driver can handle (e.g. used for sliders in the application) */ float AecCurGain; float AecCurIntegrationTime; uint16_t OldGain; /**< gain multiplier */ uint32_t OldCoarseIntegrationTime; uint32_t OldFineIntegrationTime; uint32_t preview_minimum_framerate; IsiSensorMipiInfo IsiSensorMipiInfo; } NT99252_Context_t; #ifdef __cplusplus } #endif #endif
[ "ydf8525@126.com" ]
ydf8525@126.com
292094d93f0b9b6d4ea71a2e33b5ff57c72bf797
ffdee1771094fc7c63408db75eccb26f6a7e9911
/voip-ios/Audio/ThirdParty/TPCircularBuffer/TPCircularBuffer+AudioBufferList.h
ef709c3a5f93f3eb8cf0ce9a3acca24bf9504c98
[ "Apache-2.0" ]
permissive
notfoolen/voip-ios
90dcfb5b57fb4085a7023f6023ef2f57a2ad15d0
1b984dd68404dfb59e061796f253ffff8fe3d476
refs/heads/master
2021-01-18T18:01:06.934954
2017-03-31T18:46:19
2017-03-31T18:46:19
86,836,058
1
1
null
null
null
null
UTF-8
C
false
false
9,168
h
// // TPCircularBuffer+AudioBufferList.h // Circular/Ring buffer implementation // // https://github.com/michaeltyson/TPCircularBuffer // // Created by Michael Tyson on 20/03/2012. // // Copyright (C) 2012-2013 A Tasty Pixel // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // #ifndef TPCircularBuffer_AudioBufferList_h #define TPCircularBuffer_AudioBufferList_h #ifdef __cplusplus extern "C" { #endif #include "TPCircularBuffer.h" #include <AudioToolbox/AudioToolbox.h> #define kTPCircularBufferCopyAll UINT32_MAX typedef struct { AudioTimeStamp timestamp; UInt32 totalLength; AudioBufferList bufferList; } TPCircularBufferABLBlockHeader; /*! * Prepare an empty buffer list, stored on the circular buffer * * @param buffer Circular buffer * @param numberOfBuffers The number of buffers to be contained within the buffer list * @param bytesPerBuffer The number of bytes to store for each buffer * @param timestamp The timestamp associated with the buffer, or NULL. Note that you can also pass a timestamp into TPCircularBufferProduceAudioBufferList, to set it there instead. * @return The empty buffer list, or NULL if circular buffer has insufficient space */ AudioBufferList *TPCircularBufferPrepareEmptyAudioBufferList(TPCircularBuffer *buffer, int numberOfBuffers, int bytesPerBuffer, const AudioTimeStamp *timestamp); /*! * Mark next audio buffer list as ready for reading * * This marks the audio buffer list prepared using TPCircularBufferPrepareEmptyAudioBufferList * as ready for reading. You must not call this function without first calling * TPCircularBufferPrepareEmptyAudioBufferList. * * @param buffer Circular buffer * @param timestamp The timestamp associated with the buffer, or NULL to leave as-is. Note that you can also pass a timestamp into TPCircularBufferPrepareEmptyAudioBufferList, to set it there instead. */ void TPCircularBufferProduceAudioBufferList(TPCircularBuffer *buffer, const AudioTimeStamp *inTimestamp); /*! * Copy the audio buffer list onto the buffer * * @param buffer Circular buffer * @param bufferList Buffer list containing audio to copy to buffer * @param timestamp The timestamp associated with the buffer, or NULL * @param frames Length of audio in frames. Specify kTPCircularBufferCopyAll to copy the whole buffer (audioFormat can be NULL, in this case) * @param audioFormat The AudioStreamBasicDescription describing the audio, or NULL if you specify kTPCircularBufferCopyAll to the `frames` argument * @return YES if buffer list was successfully copied; NO if there was insufficient space */ bool TPCircularBufferCopyAudioBufferList(TPCircularBuffer *buffer, const AudioBufferList *bufferList, const AudioTimeStamp *timestamp, UInt32 frames, const AudioStreamBasicDescription *audioFormat); /*! * Get a pointer to the next stored buffer list * * @param buffer Circular buffer * @param outTimestamp On output, if not NULL, the timestamp corresponding to the buffer * @return Pointer to the next buffer list in the buffer */ static __inline__ __attribute__((always_inline)) AudioBufferList *TPCircularBufferNextBufferList(TPCircularBuffer *buffer, AudioTimeStamp *outTimestamp) { int32_t dontcare; // Length of segment is contained within buffer list, so we can ignore this TPCircularBufferABLBlockHeader *block = TPCircularBufferTail(buffer, &dontcare); if ( !block ) { if ( outTimestamp ) { memset(outTimestamp, 0, sizeof(AudioTimeStamp)); } return NULL; } if ( outTimestamp ) { memcpy(outTimestamp, &block->timestamp, sizeof(AudioTimeStamp)); } return &block->bufferList; } /*! * Get a pointer to the next stored buffer list after the given one * * @param buffer Circular buffer * @param bufferList Preceding buffer list * @param outTimestamp On output, if not NULL, the timestamp corresponding to the buffer * @return Pointer to the next buffer list in the buffer, or NULL */ AudioBufferList *TPCircularBufferNextBufferListAfter(TPCircularBuffer *buffer, AudioBufferList *bufferList, AudioTimeStamp *outTimestamp); /*! * Consume the next buffer list * * @param buffer Circular buffer */ static __inline__ __attribute__((always_inline)) void TPCircularBufferConsumeNextBufferList(TPCircularBuffer *buffer) { int32_t dontcare; TPCircularBufferABLBlockHeader *block = TPCircularBufferTail(buffer, &dontcare); if ( !block ) return; TPCircularBufferConsume(buffer, block->totalLength); } /*! * Consume a portion of the next buffer list * * This will also increment the sample time and host time portions of the timestamp of * the buffer list, if present. * * @param buffer Circular buffer * @param framesToConsume The number of frames to consume from the buffer list * @param audioFormat The AudioStreamBasicDescription describing the audio */ void TPCircularBufferConsumeNextBufferListPartial(TPCircularBuffer *buffer, int framesToConsume, const AudioStreamBasicDescription *audioFormat); /*! * Consume a certain number of frames from the buffer, possibly from multiple queued buffer lists * * Copies the given number of frames from the buffer into outputBufferList, of the * given audio description, then consumes the audio buffers. If an audio buffer has * not been entirely consumed, then updates the queued buffer list structure to point * to the unconsumed data only. * * @param buffer Circular buffer * @param ioLengthInFrames On input, the number of frames in the given audio format to consume; on output, the number of frames provided * @param outputBufferList The buffer list to copy audio to, or NULL to discard audio. If not NULL, the structure must be initialised properly, and the mData pointers must not be NULL. * @param outTimestamp On output, if not NULL, the timestamp corresponding to the first audio frame returned * @param audioFormat The format of the audio stored in the buffer */ void TPCircularBufferDequeueBufferListFrames(TPCircularBuffer *buffer, UInt32 *ioLengthInFrames, AudioBufferList *outputBufferList, AudioTimeStamp *outTimestamp, const AudioStreamBasicDescription *audioFormat); /*! * Determine how many frames of audio are buffered * * Given the provided audio format, determines the frame count of all queued buffers * * @param buffer Circular buffer * @param outTimestamp On output, if not NULL, the timestamp corresponding to the first audio frame returned * @param audioFormat The format of the audio stored in the buffer * @return The number of frames in the given audio format that are in the buffer */ UInt32 TPCircularBufferPeek(TPCircularBuffer *buffer, AudioTimeStamp *outTimestamp, const AudioStreamBasicDescription *audioFormat); /*! * Determine how many contiguous frames of audio are buffered * * Given the provided audio format, determines the frame count of all queued buffers that are contiguous, * given their corresponding timestamps (sample time). * * @param buffer Circular buffer * @param outTimestamp On output, if not NULL, the timestamp corresponding to the first audio frame returned * @param audioFormat The format of the audio stored in the buffer * @param contiguousToleranceSampleTime The number of samples of discrepancy to tolerate * @return The number of frames in the given audio format that are in the buffer */ UInt32 TPCircularBufferPeekContiguous(TPCircularBuffer *buffer, AudioTimeStamp *outTimestamp, const AudioStreamBasicDescription *audioFormat, UInt32 contiguousToleranceSampleTime); #ifdef __cplusplus } #endif #endif
[ "notfoolen@Timurs-MacBook-Pro.local" ]
notfoolen@Timurs-MacBook-Pro.local
fb3612734495c19cb7adf81e653bdb64f1700e6b
9b9ecfc44fed88e2494fca3cf9d263ab4a111d56
/external/bltsville/gcbv/gcmain.c
52fd3311deb0c52418338f801dd487bbca488257
[]
no_license
ghsecuritylab/kitkat-2
4b9ee9e085d5294a73621d51d80a2cd472977b91
51b1e812a87d8bf22a135df4f054a14d9c65f87b
refs/heads/master
2021-03-01T02:21:06.299684
2015-10-16T06:13:27
2015-10-16T06:58:24
245,747,275
0
0
null
2020-03-08T03:46:03
2020-03-08T03:46:03
null
UTF-8
C
false
false
8,600
c
/* * Copyright (c) 2012, * Texas Instruments, Inc. and Vivante Corporation * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Texas Instruments, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL TEXAS INSTRUMENTS, INC. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "gcmain.h" #include <semaphore.h> #define GCZONE_NONE 0 #define GCZONE_ALL (~0U) #define GCZONE_INIT (1 << 0) #define GCZONE_CALLBACK (1 << 1) GCDBG_FILTERDEF(gcmain, GCZONE_NONE, "init", "callback") static int g_handle; /******************************************************************************* * Callback manager. */ struct gccallbackinfo { /* Callback handle. */ unsigned long handle; /* Termination semaphore. */ sem_t stop; /* Callback thread handle. */ pthread_t thread; }; struct gccallbackinfo g_callbackinfo; static void *callbackthread(void *_gccallbackinfo) { struct gccallbackinfo *gccallbackinfo; struct gccmdcallbackwait gccmdcallbackwait; int result; /* Get callback info. */ gccallbackinfo = (struct gccallbackinfo *) _gccallbackinfo; /* Initialize the command. */ gccmdcallbackwait.handle = gccallbackinfo->handle; gccmdcallbackwait.timeoutms = 2000; /* Enter wait loop. */ while (1) { /* Call the kernel to wait for callback event. */ result = ioctl(g_handle, GCIOCTL_CALLBACK_WAIT, &gccmdcallbackwait); if (result == 0) { if (gccmdcallbackwait.gcerror == GCERR_NONE) { /* Work completed. */ GCDBG(GCZONE_CALLBACK, "callback 0x%08X(0x%08X).\n", (unsigned int) gccmdcallbackwait.callback, (unsigned int) gccmdcallbackwait.callbackparam); /* Invoke the callback. */ gccmdcallbackwait.callback( gccmdcallbackwait.callbackparam); } else if (gccmdcallbackwait.gcerror == GCERR_TIMEOUT) { /* Timeout. */ GCDBG(GCZONE_CALLBACK, "callback wait timeout.\n"); } else { /* Error occurred. */ GCERR("callback wait failed (0x%08X).\n", gccmdcallbackwait.gcerror); break; } } else if (result != -EINTR) { GCERR("callback wait ioctl failed (%d).\n", result); break; } /* Stop requested? */ if (sem_trywait(&gccallbackinfo->stop) == 0) { GCDBG(GCZONE_CALLBACK, "terminating.\n"); break; } } return NULL; } static int callback_start(struct gccallbackinfo *gccallbackinfo) { int result; struct gccmdcallback gccmdcallback; /* Initialize callback. */ gccmdcallback.handle = 0; result = ioctl(g_handle, GCIOCTL_CALLBACK_ALLOC, &gccmdcallback); if (result != 0) { GCERR("callback ioctl failed (%d).\n", result); goto fail; } if (gccmdcallback.gcerror != GCERR_NONE) { GCERR("failed to initialize callback mechanism (0x%08X).\n", gccmdcallback.gcerror); goto fail; } gccallbackinfo->handle = gccmdcallback.handle; /* Initialize the termiantion semaphore. */ result = sem_init(&gccallbackinfo->stop, 0, 0); if (result != 0) { GCERR("callback semaphore init failed (%d).\n", result); goto fail; } /* Start the thread. */ result = pthread_create(&gccallbackinfo->thread, NULL, callbackthread, gccallbackinfo); if (result != 0) { GCERR("failed to start callback thread.\n"); goto fail; } /* Success. */ return 0; fail: if (gccmdcallback.handle != 0) ioctl(g_handle, GCIOCTL_CALLBACK_FREE, &gccmdcallback); return result; } static void callback_stop(struct gccallbackinfo *gccallbackinfo) { struct gccmdcallback gccmdcallback; /* Stop the thread. */ GCDBG(GCZONE_CALLBACK, "stopping active client."); sem_post(&gccallbackinfo->stop); pthread_kill(gccallbackinfo->thread, SIGINT); GCDBG(GCZONE_CALLBACK, "waiting to join callback thread...\n"); pthread_join(gccallbackinfo->thread, NULL); gccallbackinfo->thread = 0; /* Free kernel resources. */ if (gccmdcallback.handle != 0) { gccmdcallback.handle = gccallbackinfo->handle; ioctl(g_handle, GCIOCTL_CALLBACK_FREE, &gccmdcallback); gccallbackinfo->handle = 0; } } /******************************************************************************* * IOCTL wrappers. */ #if GCDEBUG_ENABLE && 0 #define GCPRINTDELAY() sleep(1) #else #define GCPRINTDELAY() #endif void gc_map_wrapper(struct gcmap *gcmap) { int result; GCPRINTDELAY(); result = ioctl(g_handle, GCIOCTL_MAP, gcmap); if (result != 0) { GCERR("ioctl failed (%d).\n", result); gcmap->gcerror = GCERR_IOCTL; } } void gc_unmap_wrapper(struct gcmap *gcmap) { int result; GCPRINTDELAY(); result = ioctl(g_handle, GCIOCTL_UNMAP, gcmap); if (result != 0) { GCERR("ioctl failed (%d).\n", result); gcmap->gcerror = GCERR_IOCTL; } } void gc_commit_wrapper(struct gccommit *gccommit) { int result; GCPRINTDELAY(); gccommit->handle = g_callbackinfo.handle; result = ioctl(g_handle, GCIOCTL_COMMIT, gccommit); if (result != 0) { GCERR("ioctl failed (%d).\n", result); gccommit->gcerror = GCERR_IOCTL; } } /******************************************************************************* * Convert floating point in 0..1 range to an 8-bit value in range 0..255. */ union gcfp { struct { unsigned int mantissa:23; unsigned int exponent:8; unsigned int sign:1; } comp; float value; }; unsigned char gcfp2norm8(float value) { union gcfp gcfp; int exponent; unsigned int mantissa; int shift; /* Get access to components. */ gcfp.value = value; /* Clamp negatives. */ if (gcfp.comp.sign) return 0; /* Get unbiased exponent. */ exponent = (int) gcfp.comp.exponent - 127; /* Clamp if too large. */ if (exponent >= 0) return 255; /* Clamp if too small. */ if (exponent < -8) return 0; /* Determine the shift value. */ shift = (23 - 8) - exponent; /* Compute the mantissa. */ mantissa = (gcfp.comp.mantissa | 0x00800000) >> shift; /* Normalize. */ mantissa = (mantissa * 255) >> 8; return (unsigned char) mantissa; } /******************************************************************************* * Cache operation wrapper. */ enum bverror gcbvcacheop(int count, struct c2dmrgn rgn[], enum bvcacheop cacheop) { int result; struct gccachexfer xfer; if ((count < 0) || (count > 3)) return BVERR_CACHEOP; xfer.count = count; xfer.dir = cacheop; memcpy(xfer.rgn, rgn, count * sizeof(struct c2dmrgn)); GCPRINTDELAY(); result = ioctl(g_handle, GCIOCTL_CACHE, &xfer); if (result != 0) GCERR("ioctl failed (%d).\n", result); return BVERR_NONE; } /******************************************************************************* * Device init/cleanup. */ void __attribute__((constructor)) dev_init(void) { char* env; env = getenv("GCBV_DEBUG"); if (env && (atol(env) != 0)) GCDBG_ENABLEDUMP(); GCDBG_INIT(); GCDBG_REGISTER(gcmain); GCENTER(GCZONE_INIT); g_handle = open("/dev/gcioctl", O_RDWR); if (g_handle == -1) { GCERR("failed to open device (%d).\n", errno); goto fail; } if (callback_start(&g_callbackinfo) != 0) goto fail; bv_init(); GCEXIT(GCZONE_INIT); return; fail: if (g_handle > 0) { close(g_handle); g_handle = 0; } GCEXIT(GCZONE_INIT); } void __attribute__((destructor)) dev_exit(void) { GCENTER(GCZONE_INIT); bv_exit(); callback_stop(&g_callbackinfo); if (g_handle != 0) { close(g_handle); g_handle = 0; } GCEXIT(GCZONE_INIT); GCDBG_EXIT(); }
[ "guido.dallolio@datalogic.com" ]
guido.dallolio@datalogic.com
35300a6d2e8a1cc78f2223775fe4748f13fdb333
81a880f7f6a6503c9a31ab5eb58eac20b79db046
/Quad-V2/00-Modules/DBG/DBG.c
bc37946f6772821ab64320a52a01de99c83da42e
[]
no_license
aceacedey/custom-pic-quad
434d831dd2132662e34a8b590ab19d5f9b34c88e
2954e2948fe7f38a32c79a2454771aab96c7e753
refs/heads/master
2021-03-12T22:36:39.512575
2014-08-22T18:46:38
2014-08-22T18:46:38
33,474,870
0
0
null
null
null
null
UTF-8
C
false
false
1,062
c
#include "DBG\DBG.h" //************************************************************ void DBGInit() { //******************************************************************* // Debugger interface uses pins AN4/RB2 and AN5/RB3 for communicating // debug signals, so they need to be released for digital I/O //------------------------------------------------------------------- _PCFG4 = 1; // Release pin AN4/RB2 for Digital I/O _PCFG5 = 1; // Release pin AN5/RB3 for Digital I/O //------------------------------------------------------------------- // Now let's configure these pins for Digital Output and set them to 0 //------------------------------------------------------------------- // Configure RB2 as OUTPUT _TRISB2 = 0; _LATB2 = 0; // Reset port //-------------------------------- // Configure RB3 as OUTPUT _TRISB3 = 0; _LATB3 = 0; // Reset port //------------------------------------------------------------------- return; } //************************************************************
[ "azarenin@gmail.com@bb90f81c-1e10-663d-700f-9058ac00d062" ]
azarenin@gmail.com@bb90f81c-1e10-663d-700f-9058ac00d062
4e707c0298711f08e88d113b7278980696962d2d
1685dd3dbe910851a3f18fa85ecaf346bc795d5f
/device-testsw-source-code/src/server.c
12e41ad3b759b406d74df678c98384db4c8c2315
[]
no_license
bleachangel/FactoryTestI8
5476287436b7cdd29e85cc07e7ec4144145ff9a1
7a8de39c9dbd4ed35869e27e7789218477de1623
refs/heads/master
2020-11-26T07:02:50.138747
2019-10-28T06:00:47
2019-10-28T06:00:47
null
0
0
null
null
null
null
UTF-8
C
false
false
25,800
c
#include <unistd.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/time.h> #include <sys/wait.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <pthread.h> #include <fcntl.h> #include <net/if.h> #include <arpa/inet.h> // mips-linux-uclibc-gnu-gcc -muclibc -march=mips32r2 sn.c -o sn.o char MacBuffer[1566]; #define SIG_MAGIC (('N'<<24)+('S'<<16)+('8'<<8)+('I'<<0)) #pragma pack(4) typedef struct { unsigned long MAGIC; char SN[16]; char MAC[16]; char VERSION[32]; char testSN; // pos 0x34 char testMic; char testIR; char testIRCut; char testLightSensor; char testKey; char testVersion; //----------------------- char rtSN; char rtMAC; char rtMic; char rtLightSensor; char rtKey; char rtVersion; char exitTest; } FACTORYTEST_DATA; #pragma pack() #pragma pack(4) typedef struct { char MAG[4]; char SN[16]; char TYPE[8]; } NOTIFY_MSG; #pragma pack() extern int AgingPlayTest (); extern int TEST_SPK_MIC (int argc, FACTORYTEST_DATA *plFtD, int vol); extern int TEST_PLAY_MUSIC(int onoff, int vol); FACTORYTEST_DATA lFtD; static int g_IrTestAuto = 1; static int g_LedTestAuto = 1; static int g_StopHeartBeat = 0; static int g_UsbNetConnected = 0; static int g_WiFiConnected = 0; static int g_button_test = 0; static int g_stop_button_monitor = 0; int DrvSaveToFile(char *cName, char *pData, int len) { int fd; int ret = 0; fd = open(cName, O_RDWR|O_CREAT|O_TRUNC, 0644); if (fd < 0) { printf("DrvSaveToFile:open %s error\n", cName); return -1; } lseek(fd, 0, SEEK_SET); if (len != write(fd, pData, len)) { ret = -2; printf("DrvSaveToFile write %s failed!\n", cName); } printf("DrvSaveToFile %s: %d bytes write ok!\n", cName, len); close(fd); return ret; } int DrvReadFileEx(char *cName, char *pData, int *pLen, int iStartKB) { int fd; int iSize = 0; int iret = 0; if ( /*(pLen == NULL) ||*/(pData == NULL)) { printf("DrvReadFile param error!\n"); return -3; } if (pLen) iSize = *pLen; fd = open(cName, O_RDWR, 777); if (fd < 0) { printf("DrvReadFile:%s error\n", cName); return -2; } // printf("DrvReadFile fd=%d: %d bytes!\n", fd, iSize); if (iSize==0) { iSize = lseek(fd, 0, SEEK_END); } lseek(fd, (iStartKB<<10), SEEK_SET); iret = read(fd, pData, iSize); if (iSize != iret) { if (pLen) *pLen = iret; printf("err: DrvReadFile %s: %d(%d) bytes!\n", cName, iret, iSize); close(fd); return -1; } else { if (pLen) *pLen = iSize; printf("DrvReadFile %s: %d(%d) bytes read ok!\n", cName, iret, iSize); } close(fd); return 0; } int CutoffChar(char *str, char c) { int i = 0; int n = strlen(str); for (i=0; i<n; i++) { if (str[i] == c) { str[i] = 0; return i; } } return 0; } int ReplanceMac(char *map, char *MAC, int cnt) { char idx = 0; int i = 0; if (MAC[0] == 'I') MAC[0] = 'F'; for (idx=0; idx<6; idx++) { if (MAC[idx*2] == 0) MAC[idx*2] = '0'; if (MAC[idx*2+1] == 0) MAC[idx*2+1] = '0'; map[i++] = MAC[idx*2]; map[i++] = MAC[idx*2+1]; i++; } MAC[12] = MAC[13] = MAC[14] = MAC[15] = 0; i = 0; printf("After map mac: "); for (idx=0; idx<6; idx++) { printf("%c%c ", map[idx*3], map[idx*3+1]); } printf("\r\n"); return 0; } int mymemcmp(char *src, char *dst, int cnt) { int i = 0; for (i=0; i<cnt; i++) { if (src[i] != dst[i]) { printf("mymemcmp mismatch @%d (%02x != %02x)\r\n", i, src[i], dst[i]); return 1; } } return 0; } int dumpChar(char *name, char *src, int cnt) { int i = 0; printf("%s: \r\n", name); for (i=0; i<cnt; i++) { printf("%c", src[i]); } return 0; } int CheckSNAndMAC(FACTORYTEST_DATA *plFtD) { char pData[1566] = {0}; char SN [32] = {0}; char MAC[32]; int iLen = 32; int res = 0; int i = 0; printf("\r\n\r\nstart CheckSNAndMAC: \r\n"); DrvReadFileEx("/dev/mtd5", pData, &iLen, 0); memcpy(SN, &pData[13], 15); printf("read SN:%s ?= %s \r\n", SN, plFtD->SN); if (memcmp(SN, plFtD->SN, 15)) { printf(">>> check SN failed!\r\n"); res |= (1 << 1); plFtD->rtSN = 0; } else { printf(">>> check SN OK!\r\n"); plFtD->rtSN = 1; } memcpy(plFtD->SN, SN, 15); // 2 check MAC for (i=0; i<6; i++) { MAC[i*3+0] = plFtD->MAC[i*2+0]; MAC[i*3+1] = plFtD->MAC[i*2+1]; MAC[i*3+2] = ' '; } system("iwpriv wlan0 efuse_get realmap > /tmp/wifi_rel_efuse.map"); // read to file iLen = sizeof(MacBuffer); DrvReadFileEx("/tmp/wifi_rel_efuse.map", pData, &iLen, 0); if (mymemcmp(&pData[0x3e2], MAC, 17)) { printf(">>> check MAC failed!\r\n"); res |= (1 << 0); plFtD->rtMAC = 0; } else { printf(">>> check MAC OK!\r\n"); plFtD->rtMAC = 1; } for (i=0; i<6; i++) { plFtD->MAC[i*2+0] = MAC[i*3+0]; plFtD->MAC[i*2+1] = MAC[i*3+1]; } return res; } int WriteAndCheckSN(FACTORYTEST_DATA *plFtD) { char pData[1566]; char SN[32]; int iLen = 0; int res = 0; printf("\r\n\r\nstart WriteAndCheckSN: \r\n"); // 1 write SN if (plFtD->rtSN == 0) { memset(SN, 0, sizeof(SN)); printf("Write SN:%s \r\n", plFtD->SN); sprintf(SN, "000000000000\n%s\n", plFtD->SN); printf("rel Write SN:<<%s>> \r\n", SN); printf("format SN part!\r\n"); system("flash_eraseall /dev/mtd5"); DrvSaveToFile("/dev/mtd5", SN, sizeof(SN)); sync(); memset(pData, 0 ,sizeof(pData)); iLen = 32; DrvReadFileEx("/dev/mtd5", pData, &iLen, 0); memset(SN,0,sizeof(SN)); memcpy(SN, &pData[13], 15); printf("read SN:%s ?= %s \r\n", SN, plFtD->SN); if (memcmp(SN, plFtD->SN, 15)) { printf(">>> Write SN failed!\r\n"); res |= (1 << 1); plFtD->rtSN = 0; } else { printf(">>> Write SN OK!\r\n"); plFtD->rtSN = 1; } } // 2 write MAC if (plFtD->rtMAC == 0) { if (1) { printf("Write MAC (SD):%s \r\n", plFtD->MAC); iLen = 0; // all file bytes DrvReadFileEx("./wifi_efuse_8189fs.map", MacBuffer, &iLen, 0); ReplanceMac((char*)&MacBuffer[0x35f], (char*)&plFtD->MAC, 6); // dumpChar("MacBuffer1", MacBuffer, 1566); DrvSaveToFile("/tmp/wifi_efuse_8189fs_new.map", MacBuffer, sizeof(MacBuffer)); sync(); system("iwpriv wlan0 efuse_file /tmp/wifi_efuse_8189fs_new.map"); } system("iwpriv wlan0 efuse_set wlfk2map"); //write system("iwpriv wlan0 efuse_get realmap > /tmp/wifi_rel_efuse.map"); //read to file iLen = sizeof(MacBuffer); DrvReadFileEx("/tmp/wifi_rel_efuse.map", pData, &iLen, 0); // dumpChar("MacBuffer", MacBuffer, 1566); // dumpChar("\r\npData", pData, 1566); if (mymemcmp(&pData[0x3e2], &MacBuffer[0x35f], 17)) { printf(">>> Write MAC failed!\r\n"); res |= (1 << 0); plFtD->rtMAC = 0; } else { printf(">>> Write MAC OK!\r\n"); plFtD->rtMAC = 1; } } return res; } int ChechVersion(FACTORYTEST_DATA *plFtD) { char ver[64]; int iLen = 64; // printf("\r\n\r\nstart ChechVersion: \r\n"); memset(ver, 0, sizeof(ver)); DrvReadFileEx("/etc/version", ver, &iLen, 0); ver[63] = 0; CutoffChar(plFtD->VERSION, '\r'); CutoffChar(plFtD->VERSION, '\n'); CutoffChar(ver, '\n'); if (strcmp(plFtD->VERSION, ver)) { printf("ver:%s != %s\r\n", ver, plFtD->VERSION); plFtD->rtVersion = 0; strcpy(plFtD->VERSION, ver); return -1; } else { printf("ver:%s == %s\r\n", ver, plFtD->VERSION); strcpy(plFtD->VERSION, ver); plFtD->rtVersion = 1; } return 0; } int TestIRCut(FACTORYTEST_DATA *plFtD) { // printf("\r\n\r\nstart TestIRCut: %d\r\n", plFtD->testIRCut); if (plFtD->testIRCut == '1') { system("echo 0 > /sys/class/gpio/gpio81/value"); system("echo 1 > /sys/class/gpio/gpio82/value"); } else if (plFtD->testIRCut == '2') { system("echo 1 > /sys/class/gpio/gpio81/value"); system("echo 0 > /sys/class/gpio/gpio82/value"); } return 0; } int EnIR(FACTORYTEST_DATA *plFtD) { // printf("\r\n\r\nstart EnIR: %d\r\n", plFtD->testIR); if (plFtD->testIR == '1') { system("echo 0 > /sys/class/gpio/gpio61/value"); } else if (plFtD->testIR == '2') { system("echo 1 > /sys/class/gpio/gpio61/value"); } return 0; } int TestLightSensor(FACTORYTEST_DATA *plFtD) { static int MaxV = 0; static int MinV = 0x400; int val = 0; int fd; const char *cName = "/dev/jz_adc_aux_0"; // printf("\r\n\r\nstart TestLightSensor: %d\r\n", plFtD->rtLightSensor); plFtD->rtLightSensor = 0; fd = open(cName, O_RDONLY, 0644); if (fd < 0) { // printf("TestLightSensor:open %s error\n", cName); return -1; } if (32 != read(fd, &val, 32)) { // printf("TestLightSensor read %s failed!\n", cName); } printf("TestLightSensor %s: read ok :%x!\n", cName, val); if (val > MaxV) MaxV = val; if (val < MinV) MinV = val; if (MaxV > 0x400 && MinV < 0x100) { // printf("TestLightSensor OK! [%x, %x]\n", MinV, MaxV); plFtD->rtLightSensor = 1; } if (val > 0x350 && val < 0x550) { plFtD->rtLightSensor = 1; } close(fd); return 0; } int EnIRCutForAuto(int en) { // printf("\r\n\r\nstart EnIRCut: %d\r\n", en); if (en == 1) { system("echo 0 > /sys/class/gpio/gpio81/value"); system("echo 1 > /sys/class/gpio/gpio82/value"); } else { system("echo 1 > /sys/class/gpio/gpio81/value"); system("echo 0 > /sys/class/gpio/gpio82/value"); } return 0; } int EnIRForAuto(int en) { // printf("\r\n\r\nstart EnIR: %d\r\n", en); if (en == 1) { system("echo 0 > /sys/class/gpio/gpio61/value"); } else { system("echo 1 > /sys/class/gpio/gpio61/value"); } return 0; } int GetLightSensor() { int val = 0; int fd = 0; const char *cName = "/dev/jz_adc_aux_0"; // printf("\r\n\r\nGettLightSensor value\r\n"); fd = open(cName, O_RDONLY, 0644); if (fd < 0) { printf("GetLightSensor:open %s error\n", cName); return -1; } if (32 != read(fd, &val, 32)) { // printf("GetLightSensor read %s failed!\n", cName); } // printf("GetLightSensor %s: read ok :0x%x!\n", cName, val); close(fd); if (val > 0x350 && val < 0x550) { return 1; } else { return 0; } } int getBroadcastIPWiFi(char *ip) { int inet_sock; struct ifreq ifr = {}; struct in_addr broadcastip = {}; inet_sock = socket(AF_INET, SOCK_DGRAM, 0); strcpy(ifr.ifr_name, "wlan0"); ioctl(inet_sock, SIOCGIFADDR, &ifr); broadcastip = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr; broadcastip.s_addr |= (255 << 24); strcpy(ip , inet_ntoa(broadcastip)); // printf("BroadcastIPWiFi: %s\r\n", ip); return ip[0] == '1' ? 0 : -1; } int getBroadcastIPUsbNet(char *ip) { int inet_sock; struct ifreq ifr = {}; struct in_addr broadcastip = {}; inet_sock = socket(AF_INET, SOCK_DGRAM, 0); strcpy(ifr.ifr_name, "usb0"); ioctl(inet_sock, SIOCGIFADDR, &ifr); broadcastip = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr; broadcastip.s_addr |= (255 << 24); strcpy(ip , inet_ntoa(broadcastip)); // printf("BroadcastIPUsbNet: %s\r\n", ip); return ip[0] == '1' ? 0 : -1; } static void *heart_beat_thread(void *argv) { struct sockaddr_in servaddr = {0}; int sockfd = 0 ; NOTIFY_MSG msg = {}; char pData [64] = {}; char SN [16] = {}; char wifiip[16] = {}; char usbnip[16] = {}; char servip[16] = {}; struct timeval t; int led = 0; int opt = 0; // read sn from mtd5 int len = 32; DrvReadFileEx("/dev/mtd5", pData, &len, 0); memcpy(SN, &pData[13], 15); // init for msg, set magic code, and set SN // note !!, the msg.IP is used for store SN memcpy(msg.MAG, "NMSG", 4); strcpy(msg.SN , SN); // open socket sockfd = socket(AF_INET, SOCK_DGRAM, 0); // set non-block io opt = 1; ioctl(sockfd, FIONBIO, &opt); // set udp send & recv timeout t.tv_sec = 1; t.tv_usec = 0; setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (char*)&t, sizeof(t)); setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char*)&t, sizeof(t)); // set udp broadcast if (argv == NULL) { opt = 1; setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (char*)&opt, sizeof(opt)); } // for server addr servaddr.sin_family = AF_INET; servaddr.sin_port = htons(8989); while (!g_StopHeartBeat) { if (!g_UsbNetConnected) { if (getBroadcastIPUsbNet(usbnip) == 0) { msg.TYPE[0] = g_UsbNetConnected = 1; strcpy(servip, argv ? argv : usbnip); inet_pton(AF_INET, servip, &servaddr.sin_addr); } } if (!g_WiFiConnected) { if (getBroadcastIPWiFi(wifiip) == 0) { msg.TYPE[1] = g_WiFiConnected = 1; if (!g_UsbNetConnected) { strcpy(servip, argv ? argv : wifiip); inet_pton(AF_INET, servip, &servaddr.sin_addr); } system("echo 1 > /sys/class/gpio/gpio49/value"); // turn on blue led } } // button test msg.TYPE[2] = g_button_test; if (servaddr.sin_addr.s_addr != 0) { if (sendto(sockfd, &msg, sizeof(msg), 0, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1) { printf("sendto failed ! %s, %s, %s\n", wifiip, usbnip, servip); } else { printf("heartbeat: %s\r\n", servip); } } // auto led if (g_LedTestAuto) { if (g_WiFiConnected) { led++; led %= 3; } else { led++; led %= 2; } switch (led) { case 0: system("echo 1 > /sys/class/gpio/gpio50/value"); system("echo 0 > /sys/class/gpio/gpio72/value"); system("echo 0 > /sys/class/gpio/gpio49/value"); break; case 1: system("echo 0 > /sys/class/gpio/gpio50/value"); system("echo 1 > /sys/class/gpio/gpio72/value"); system("echo 0 > /sys/class/gpio/gpio49/value"); break; case 2: system("echo 0 > /sys/class/gpio/gpio50/value"); system("echo 0 > /sys/class/gpio/gpio72/value"); system("echo 1 > /sys/class/gpio/gpio49/value"); break; } } // auto IRCut if (g_IrTestAuto) { if (GetLightSensor() == 1) { EnIRForAuto (1); EnIRCutForAuto(1); } else { EnIRForAuto (0); EnIRCutForAuto(0); } } sleep(1); } close(sockfd); return NULL; } static void* button_monitor_thread(void *argv) { int fd = 0; int key = 0; int ir = 0; int press = 0; const char *cName = "/sys/class/gpio/gpio60/value"; while (!g_stop_button_monitor) { fd = open(cName, O_RDONLY, 0644); if (fd) { int val = 0; if (1 == read(fd, &val, 1)) { key = val == '0' ? 0 : 1; } close(fd); } if (key == 0) g_button_test |= (1 << 0); if (key == 1) g_button_test |= (1 << 1); if (key == 0) { if (++press == 3) { TEST_PLAY_MUSIC(0, 0); g_IrTestAuto = 0; ir = !ir; if (ir) { system("echo 1 > /sys/class/gpio/gpio61/value"); system("echo 1 > /sys/class/gpio/gpio81/value"); system("echo 0 > /sys/class/gpio/gpio82/value"); } else { system("echo 0 > /sys/class/gpio/gpio61/value"); system("echo 0 > /sys/class/gpio/gpio81/value"); system("echo 1 > /sys/class/gpio/gpio82/value"); } } } else { press = 0; } usleep(100000); } return NULL; } void StartAgainTest() { int i = 0; int cnt = 0; int ir = 0; int led = 0; int val = 0; int fd = 0; const char *cName = "/sys/class/gpio/gpio60/value"; while (1) { // switch ir & ircut ir = !ir; EnIRForAuto(ir); EnIRCutForAuto(ir); // check destory key for (cnt=0,i=0; i<20; i++) { if (i % 5 == 0) { led = !led; if (led) { system("echo 0 > /sys/class/gpio/gpio72/value"); system("echo 1 > /sys/class/gpio/gpio50/value"); } else { system("echo 1 > /sys/class/gpio/gpio72/value"); system("echo 0 > /sys/class/gpio/gpio50/value"); } } fd = open(cName, O_RDONLY, 0644); if (fd) { if (1 != read(fd, &val, 1)) { // printf("TestKey read %s failed!\n", cName); } close(fd); } printf("KEY:0x%x\r\n", val); if (val == '0') { cnt++; } if (cnt > 5) { // 销毁程序 printf("test over, destory!!!\r\n"); system("mv /etc/init.d/rcS.dh /etc/init.d/rcS"); system("rm -rf /etc/apkft"); system("sync"); printf("\r\n server:remove test app & exit.\n\r\n"); system("echo 0 > /sys/class/gpio/gpio50/value"); system("echo 0 > /sys/class/gpio/gpio72/value"); while (1) { // 蓝灯闪烁 system("echo 1 > /sys/class/gpio/gpio49/value"); usleep(300000); // 300ms system("echo 0 > /sys/class/gpio/gpio49/value"); usleep(300000); // 300ms } } sleep(1); } } } #define MAXDATASIZE 100 /* 每次最大数据传输量 */ int main(int argc, char *argv[]) { int sockfd, new_fd; /* 监听 socket: sock_fd, 数据传输 socket: new_fd */ struct sockaddr_in my_addr = {0}; /* 本机地址信息 */ struct sockaddr_in their_addr= {0}; /* 客户地址信息 */ unsigned int myport, lisnum; pthread_t tid_heart_beat; pthread_t tid_btn_monitor; int cnt = 0; int iRecvBytes; char buf[MAXDATASIZE]; //++ init gpios // led gpio rgb system("echo 50 > /sys/class/gpio/export"); system("echo out > /sys/class/gpio/gpio50/direction"); system("echo 72 > /sys/class/gpio/export"); system("echo out > /sys/class/gpio/gpio72/direction"); system("echo 49 > /sys/class/gpio/export"); system("echo out > /sys/class/gpio/gpio49/direction"); system("echo 0 > /sys/class/gpio/gpio49/value"); // turn off blue led // button gpio system("echo 60 > /sys/class/gpio/export"); system("echo in > /sys/class/gpio/gpio60/direction"); // ir gpio system("echo 61 > /sys/class/gpio/export"); system("echo out > /sys/class/gpio/gpio61/direction"); // filter gpio system("echo 81 > /sys/class/gpio/export"); system("echo out > /sys/class/gpio/gpio81/direction"); system("echo 82 > /sys/class/gpio/export"); system("echo out > /sys/class/gpio/gpio82/direction"); //-- init gpios myport = 7838; lisnum = 5; if (argv[1]) { if (strcmp(argv[1], "aging") == 0) { TEST_PLAY_MUSIC(1, 16); StartAgainTest(); return 0; } else if (strcmp(argv[1], "all") == 0) { TEST_PLAY_MUSIC(1, 0); pthread_create(&tid_heart_beat , NULL, heart_beat_thread , argc >= 3 ? argv[2] : NULL); pthread_create(&tid_btn_monitor, NULL, button_monitor_thread, NULL); } else if (strstr(argv[1], "192.168.") == argv[1]) { pthread_create(&tid_heart_beat , NULL, heart_beat_thread , argv[1]); pthread_create(&tid_btn_monitor, NULL, button_monitor_thread, NULL); } else { pthread_create(&tid_heart_beat , NULL, heart_beat_thread , argc >= 3 ? argv[2] : NULL); } } memset(&lFtD, 0, sizeof(lFtD)); if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } my_addr.sin_family = PF_INET; my_addr.sin_port = htons(myport); my_addr.sin_addr.s_addr = INADDR_ANY; printf("server:binding...\n"); if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); exit(1); } printf("server:listening...\n"); if (listen(sockfd, lisnum) == -1) { perror("listen"); exit(1); } while (1) { unsigned sin_size = sizeof(struct sockaddr_in); if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { printf("accept failed !"); continue; } printf("\r\n>>[%d] server: got connection from %s\n", cnt++, inet_ntoa(their_addr.sin_addr)); while (1) { iRecvBytes = recv(new_fd, &lFtD, sizeof(lFtD), 0); if (iRecvBytes <= 0) { printf("\r\n server: recv connect losed! \r\n"); close(new_fd); break; } memset(buf, 0, sizeof(buf)); memcpy(buf, &lFtD.MAGIC, 4); // SN & MAC if (lFtD.testSN=='1') { WriteAndCheckSN(&lFtD); } if (lFtD.testSN=='2') { CheckSNAndMAC(&lFtD); } // SPK & MIC if (lFtD.testMic) { switch (lFtD.testMic) { case '1': // auto test spk & mic TEST_SPK_MIC(2, &lFtD, 30); if (lFtD.rtMic) { // 写号 + wifi 吞吐量 + 喇叭咪头,测试通过,下一步功能测试 printf("change stage to all\r\n"); system("echo all > /etc/apkft/stage"); } break; case '2': TEST_PLAY_MUSIC(1, 0); break; case '3': TEST_PLAY_MUSIC(0, 0); break; } } // LightSensor if (lFtD.testLightSensor) { TestLightSensor(&lFtD); } // IRCut if (lFtD.testIRCut) { TestIRCut(&lFtD); } // KEY if (lFtD.testKey) { lFtD.rtKey = (g_button_test == 3); } // IR LED if (lFtD.testIR) { g_IrTestAuto = 0; printf("\r\nserver:testIR:%d dis auto IR test\n\r\n", lFtD.testIR); EnIR(&lFtD); } // Version if (lFtD.testVersion) { ChechVersion(&lFtD); } if (lFtD.exitTest == 'f') { // 下一步进入功能测试 system("echo all > /etc/apkft/stage"); system("sync"); } else if (lFtD.exitTest == 'a') { // 下一步进入老化测试 system("echo aging > /etc/apkft/stage"); system("sync"); } printf("\r\nserver:sending...mic:%d, key=%d, exitTest=%d\n\r\n", lFtD.rtMic, lFtD.rtKey, lFtD.exitTest); if (send(new_fd, &lFtD, sizeof(lFtD), 0) <= 0) { printf("\r\nserver:send connect losed.\n\r\n"); close(new_fd); break; } } close(new_fd); } g_StopHeartBeat = 1; g_stop_button_monitor = 1; pthread_join(tid_heart_beat , NULL); pthread_join(tid_btn_monitor, NULL); TEST_PLAY_MUSIC(0, 0); printf("\r\nserver:EXIT.\n\r\n"); return 0; }
[ "chenk@apical.com.cn" ]
chenk@apical.com.cn
6986000c8d1d85a8046b64adb46f1bbbbf32a1c3
5da89940b22d64ccf3c8aba8cd8175bf1e251b58
/Outdated Code/calculationsWithOptimizedTurnNOWORK.c
d03d4d40e7c5f36e4208b4acefead15f6f89c228
[]
no_license
lukaswormald1/goose-destroyer
bbbda776bba4b37b3dca2546b86915b79f901296
e6e107676615dc331f8bdfae1e764720ee6ef033
refs/heads/master
2020-05-18T04:27:28.424200
2018-11-27T01:39:19
2018-11-27T01:39:19
184,173,435
0
0
null
null
null
null
UTF-8
C
false
false
1,819
c
#include "initialization.c" #ifndef CALCULATIONS #define CALCULATIONS //Calculations //Distance to closest firing position float distToRange (Coordinate const & tank0Loc, Coordinate const & target) { return sqrt(pow(tank0Loc.x - target.x, 2) + pow(tank0Loc.y - target.y, 2)) - RANGE; } float distToCoordinate (Coordinate const & tank0Loc, Coordinate const & target) { return sqrt(pow(tank0Loc.x - target.x, 2) + pow(tank0Loc.y - target.y, 2)); } //Angle between tank and target Coordinate in radians float angleBetween (Coordinate const & tank0Loc, Coordinate const & target) { float delx = target.x - tank0Loc.x; float dely = target.y - tank0Loc.y; float angle = 0; //range of arctan is -PI/2 to PI/2 if (delx<0 && dely>=0) return atan(dely / delx) + PI; else if (abs(delx) < TOL && dely > 0) return PI / 2.0; else if (abs(delx) < TOL && dely < 0) return -(PI / 2.0); else if (delx<0 && dely<0) return atan(dely / delx) - PI; else if (delx>0) return atan(dely / delx); return 0; } float minTankTurn (Tank const & tank0, float calculatedAngle) { float turn = calculatedAngle - tank0.angle; //So it will never turn more than PI if(fabs(turn) > PI) { if(turn<0) { displayString(10, "Adjusting + PI"); turn = turn + (PI) + (PI); } else if(turn>0) { turn -= (2 * (PI)); displayString(10, "Adjusting - PI"); } } return turn; } //Coordinate of the closest firing position, used to redefine tank location void findFiringPosition (Coordinate const & tank0Loc, Coordinate const & target, Coordinate & firingLocation) { firingLocation.x = cos(angleBetween(tank0Loc, target)) * distToRange(tank0Loc, target); firingLocation.y = sin(angleBetween(tank0Loc, target)) * distToRange(tank0Loc, target); } #endif
[ "noreply@github.com" ]
lukaswormald1.noreply@github.com
a8b154a228a7e2b0c85200640ea62b6db94d30c8
7f38190ac54a56d7cd71b59edc3dc440f5ae97c5
/C/dynamiclib/main_func.c
69874bd17761d5907d09d11a68a32436de5e81dd
[]
no_license
R7J/MyProgramsBkp
88d83306280dadca59ed9a28ebe29417568a4347
86cb0a39ee0ae5b275e7df587303557db7b31e0f
refs/heads/master
2020-03-24T12:10:56.932249
2018-07-26T08:13:49
2018-07-26T08:13:49
null
0
0
null
null
null
null
UTF-8
C
false
false
55
c
#include<stdio.h> int main(void){ func(); func2(); }
[ "ramanareddy1892@gmail.com" ]
ramanareddy1892@gmail.com
81a530235e7fd56b137da5fcc4d12090d80236b9
e756ed6ee299745978763622e5ed3cc8a27a2a3c
/0x01-variables_if_else_while/4-print_alphabt.c
fb8663c491984e6f89f78d8f658e212a8831e250
[]
no_license
Kawkaawaa/holbertonschool-low_level_programming
efde00040eb2d636e2225c4d77a402390fafcf8c
bfe8cfbf05b5f3b99d6d236d16ab7299365f2f8e
refs/heads/master
2023-04-14T08:48:52.216703
2020-01-10T22:33:28
2020-01-10T22:33:28
null
0
0
null
null
null
null
UTF-8
C
false
false
315
c
#include <stdio.h> /** *main - print the alphabet in lowercase * *description: Will print out the entire alphabet in lowercase *Return: 0 */ int main(void) { char a = 'a'; while (a <= 'z') { if (a == 'e' || a == 'q') { a++; } else { putchar(a); a++; } } putchar('\n'); return (0); }
[ "mcavigli@gmail.com" ]
mcavigli@gmail.com
1ed1740485b8aed3c8282bcbf2155757bc1d3ba2
7dfa3a5a873d4c0fc74d13e78f685daec543d621
/src/libdatastruct/avltree.h
2fc944b2763e40bf72228c06a3e27c81f83efbb7
[]
no_license
djbtao/skalibs
1c500ea0823c57dd6932b9aa80b54f2174a55064
c2ed75c9838767af60a05451b6d216331c1dbccf
refs/heads/master
2021-01-01T16:21:03.750988
2014-03-31T14:59:23
2014-03-31T14:59:23
null
0
0
null
null
null
null
UTF-8
C
false
false
2,381
h
/* ISC license. */ #ifndef AVLTREE_H #define AVLTREE_H #include "functypes.h" #include "gensetdyn.h" #include "avlnode.h" typedef struct avltree_s avltree, *avltree_ref ; struct avltree_s { gensetdyn x ; unsigned int root ; uintcmpfunc_t_ref cmp ; void *external ; } ; #define AVLTREE_ZERO { .x = GENSETDYN_ZERO, .root = (unsigned int)-1, .cmp = 0, .external = 0 } extern avltree const avltree_zero ; #define avltree_len(t) gensetdyn_n(&(t)->x) #define avltree_totalsize(t) ((t)->x.storage.len) #define avltree_nodes(t) ((avlnode_ref)(t)->x.storage.s) #define avltree_data(t, i) (avltree_nodes(t)[i].data) #define avltree_root(t) ((t)->root) #define avltree_setroot(t, r) ((t)->root = (r)) extern void avltree_free (avltree_ref) ; extern void avltree_init (avltree_ref, unsigned int, unsigned int, unsigned int, uintcmpfunc_t_ref, void *) ; #define AVLTREE_INIT(b, num, den, f, p) { .x = GENSETDYN_INIT(avlnode, (b), num, den), .root = (unsigned int)-1, .cmp = (f), .external = (p) } #define avltree_searchnode(t, k) avlnode_searchnode(avltree_nodes(t), avltree_totalsize(t), avltree_root(t), (k), (t)->cmp, (t)->external) #define avltree_search(t, k, data) avlnode_search(avltree_nodes(t), avltree_totalsize(t), avltree_root(t), (k), (data), (t)->cmp, (t)->external) #define avltree_height(t) avlnode_height(avltree_nodes(t), avltree_totalsize(t), avltree_root(t)) #define avltree_extremenode(t, h) avlnode_extremenode(avltree_nodes(t), avltree_totalsize(t), avltree_root(t), h) #define avltree_minnode(t) avltree_extremenode((t), 0) #define avltree_maxnode(t) avltree_extremenode((t), 1) #define avltree_extreme(t, h, data) avlnode_extreme(avltree_nodes(t), avltree_totalsize(t), avltree_root(t), (h), data) #define avltree_min(t, data) avltree_extreme((t), 0, data) #define avltree_max(t, data) avltree_extreme((t), 1, data) extern int avltree_newnode (avltree_ref, unsigned int, unsigned int *) ; #define avltree_insertnode(t, i) avltree_setroot(t, avlnode_insertnode(avltree_nodes(t), avltree_totalsize(t), avltree_root(t), i, (t)->cmp, (t)->external)) extern int avltree_insert (avltree_ref, unsigned int) ; #define avltree_deletenode(t, i, j) avltree_delete(t, avltree_data(t, i), j) extern int avltree_delete (avltree_ref, unsigned int) ; #define avltree_iter(t, f, p) avlnode_iter(avltree_nodes(t), avltree_totalsize(t), avltree_root(t), f, p) #endif
[ "k.os.tao@gmail.com" ]
k.os.tao@gmail.com
518ca93577f51bd0cf82850ddc1300e6aa14ea5b
385c82fd691b71803f20dc127fd109706c994b94
/include/dllist.h
f932a0b3d488026ae592dcf4ab2dbad302b0f741
[]
no_license
kevwargo/npr-distmon
9bb47574e489527a8fc79d8d5a9757dbf4913184
ee9ba7e2adaef1d2e7fa0e9ba7419046cb4d8d9b
refs/heads/master
2021-01-23T01:08:58.587341
2017-09-29T08:17:44
2017-09-29T08:17:44
85,883,049
0
0
null
null
null
null
UTF-8
C
false
false
948
h
#ifndef _DLLIST_H_INCLUDED_ #define _DLLIST_H_INCLUDED_ struct dll_entry { struct dll_entry *prev; struct dll_entry *next; unsigned char item[0]; }; struct dllist { struct dll_entry *head; struct dll_entry *tail; int size; }; #define dllist_append(list, item) \ dllist_new(list, item, sizeof(*(item)), 0) #define dllist_prepend(list, item) \ dllist_new(list, item, sizeof(*(item)), 1) #define dllist_entry(item) \ (struct dll_entry *)((char *)item - sizeof(struct dll_entry)) #define dllist_foreach(var, list) \ for (struct dll_entry *_dle = (list)->head; _dle && (var = (typeof(var))_dle->item); _dle = _dle->next) extern struct dllist *dllist_create(); extern void *dllist_new(struct dllist *list, void *item, size_t size, int prepend); extern void dllist_remove(struct dllist *list, void *item); extern void dllist_clear(struct dllist *list); extern void dllist_destroy(struct dllist *list); #endif
[ "jarasz.kevwargo@gmail.com" ]
jarasz.kevwargo@gmail.com
d55b6ba0d25405ab316567c890d45f7c206450dc
12c593b92674fda381d4a1052781914a5f3bba4a
/VerneRefreshTableView/Controls/EGO/EGORefreshConstant.h
0636fb159e20f1dae601ddcf3609e63f4853a7ea
[]
no_license
vernepung/VerneRefreshTableViewByEgoRefresh
f960ebb2ff7b35b23e7445f5de32288ec8529b0e
4d530b3f1bc87721f61a64d7b362dda45fd9f8e2
refs/heads/master
2020-04-05T04:29:41.981659
2015-04-29T03:52:10
2015-04-29T03:52:10
34,736,165
1
0
null
null
null
null
UTF-8
C
false
false
797
h
// // EGORefreshConstant.h // UITabViewDemo // // Created by Bob on 14-4-23. // Copyright (c) 2014年 guobo. All rights reserved. // #ifndef UITabViewDemo_EGORefreshConstant_h #define UITabViewDemo_EGORefreshConstant_h #define TEXT_PULL_UP_TITLE @"下拉刷新" #define TEXT_PULL_UP_RELEX @"松开即可刷新" #define TEXT_PULL_LOADING @"加载中..." //typedef enum //{ // EGOPULLHEADVIEW_STYLE_ROTATE_IMAGE=0,//旋转图片 // EGOPULLHEADVIEW_STYLE_ACTIVITY_VIEW=1//UIActivityIndicatorView //}EGOPULLHEADVIEW_STYLE; typedef enum{ /** * 正在拉动 */ EGOOPullRefreshPulling = 0, /** * 已经超出刷新offsetY的临界值 */ EGOOPullRefreshNormal, /** * 正在执行动画 */ EGOOPullRefreshLoading, } EGOPullRefreshState; #endif
[ "vernepung@hotmail.com" ]
vernepung@hotmail.com
00ad7f9ace533dc2ec9ee4f51795cc6dd48ab4a6
37051470adf20f7de7cc8bc068152ee9cd34579c
/src/tor/src/lib/encoding/time_fmt.c
573dfaad8281e4a29a8589be0805d95c1b5db0d8
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-maxmind-odl", "GPL-2.0-or-later", "OpenSSL", "Autoconf-exception-generic", "NCSA", "ISC", "BSD-2-Clause" ]
permissive
noirofficial/noir
6f1b8ed4b58a37d5e8cb793550b1455651a51abd
e30c03e6b77fe6173cf0c4890ecd7d3681c9abed
refs/heads/master
2022-06-13T19:58:07.656991
2020-10-13T17:46:46
2020-10-13T17:46:46
149,126,565
24
18
MIT
2022-06-06T19:17:36
2018-09-17T13:06:49
C++
UTF-8
C
false
false
15,270
c
/* Copyright (c) 2001, Matej Pfajfar. * Copyright (c) 2001-2004, Roger Dingledine. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. * Copyright (c) 2007-2020, The Tor Project, Inc. */ /* See LICENSE for licensing information */ /** * \file time_fmt.c * * \brief Encode and decode time in various formats. * * This module is higher-level than the conversion functions in "wallclock", * and handles a larger variety of types. It converts between different time * formats, and encodes and decodes them from strings. **/ #include "lib/encoding/time_fmt.h" #include "lib/log/log.h" #include "lib/log/escape.h" #include "lib/log/util_bug.h" #include "lib/malloc/malloc.h" #include "lib/string/printf.h" #include "lib/string/scanf.h" #include "lib/wallclock/time_to_tm.h" #include <string.h> #include <time.h> #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef _WIN32 /* For struct timeval */ #include <winsock2.h> #endif /** As localtime_r, but defined for platforms that don't have it: * * Convert *<b>timep</b> to a struct tm in local time, and store the value in * *<b>result</b>. Return the result on success, or NULL on failure. * * Treat malformatted inputs localtime outputs as a BUG. */ struct tm * tor_localtime_r(const time_t *timep, struct tm *result) { char *err = NULL; struct tm *r = tor_localtime_r_msg(timep, result, &err); if (err) { log_warn(LD_BUG, "%s", err); tor_free(err); } return r; } /** As gmtime_r, but defined for platforms that don't have it: * * Convert *<b>timep</b> to a struct tm in UTC, and store the value in * *<b>result</b>. Return the result on success, or NULL on failure. * * Treat malformatted inputs or gmtime outputs as a BUG. */ struct tm * tor_gmtime_r(const time_t *timep, struct tm *result) { char *err = NULL; struct tm *r = tor_gmtime_r_msg(timep, result, &err); if (err) { log_warn(LD_BUG, "%s", err); tor_free(err); } return r; } /** Yield true iff <b>y</b> is a leap-year. */ #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400))) /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */ static int n_leapdays(int year1, int year2) { --year1; --year2; return (year2/4 - year1/4) - (year2/100 - year1/100) + (year2/400 - year1/400); } /** Number of days per month in non-leap year; used by tor_timegm and * parse_rfc1123_time. */ static const int days_per_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /** Compute a time_t given a struct tm. The result is given in UTC, and * does not account for leap seconds. Return 0 on success, -1 on failure. */ int tor_timegm(const struct tm *tm, time_t *time_out) { /* This is a pretty ironclad timegm implementation, snarfed from Python2.2. * It's way more brute-force than fiddling with tzset(). * * We use int64_t rather than time_t to avoid overflow on multiplication on * platforms with 32-bit time_t. Since year is clipped to INT32_MAX, and * since 365 * 24 * 60 * 60 is approximately 31 million, it's not possible * for INT32_MAX years to overflow int64_t when converted to seconds. */ int64_t year, days, hours, minutes, seconds; int i, invalid_year, dpm; /* Initialize time_out to 0 for now, to avoid bad usage in case this function fails and the caller ignores the return value. */ tor_assert(time_out); *time_out = 0; /* avoid int overflow on addition */ if (tm->tm_year < INT32_MAX-1900) { year = tm->tm_year + 1900; } else { /* clamp year */ year = INT32_MAX; } invalid_year = (year < 1970 || tm->tm_year >= INT32_MAX-1900); if (tm->tm_mon >= 0 && tm->tm_mon <= 11) { dpm = days_per_month[tm->tm_mon]; if (tm->tm_mon == 1 && !invalid_year && IS_LEAPYEAR(tm->tm_year)) { dpm = 29; } } else { /* invalid month - default to 0 days per month */ dpm = 0; } if (invalid_year || tm->tm_mon < 0 || tm->tm_mon > 11 || tm->tm_mday < 1 || tm->tm_mday > dpm || tm->tm_hour < 0 || tm->tm_hour > 23 || tm->tm_min < 0 || tm->tm_min > 59 || tm->tm_sec < 0 || tm->tm_sec > 60) { log_warn(LD_BUG, "Out-of-range argument to tor_timegm"); return -1; } days = 365 * (year-1970) + n_leapdays(1970,(int)year); for (i = 0; i < tm->tm_mon; ++i) days += days_per_month[i]; if (tm->tm_mon > 1 && IS_LEAPYEAR(year)) ++days; days += tm->tm_mday - 1; hours = days*24 + tm->tm_hour; minutes = hours*60 + tm->tm_min; seconds = minutes*60 + tm->tm_sec; /* Check that "seconds" will fit in a time_t. On platforms where time_t is * 32-bit, this check will fail for dates in and after 2038. * * We already know that "seconds" can't be negative because "year" >= 1970 */ #if SIZEOF_TIME_T < 8 if (seconds < TIME_MIN || seconds > TIME_MAX) { log_warn(LD_BUG, "Result does not fit in tor_timegm"); return -1; } #endif /* SIZEOF_TIME_T < 8 */ *time_out = (time_t)seconds; return 0; } /* strftime is locale-specific, so we need to replace those parts */ /** A c-locale array of 3-letter names of weekdays, starting with Sun. */ static const char *WEEKDAY_NAMES[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; /** A c-locale array of 3-letter names of months, starting with Jan. */ static const char *MONTH_NAMES[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; /** Set <b>buf</b> to the RFC1123 encoding of the UTC value of <b>t</b>. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long. * * (RFC1123 format is "Fri, 29 Sep 2006 15:54:20 GMT". Note the "GMT" * rather than "UTC".) */ void format_rfc1123_time(char *buf, time_t t) { struct tm tm; tor_gmtime_r(&t, &tm); strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm); tor_assert(tm.tm_wday >= 0); tor_assert(tm.tm_wday <= 6); memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3); tor_assert(tm.tm_mon >= 0); tor_assert(tm.tm_mon <= 11); memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3); } /** Parse the (a subset of) the RFC1123 encoding of some time (in UTC) from * <b>buf</b>, and store the result in *<b>t</b>. * * Note that we only accept the subset generated by format_rfc1123_time above, * not the full range of formats suggested by RFC 1123. * * Return 0 on success, -1 on failure. */ int parse_rfc1123_time(const char *buf, time_t *t) { struct tm tm; char month[4]; char weekday[4]; int i, m, invalid_year; unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec; unsigned dpm; if (strlen(buf) != RFC1123_TIME_LEN) return -1; memset(&tm, 0, sizeof(tm)); if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday, &tm_mday, month, &tm_year, &tm_hour, &tm_min, &tm_sec) < 7) { char *esc = esc_for_log(buf); log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc); tor_free(esc); return -1; } m = -1; for (i = 0; i < 12; ++i) { if (!strcmp(month, MONTH_NAMES[i])) { m = i; break; } } if (m<0) { char *esc = esc_for_log(buf); log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc); tor_free(esc); return -1; } tm.tm_mon = m; invalid_year = (tm_year >= INT32_MAX || tm_year < 1970); tor_assert(m >= 0 && m <= 11); dpm = days_per_month[m]; if (m == 1 && !invalid_year && IS_LEAPYEAR(tm_year)) { dpm = 29; } if (invalid_year || tm_mday < 1 || tm_mday > dpm || tm_hour > 23 || tm_min > 59 || tm_sec > 60) { char *esc = esc_for_log(buf); log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc); tor_free(esc); return -1; } tm.tm_mday = (int)tm_mday; tm.tm_year = (int)tm_year; tm.tm_hour = (int)tm_hour; tm.tm_min = (int)tm_min; tm.tm_sec = (int)tm_sec; if (tm.tm_year < 1970) { /* LCOV_EXCL_START * XXXX I think this is dead code; we already checked for * invalid_year above. */ tor_assert_nonfatal_unreached(); char *esc = esc_for_log(buf); log_warn(LD_GENERAL, "Got invalid RFC1123 time %s. (Before 1970)", esc); tor_free(esc); return -1; /* LCOV_EXCL_STOP */ } tm.tm_year -= 1900; return tor_timegm(&tm, t); } /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>. * The buffer must be at least ISO_TIME_LEN+1 bytes long. * * (ISO8601 format is 2006-10-29 10:57:20) */ void format_local_iso_time(char *buf, time_t t) { struct tm tm; strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm)); } /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>. * The buffer must be at least ISO_TIME_LEN+1 bytes long. */ void format_iso_time(char *buf, time_t t) { struct tm tm; strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm)); } /** As format_local_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid * embedding an internal space. */ void format_local_iso_time_nospace(char *buf, time_t t) { format_local_iso_time(buf, t); buf[10] = 'T'; } /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid * embedding an internal space. */ void format_iso_time_nospace(char *buf, time_t t) { format_iso_time(buf, t); buf[10] = 'T'; } /** As format_iso_time_nospace, but include microseconds in decimal * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1 * bytes long. */ void format_iso_time_nospace_usec(char *buf, const struct timeval *tv) { tor_assert(tv); format_iso_time_nospace(buf, (time_t)tv->tv_sec); tor_snprintf(buf+ISO_TIME_LEN, 8, ".%06d", (int)tv->tv_usec); } /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>, * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on * failure. Ignore extraneous stuff in <b>cp</b> after the end of the time * string, unless <b>strict</b> is set. If <b>nospace</b> is set, * expect the YYYY-MM-DDTHH:MM:SS format. */ int parse_iso_time_(const char *cp, time_t *t, int strict, int nospace) { struct tm st_tm; unsigned int year=0, month=0, day=0, hour=0, minute=0, second=0; int n_fields; char extra_char, separator_char; n_fields = tor_sscanf(cp, "%u-%2u-%2u%c%2u:%2u:%2u%c", &year, &month, &day, &separator_char, &hour, &minute, &second, &extra_char); if (strict ? (n_fields != 7) : (n_fields < 7)) { char *esc = esc_for_log(cp); log_warn(LD_GENERAL, "ISO time %s was unparseable", esc); tor_free(esc); return -1; } if (separator_char != (nospace ? 'T' : ' ')) { char *esc = esc_for_log(cp); log_warn(LD_GENERAL, "ISO time %s was unparseable", esc); tor_free(esc); return -1; } if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 60 || year >= INT32_MAX) { char *esc = esc_for_log(cp); log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc); tor_free(esc); return -1; } st_tm.tm_year = (int)year-1900; st_tm.tm_mon = month-1; st_tm.tm_mday = day; st_tm.tm_hour = hour; st_tm.tm_min = minute; st_tm.tm_sec = second; st_tm.tm_wday = 0; /* Should be ignored. */ if (st_tm.tm_year < 70) { /* LCOV_EXCL_START * XXXX I think this is dead code; we already checked for * year < 1970 above. */ tor_assert_nonfatal_unreached(); char *esc = esc_for_log(cp); log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc); tor_free(esc); return -1; /* LCOV_EXCL_STOP */ } return tor_timegm(&st_tm, t); } /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>, * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on * failure. Reject the string if any characters are present after the time. */ int parse_iso_time(const char *cp, time_t *t) { return parse_iso_time_(cp, t, 1, 0); } /** * As parse_iso_time, but parses a time encoded by format_iso_time_nospace(). */ int parse_iso_time_nospace(const char *cp, time_t *t) { return parse_iso_time_(cp, t, 1, 1); } /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh), * parse it into <b>tm</b>. Return 0 on success, negative on failure. */ int parse_http_time(const char *date, struct tm *tm) { const char *cp; char month[4]; char wkday[4]; int i; unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec; tor_assert(tm); memset(tm, 0, sizeof(*tm)); /* First, try RFC1123 or RFC850 format: skip the weekday. */ if ((cp = strchr(date, ','))) { ++cp; if (*cp != ' ') return -1; ++cp; if (tor_sscanf(cp, "%2u %3s %4u %2u:%2u:%2u GMT", &tm_mday, month, &tm_year, &tm_hour, &tm_min, &tm_sec) == 6) { /* rfc1123-date */ tm_year -= 1900; } else if (tor_sscanf(cp, "%2u-%3s-%2u %2u:%2u:%2u GMT", &tm_mday, month, &tm_year, &tm_hour, &tm_min, &tm_sec) == 6) { /* rfc850-date */ } else { return -1; } } else { /* No comma; possibly asctime() format. */ if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u", wkday, month, &tm_mday, &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) { tm_year -= 1900; } else { return -1; } } tm->tm_mday = (int)tm_mday; tm->tm_year = (int)tm_year; tm->tm_hour = (int)tm_hour; tm->tm_min = (int)tm_min; tm->tm_sec = (int)tm_sec; tm->tm_wday = 0; /* Leave this unset. */ month[3] = '\0'; /* Okay, now decode the month. */ /* set tm->tm_mon to dummy value so the check below fails. */ tm->tm_mon = -1; for (i = 0; i < 12; ++i) { if (!strcasecmp(MONTH_NAMES[i], month)) { tm->tm_mon = i; } } if (tm->tm_year < 0 || tm->tm_mon < 0 || tm->tm_mon > 11 || tm->tm_mday < 1 || tm->tm_mday > 31 || tm->tm_hour < 0 || tm->tm_hour > 23 || tm->tm_min < 0 || tm->tm_min > 59 || tm->tm_sec < 0 || tm->tm_sec > 60) return -1; /* Out of range, or bad month. */ return 0; } /** Given an <b>interval</b> in seconds, try to write it to the * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form. * Returns a non-negative integer on success, -1 on failure. */ int format_time_interval(char *out, size_t out_len, long interval) { /* We only report seconds if there's no hours. */ long sec = 0, min = 0, hour = 0, day = 0; /* -LONG_MIN is LONG_MAX + 1, which causes signed overflow */ if (interval < -LONG_MAX) interval = LONG_MAX; else if (interval < 0) interval = -interval; if (interval >= 86400) { day = interval / 86400; interval %= 86400; } if (interval >= 3600) { hour = interval / 3600; interval %= 3600; } if (interval >= 60) { min = interval / 60; interval %= 60; } sec = interval; if (day) { return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes", day, hour, min); } else if (hour) { return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min); } else if (min) { return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec); } else { return tor_snprintf(out, out_len, "%ld seconds", sec); } }
[ "flo071@gmx.at" ]
flo071@gmx.at
3a5125d89c8361432b24fa991f254d0b962e2263
fc81e71c194404696b40a13aa6aaf7d5490c95ae
/Laba12. 1 201-726.c
b03808241412cc98058f5cd152d359128c7332f9
[]
no_license
Wevepon3/Podkolodnikov
3df271af2b7dc76dd29d17982df5bd68e237bea0
f8394ea8f81637987764ca0eabb413f9d1bcffdc
refs/heads/master
2023-02-08T14:03:07.823099
2020-12-17T17:44:31
2020-12-17T17:44:31
298,334,779
0
0
null
null
null
null
UTF-8
C
false
false
2,274
c
#include <locale.h> #include <stdio.h> #include <math.h> main() { setlocale(LC_ALL, "Rus"); int x, y, z, g; int k, c; printf("X (день) - "); scanf_s("%i", &x); printf("y (месяц) - "); scanf_s("%i", &y); g = x / 10; //десяток z = x % 10; //еденицы k = 0; while ((x > 10) && (x < 20)) { switch (x) { case(11): printf("Одиннадцатое "); break; case(12): printf("Двенадцатое "); break; case(13): printf("Тринадцатое "); break; case(14): printf("Четырнадцатое "); break; case(15): printf("Пятнадцатое "); break; case(16): printf("Шестнадцатое "); break; case(17): printf("Семнадцатое "); break; case(18): printf("Восемнадцатое "); break; case(19): printf("Девятнадцатое "); break; } k = 1; break; } if (k != 1) { switch (g) { case(1): printf("Десятое "); break; case(2): printf("Двадцать "); break; case(3): printf("Тридцать "); break; } switch (z) { case(1): printf("Первое "); break; case(2): printf("Второе "); break; case(3): printf("Третье "); break; case(4): printf("Четвертое "); break; case(5): printf("Пятое "); break; case(6): printf("Шестое "); break; case(7): printf("Седьмое "); break; case(8): printf("Восьмое "); break; case(9): printf("Девятое "); } } switch (y) { case(1): printf("Января"); break; case(2): printf("Февраля"); break; case(3): printf("Марта"); break; case(4): printf("Апреля"); break; case(5): printf("Мая"); break; case(6): printf("Июня"); break; case(7): printf("Июля"); break; case(8): printf("Августа"); break; case(9): printf("Сентября"); break; case(10): printf("Октября"); break; case(11): printf("Ноября"); break; case(12): printf("Декабря"); break; } }
[ "noreply@github.com" ]
Wevepon3.noreply@github.com
6b0f1293631790dab657be358b6a1bd2f14ba42e
3d9eff985b33d617a1c73ea0a78ea62594a309c6
/libraries/net/https/axTLS/ssl/gen_cert.c
c2fe381eb944635b8b80b5c53a475498d23306ad
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
IlliniSolarCar/mbed
1dfd83d93eb3fb1f5c405c11866958feac477ca0
58a1f8e76c443988eadae3447d4c7681266edb80
refs/heads/master
2023-05-15T02:47:06.532504
2022-06-16T18:53:17
2022-06-16T18:53:17
201,303,329
4
0
Apache-2.0
2022-06-16T18:53:18
2019-08-08T17:10:08
C
UTF-8
C
false
false
11,235
c
/* * Copyright (c) 2007, Cameron Rich * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the axTLS project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #include "config.h" #ifdef CONFIG_SSL_GENERATE_X509_CERT #include <string.h> #include <stdlib.h> #include "os_port.h" #include "ssl.h" /** * Generate a basic X.509 certificate */ static uint8_t set_gen_length(int len, uint8_t *buf, int *offset) { if (len < 0x80) /* short form */ { buf[(*offset)++] = len; return 1; } else /* long form */ { int i, length_bytes = 0; if (len & 0x00FF0000) length_bytes = 3; else if (len & 0x0000FF00) length_bytes = 2; else if (len & 0x000000FF) length_bytes = 1; buf[(*offset)++] = 0x80 + length_bytes; for (i = length_bytes-1; i >= 0; i--) { buf[*offset+i] = len & 0xFF; len >>= 8; } *offset += length_bytes; return length_bytes+1; } } static int pre_adjust_with_size(uint8_t type, int *seq_offset, uint8_t *buf, int *offset) { buf[(*offset)++] = type; *seq_offset = *offset; *offset += 4; /* fill in later */ return *offset; } static void adjust_with_size(int seq_size, int seq_start, uint8_t *buf, int *offset) { uint8_t seq_byte_size; int orig_seq_size = seq_size; int orig_seq_start = seq_start; seq_size = *offset-seq_size; seq_byte_size = set_gen_length(seq_size, buf, &seq_start); if (seq_byte_size != 4) { memmove(&buf[orig_seq_start+seq_byte_size], &buf[orig_seq_size], seq_size); *offset -= 4-seq_byte_size; } } static void gen_serial_number(uint8_t *buf, int *offset) { static const uint8_t ser_oid[] = { ASN1_INTEGER, 1, 0x7F }; memcpy(&buf[*offset], ser_oid , sizeof(ser_oid)); *offset += sizeof(ser_oid); } static void gen_signature_alg(uint8_t *buf, int *offset) { /* OBJECT IDENTIFIER sha1withRSAEncryption (1 2 840 113549 1 1 5) */ static const uint8_t sig_oid[] = { ASN1_SEQUENCE, 0x0d, ASN1_OID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, ASN1_NULL, 0x00 }; memcpy(&buf[*offset], sig_oid, sizeof(sig_oid)); *offset += sizeof(sig_oid); } static int gen_dn(const char *name, uint8_t dn_type, uint8_t *buf, int *offset) { int ret = X509_OK; int name_size = strlen(name); if (name_size > 0x70) /* just too big */ { ret = X509_NOT_OK; goto error; } buf[(*offset)++] = ASN1_SET; set_gen_length(9+name_size, buf, offset); buf[(*offset)++] = ASN1_SEQUENCE; set_gen_length(7+name_size, buf, offset); buf[(*offset)++] = ASN1_OID; buf[(*offset)++] = 3; buf[(*offset)++] = 0x55; buf[(*offset)++] = 0x04; buf[(*offset)++] = dn_type; buf[(*offset)++] = ASN1_PRINTABLE_STR; buf[(*offset)++] = name_size; strcpy(&buf[*offset], name); *offset += name_size; error: return ret; } static int gen_issuer(const char * dn[], uint8_t *buf, int *offset) { int ret = X509_OK; int seq_offset; int seq_size = pre_adjust_with_size( ASN1_SEQUENCE, &seq_offset, buf, offset); char fqdn[128]; /* we need the common name, so if not configured, work out the fully * qualified domain name */ if (dn[X509_COMMON_NAME] == NULL || strlen(dn[X509_COMMON_NAME]) == 0) { int fqdn_len; gethostname(fqdn, sizeof(fqdn)); fqdn_len = strlen(fqdn); fqdn[fqdn_len++] = '.'; getdomainname(&fqdn[fqdn_len], sizeof(fqdn)-fqdn_len); fqdn_len = strlen(fqdn); if (fqdn[fqdn_len-1] == '.') /* ensure '.' is not last char */ fqdn[fqdn_len-1] = 0; dn[X509_COMMON_NAME] = fqdn; } if ((ret = gen_dn(dn[X509_COMMON_NAME], 3, buf, offset))) goto error; if (dn[X509_ORGANIZATION] != NULL && strlen(dn[X509_ORGANIZATION]) > 0) { if ((ret = gen_dn(dn[X509_ORGANIZATION], 10, buf, offset))) goto error; } if (dn[X509_ORGANIZATIONAL_UNIT] != NULL && strlen(dn[X509_ORGANIZATIONAL_UNIT]) > 0) { if ((ret = gen_dn(dn[X509_ORGANIZATIONAL_UNIT], 11, buf, offset))) goto error; } adjust_with_size(seq_size, seq_offset, buf, offset); error: return ret; } static void gen_utc_time(uint8_t *buf, int *offset) { static const uint8_t time_seq[] = { ASN1_SEQUENCE, 30, ASN1_UTC_TIME, 13, '0', '7', '0', '1', '0', '1', '0', '0', '0', '0', '0', '0', 'Z', ASN1_UTC_TIME, 13, /* make it good for 30 or so years */ '3', '8', '0', '1', '0', '1', '0', '0', '0', '0', '0', '0', 'Z' }; /* fixed time */ memcpy(&buf[*offset], time_seq, sizeof(time_seq)); *offset += sizeof(time_seq); } static void gen_pub_key2(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset) { static const uint8_t pub_key_seq[] = { ASN1_INTEGER, 0x03, 0x01, 0x00, 0x01 /* INTEGER 65537 */ }; int seq_offset; int pub_key_size = rsa_ctx->num_octets; uint8_t *block = (uint8_t *)alloca(pub_key_size); int seq_size = pre_adjust_with_size( ASN1_SEQUENCE, &seq_offset, buf, offset); buf[(*offset)++] = ASN1_INTEGER; bi_export(rsa_ctx->bi_ctx, rsa_ctx->m, block, pub_key_size); if (*block & 0x80) /* make integer positive */ { set_gen_length(pub_key_size+1, buf, offset); buf[(*offset)++] = 0; } else set_gen_length(pub_key_size, buf, offset); memcpy(&buf[*offset], block, pub_key_size); *offset += pub_key_size; memcpy(&buf[*offset], pub_key_seq, sizeof(pub_key_seq)); *offset += sizeof(pub_key_seq); adjust_with_size(seq_size, seq_offset, buf, offset); } static void gen_pub_key1(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset) { int seq_offset; int seq_size = pre_adjust_with_size( ASN1_BIT_STRING, &seq_offset, buf, offset); buf[(*offset)++] = 0; /* bit string is multiple of 8 */ gen_pub_key2(rsa_ctx, buf, offset); adjust_with_size(seq_size, seq_offset, buf, offset); } static void gen_pub_key(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset) { /* OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1) */ static const uint8_t rsa_enc_oid[] = { ASN1_SEQUENCE, 0x0d, ASN1_OID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, ASN1_NULL, 0x00 }; int seq_offset; int seq_size = pre_adjust_with_size( ASN1_SEQUENCE, &seq_offset, buf, offset); memcpy(&buf[*offset], rsa_enc_oid, sizeof(rsa_enc_oid)); *offset += sizeof(rsa_enc_oid); gen_pub_key1(rsa_ctx, buf, offset); adjust_with_size(seq_size, seq_offset, buf, offset); } static void gen_signature(const RSA_CTX *rsa_ctx, const uint8_t *sha_dgst, uint8_t *buf, int *offset) { static const uint8_t asn1_sig[] = { ASN1_SEQUENCE, 0x21, ASN1_SEQUENCE, 0x09, ASN1_OID, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, /* sha1 (1 3 14 3 2 26) */ ASN1_NULL, 0x00, ASN1_OCTET_STRING, 0x14 }; uint8_t *enc_block = (uint8_t *)alloca(rsa_ctx->num_octets); uint8_t *block = (uint8_t *)alloca(sizeof(asn1_sig) + SHA1_SIZE); int sig_size; /* add the digest as an embedded asn.1 sequence */ memcpy(block, asn1_sig, sizeof(asn1_sig)); memcpy(&block[sizeof(asn1_sig)], sha_dgst, SHA1_SIZE); sig_size = RSA_encrypt(rsa_ctx, block, sizeof(asn1_sig) + SHA1_SIZE, enc_block, 1); buf[(*offset)++] = ASN1_BIT_STRING; set_gen_length(sig_size+1, buf, offset); buf[(*offset)++] = 0; /* bit string is multiple of 8 */ memcpy(&buf[*offset], enc_block, sig_size); *offset += sig_size; } static int gen_tbs_cert(const char * dn[], const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset, uint8_t *sha_dgst) { int ret = X509_OK; SHA1_CTX sha_ctx; int seq_offset; int begin_tbs = *offset; int seq_size = pre_adjust_with_size( ASN1_SEQUENCE, &seq_offset, buf, offset); gen_serial_number(buf, offset); gen_signature_alg(buf, offset); /* CA certicate issuer */ if ((ret = gen_issuer(dn, buf, offset))) goto error; gen_utc_time(buf, offset); /* certificate issuer */ if ((ret = gen_issuer(dn, buf, offset))) goto error; gen_pub_key(rsa_ctx, buf, offset); adjust_with_size(seq_size, seq_offset, buf, offset); SHA1_Init(&sha_ctx); SHA1_Update(&sha_ctx, &buf[begin_tbs], *offset-begin_tbs); SHA1_Final(sha_dgst, &sha_ctx); error: return ret; } /** * Create a new certificate. */ EXP_FUNC int STDCALL ssl_x509_create(SSL_CTX *ssl_ctx, uint32_t options, const char * dn[], uint8_t **cert_data) { int ret = X509_OK, offset = 0, seq_offset; /* allocate enough space to load a new certificate */ uint8_t *buf = (uint8_t *)alloca(ssl_ctx->rsa_ctx->num_octets*2 + 512); uint8_t sha_dgst[SHA1_SIZE]; int seq_size = pre_adjust_with_size(ASN1_SEQUENCE, &seq_offset, buf, &offset); if ((ret = gen_tbs_cert(dn, ssl_ctx->rsa_ctx, buf, &offset, sha_dgst)) < 0) goto error; gen_signature_alg(buf, &offset); gen_signature(ssl_ctx->rsa_ctx, sha_dgst, buf, &offset); adjust_with_size(seq_size, seq_offset, buf, &offset); *cert_data = (uint8_t *)malloc(offset); /* create the exact memory for it */ memcpy(*cert_data, buf, offset); error: return ret < 0 ? ret : offset; } #endif
[ "bogdan.marinescu@arm.com" ]
bogdan.marinescu@arm.com
016c258c246652b4d834293d1b91c9879a0c219d
555422ac465e1325b598bed32a7307abd5b649c1
/src/uml/connection_point_reference.h
a9a5d60291577e95187e61077ab7ded31b725049
[ "MIT" ]
permissive
Quicksilver-Project/quicksilveruml
f73d072c6950d597743aa4ca99947c267d54d9cc
c9019443360c98c61edbd60c93cf2c1701912c2e
refs/heads/master
2020-04-10T03:24:47.202448
2018-12-12T04:51:57
2018-12-12T04:51:57
160,769,500
0
1
null
null
null
null
UTF-8
C
false
false
666
h
/**~state machine~ * A_connection_state [Association] * * Diagrams * * Behavior State Machines * * Member Ends * *  State::connection * *  ConnectionPointReference::state **/ /** * A_entry_connectionPointReference [Association] * * Diagrams * * Behavior State Machines * * Owned Ends * *  connectionPointReference : ConnectionPointReference [0..1] (opposite ConnectionPointReference::entry) **/ /** * A_exit_connectionPointReference [Association] * * Diagrams * * Behavior State Machines * * Owned Ends * *  connectionPointReference : ConnectionPointReference [0..1] (opposite ConnectionPointReference::exit) **/
[ "logan.campos123@gmail.com" ]
logan.campos123@gmail.com
ac87e51a0115c08a4536e4d597bf50ddcb1d61b8
e44893a8c331d7d50b3b6a0608eb90be645e0de6
/裸板/Relocate/usart.c
504d3794f48b8c575c342c3fd1b1f74fe7ca81fe
[]
no_license
tangwangCHR/All-come-in
9c29c7009823f18ed7ec45c5b4b8668b5d145aa6
2cca49a6de2f5e5ccadec648722fe585380ed8b8
refs/heads/master
2020-04-08T23:01:45.713432
2018-12-24T11:19:24
2018-12-24T11:19:24
159,808,532
0
0
null
null
null
null
GB18030
C
false
false
904
c
#include "usart.h" #include "s3c2440_soc.h" /* * TXD0 RXD0 TXD1 RXD1 TXD2 RXD2 * PH2 PH3 PH4 PH5 PH6 PH7 */ void usart0_init() { GPHCON &= ~((3<<4)|(3<<6)); //设置PH2 PH3 工作在串口模式 GPHCON |= ((2<<4)|(2<<6)); GPHUP &= ~((1<<2)|(1<<3)); //使能上拉功能 ULCON0 |= 0x3; //8n1 UCON0 |=5<<0; //PCLK作为串口时钟 50Mhz UBRDIV0 =26; //波特率115200 } int putchar(int c) //输出一个字符 发送 { while(!(UTRSTAT0&(1<<2))); //等待发送完成 UTXH0=(unsigned char)c; } int getchar(void) //得到一个字符 接收 { while (!(UTRSTAT0 & (1<<0))); // 缓冲寄存器接收到有效数据 return URXH0; } int puts(const char *s) { while(*s) { putchar(*s); s++; } }
[ "1157727586@qq.com" ]
1157727586@qq.com
d6457bf164d79140766250005dc23c33930bc7c5
42ed1af689163cce9909a55fafcd69a0543c09c9
/TestCase/UEFI/IHV/Protocol/DriverSupportedEfiVersion/BlackBoxTest/DriverSupportedEfiVersionProtocol.h
6e8c1c9a1e2a4afad17d7f1a048293fd1a4aab6c
[]
no_license
sjtupt/2ndProject
933ba01b30068b9fd9c39696f77dc3655ce5ff8f
f4de5400b9922e42ac3263ddf34021a3822ff418
refs/heads/master
2021-01-18T14:16:04.685713
2013-10-29T05:25:32
2013-10-29T05:25:32
13,824,155
1
1
null
null
null
null
UTF-8
C
false
false
3,459
h
/*++ The material contained herein is not a license, either expressly or impliedly, to any intellectual property owned or controlled by any of the authors or developers of this material or to any contribution thereto. The material contained herein is provided on an "AS IS" basis and, to the maximum extent permitted by applicable law, this information is provided AS IS AND WITH ALL FAULTS, and the authors and developers of this material hereby disclaim all other warranties and conditions, either express, implied or statutory, including, but not limited to, any (if any) implied warranties, duties or conditions of merchantability, of fitness for a particular purpose, of accuracy or completeness of responses, of results, of workmanlike effort, of lack of viruses and of lack of negligence, all with regard to this material and any contribution thereto. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined." The Unified EFI Forum, Inc. reserves any features or instructions so marked for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. ALSO, THERE IS NO WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT, QUIET POSSESSION, CORRESPONDENCE TO DESCRIPTION OR NON-INFRINGEMENT WITH REGARD TO THE TEST SUITE AND ANY CONTRIBUTION THERETO. IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THIS MATERIAL OR ANY CONTRIBUTION THERETO BE LIABLE TO ANY OTHER PARTY FOR THE COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT, INDIRECT, OR SPECIAL DAMAGES WHETHER UNDER CONTRACT, TORT, WARRANTY, OR OTHERWISE, ARISING IN ANY WAY OUT OF THIS OR ANY OTHER AGREEMENT RELATING TO THIS DOCUMENT, WHETHER OR NOT SUCH PARTY HAD ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. Copyright 2006 - 2012 Unified EFI, Inc. All Rights Reserved, subject to all existing rights in all matters included within this Test Suite, to which United EFI, Inc. makes no claim of right. Copyright (c) 2010 - 2012, Byosoft Corporation. All rights reserved.<BR> --*/ /*++ Module Name: DriverSupportedEfiVersionProtocol.h Abstract: Driver Support Efi Version Protocol(define according to the UEFI Spec 2.1 ) --*/ #ifndef _DRIVER_SUPPORTED_EFI_VERSION_FOR_TEST_H_ #define _DRIVER_SUPPORTED_EFI_VERSION_FOR_TEST_H_ //#include EFI_PROTOCOL_DEFINITION (DebugSupport) #define EFI_DRIVER_SUPPORTED_EFI_VERSION_PROTOCOL_GUID \ { 0x5c198761, 0x16a8, 0x4e69, 0x97, 0x2c, 0x89, 0xd6, 0x79, 0x54, 0xf8, 0x1d } EFI_FORWARD_DECLARATION(EFI_DRIVER_SUPPORTED_EFI_VERSION_PROTOCOL); struct _EFI_DRIVER_SUPPORTED_EFI_VERSION_PROTOCOL { UINT32 Length; UINT32 FirmwareVersion; }; extern EFI_GUID gEfiDriverSupportedEfiVersionProtocolGuid; #endif
[ "eric.jingjin@gmail.com" ]
eric.jingjin@gmail.com
1b04c1d0856828c1a1ffdbd3db23741c2149906d
b945b2fac11f237a49de33af1b8fa02ba3ed1814
/legacy/ris/riscli/dict/dicclsch.c
1fddda7ecd6be0818a0730e8faeb01be43852304
[]
no_license
ahundiak/isdp
b94f56f7a7b02b806209ff06da8e22497f6e1386
07572eb18f07cbf762505ef34e471fa47c102df4
refs/heads/master
2021-03-12T20:02:34.067237
2011-12-16T20:03:20
2011-12-16T20:03:20
37,136,442
0
0
null
null
null
null
UTF-8
C
false
false
3,865
c
/* ** NAME: DICclose_sch.c ** AUTHORS: David Michal ** CREATION DATE: 10/90 ** ABSTRACT: ** ** ** REVISION HISTORY: */ /* ** INCLUDES */ #include "risasync.h" #include "rismem.h" #include "ristoken.h" #include "dict.h" /* ** DEFINES */ /* ** VARIABLES */ /* ** FUNCTIONS */ /* ** FUNCTION PROTOTYPES */ #define dicclsch_c #include "ccoschid.prt" #include "ccosqlca.prt" #include "comfree.prt" #include "comdebug.prt" #include "comjmp.prt" #include "dicclsch.prt" #include "dicrem.prt" #include "diclook.prt" #include "dictrans.prt" #include "dicundss.prt" #include "filtrans.prt" #include "usrkill.prt" #include "sys.prt" /******************************************************************************/ extern void RISdic_close_schema( char *schname, int exec_mode) { int status; risschema *schema; rissuperschema *ss_schema; DIC_DBG(("RISdic_close_schema(schname:<%s> exec_mode:%d)\n", STRING(schname), exec_mode)); status = SETJMP(); if (status) { RESETJMP(); RIScco_push_risca_dbca(); RISdic_rollback_hash(); RISfil_rollback_schema_transact(); RIScco_pop_risca_dbca(); LONGJMP(status); } /* if its a superschema dont proceed further */ if (IN_START_MODE(exec_mode) && (ss_schema=RISdic_find_supersch(schname))) { LONGJMP(RIS_E_CANT_EXEC_STMT_ON_SUPERSCHEMA); } schema = RISdic_lookup_schema(schname, HASH_TABLE); if (schema) { if (IN_START_MODE(exec_mode) && (schema->superschema_flag == PRIMARY_SCHEMA || schema->superschema_flag == SECONDARY_SCHEMA)) { LONGJMP(RIS_E_CANT_EXEC_STMT_ON_SUPERSCHEMA); } RISusr_kill_srv(schema,CLOSE_SCHEMA|CLEAR_SCHEMA|CLOSE_NET, exec_mode); /* ** Added a check by calling RISdic_lookup_schema again as the call to ** RISusr_kill_srv may have potentially removed the schema from the hash table ** if a RIS_E_SERVER_NOT_RESPONDING error was detected. - 12/25/92 */ schema = RISdic_lookup_schema(schname, HASH_TABLE); if (IN_FINISH_MODE(exec_mode)) { RISdic_remove_hash(RIS_TOK_SCHEMA, schema); } } else { if (!RISdic_lookup_schema(schname, SCHEMA_FILE)) { LONGJMP(RIS_E_UNKNOWN_SCHEMA); } } RESETJMP(); if (IN_FINISH_MODE(exec_mode)) { RISdic_commit_hash(); } RISfil_commit_schema_transact(); if (IN_FINISH_MODE(exec_mode)) { if (schema) { FREES(schema->schid); RIScco_clear_schema_id(schema->schid); } } DIC_DBG(("RISdic_close_schema:returning\n")); } /******************************************************************************/ extern void RISdic_close_mult_schemas( ristree * tp, int exec_mode) { DIC_DBG(("RISdic_close_mult_schemas(tp:0x%x exec_mode:0x%x)\n",tp,exec_mode)); if (tp->rhs->tok == RIS_TOK_ALL) { if (IN_START_MODE(exec_mode)) { RISdic_close_all_schemas(); } } else { for (tp=tp->rhs;tp;tp=tp->rhs) { if (tp->rhs) { if (IN_START_MODE(exec_mode)) { RISdic_close_schema(tp->lhs->info.val, SYNC_MODE); } } else { RISdic_close_schema(tp->lhs->info.val, exec_mode); } } } DIC_DBG(("RISdic_close_mult_schemas:returing\n")); } /******************************************************************************/ extern void RISdic_close_all_schemas() { risschema *schema, *next_schema; DIC_DBG(("RISdic_close_all_schemas()\n")); /* ** NOTE: We have to traverse the schema list in this strange way ** because RISdic_close_schema removes the schema from the ** list. By saving a pointer to the next schema, we won't ** loose our place in the list when this happens. */ schema = RIS_srvs; while(schema) { next_schema = schema->next; RISdic_close_schema(schema->schname, SYNC_MODE); schema = next_schema; } DIC_DBG(("RISdic_close_all_schemas:returing\n")); } /******************************************************************************/
[ "ahundiak@e9faf64c-7e38-11de-a453-d5a50d962d30" ]
ahundiak@e9faf64c-7e38-11de-a453-d5a50d962d30
cc088036c413533d2440f90dfde73d03c512a0b6
66173d6fe0a4a6e252ed3bbf8ea1b9ad446349ab
/srcs/colider/capsule_collider.c
0daff6d17043859e9b927f52cec16f93b77aca49
[]
no_license
juveron/Doom-Nukem
4bb2fee81aff900645df199b4408699b30f0aa9d
53b54bb8807077b7c2c7552a42386a6831cf8da3
refs/heads/master
2022-11-30T15:33:36.382717
2020-07-29T16:05:53
2020-07-29T16:05:53
280,649,328
1
0
null
null
null
null
UTF-8
C
false
false
3,017
c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* capsule_collider.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: thboura <thboura@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/28 12:04:07 by kguibout #+# #+# */ /* Updated: 2020/06/06 12:10:27 by thboura ### ########.fr */ /* */ /* ************************************************************************** */ #include "collider.h" static void init(t_segment_dist *dist) { dist->a = vec3f_dot(dist->u, dist->u); dist->b = vec3f_dot(dist->u, dist->v); dist->c = vec3f_dot(dist->v, dist->v); dist->d = vec3f_dot(dist->u, dist->w); dist->e = vec3f_dot(dist->v, dist->w); dist->caps_d = dist->a * dist->c - dist->b * dist->b; dist->sc = dist->caps_d; dist->sn = dist->caps_d; dist->sd = dist->caps_d; dist->tc = dist->caps_d; dist->tn = dist->caps_d; dist->td = dist->caps_d; } static void segment_dist_p2(t_segment_dist *dist) { if (dist->caps_d < 0.0000001f) { dist->sn = 0.f; dist->sd = 1.f; dist->tn = dist->e; dist->td = dist->c; } else { dist->sn = dist->b * dist->e - dist->c * dist->d; dist->tn = dist->a * dist->e - dist->b * dist->d; if (dist->sn < 0.f) { dist->sn = 0.f; dist->tn = dist->e; dist->td = dist->c; } else if (dist->sn > dist->sd) { dist->sn = dist->sd; dist->tn = dist->e + dist->b; dist->td = dist->c; } } } static void segment_dist_p3(t_segment_dist *dist) { dist->tn = 0.f; if (-dist->d < 0.f) dist->sn = 0.f; else if (-dist->d > dist->a) dist->sn = dist->sd; else { dist->sn = -dist->d; dist->sd = dist->a; } } static void segment_dist_p4(t_segment_dist *dist) { dist->tn = dist->td; if (-dist->d + dist->b < 0.f) dist->sn = 0.f; else if (-dist->d + dist->b > dist->a) dist->sn = dist->sd; else { dist->sn = -dist->d + dist->b; dist->sd = dist->a; } } t_vec3f segment_dist(const t_vec3f *s11, const t_vec3f *s12, const t_vec3f *s21, const t_vec3f *s22) { t_segment_dist dist; t_vec3f a; t_vec3f b; t_vec3f dp; dist.u = vec3f_sub(*s12, *s11); dist.v = vec3f_sub(*s22, *s21); dist.w = vec3f_sub(*s11, *s21); init(&dist); segment_dist_p2(&dist); if (dist.tn < 0.f) segment_dist_p3(&dist); else if (dist.tn > dist.td) segment_dist_p4(&dist); dist.sc = fabsf(dist.sn) < 0.0000001f ? 0.f : dist.sn / dist.sd; dist.tc = fabsf(dist.tn) < 0.0000001f ? 0.f : dist.tn / dist.td; a = vec3f_mul(dist.u, dist.sc); b = vec3f_mul(dist.v, dist.tc); dp = vec3f_add(dist.w, vec3f_sub(a, b)); return (dp); }
[ "juveron@student.42.fr" ]
juveron@student.42.fr
80ee56aaf55f093d17e3318c141eb45e5784e511
6b2ac45fe6031e925a8aa756170e376dbcefed77
/dns_he.c
61a2e825234e74561441bc9feffc51330ac00938
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
niklata/ndyndns
577096d2d86ee47a034732c2afbaaf9f92b64986
6b54d67c20165263f661a66894040e138aac541c
refs/heads/master
2023-01-31T09:16:00.860899
2023-01-08T01:47:50
2023-01-08T01:47:50
48,724,648
6
2
null
2017-11-13T15:20:18
2015-12-29T03:09:05
C
UTF-8
C
false
false
7,025
c
/* dns_he.c * * Copyright (c) 2010-2013 Nicholas J. Kain <njkain at gmail dot com> * 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include "config.h" #include "defines.h" #include "dns_he.h" #include "dns_helpers.h" #include "log.h" #include "util.h" #include "strl.h" #include "malloc.h" he_conf_t he_conf; void init_he_conf() { he_conf.userid = NULL; he_conf.passhash = NULL; he_conf.hostpairs = NULL; he_conf.tunlist = NULL; } static void modify_he_hostip_in_list(hostdata_t *t, char *host, char *ip) { if (!t || !host) return; for (; t && strcmp(t->host, host); t = t->next); if (t) { free(t->ip); t->ip = NULL; if (ip) { size_t len = strlen(ip) + 1; char *buf = xmalloc(len); strnkcpy(buf, ip, len); t->ip = buf; } } } static void modify_he_hostip_in_conf(he_conf_t *conf, char *host, char *ip) { if (conf) modify_he_hostip_in_list(conf->hostpairs, host, ip); } static void modify_he_hostdate_in_list(hostdata_t *t, char *host, time_t time) { if (!t || !host) return; for (; t && strcmp(t->host, host); t = t->next); if (t) t->date = time; } static void modify_he_hostdate_in_conf(he_conf_t *conf, char *host, time_t time) { if (conf) modify_he_hostdate_in_list(conf->hostpairs, host, time); } static void he_update_host(char *host, char *password, char *curip) { char url[MAX_BUF]; conn_data_t data; if (!host || !password || !curip) return; /* set up the authentication url */ if (use_ssl) DDCB_CPY(url, "https://"); else DDCB_CPY(url, "http://"); DDCB_CAT(url, host); DDCB_CAT(url, ":"); DDCB_CAT(url, password); DDCB_CAT(url, "@dyn.dns.he.net/nic/update?hostname="); DDCB_CAT(url, host); DDCB_CAT(url, "&myip="); DDCB_CAT(url, curip); data.buf = xmalloc(MAX_CHUNKS * CURL_MAX_WRITE_SIZE + 1); memset(data.buf, '\0', MAX_CHUNKS * CURL_MAX_WRITE_SIZE + 1); data.buflen = MAX_CHUNKS * CURL_MAX_WRITE_SIZE + 1; data.idx = 0; if (!dyndns_curl_send(url, &data, NULL)) { // "good x.x.x.x" is success log_line("response returned: [%s]", data.buf); if (strstr(data.buf, "good")) { log_line("%s: [good] - Update successful.", host); write_dnsip(host, curip); write_dnsdate(host, clock_time()); modify_he_hostdate_in_conf(&he_conf, host, clock_time()); modify_he_hostip_in_conf(&he_conf, host, curip); } else { log_line("%s: [fail] - Failed to update.", host); } } free(data.buf); } void he_dns_work(char *curip) { char host[MAX_BUF], *pass, *p; for (hostdata_t *tp = he_conf.hostpairs; tp != NULL; tp = tp->next) { if (strcmp(curip, tp->ip)) { if (strnkcpy(host, tp->host, sizeof host)) goto too_short; if (strnkcat(host, ":", sizeof host)) goto too_short; if (strnkcat(host, tp->password, sizeof host)) { too_short: log_line("he_dns_work: host+password is too long"); continue; } p = strchr(host, ':'); if (!p) continue; *p = '\0'; pass = p + 1; log_line("adding for update [%s]", host); he_update_host(host, pass, curip); } } } static void he_update_tunid(char *tunid, char *curip) { char url[MAX_BUF]; conn_data_t data; if (!tunid || !curip) return; /* set up the authentication url */ if (use_ssl) DDCB_CPY(url, "https"); else DDCB_CPY(url, "http"); DDCB_CAT(url, "://ipv4.tunnelbroker.net/ipv4_end.php?ip="); DDCB_CAT(url, curip); DDCB_CAT(url, "&pass="); DDCB_CAT(url, he_conf.passhash); DDCB_CAT(url, "&apikey="); DDCB_CAT(url, he_conf.userid); DDCB_CAT(url, "&tid="); DDCB_CAT(url, tunid); data.buf = xmalloc(MAX_CHUNKS * CURL_MAX_WRITE_SIZE + 1); memset(data.buf, '\0', MAX_CHUNKS * CURL_MAX_WRITE_SIZE + 1); data.buflen = MAX_CHUNKS * CURL_MAX_WRITE_SIZE + 1; data.idx = 0; if (!dyndns_curl_send(url, &data, NULL)) { // "+OK: Tunnel endpoint updated to: x.x.x.x" is success log_line("response returned: [%s]", data.buf); if (strstr(data.buf, "+OK")) { log_line("%s: [good] - Update successful.", tunid); write_dnsip(tunid, curip); write_dnsdate(tunid, clock_time()); modify_he_hostdate_in_list(he_conf.tunlist, tunid, clock_time()); modify_he_hostip_in_list(he_conf.tunlist, tunid, curip); } else if (strstr(data.buf, "-ERROR: This tunnel is already associated with this IP address.")) { log_line("%s: [nochg] - Unnecessary update; further updates will be considered abusive." , tunid); write_dnsip(tunid, curip); write_dnsdate(tunid, clock_time()); } else if (strstr(data.buf, "abuse")) { log_line("[%s] has a configuration problem. Refusing to update until %s-dnserr is removed.", tunid, tunid); write_dnserr(tunid, -2); remove_host_from_hostdata_list(&he_conf.tunlist, tunid); } else { log_line("%s: [fail] - Failed to update.", tunid); } } free(data.buf); } void he_tun_work(char *curip) { for (hostdata_t *t = he_conf.tunlist; t != NULL; t = t->next) { if (strcmp(curip, t->ip)) { log_line("adding for update [%s]", t->host); he_update_tunid(t->host, curip); } } }
[ "nicholas@kain.us" ]
nicholas@kain.us
0ab7b5443284585cbed2e544365c6bb7bdb09055
d89ccad9cac26ede06eef9ace379f2ad9903192e
/service/sst/include/swtr.h
d5eb6a4cf6741357dff4af84ba2760c97e81be1b
[]
no_license
Pablito2020/mediatek-modem
466b1512b8e87a44bd54ce0aab4a90b6d0d59710
866a103a6d0520db0e80a978cd39d2916196fcbd
refs/heads/master
2021-06-10T19:40:54.961612
2017-02-19T15:12:44
2017-02-19T15:12:44
82,467,464
1
0
null
null
null
null
UTF-8
C
false
false
3,873
h
/***************************************************************************** * Copyright Statement: * -------------------- * This software is protected by Copyright and the information contained * herein is confidential. The software may not be copied and the information * contained herein may not be used or disclosed except with the written * permission of MediaTek Inc. (C) 2005 * * BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO * NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S * SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * * BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE * LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE * WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF * LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND * RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER * THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC). * *****************************************************************************/ /***************************************************************************** * * Filename: * --------- * swtr.h * * Project: * -------- * Maui_Software * * Description: * ------------ * * Author: * ------- * ------- * *============================================================================ * HISTORY * Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!! *------------------------------------------------------------------------------ * removed! * removed! * removed! * removed! * removed! * removed! * removed! * removed! * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * * removed! * removed! * removed! * removed! *------------------------------------------------------------------------------ * Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!! *============================================================================ ****************************************************************************/ #ifndef SWTR_H #define SWTR_H #include "kal_general_types.h" #include "swtr_public.h" #if defined(__MALMO_ASM_SWTR__) kal_int32 ST_MALMO_ASM_Register(MALMO_ASM_MONITORED_REGISTERS reg); #endif #endif /* SWTR_H */
[ "socdelbarca72@gmail.com" ]
socdelbarca72@gmail.com
6e52cf36ecbedcb8e98ad2150158b3a545bae527
4d5d82b7b078dc2547d015f6747c31359d016aab
/sensor.h
ba12be075338a83393ab78f741191dc41372cd74
[ "MIT" ]
permissive
clean-code-craft-tcq-1/ms1snippet-c-SreeKiruthika
5a685e5b766de38d0ea9f9800d2337c04e6c505f
33b2aed54d4ddfd7f1aa453a75831d3a082a0155
refs/heads/main
2023-03-27T01:31:26.919474
2021-03-26T11:46:56
2021-03-26T11:46:56
350,351,221
0
0
null
null
null
null
UTF-8
C
false
false
1,386
h
/************************************************************************************************************************/ /* This file contains the inclusions and definitions needed for sensor validation*/ /************************************************************************************************************************/ #include <stdio.h> #include <math.h> /***************DEFINES section ******************************/ #define TOLERANCE_SOC 0.05 #define TOLERANCE_CURRENT 0.1 #define INVALID_DATA 255 #define VALID_DATA 0 #define NOISY 0 #define NOISE_FREE 1 /*************************************************************/ /***************** Global variables declaration***************/ enum SENSOR_TYPE {SOC, CURRENT, NUMSENSOR}; struct SensorProp_s { char name[10]; double tolerance; }; /**************************************************************/ /**************Function prototype section**********************/ int IsWithinTolerance(double value, double nextValue, double tolerance); int IsSensorReadingsNoiseFree(double* sensorReading, int numOfReadings, struct SensorProp_s Sensor); int validateSensorReadings(double* sensorReading, int numOfReadings, struct SensorProp_s Sensor); int IsReadingsDataValid(double* dataBuffer, int sizeofBuffer); /**************************************************************/
[ "noreply@github.com" ]
clean-code-craft-tcq-1.noreply@github.com
e8f9382071de6e1da4d8b5870a9bf3b5111f7765
ad8271700e52ec93bc62a6fa3ee52ef080e320f2
/CatalystRichPresence/CatalystSDK/SoundWaveStreamingMode.h
29f2dd2b04813616eeb18c00649d9d3e68c5c675
[]
no_license
RubberDuckShobe/CatalystRPC
6b0cd4482d514a8be3b992b55ec143273b3ada7b
92d0e2723e600d03c33f9f027c3980d0f087c6bf
refs/heads/master
2022-07-29T20:50:50.640653
2021-03-25T06:21:35
2021-03-25T06:21:35
351,097,185
2
0
null
null
null
null
UTF-8
C
false
false
398
h
// // Generated with FrostbiteGen by Chod // File: SDK\SoundWaveStreamingMode.h // Created: Wed Mar 10 19:01:07 2021 // #ifndef FBGEN_SoundWaveStreamingMode_H #define FBGEN_SoundWaveStreamingMode_H enum SoundWaveStreamingMode { SoundWaveStreamingMode_Normal = 0x0, SoundWaveStreamingMode_ZeroLatency = 0x1, SoundWaveStreamingMode_LowLatency = 0x2, }; #endif // FBGEN_SoundWaveStreamingMode_H
[ "dog@dog.dog" ]
dog@dog.dog
d149a7e289078dd8dd70f90544051cd763cb9b49
5aecf0283ae309f4f15345fbbf76c0fc2a730160
/lab2/example/main.c
b6e9ab6431096169f18beec3cefecf5f129deafb
[]
no_license
ptimofeyeff/IO-labs
abead0b313355eeaf15d6ef1ebfd888d3d0d6dc5
39a9c9226bb26bf6abc36f6756637b1c46f2c9b4
refs/heads/master
2023-04-13T06:38:27.661948
2021-04-30T03:56:20
2021-04-30T03:56:20
357,862,144
0
0
null
null
null
null
UTF-8
C
false
false
11,170
c
#include <linux/module.h> #include <linux/fs.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/vmalloc.h> #include <linux/genhd.h> #include <linux/blkdev.h> #include <linux/bio.h> #include <linux/string.h> #define MEMSIZE 0xF000 // Size of Ram disk in sectors int c = 0; //Variable for Major Number #define SECTOR_SIZE 512 #define MBR_SIZE SECTOR_SIZE #define MBR_DISK_SIGNATURE_OFFSET 440 #define MBR_DISK_SIGNATURE_SIZE 4 #define PARTITION_TABLE_OFFSET 446 #define PARTITION_ENTRY_SIZE 16 #define PARTITION_TABLE_SIZE 64 #define MBR_SIGNATURE_OFFSET 510 #define MBR_SIGNATURE_SIZE 2 #define MBR_SIGNATURE 0xAA55 #define BR_SIZE SECTOR_SIZE #define BR_SIGNATURE_OFFSET 510 #define BR_SIGNATURE_SIZE 2 #define BR_SIGNATURE 0xAA55 typedef struct { // флаг активности раздела - является ли раздел системным загрузочным // и есть ли необходимость производить загрузку операционной системы с него при старте unsigned char boot_type; // 0x00 - Inactive; 0x80 - Active (Bootable) // Координаты начала раздела - 3 байта // Номер головки диска, с которой начинается раздел unsigned char start_head; // Номер сектора с которых начинается раздел unsigned char start_sec:6; // и номер цилиндра, c которого начинается раздел unsigned char start_cyl_hi:2; unsigned char start_cyl; // System ID - указывает на пренадлежность раздела к Операционной системе // primary or extended. Max count of primary = 4; One primary are required. // extended может быть разделен на большее число подразделов, primary имеет только один лог. диск unsigned char part_type; // Координаты окончания раздела - 3 байта // Номер головки диска, на которой оканчивается раздел unsigned char end_head; // Номер сектора c которого оканчивается раздел unsigned char end_sec:6; // и номер цилиндра, c которого оканчивается раздел unsigned char end_cyl_hi:2; unsigned char end_cyl; // число секторов перед разделом unsigned int abs_start_sec; // число секторов в разделе unsigned int sec_in_part; } PartEntry; typedef PartEntry PartTable[4]; #define SEC_PER_HEAD 63 #define HEAD_PER_CYL 255 #define HEAD_SIZE (SEC_PER_HEAD * SECTOR_SIZE) #define CYL_SIZE (SEC_PER_HEAD * HEAD_PER_CYL * SECTOR_SIZE) #define sec4size(s) ((((s) % CYL_SIZE) % HEAD_SIZE) / SECTOR_SIZE) #define head4size(s) (((s) % CYL_SIZE) / HEAD_SIZE) #define cyl4size(s) ((s) / CYL_SIZE) static PartTable def_part_table = { { boot_type: 0x00, start_sec: 0x2, start_head: 0x0, start_cyl: 0x0, part_type: 0x83, end_head: 0x3, end_sec: 0x20, end_cyl: 0x9F, abs_start_sec: 0x1, sec_in_part: 0x4FFF // 10Mbyte }, { boot_type: 0x00, start_head: 0x4, start_sec: 0x1, start_cyl: 0x0, part_type: 0x05, // extended partition type end_sec: 0x20, end_head: 0xB, end_cyl: 0x9F, abs_start_sec: 0x5000, sec_in_part: 0xA000 } }; static unsigned int def_log_part_br_abs_start_sector[] = {0x5000, 0xA000}; static const PartTable def_log_part_table[] = { { { boot_type: 0x00, start_head: 0x4, start_sec: 0x2, start_cyl: 0x0, part_type: 0x83, end_head: 0x7, end_sec: 0x20, end_cyl: 0x9F, abs_start_sec: 0x1, sec_in_part: 0x4FFF }, { boot_type: 0x00, start_head: 0x8, start_sec: 0x01, start_cyl: 0x00, part_type: 0x05, end_head: 0xB, end_sec: 0x20, end_cyl: 0x9F, abs_start_sec: 0x5000, sec_in_part: 0x5000 } }, { { boot_type: 0x00, start_head: 0x8, start_sec: 0x02, start_cyl: 0x00, part_type: 0x83, end_head: 0xB, end_sec: 0x20, end_cyl: 0x9F, abs_start_sec: 0x1, sec_in_part: 0x4FFF } } }; static void copy_mbr(u8 *disk) { memset(disk, 0x0, MBR_SIZE); *(unsigned long *)(disk + MBR_DISK_SIGNATURE_OFFSET) = 0x36E5756D; memcpy(disk + PARTITION_TABLE_OFFSET, &def_part_table, PARTITION_TABLE_SIZE); *(unsigned short *)(disk + MBR_SIGNATURE_OFFSET) = MBR_SIGNATURE; } static void copy_br(u8 *disk, int abs_start_sector, const PartTable *part_table) { disk += (abs_start_sector * SECTOR_SIZE); memset(disk, 0x0, BR_SIZE); memcpy(disk + PARTITION_TABLE_OFFSET, part_table, PARTITION_TABLE_SIZE); *(unsigned short *)(disk + BR_SIGNATURE_OFFSET) = BR_SIGNATURE; } void copy_mbr_n_br(u8 *disk) { int i; copy_mbr(disk); for (i = 0; i < ARRAY_SIZE(def_log_part_table); i++) { copy_br(disk, def_log_part_br_abs_start_sector[i], &def_log_part_table[i]); } } /* Structure associated with Block device*/ // В неё заносятся операции для работы с файлами устройств с зарегистрированными старшими номерами struct mydiskdrive_dev { int size; u8 *data; spinlock_t lock; struct request_queue *queue; struct gendisk *gd; }device; struct mydiskdrive_dev *x; static int my_open(struct block_device *x, fmode_t mode) { int ret=0; printk(KERN_INFO "mydiskdrive : open \n"); return ret; } static void my_release(struct gendisk *disk, fmode_t mode) { printk(KERN_INFO "mydiskdrive : closed \n"); } static struct block_device_operations fops = { // в fops заносятся операции для работы с файлами устройств с зарегистрированными старшими номерами. .owner = THIS_MODULE, .open = my_open, .release = my_release, }; int mydisk_init(void) { (device.data) = vmalloc(MEMSIZE * SECTOR_SIZE); /* Setup its partition table */ copy_mbr_n_br(device.data); return MEMSIZE; } static int rb_transfer(struct request *req) { int dir = rq_data_dir(req); // get opration type (0 - read, otherwise - write) int ret = 0; /*starting sector (начальный сектор) *where to do operation*/ sector_t start_sector = blk_rq_pos(req); // Общее кол-во секторов для операции unsigned int sector_cnt = blk_rq_sectors(req); /* no of sector on which opn to be done*/ struct bio_vec bv; #define BV_PAGE(bv) ((bv).bv_page) #define BV_OFFSET(bv) ((bv).bv_offset) #define BV_LEN(bv) ((bv).bv_len) struct req_iterator iter; sector_t sector_offset; unsigned int sectors; u8 *buffer; sector_offset = 0; // с помощью iter происходит обращение к req // при каждой итерации выполняется извлечение конкретных данных из буфера в bio_vec rq_for_each_segment(bv, req, iter) { buffer = page_address(BV_PAGE(bv)) + BV_OFFSET(bv); if (BV_LEN(bv) % (SECTOR_SIZE) != 0) { printk(KERN_ERR"bio size is not a multiple ofsector size\n"); ret = -EIO; } sectors = BV_LEN(bv) / SECTOR_SIZE; printk(KERN_DEBUG "my disk: Start Sector: %llu, Sector Offset: %llu;\ Buffer: %p; Length: %u sectors\n",\ (unsigned long long)(start_sector), (unsigned long long) \ (sector_offset), buffer, sectors); if (dir == WRITE) /* Write to the device */ { memcpy((device.data)+((start_sector+sector_offset)*SECTOR_SIZE)\ ,buffer,sectors*SECTOR_SIZE); } else /* Read from the device */ { memcpy(buffer,(device.data)+((start_sector+sector_offset)\ *SECTOR_SIZE),sectors*SECTOR_SIZE); } sector_offset += sectors; } if (sector_offset != sector_cnt) { printk(KERN_ERR "mydisk: bio info doesn't match with the request info"); ret = -EIO; } return ret; } /** request handling function**/ static void dev_request(struct request_queue *q) { struct request *req; int error; // Получаем запрос из очереди while ((req = blk_fetch_request(q)) != NULL) /*check active request *for data transfer*/ { // Обрабатываем запрос error=rb_transfer(req);// transfer the request for operation // Информируем что запрос обраболася с результатом error __blk_end_request_all(req, error); // end the request } } void device_setup(void) { mydisk_init(); // Регистрируем старший номер и имя устройства c = register_blkdev(c, "mydisk");// major no. allocation printk(KERN_ALERT "Major Number is : %d",c); // Инициализируем механизм блокировки для очередей spin_lock_init(&device.lock); // lock for queue // Инициализируем очередь запросов - передаем функцию для обработки запросов и механизм блокировок device.queue = blk_init_queue( dev_request, &device.lock); // Выделяем память под структуру устройства // Передаем общее кол-во разделов, поддерживаемых для этого диска device.gd = alloc_disk(8); // gendisk allocation // Инициализируем старщий номер устройства (device.gd)->major=c; // major no to gendisk // Инициализируем младший номер устройства device.gd->first_minor=0; // first minor of gendisk // Регистрируем операции для работы с файлами устройств device.gd->fops = &fops; device.gd->private_data = &device; // Регистрируем очередь device.gd->queue = device.queue; // Инициалищируем размер устройства в единицах 512-байтовых секторов device.size= mydisk_init(); printk(KERN_INFO"THIS IS DEVICE SIZE %d",device.size); // Инициализируем префикс имени файла устройства sprintf(((device.gd)->disk_name), "mydisk"); // Устанавливаем объем устройства set_capacity(device.gd, device.size); // Регистрируем устройство add_disk(device.gd); } static int __init mydiskdrive_init(void) { int ret=0; device_setup(); return ret; } void mydisk_cleanup(void) { vfree(device.data); } void __exit mydiskdrive_exit(void) { // де-регистрируем наше устройство del_gendisk(device.gd); // освобождаем память для структуры устройства put_disk(device.gd); blk_cleanup_queue(device.queue); unregister_blkdev(c, "mydisk"); mydisk_cleanup(); } // Регистрируем функцию инициализации драйвера module_init(mydiskdrive_init); // Регистрируем функцию финализации драйвера module_exit(mydiskdrive_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Author"); MODULE_DESCRIPTION("BLOCK DRIVER");
[ "ptimofeev@okko.tv" ]
ptimofeev@okko.tv
4a1e4fa3e62bfc5421f4a1c2408c2ea408b2f705
c953b84ab4f12f7684d10112df2ae49d9c9fb363
/ra305x_ap_adv/ra305x_router/l2tp/src/session.c
a12267fbd6c5e4fcc1accba700a9fc580c47ff4e
[]
no_license
resper-guo/Umind-eCos-mt7628
768396a9b7457a75690d4fe6c76263ee22dd0c30
c98eb43702500c80a021388014162adce73c3b1a
refs/heads/master
2022-10-22T02:41:44.750239
2020-06-12T01:15:20
2020-06-12T01:15:20
null
0
0
null
null
null
null
UTF-8
C
false
false
10,583
c
/**************************************************************************** * Ralink Tech Inc. * Taiwan, R.O.C. * * (c) Copyright 2002, Ralink Technology, Inc. * * All rights reserved. Ralink's source code is an unpublished work and the * use of a copyright notice does not imply otherwise. This source code * contains confidential trade secret material of Ralink Tech. Any attemp * or participation in deciphering, decoding, reverse engineering or in any * way altering the source code is stricitly prohibited, unless the prior * written consent of Ralink Technology, Inc. is obtained. ***************************************************************************/ #include <stddef.h> #include <string.h> #include <stdarg.h> #include <stdio.h> #include <network.h> #include <l2tp.h> #include <l2tp_ppp.h> extern struct l2tp_cfg L2tp_config_param; static uint16_t ls_MakeId(l2tp_tunnel *tunnel); static void ls_SetState(l2tp_session *session, int state); static uint32_t call_serial_number = 0; static char *state_names[] = { "idle", "wait-tunnel", "wait-reply", "wait-connect", "established" }; /*-------------------------------------------------------------- * ROUTINE NAME - ls_Release *--------------------------------------------------------------- * FUNCTION: * * INPUT: None * OUTPUT: None * RETURN: None * NOTE: *---------------------------------------------------------------*/ void ls_Release(l2tp_session *ses, char const *reason) { ls_SetState(ses, SESSION_IDLE); DBG(ld_Debug(DBG_SESSION, "session_free(%s) %s\n", ld_Ses2Str(ses), reason)); l2_PppClose(ses); memset(ses, 0, sizeof(l2tp_session)); } /*-------------------------------------------------------------- * ROUTINE NAME - ls_CallINS *--------------------------------------------------------------- * FUNCTION: * * INPUT: None * OUTPUT: None * RETURN: None * NOTE: *---------------------------------------------------------------*/ l2tp_session * ls_CallINS(l2tp_peer *peer, char const *calling_number, L2tpSelector *es, void *private) { l2tp_session *ses; l2tp_tunnel *tunnel; struct l2tp_if *pInfo; /* Find a tunnel to the peer */ tunnel = lt_FindForPeer(peer, es); if (!tunnel) return NULL; ses = (l2tp_session *)tunnel; memset(ses,0,sizeof(l2tp_session)); //yfchou added { struct l2tp_cfg *pParam; pParam = &L2tp_config_param; pInfo = l2tp_IfNameToInfoList(pParam->pppname); if(pInfo) pInfo->ses = ses; else diag_printf("%s pInfo=NULL\n",__FUNCTION__); } /* Init fields */ memset(ses, 0, sizeof(l2tp_session)); ses->tunnel = tunnel; ses->my_id = ls_MakeId(tunnel); ses->state = SESSION_WAIT_TUNNEL; strncpy(ses->calling_number, calling_number, MAX_HOSTNAME); ses->calling_number[MAX_HOSTNAME-1] = 0; ses->private = private; ses->send_accm = 0xFFFFFFFF; ses->recv_accm = 0xFFFFFFFF; /* Add it to the tunnel */ lt_AddSession(ses); return ses; } /*-------------------------------------------------------------- * ROUTINE NAME - ls_MakeId *--------------------------------------------------------------- * FUNCTION: * * INPUT: None * OUTPUT: None * RETURN: None * NOTE: *---------------------------------------------------------------*/ static uint16_t ls_MakeId(l2tp_tunnel *tunnel) { uint16_t sid; while(1) { L2TP_RANDOM_FILL(sid); if (!sid) continue; if (!lt_FindSession(tunnel, sid)) return sid; } } /*-------------------------------------------------------------- * ROUTINE NAME - ls_NotifyTunnelOpen *--------------------------------------------------------------- * FUNCTION: * * INPUT: None * OUTPUT: None * RETURN: None * NOTE: *---------------------------------------------------------------*/ void ls_NotifyTunnelOpen(l2tp_session *ses) { uint16_t u16; uint32_t u32; l2tp_dgram *dgram; l2tp_tunnel *tunnel = ses->tunnel; if (ses->state != SESSION_WAIT_TUNNEL) return; /* Send ICRQ */ DBG(ld_Debug(DBG_SESSION, "Session %s tunnel open\n", ld_Ses2Str(ses))); dgram = lf_NewCtl(MESSAGE_ICRQ, tunnel->assigned_id, 0); if (!dgram) { l2tp_set_errmsg("Could not establish session - out of memory"); lt_DeleteSession(ses, "Out of memory"); return; } /* assigned session ID */ u16 = htons(ses->my_id); lf_AddAvp(dgram, tunnel, MANDATORY, sizeof(u16), VENDOR_IETF, AVP_ASSIGNED_SESSION_ID, &u16); /* Call serial number */ u32 = htonl(call_serial_number); call_serial_number++; lf_AddAvp(dgram, tunnel, MANDATORY, sizeof(u32), VENDOR_IETF, AVP_CALL_SERIAL_NUMBER, &u32); /* Ship it out */ lt_XmitCtlMessage(tunnel, dgram); ls_SetState(ses, SESSION_WAIT_REPLY); } /*-------------------------------------------------------------- * ROUTINE NAME - ls_SetState *--------------------------------------------------------------- * FUNCTION: * * INPUT: None * OUTPUT: None * RETURN: None * NOTE: *---------------------------------------------------------------*/ static void ls_SetState(l2tp_session *session, int state) { if (state == session->state) return; DBG(ld_Debug(DBG_SESSION, "session(%s) state %s -> %s\n", ld_Ses2Str(session), state_names[session->state], state_names[state])); session->state = state; } /*-------------------------------------------------------------- * ROUTINE NAME - *--------------------------------------------------------------- * FUNCTION: Sends CDN with specified result code and message. * * INPUT: None * OUTPUT: None * RETURN: None * NOTE: *---------------------------------------------------------------*/ void ls_SendCDN(l2tp_session *ses, int result_code, int error_code, char const *fmt, ...) { char buf[256]; va_list ap; l2tp_tunnel *tunnel = ses->tunnel; uint16_t len; l2tp_dgram *dgram; uint16_t u16; /* Build the buffer for the result-code AVP */ buf[0] = result_code / 256; buf[1] = result_code & 255; buf[2] = error_code / 256; buf[3] = error_code & 255; va_start(ap, fmt); vsnprintf(buf+4, 256-4, fmt, ap); buf[255] = 0; va_end(ap); DBG(ld_Debug(DBG_SESSION, "session_send_CDN(%s): %s\n", ld_Ses2Str(ses), buf+4)); len = 4 + strlen(buf+4); /* Build the datagram */ dgram = lf_NewCtl(MESSAGE_CDN, tunnel->assigned_id, ses->assigned_id); if (!dgram) return; /* Add assigned session ID */ u16 = htons(ses->my_id); lf_AddAvp(dgram, tunnel, MANDATORY, sizeof(u16), VENDOR_IETF, AVP_ASSIGNED_SESSION_ID, &u16); /* Add result code */ lf_AddAvp(dgram, tunnel, MANDATORY, len, VENDOR_IETF, AVP_RESULT_CODE, buf); /* TODO: Clean up */ ls_SetState(ses, SESSION_IDLE); /* Ship it out */ lt_XmitCtlMessage(tunnel, dgram); /* Free session */ lt_DeleteSession(ses, buf+4); } /*-------------------------------------------------------------- * ROUTINE NAME - *--------------------------------------------------------------- * FUNCTION: Handles a CDN by destroying session * * INPUT: None * OUTPUT: None * RETURN: None * NOTE: *---------------------------------------------------------------*/ void ls_HandleCDN(l2tp_session *ses, l2tp_dgram *dgram) { char buf[1024]; unsigned char *val; uint16_t len; val = lf_SearchAvp(dgram, ses->tunnel, NULL, NULL, &len, VENDOR_IETF, AVP_RESULT_CODE); if (!val || len < 4) { lt_DeleteSession(ses, "Received CDN"); } else { uint16_t result_code, error_code; char *msg; result_code = ((uint16_t) val[0]) * 256 + (uint16_t) val[1]; error_code = ((uint16_t) val[2]) * 256 + (uint16_t) val[3]; if (len > 4) { msg = (char *) &val[4]; } else { msg = ""; } snprintf(buf, sizeof(buf), "Received CDN: result-code = %d, error-code = %d, message = '%.*s'", result_code, error_code, (int) len-4, msg); buf[1023] = 0; lt_DeleteSession(ses, buf); } } /*-------------------------------------------------------------- * ROUTINE NAME - *--------------------------------------------------------------- * FUNCTION: * * INPUT: None * OUTPUT: None * RETURN: None * NOTE: *---------------------------------------------------------------*/ void ls_HandleICRP(l2tp_session *ses, l2tp_dgram *dgram) { uint16_t u16; unsigned char *val; uint16_t len; uint32_t u32; int mandatory, hidden; l2tp_tunnel *tunnel = ses->tunnel; /* Get assigned session ID */ val = lf_SearchAvp(dgram, tunnel, &mandatory, &hidden, &len, VENDOR_IETF, AVP_ASSIGNED_SESSION_ID); if (!val) { l2tp_set_errmsg("No assigned session-ID in ICRP"); return; } if (!lf_ValidateAvp(VENDOR_IETF, AVP_ASSIGNED_SESSION_ID, len, mandatory)) { l2tp_set_errmsg("Invalid assigned session-ID in ICRP"); return; } /* Set assigned session ID */ u16 = ((uint16_t) val[0]) * 256 + (uint16_t) val[1]; if (!u16) { l2tp_set_errmsg("Invalid assigned session-ID in ICRP"); return; } ses->assigned_id = u16; /* If state is not WAIT_REPLY, fubar */ if (ses->state != SESSION_WAIT_REPLY) { ls_SendCDN(ses, RESULT_FSM_ERROR, 0, "Received ICRP for session in state %s", state_names[ses->state]); return; } /* Send ICCN */ dgram = lf_NewCtl(MESSAGE_ICCN, tunnel->assigned_id, ses->assigned_id); if (!dgram) { /* Ugh... not much chance of this working... */ ls_SendCDN(ses, RESULT_GENERAL_ERROR, ERROR_OUT_OF_RESOURCES, "Out of memory"); return; } /* TODO: Speed, etc. are faked for now. */ /* Connect speed */ u32 = htonl(57600); lf_AddAvp(dgram, tunnel, MANDATORY, sizeof(u32), VENDOR_IETF, AVP_TX_CONNECT_SPEED, &u32); /* Framing Type */ u32 = htonl(1); lf_AddAvp(dgram, tunnel, MANDATORY, sizeof(u32), VENDOR_IETF, AVP_FRAMING_TYPE, &u32); /* Ship it out */ lt_XmitCtlMessage(tunnel, dgram); /* Set session state */ ls_SetState(ses, SESSION_ESTABLISHED); l2_PppEstablish(ses); }
[ "421811575@qq.com" ]
421811575@qq.com
d98391e55e37d50909ff0eefa5a8d6969cc3d675
5c255f911786e984286b1f7a4e6091a68419d049
/code/6f1eadb3-8f0f-40bb-b86e-856486ef5fe8.c
507aa31f3714969271d1d8537186d362db764f14
[]
no_license
nmharmon8/Deep-Buffer-Overflow-Detection
70fe02c8dc75d12e91f5bc4468cf260e490af1a4
e0c86210c86afb07c8d4abcc957c7f1b252b4eb2
refs/heads/master
2021-09-11T19:09:59.944740
2018-04-06T16:26:34
2018-04-06T16:26:34
125,521,331
0
0
null
null
null
null
UTF-8
C
false
false
229
c
#include <stdio.h> int main() { int i=4; int j=12; int k; int l; k = 53; l = 64; k = i%j; l = l/j; l = i%j; l = i+j; j = k-k*i; printf("vulnerability"); printf("%d%d\n",k,l); return 0; }
[ "nharmon8@gmail.com" ]
nharmon8@gmail.com
9c2d003240c21ca4a51d8501848b1bc4ad6eb6ba
bb7d83cd9ab2fa9995bcfb970d2dcccd0fcc7cc4
/xlockmore/5.x/5.02/xlockmore-5.02/modes/braid.c
b4db62761eb492836116283f37ba2886f412d3df
[]
no_license
daveriesz/xlockmore-releases
8e6b4aeab63427e605e693cb55f68524a5dde319
a85e159040ed993be28fea691d5bbaf4e53dcd3f
refs/heads/master
2023-04-06T16:21:33.544578
2023-03-17T23:25:32
2023-03-17T23:25:32
292,445,787
0
0
null
null
null
null
UTF-8
C
false
false
13,779
c
/* -*- Mode: C; tab-width: 4 -*- */ /*- * braid --- random braids around a circle and then changes the color in * a rotational pattern */ #if !defined( lint ) && !defined( SABER ) static const char sccsid[] = "@(#)braid.c 5.00 2000/11/01 xlockmore"; #endif /*- * Copyright (c) 1995 by John Neil. * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that * both that copyright notice and this permission notice appear in * supporting documentation. * * This file is provided AS IS with no warranties of any kind. The author * shall have no liability with respect to the infringement of copyrights, * trade secrets or any patents by this file or any part thereof. In no * event will the author be liable for any lost revenue or profits or * other special, indirect and consequential damages. * * Revision History: * 01-Nov-2000: Allocation checks * 10-May-1997: Jamie Zawinski <jwz@jwz.org> compatible with xscreensaver * 01-Sep-1995: color knotted components differently, J. Neil. * 29-Aug-1995: Written. John Neil <neil@math.idbsu.edu> */ #ifdef STANDALONE #define PROGCLASS "Braid" #define HACK_INIT init_braid #define HACK_DRAW draw_braid #define braid_opts xlockmore_opts #define DEFAULTS "*delay: 1000 \n" \ "*count: 15 \n" \ "*cycles: 100 \n" \ "*size: -7 \n" \ "*ncolors: 64 \n" #define UNIFORM_COLORS #include "xlockmore.h" #else /* STANDALONE */ #include "xlock.h" #endif /* STANDALONE */ #ifdef MODE_braid ModeSpecOpt braid_opts = {0, (XrmOptionDescRec *) NULL, 0, (argtype *) NULL, (OptionStruct *) NULL}; #ifdef USE_MODULES ModStruct braid_description = {"braid", "init_braid", "draw_braid", "release_braid", "refresh_braid", "init_braid", (char *) NULL, &braid_opts, 1000, 15, 100, 1, 64, 1.0, "", "Shows random braids and knots", 0, NULL}; #endif #if defined( COLORROUND ) && defined( COLORCOMP ) #undef COLORROUND #undef COLORCOMP #endif #if !defined( COLORROUND ) && !defined( COLORCOMP ) #if 0 /* to color in a circular pattern use COLORROUND */ #define COLORROUND #else /* to color by component use COLORCOMP */ #define COLORCOMP #endif #endif #define MAXLENGTH 50 /* the maximum length of a braid word */ #define MINLENGTH 8 /* the minimum length of a braid word */ #define MAXSTRANDS 15 /* the maximum number of strands in the braid */ #define MINSTRANDS 3 /* the minimum number of strands in the braid */ #define SPINRATE 12.0 /* the rate at which the colors spin */ #define INTRAND(min,max) (NRAND((max+1)-(min))+(min)) #define FLOATRAND(min,max) ((min)+((double) LRAND()/((double) MAXRAND))*((max)-(min))) typedef struct { int linewidth; int braidword[MAXLENGTH]; int components[MAXSTRANDS]; int startcomp[MAXLENGTH][MAXSTRANDS]; int nstrands; int braidlength; float startcolor; int center_x; int center_y; float min_radius; float max_radius; float top, bottom, left, right; int age; int color_direction; } braidtype; static braidtype *braids = (braidtype *) NULL; static int applyword(braidtype * braid, int string, int position) { int i, c; c = string; for (i = position; i < braid->braidlength; i++) { if (c == ABS(braid->braidword[i])) c--; else if (c == ABS(braid->braidword[i]) - 1) c++; } for (i = 0; i < position; i++) { if (c == ABS(braid->braidword[i])) c--; else if (c == ABS(braid->braidword[i]) - 1) c++; } return c; } #if 0 static int applywordto(braidtype * braid, int string, int position) { int i, c; c = string; for (i = 0; i < position; i++) { if (c == ABS(braid->braidword[i])) { c--; } else if (c == ABS(braid->braidword[i]) - 1) { c++; } } return c; } #endif static int applywordbackto(braidtype * braid, int string, int position) { int i, c; c = string; for (i = position - 1; i >= 0; i--) { if (c == ABS(braid->braidword[i])) { c--; } else if (c == ABS(braid->braidword[i]) - 1) { c++; } } return c; } void init_braid(ModeInfo * mi) { braidtype *braid; int used[MAXSTRANDS]; int i, count, comp, c; float min_length; if (braids == NULL) { if ((braids = (braidtype *) calloc(MI_NUM_SCREENS(mi), sizeof (braidtype))) == NULL) return; } braid = &braids[MI_SCREEN(mi)]; braid->center_x = MI_WIDTH(mi) / 2; braid->center_y = MI_HEIGHT(mi) / 2; braid->age = 0; /* jwz: go in the other direction sometimes. */ braid->color_direction = ((LRAND() & 1) ? 1 : -1); MI_CLEARWINDOW(mi); min_length = (braid->center_x > braid->center_y) ? braid->center_y : braid->center_x; braid->min_radius = min_length * 0.30; braid->max_radius = min_length * 0.90; if (MI_COUNT(mi) < MINSTRANDS) braid->nstrands = MINSTRANDS; else braid->nstrands = INTRAND(MINSTRANDS, MAX(MIN(MIN(MAXSTRANDS, MI_COUNT(mi)), (int) ((braid->max_radius - braid->min_radius) / 5.0)), MINSTRANDS)); braid->braidlength = INTRAND(MINLENGTH, MIN(MAXLENGTH, braid->nstrands * 6)); for (i = 0; i < braid->braidlength; i++) { braid->braidword[i] = INTRAND(1, braid->nstrands - 1) * (INTRAND(1, 2) * 2 - 3); if (i > 0) while (braid->braidword[i] == -braid->braidword[i - 1]) braid->braidword[i] = INTRAND(1, braid->nstrands - 1) * (INTRAND(1, 2) * 2 - 3); } while (braid->braidword[0] == -braid->braidword[braid->braidlength - 1]) braid->braidword[braid->braidlength - 1] = INTRAND(1, braid->nstrands - 1) * (INTRAND(1, 2) * 2 - 3); do { (void) memset((char *) used, 0, sizeof (used)); count = 0; for (i = 0; i < braid->braidlength; i++) used[ABS(braid->braidword[i])]++; for (i = 0; i < braid->nstrands; i++) count += (used[i] > 0) ? 1 : 0; if (count < braid->nstrands - 1) { braid->braidword[braid->braidlength] = INTRAND(1, braid->nstrands - 1) * (INTRAND(1, 2) * 2 - 3); while (braid->braidword[braid->braidlength] == -braid->braidword[braid->braidlength - 1] && braid->braidword[0] == -braid->braidword[braid->braidlength]) braid->braidword[braid->braidlength] = INTRAND(1, braid->nstrands - 1) * (INTRAND(1, 2) * 2 - 3); braid->braidlength++; } } while (count < braid->nstrands - 1 && braid->braidlength < MAXLENGTH); braid->startcolor = (MI_NPIXELS(mi) > 2) ? (float) NRAND(MI_NPIXELS(mi)) : 0.0; /* XSetLineAttributes (display, MI_GC(mi), 2, LineSolid, CapRound, JoinRound); */ (void) memset((char *) braid->components, 0, sizeof (braid->components)); c = 1; comp = 0; braid->components[0] = 1; do { i = comp; do { i = applyword(braid, i, 0); braid->components[i] = braid->components[comp]; } while (i != comp); count = 0; for (i = 0; i < braid->nstrands; i++) if (braid->components[i] == 0) count++; if (count > 0) { for (comp = 0; braid->components[comp] != 0; comp++); braid->components[comp] = ++c; } } while (count > 0); braid->linewidth = MI_SIZE(mi); if (braid->linewidth < 0) braid->linewidth = NRAND(-braid->linewidth) + 1; if (braid->linewidth * braid->linewidth * 8 > MIN(MI_WIDTH(mi), MI_HEIGHT(mi))) braid->linewidth = MIN(1, (int) sqrt((double) MIN(MI_WIDTH(mi), MI_HEIGHT(mi)) / 8)); for (i = 0; i < braid->nstrands; i++) if (!(braid->components[i] & 1)) braid->components[i] *= -1; } void draw_braid(ModeInfo * mi) { Display *display = MI_DISPLAY(mi); Window window = MI_WINDOW(mi); int num_points = 500; float t_inc; float theta, psi; float t, r_diff; int i, s; float x_1, y_1, x_2, y_2, r1, r2; float color, color_use = 0.0, color_inc; braidtype *braid; if (braids == NULL) return; braid = &braids[MI_SCREEN(mi)]; MI_IS_DRAWN(mi) = True; XSetLineAttributes(display, MI_GC(mi), braid->linewidth, LineSolid, (braid->linewidth <= 3 ? CapButt : CapRound), JoinMiter); theta = (2.0 * M_PI) / (float) (braid->braidlength); t_inc = (2.0 * M_PI) / (float) num_points; color_inc = (float) MI_NPIXELS(mi) * braid->color_direction / (float) num_points; braid->startcolor += SPINRATE * color_inc; if (((int) braid->startcolor) >= MI_NPIXELS(mi)) braid->startcolor = 0.0; r_diff = (braid->max_radius - braid->min_radius) / (float) (braid->nstrands); color = braid->startcolor; psi = 0.0; for (i = 0; i < braid->braidlength; i++) { psi += theta; for (t = 0.0; t < theta; t += t_inc) { #ifdef COLORROUND color += color_inc; if (((int) color) >= MI_NPIXELS(mi)) color = 0.0; color_use = color; #endif for (s = 0; s < braid->nstrands; s++) { if (ABS(braid->braidword[i]) == s) continue; if (ABS(braid->braidword[i]) - 1 == s) { /* crosSINFg */ #ifdef COLORCOMP if (MI_NPIXELS(mi) > 2) { color_use = color + SPINRATE * braid->components[applywordbackto(braid, s, i)] + (psi + t) / 2.0 / M_PI * (float) MI_NPIXELS(mi); while (((int) color_use) >= MI_NPIXELS(mi)) color_use -= (float) MI_NPIXELS(mi); while (((int) color_use) < 0) color_use += (float) MI_NPIXELS(mi); } #endif #ifdef COLORROUND if (MI_NPIXELS(mi) > 2) { color_use += SPINRATE * color_inc; while (((int) color_use) >= MI_NPIXELS(mi)) color_use -= (float) MI_NPIXELS(mi); } #endif r1 = braid->min_radius + r_diff * (float) (s); r2 = braid->min_radius + r_diff * (float) (s + 1); if (braid->braidword[i] > 0 || (FABSF(t - theta / 2.0) > theta / 7.0)) { x_1 = ((0.5 * (1.0 + SINF(t / theta * M_PI - M_PI_2)) * r2 + 0.5 * (1.0 + SINF((theta - t) / theta * M_PI - M_PI_2)) * r1)) * COSF(t + psi) + braid->center_x; y_1 = ((0.5 * (1.0 + SINF(t / theta * M_PI - M_PI_2)) * r2 + 0.5 * (1.0 + SINF((theta - t) / theta * M_PI - M_PI_2)) * r1)) * SINF(t + psi) + braid->center_y; x_2 = ((0.5 * (1.0 + SINF((t + t_inc) / theta * M_PI - M_PI_2)) * r2 + 0.5 * (1.0 + SINF((theta - t - t_inc) / theta * M_PI - M_PI_2)) * r1)) * COSF(t + t_inc + psi) + braid->center_x; y_2 = ((0.5 * (1.0 + SINF((t + t_inc) / theta * M_PI - M_PI_2)) * r2 + 0.5 * (1.0 + SINF((theta - t - t_inc) / theta * M_PI - M_PI_2)) * r1)) * SINF(t + t_inc + psi) + braid->center_y; if (MI_NPIXELS(mi) > 2) XSetForeground(display, MI_GC(mi), MI_PIXEL(mi, (int) color_use)); else XSetForeground(display, MI_GC(mi), MI_WHITE_PIXEL(mi)); XDrawLine(display, window, MI_GC(mi), (int) (x_1), (int) (y_1), (int) (x_2), (int) (y_2)); } #ifdef COLORCOMP if (MI_NPIXELS(mi) > 2) { color_use = color + SPINRATE * braid->components[applywordbackto(braid, s + 1, i)] + (psi + t) / 2.0 / M_PI * (float) MI_NPIXELS(mi); while (((int) color_use) >= MI_NPIXELS(mi)) color_use -= (float) MI_NPIXELS(mi); while (((int) color_use) < 0) color_use += (float) MI_NPIXELS(mi); } #endif if (braid->braidword[i] < 0 || (FABSF(t - theta / 2.0) > theta / 7.0)) { x_1 = ((0.5 * (1.0 + SINF(t / theta * M_PI - M_PI_2)) * r1 + 0.5 * (1.0 + SINF((theta - t) / theta * M_PI - M_PI_2)) * r2)) * COSF(t + psi) + braid->center_x; y_1 = ((0.5 * (1.0 + SINF(t / theta * M_PI - M_PI_2)) * r1 + 0.5 * (1.0 + SINF((theta - t) / theta * M_PI - M_PI_2)) * r2)) * SINF(t + psi) + braid->center_y; x_2 = ((0.5 * (1.0 + SINF((t + t_inc) / theta * M_PI - M_PI_2)) * r1 + 0.5 * (1.0 + SINF((theta - t - t_inc) / theta * M_PI - M_PI_2)) * r2)) * COSF(t + t_inc + psi) + braid->center_x; y_2 = ((0.5 * (1.0 + SINF((t + t_inc) / theta * M_PI - M_PI_2)) * r1 + 0.5 * (1.0 + SINF((theta - t - t_inc) / theta * M_PI - M_PI_2)) * r2)) * SINF(t + t_inc + psi) + braid->center_y; if (MI_NPIXELS(mi) > 2) XSetForeground(display, MI_GC(mi), MI_PIXEL(mi, (int) color_use)); else XSetForeground(display, MI_GC(mi), MI_WHITE_PIXEL(mi)); XDrawLine(display, window, MI_GC(mi), (int) (x_1), (int) (y_1), (int) (x_2), (int) (y_2)); } } else { /* no crosSINFg */ #ifdef COLORCOMP if (MI_NPIXELS(mi) > 2) { color_use = color + SPINRATE * braid->components[applywordbackto(braid, s, i)] + (psi + t) / 2.0 / M_PI * (float) MI_NPIXELS(mi); while (((int) color_use) >= MI_NPIXELS(mi)) color_use -= (float) MI_NPIXELS(mi); while (((int) color_use) < 0) color_use += (float) MI_NPIXELS(mi); } #endif #ifdef COLORROUND if (MI_NPIXELS(mi) > 2) { color_use += SPINRATE * color_inc; while (((int) color_use) >= MI_NPIXELS(mi)) color_use -= (float) MI_NPIXELS(mi); } #endif r1 = braid->min_radius + r_diff * (float) (s); x_1 = r1 * COSF(t + psi) + braid->center_x; y_1 = r1 * SINF(t + psi) + braid->center_y; x_2 = r1 * COSF(t + t_inc + psi) + braid->center_x; y_2 = r1 * SINF(t + t_inc + psi) + braid->center_y; if (MI_NPIXELS(mi) > 2) XSetForeground(display, MI_GC(mi), MI_PIXEL(mi, (int) color_use)); else XSetForeground(display, MI_GC(mi), MI_WHITE_PIXEL(mi)); XDrawLine(display, window, MI_GC(mi), (int) (x_1), (int) (y_1), (int) (x_2), (int) (y_2)); } } } } XSetLineAttributes(display, MI_GC(mi), 1, LineSolid, CapNotLast, JoinRound); if (++braid->age > MI_CYCLES(mi)) { init_braid(mi); } } void release_braid(ModeInfo * mi) { if (braids != NULL) { (void) free((void *) braids); braids = (braidtype *) NULL; } } void refresh_braid(ModeInfo * mi) { MI_CLEARWINDOW(mi); } #endif /* MODE_braid */
[ "dave@riesz.net" ]
dave@riesz.net
393512620758ded8669b55258eb666be27a49752
b54522bd1eb8d1be1cf65aa53bdde8b17fdc448c
/v1.0/fw/etna-fw-v1.0.0/components/nrf5_sdk/libraries/gpiote/app_gpiote.c
b45271699e2d8e9ba3e042b924e45a119b6fc214
[]
no_license
illysky/etna
ba3fec30f73088015ab903d896af8c327008f6c3
fd2abafb494a73ac27d394f7afbbdf46ba11feb5
refs/heads/master
2021-10-11T10:28:52.630576
2021-10-10T10:56:03
2021-10-10T10:56:03
168,384,412
4
0
null
null
null
null
UTF-8
C
false
false
8,705
c
/* Copyright (c) 2015 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #include "sdk_common.h" #if NRF_MODULE_ENABLED(APP_GPIOTE) #include "app_gpiote.h" #include "nrf_drv_gpiote.h" #include "nrf_bitmask.h" #define MODULE_INITIALIZED (mp_users != NULL) /**< Macro designating whether the module has been initialized properly. */ /**@brief GPIOTE user type. */ typedef struct { uint32_t pins_mask[GPIO_COUNT]; /**< Mask defining which pins user wants to monitor. */ uint32_t pins_low_to_high_mask[GPIO_COUNT]; /**< Mask defining which pins will generate events to this user when toggling low->high. */ uint32_t pins_high_to_low_mask[GPIO_COUNT]; /**< Mask defining which pins will generate events to this user when toggling high->low. */ uint32_t sense_high_pins[GPIO_COUNT]; /**< Mask defining which pins are configured to generate GPIOTE interrupt on transition to high level. */ app_gpiote_event_handler_t event_handler; /**< Pointer to function to be executed when an event occurs. */ bool enabled; /**< Flag indicating whether user is enabled. */ } gpiote_user_t; STATIC_ASSERT(sizeof(gpiote_user_t) <= GPIOTE_USER_NODE_SIZE); STATIC_ASSERT(sizeof(gpiote_user_t) % 4 == 0); static uint8_t m_user_array_size; /**< Size of user array. */ static uint8_t m_user_count; /**< Number of registered users. */ static gpiote_user_t * mp_users = NULL; /**< Array of GPIOTE users. */ static uint32_t m_pins[GPIO_COUNT]; /**< Mask of initialized pins. */ static uint32_t m_last_pins_state[GPIO_COUNT]; /**< Most recent state of pins. */ void gpiote_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action) { int i; uint32_t pin_mask[GPIO_COUNT] = {0}; uint32_t empty_pin_mask[GPIO_COUNT] = {0}; nrf_bitmask_bit_set(pin, pin_mask); bool hitolo = nrf_bitmask_bit_is_set(pin, m_last_pins_state); nrf_gpio_ports_read(0, GPIO_COUNT, m_last_pins_state); for (i = 0; i < m_user_count; i++) { if (mp_users[i].enabled && nrf_bitmask_bit_is_set(pin, mp_users[i].pins_mask)) { if ( nrf_bitmask_bit_is_set(pin, mp_users[i].pins_high_to_low_mask) && hitolo) { mp_users[i].event_handler(empty_pin_mask,pin_mask); } else if ( nrf_bitmask_bit_is_set(pin, mp_users[i].pins_low_to_high_mask) && !hitolo) { mp_users[i].event_handler(pin_mask,empty_pin_mask); } } } } uint32_t app_gpiote_init(uint8_t max_users, void * p_buffer) { uint32_t ret_code = NRF_SUCCESS; if (p_buffer == NULL) { return NRF_ERROR_INVALID_PARAM; } // Check that buffer is correctly aligned. if (!is_word_aligned(p_buffer)) { return NRF_ERROR_INVALID_PARAM; } // Initialize file globals. mp_users = (gpiote_user_t *)p_buffer; m_user_array_size = max_users; m_user_count = 0; memset(m_pins,0, sizeof(m_pins)); memset(mp_users, 0, m_user_array_size * sizeof(gpiote_user_t)); if (nrf_drv_gpiote_is_init()==false) { ret_code = nrf_drv_gpiote_init(); } return ret_code; } uint32_t app_gpiote_user_register(app_gpiote_user_id_t * p_user_id, uint32_t const * p_pins_low_to_high_mask, uint32_t const * p_pins_high_to_low_mask, app_gpiote_event_handler_t event_handler) { uint32_t user_pin_mask[GPIO_COUNT]; uint32_t ret_val = NRF_SUCCESS; // Check state and parameters. VERIFY_MODULE_INITIALIZED(); if (event_handler == NULL) { return NRF_ERROR_INVALID_PARAM; } if (m_user_count >= m_user_array_size) { return NRF_ERROR_NO_MEM; } nrf_bitmask_masks_or(p_pins_low_to_high_mask, p_pins_high_to_low_mask, user_pin_mask, sizeof(user_pin_mask)); // Allocate new user. memcpy(mp_users[m_user_count].pins_mask, user_pin_mask, sizeof(mp_users[m_user_count].pins_mask)); memcpy(mp_users[m_user_count].pins_low_to_high_mask, p_pins_low_to_high_mask, sizeof(mp_users[m_user_count].pins_low_to_high_mask)); memcpy(mp_users[m_user_count].pins_high_to_low_mask, p_pins_high_to_low_mask, sizeof(mp_users[m_user_count].pins_high_to_low_mask)); mp_users[m_user_count].event_handler = event_handler; mp_users[m_user_count].enabled = false; *p_user_id = m_user_count++; uint32_t i; const nrf_drv_gpiote_in_config_t config = GPIOTE_CONFIG_IN_SENSE_TOGGLE(false); uint32_t num_of_pins = NUMBER_OF_PINS ; for (i = 0; i < num_of_pins; i++) { if (nrf_bitmask_bit_is_set(i, user_pin_mask) && !nrf_bitmask_bit_is_set(i, m_pins)) { ret_val = nrf_drv_gpiote_in_init(i, &config, gpiote_handler); VERIFY_SUCCESS(ret_val); nrf_bitmask_bit_set(i, m_pins); } } return ret_val; } __STATIC_INLINE uint32_t error_check(app_gpiote_user_id_t user_id) { // Check state and parameters. VERIFY_MODULE_INITIALIZED(); if (user_id >= m_user_count) { return NRF_ERROR_INVALID_PARAM; } return NRF_SUCCESS; } /** * @brief Function for enabling event on pin (if not yet enabled) or disabling the event if no other * user requires it. * * @param pin Pin to enable * @param enable If true function will attempt to enable the pin else it will attempt to disable it. */ static void pin_event_enable(uint32_t pin, bool enable) { uint32_t i; bool enabled = false; //search if any user already enabled given pin for (i = 0; i < m_user_count; i++) { if (mp_users[i].enabled && nrf_bitmask_bit_is_set(pin, mp_users[i].pins_mask)) { enabled = true; break; } } if (!enabled) { if (enable) { nrf_gpio_ports_read(0, GPIO_COUNT, m_last_pins_state); nrf_drv_gpiote_in_event_enable(pin, true); } else { nrf_drv_gpiote_in_event_disable(pin); } } } /** * @brief Function for enabling or disabling events for pins used by the user. * * Function will enable pin events only if they are not yet enabled. Function will disable pin * events only if there is no other enabled user that is using them. * * @param user_id User id. * @param enable If true function will attempt to enable the pin else it will attempt to disable it. */ static uint32_t user_enable(app_gpiote_user_id_t user_id, bool enable) { uint32_t ret_code = error_check(user_id); if (ret_code == NRF_SUCCESS) { uint32_t i; for (i = 0; i < NUMBER_OF_PINS; i++) { if (nrf_bitmask_bit_is_set(i, mp_users[user_id].pins_mask)) { pin_event_enable(i, enable); } } } return ret_code; } uint32_t app_gpiote_user_enable(app_gpiote_user_id_t user_id) { uint32_t ret_code = NRF_SUCCESS; if (mp_users[user_id].enabled == false) { ret_code = user_enable(user_id, true); VERIFY_SUCCESS(ret_code); mp_users[user_id].enabled = true; return ret_code; } else { return ret_code; } } uint32_t app_gpiote_user_disable(app_gpiote_user_id_t user_id) { uint32_t ret_code = NRF_SUCCESS; if (mp_users[user_id].enabled) { mp_users[user_id].enabled = false; ret_code = user_enable(user_id, false); } return ret_code; } uint32_t app_gpiote_pins_state_get(app_gpiote_user_id_t user_id, uint32_t * p_pins) { gpiote_user_t * p_user; uint32_t ret_code = error_check(user_id); if (ret_code == NRF_SUCCESS) { p_user = &mp_users[user_id]; nrf_gpio_ports_read(0, GPIO_COUNT, p_pins); nrf_bitmask_masks_and(p_pins, p_user->pins_mask, p_pins, sizeof(p_user->pins_mask)); } return ret_code; } #endif //NRF_MODULE_ENABLED(APP_GPIOTE)
[ "dom@illysky.com" ]
dom@illysky.com
74c341bd34481f964f37e4d82b0780f3093ecd1e
abda4958a50ad0b89a52eaa0cec426b9d33b3287
/module_1/Assignment_1b.c
df8a9bb7c0c7e8a1c33f3e3d91a56659067997ff
[]
no_license
mbarajas/Parallel-Programming
c203f006e4ffe7f7512767398be8d15344b03381
1a7dcfa3656378c12e545aa2254c4630fb73872c
refs/heads/master
2021-07-11T07:43:32.271058
2021-03-09T15:02:20
2021-03-09T15:02:20
20,064,299
0
0
null
2021-03-09T15:02:21
2014-05-22T14:34:07
Rich Text Format
UTF-8
C
false
false
1,158
c
#include <pthread.h> #define THREADS 2 #define ARRAYSIZE 6 #define ITERATIONS ARRAYSIZE / THREADS int sum=0; int numArray[ARRAYSIZE]; pthread_mutex_t sum_mutex; void *thread_sum(void *tid) { int start; int *mytid; int end; int mysum=0; mytid = (int *) tid; start = (*mytid * ITERATIONS); end = start + ITERATIONS; int i; for (i=start; i < end ; i++) { mysum = mysum + numArray[i]; } pthread_mutex_lock (&sum_mutex); sum = sum + mysum; pthread_mutex_unlock (&sum_mutex); pthread_exit(NULL); } void main(int argc, char *argv[]) { int i; for(i=0; i<argc; i++){ numArray[i] = atoi(argv[i]); } pthread_t threads[THREADS]; pthread_attr_t attr; pthread_mutex_init(&sum_mutex, NULL); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); int tids[THREADS]; for (i=0; i<THREADS; i++) { tids[i] = i; pthread_create(&threads[i], &attr, thread_sum, (void *) &tids[i]); } for (i=0; i<THREADS; i++) { pthread_join(threads[i], NULL); } printf ("%d", sum); pthread_attr_destroy(&attr); pthread_mutex_destroy(&sum_mutex); pthread_exit (NULL); }
[ "manuel.barajas@careerbuilder.com" ]
manuel.barajas@careerbuilder.com
3bef066aea4342f6790b8420964f6237c77e9067
4fd01b159ee63d9d98cb1f2856fb6756d563b35a
/Example/Pods/SVGKit/Source/DOM classes/SVG-DOM/SVGUnitTypes.h
d5bb2d2ca2ec01c06efceef1a36093c336ae0289
[ "MIT" ]
permissive
HajjiAnwer/AvatarUIKit
80c591576939f191e80dcc0086a7e6ca7c8e7b43
44a0575ba15e77702aed9c681bd551c31dfd1f62
refs/heads/master
2023-08-14T11:03:49.745675
2021-10-20T12:21:36
2021-10-20T12:21:36
255,456,963
4
0
MIT
2021-10-20T12:16:47
2020-04-13T22:41:37
Swift
UTF-8
C
false
false
383
h
// // SVGUnitTypes.h // SVGKit-iOS // // Created by David Gileadi on 8/14/14. // Copyright (c) 2014 na. All rights reserved. // #ifndef SVGKit_iOS_SVGUnitTypes_h #define SVGKit_iOS_SVGUnitTypes_h typedef enum SVG_UNIT_TYPE { // Unit Types SVG_UNIT_TYPE_UNKNOWN = 0, SVG_UNIT_TYPE_USERSPACEONUSE = 1, SVG_UNIT_TYPE_OBJECTBOUNDINGBOX = 2 } SVG_UNIT_TYPE; #endif
[ "hajjianwar@Mac-mini.local" ]
hajjianwar@Mac-mini.local
feacaed5654379c9eb3f29ddd52120bdea376903
2f985000a455280288cd137a0dd72c0e8abff777
/tun.c
bf22d33576acdf94aeffe8b470ea288cf712e693
[]
no_license
dangnhat/tsps
55055c14f1db62f0fb90f9d3c240a5fdb4b99550
d081eaee7104ff691df18cdb842e5b10fade070a
refs/heads/master
2020-12-03T09:17:52.376259
2016-02-04T07:11:37
2016-02-04T07:11:37
null
0
0
null
null
null
null
UTF-8
C
false
false
5,269
c
/* * TSP Server * * A TSP Server implementation that follows RFC5572 as much as possible. * It is designed to be compatible with FreeNET6 service. * * Copyright (C) 2011 Guo-Fu Tseng <cooldavid@cooldavid.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "tsps.h" #include <stdio.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <net/if.h> #include <string.h> #include <stdlib.h> #include <pthread.h> static int tun_open(void) { if (!*server.tundev) return -1; if ((server.tunfd = open(server.tundev, O_RDWR)) < 0) return -1; return 0; } #ifdef linux #include <linux/if_tun.h> /* * struct in6_ifreq defined in <linux/ipv6.h> * Putted it here because the redefinition conflict. */ struct in6_ifreq { struct in6_addr ifr6_addr; __u32 ifr6_prefixlen; int ifr6_ifindex; }; static int tun_alloc(void) { struct ifreq ifr; int fd, err; if ((fd = open("/dev/net/tun", O_RDWR)) < 0) return tun_open(); memset(&ifr, 0, sizeof(ifr)); /* Flags: IFF_TUN - TUN device (no Ethernet headers) * IFF_TAP - TAP device * * IFF_NO_PI - Do not provide packet information */ ifr.ifr_flags = IFF_TUN; if (*server.tundev) strncpy(ifr.ifr_name, server.tundev, IFNAMSIZ); if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0) { perror("Allocate tundev"); close(fd); return err; } strcpy(server.tundev, ifr.ifr_name); server.tunfd = fd; return 0; } static int tun_linux_setaddr(void) { char errbuf[64]; struct in6_ifreq ifr6; struct ifreq ifr; int fd; memcpy((char *) &ifr6.ifr6_addr, (char *) &server.v6sockaddr.sin6_addr, sizeof(struct in6_addr)); /* * Setup interface address */ fd = socket(AF_INET6, SOCK_DGRAM, 0); if (fd < 0) { tspslog(LOG_ERR, "No support for INET6 on this system"); return -1; } strcpy(ifr.ifr_name, server.tundev); if (ioctl(fd, SIOGIFINDEX, &ifr) < 0) { strerror_r(errno, errbuf, sizeof(errbuf)); tspslog(LOG_ERR, "Getting interface index error: %s", errbuf); return -1; } ifr6.ifr6_ifindex = ifr.ifr_ifindex; ifr6.ifr6_prefixlen = server.v6prefixlen; if (ioctl(fd, SIOCSIFADDR, &ifr6) < 0) { strerror_r(errno, errbuf, sizeof(errbuf)); tspslog(LOG_ERR, "Setting interface address error: %s", errbuf); return -1; } /* * Bring up interface */ strcpy(ifr.ifr_name, server.tundev); if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) { strerror_r(errno, errbuf, sizeof(errbuf)); tspslog(LOG_ERR, "Getting interface flags error: %s", errbuf); return -1; } strcpy(ifr.ifr_name, server.tundev); ifr.ifr_flags |= (IFF_UP | IFF_RUNNING); if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0) { strerror_r(errno, errbuf, sizeof(errbuf)); tspslog(LOG_ERR, "Setting interface flags error: %s", errbuf); return -1; } return 0; } #endif int tun_setaddr(void) { #ifdef linux return tun_linux_setaddr(); #else tspslog(LOG_ERR, "Address setting not implement"); return -1; #endif } int bind_tunif(void) { #ifdef linux return tun_alloc(); #else return tun_open(); #endif } static pthread_mutex_t tun_lock = PTHREAD_MUTEX_INITIALIZER; void tun_read(void *data, ssize_t *len) { struct tun_pi *pi = (struct tun_pi *)data; struct ip6_hdr *ip6 = (struct ip6_hdr *)(pi + 1); static const int hdrlen = sizeof(struct tun_pi) + sizeof(struct ip6_hdr); int offset = 0, datalen = 0; pthread_mutex_lock(&tun_lock); memset(data, 0xFF, PHDRSZ + MTU); do { *len = read(server.tunfd, data + offset, PHDRSZ + MTU - offset); if (*len == -1 && errno != EAGAIN && errno != EINTR) { tspslog(LOG_ERR, "Fail to read from server tun interface"); exit(EXIT_FAILURE); } if (*len > 0) offset += *len; if (datalen == 0 && offset >= hdrlen) { if (ntohs(pi->proto) != ETH_P_IPV6) break; datalen = ntohs(ip6->ip6_plen) + hdrlen; } } while (*len <= 0 || datalen == 0 || offset < datalen); pthread_mutex_unlock(&tun_lock); } void tun_write(void *data, size_t len) { struct tun_pi *pi; int rc, offset = 0; if (sizeof(struct tun_pi) > PHDRSZ) { tspslog(LOG_ERR, "Preserved header space not enough"); exit(EXIT_FAILURE); } pi = (struct tun_pi *)((uint8_t *)data - sizeof(struct tun_pi)); len += sizeof(struct tun_pi); pi->flags = 0; pi->proto = htons(ETH_P_IPV6); pthread_mutex_lock(&tun_lock); do { rc = write(server.tunfd, ((void *)pi) + offset, len - offset); if (rc == -1 && errno != EAGAIN && errno != EINTR) { tspslog(LOG_ERR, "Fail to write to server tun interface"); break; } if (rc > 0) offset += rc; } while (rc <= 0 || offset < len); pthread_mutex_unlock(&tun_lock); }
[ "cooldavid@cooldavid.org" ]
cooldavid@cooldavid.org
a48d469a2f92a095dd7d92fca269ebaa86ce3195
b3168f21185a89d889859c353e1847172b47872d
/sparsemat.c
2315adbcc5945c961815584b24675a80fb9e6909
[]
no_license
Soumali-coder19/Haveli-of-programs
677a880132e0b2e4003b0afe56415ef0f20dbf67
a9c7463588c823c1a8b611b4a8ca9bb556fa4079
refs/heads/master
2021-06-22T05:02:54.175794
2021-05-06T20:05:05
2021-05-06T20:05:05
215,520,479
0
0
null
null
null
null
UTF-8
C
false
false
858
c
#include<stdio.h> #include<conio.h> void main() { int A[10][10],B[10][3],m,n,s=0,i,j; //clrscr(); printf("\nEnter the order m x n of the sparse matrix:"); scanf("%d%d",&m,&n); printf("\nEnter the elements in the sparse matrix(mostly zeroes):"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { printf("\n%d row and %d column: ",i,j); scanf("%d",&A[i][j]); } } printf("\nThe given matrix is:\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { printf("%d ",A[i][j]); } printf("\n"); } for(i=0;i<m;i++) { for(j=0;j<n;j++) { if(A[i][j]!=0) { B[s][0]=A[i][j]; B[s][1]=i; B[s][2]=j; s++; } } } printf("\nThe sparse matrix is given by:"); printf("\n"); for(i=0;i<s;i++) { for(j=0;j<3;j++) { printf("%d ",B[i][j]); } printf("\n"); } getch(); }
[ "noreply@github.com" ]
Soumali-coder19.noreply@github.com
9cd28204150100732353617897895cc132a586ce
3d3df078a9bac071a619629e0466f8ab3d619d23
/IOT_alarmclock/src/lm35.h
ecee96f066fd52766c522559960c0f38510ab6f2
[]
no_license
dani8266/IOT_alarm_clock
807eeca6169ecba51814d993b2bcba880c55184f
0b52f702c28e142189a54e5ef824022272a82700
refs/heads/master
2020-07-24T18:27:16.844570
2019-12-12T10:50:02
2019-12-12T10:50:02
208,009,581
0
1
null
null
null
null
UTF-8
C
false
false
67
h
#include "Particle.h" #define lm35_pin A0 int IndoorTemp();
[ "noreply@github.com" ]
dani8266.noreply@github.com
a5a8748b4dc789533b2dfeb101f83a9072e95fb8
8838eb997879add5759b6dfb23f9a646464e53ca
/platform/efm32/efm32zg_stk3200/efm32_conf.h
3eec1cc6c72a3ad37bae2a1b43183ddb31e5effd
[ "BSD-2-Clause" ]
permissive
embox/embox
d6aacec876978522f01cdc4b8de37a668c6f4c80
98e3c06e33f3fdac10a29c069c20775568e0a6d1
refs/heads/master
2023-09-04T03:02:20.165042
2023-09-02T14:55:31
2023-09-02T14:55:31
33,078,138
1,087
325
BSD-2-Clause
2023-09-14T16:58:34
2015-03-29T15:27:48
C
UTF-8
C
false
false
243
h
/** * @file * @brief * * @author Anton Kozlov * @date 24.04.2014 */ #ifndef EFM32ZG_SK3200_SRC_BSP_API_IMPL_H_ #define EFM32ZG_SK3200_SRC_BSP_API_IMPL_H_ #include <efm32zg222f32.h> #endif /* EFM32ZG_SK3200_SRC_BSP_API_IMPL_H_ */
[ "drakon.mega@gmail.com" ]
drakon.mega@gmail.com
0c35a6f566901bd436eb32f2d4590c8480658ac7
03525ead807f6851047885831bfd6446f3c2280f
/5º semestre/4ª Bolinha/Exercicios - Revisão Vetores/Ex. 3.c
9adc3df208c6bb7cdde23f49e8052db0e1fd5c65
[ "MIT" ]
permissive
sartinicj/Kroton-Anhanguera-2014-a-2018
b5942daf586e8b2a84efd510c6f38eaf5cf83204
cb3ffd2c8683cb42b37a7cb08e07c45f4a7f752d
refs/heads/main
2023-07-13T22:28:14.256648
2021-08-24T14:36:15
2021-08-24T14:36:15
399,253,145
0
0
null
null
null
null
UTF-8
C
false
false
588
c
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { int vet[4], i, ma, me; float med, soma; i=1; soma=0; for(i=0; i<4; i++){ printf("Digite um valor: "); scanf("%d", &vet[i]); } ma=vet[0]; me=vet[0]; for (i=0;i<4;i++){ if (vet[i]>ma){ ma=vet[i]; } if (vet[i]<me){ me=vet[i]; } soma= soma+vet[i]; } med=soma/4; //printf("%d", vet[i]); printf("O maior numero = %d", ma); printf("O menor numero = %d", me); printf("A media dos numeros = %f", med); return 0; }
[ "sartinicj@outlook.com" ]
sartinicj@outlook.com
770ef27fbd3514fecba6587bfb13abefc32daec0
d99077b3d25dd4109acf49734078c96bd754bebd
/deamon/srcs/conf_file_parsing/ft_get_parsing_path.c
4e591c6dcfb672678a922e3b7c32df61fe3d00e4
[]
no_license
sclolus/taskmaster
3ca39ae5d4a7f2184500b63531a9ed903f1ea90f
472a8e1d88bb129fdd3c087f0b9ba9613e759fce
refs/heads/master
2021-01-19T13:08:38.477567
2017-09-16T04:57:27
2017-09-16T04:57:27
100,827,703
1
0
null
null
null
null
UTF-8
C
false
false
1,226
c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_get_parsing_path.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sclolus <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/08/22 16:55:30 by sclolus #+# #+# */ /* Updated: 2017/08/22 18:12:29 by sclolus ### ########.fr */ /* */ /* ************************************************************************** */ #include "deamon.h" inline char *ft_get_parsing_path(char *line, uint32_t index) { char *path; uint32_t i; uint32_t len; i = index; len = 0; while (line[i] && line[i] != '\n') { i++; len++; } if (!(path = ft_strndup(line + i - len, len))) ft_error_exit(1, (char*[]){MALLOC_FAILURE}, EXIT_FAILURE); return (path); }
[ "sclolus@e1r13p14.42.fr" ]
sclolus@e1r13p14.42.fr
fd9959dfd9eebfde46c3b0dc99e6419d36c754b2
bfa2e88db326740249b2d8023d9672050009326c
/monitoring.c
61347fc858348caf5042edfff90fc53223967403
[]
no_license
AleksandraTyrlikova/monitoring
f058f906cdba631146f4e8b92d721fc284df3393
5756098dbc77669a5fc061b637907dc134f55a15
refs/heads/master
2020-05-01T17:05:22.321329
2019-03-25T13:22:12
2019-03-25T13:22:12
177,589,508
0
0
null
null
null
null
UTF-8
C
false
false
1,892
c
#include <unistd.h> // g++ monitoring.c -o monitoring.out -I/usr/include/ -lmraa #include "mraa/aio.h" #include "mraa/gpio.h" #include "math.h" int main() { mraa_aio_context adc_a[2]; mraa_gpio_context gpio_in; uint16_t adc_value = 0; int i; int B=3975;//константа для работы с температурой int D2=0; float tmp, light,temperature; //инициализация входов //стандартная работа с библиотекой для работы с аналоговыми входами for(i=0;i<2;i++) { adc_a[i] = mraa_aio_init(i); if (adc_a[i] == NULL) return 1; } gpio_in = mraa_gpio_init(2); if (gpio_in == NULL) return 1; mraa_gpio_dir(gpio_in, MRAA_GPIO_IN); //конец инициализации while(D2==0)//Если не нажата кнопка, то выполняются следующие действия { for(i=0;i<2;i++)//цикл по входам { adc_value = mraa_aio_read(adc_a[i]);//читается значение с аналогово входа с номером i if(i==0)//если i равно 0, то это датчик освещенности { light = (float)adc_value; // значение освещенности в Люксах fprintf(stdout, "ADC A[%d]=%f\n", i, light); } else // перевод значения температуры в градусы Цельсия { tmp = (float)(1023-adc_value)*10000 / adc_value; temperature = 1/ (log(tmp/10000) / B+1 /298.15) - 273.15; fprintf(stdout, "ADC A[%d]=%8f\n", i, temperature ); } D2=mraa_gpio_read(gpio_in); sleep(1); } } //Завершение работы со входами for(i=0;i<2;i++) mraa_aio_close(adc_a[i]); mraa_gpio_close(gpio_in); return MRAA_SUCCESS; } //! [Interesting]
[ "noreply@github.com" ]
AleksandraTyrlikova.noreply@github.com
c1467b6bc4c9b5ead31097f34520030f2ef7279f
0c5d3b088080577388f5766431487534f93a2c40
/Github-Projects-Origin/linux-master/drivers/input/touchscreen/tsc2007_core.c.bak.c
90a16f5d94159d3a38fbda5dda5a0d66294b6b5e
[]
no_license
zhiyuanjia/WoBench
878255ce45e76ef57f88743c7f43acdfa59e93e7
6b337780cbd598de98fc0eabd19efaf1a01b6012
refs/heads/master
2021-09-23T03:12:08.091319
2018-06-14T10:17:59
2018-06-14T10:17:59
null
0
0
null
null
null
null
UTF-8
C
false
false
11,016
c
#include <assert.h> #include <string.h> #define INCLUDEMAIN /* * drivers/input/touchscreen/tsc2007.c * * Copyright (c) 2008 MtekVision Co., Ltd. * Kwangwoo Lee <kwlee@mtekvision.com> * * Using code from: * - ads7846.c * Copyright (c) 2005 David Brownell * Copyright (c) 2006 Nokia Corporation * - corgi_ts.c * Copyright (C) 2004-2005 Richard Purdie * - omap_ts.[hc], ads7846.h, ts_osk.c * Copyright (C) 2002 MontaVista Software * Copyright (C) 2004 Texas Instruments * Copyright (C) 2005 Dirk Behme * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/of_device.h> #include <linux/of_gpio.h> #include <linux/platform_data/tsc2007.h> #include "tsc2007.h" int tsc2007_xfer(struct tsc2007 *tsc, u8 cmd) { s32 data; u16 val; data = i2c_smbus_read_word_data(tsc->client, cmd); if (data < 0) { dev_err(&tsc->client->dev, "i2c io error: %d\n", data); return data; } /* The protocol and raw data format from i2c interface: * S Addr Wr [A] Comm [A] S Addr Rd [A] [DataLow] A [DataHigh] NA P * Where DataLow has [D11-D4], DataHigh has [D3-D0 << 4 | Dummy 4bit]. */ val = swab16(data) >> 4; dev_dbg(&tsc->client->dev, "data: 0x%x, val: 0x%x\n", data, val); return val; } static void tsc2007_read_values(struct tsc2007 *tsc, struct ts_event *tc) { /* y- still on; turn on only y+ (and ADC) */ tc->y = tsc2007_xfer(tsc, READ_Y); /* turn y- off, x+ on, then leave in lowpower */ tc->x = tsc2007_xfer(tsc, READ_X); /* turn y+ off, x- on; we'll use formula #1 */ tc->z1 = tsc2007_xfer(tsc, READ_Z1); tc->z2 = tsc2007_xfer(tsc, READ_Z2); /* Prepare for next touch reading - power down ADC, enable PENIRQ */ tsc2007_xfer(tsc, PWRDOWN); } u32 tsc2007_calculate_resistance(struct tsc2007 *tsc, struct ts_event *tc) { u32 rt = 0; /* range filtering */ if (tc->x == MAX_12BIT) tc->x = 0; if (likely(tc->x && tc->z1)) { /* compute touch resistance using equation #1 */ rt = tc->z2 - tc->z1; rt *= tc->x; rt *= tsc->x_plate_ohms; rt /= tc->z1; rt = (rt + 2047) >> 12; } return rt; } bool tsc2007_is_pen_down(struct tsc2007 *ts) { /* * NOTE: We can't rely on the pressure to determine the pen down * state, even though this controller has a pressure sensor. * The pressure value can fluctuate for quite a while after * lifting the pen and in some cases may not even settle at the * expected value. * * The only safe way to check for the pen up condition is in the * work function by reading the pen signal state (it's a GPIO * and IRQ). Unfortunately such callback is not always available, * in that case we assume that the pen is down and expect caller * to fall back on the pressure reading. */ if (!ts->get_pendown_state) return true; return ts->get_pendown_state(&ts->client->dev); } static irqreturn_t tsc2007_soft_irq(int irq, void *handle) { struct tsc2007 *ts = handle; struct input_dev *input = ts->input; struct ts_event tc; u32 rt; while (!ts->stopped && tsc2007_is_pen_down(ts)) { /* pen is down, continue with the measurement */ mutex_lock(&ts->mlock); tsc2007_read_values(ts, &tc); mutex_unlock(&ts->mlock); rt = tsc2007_calculate_resistance(ts, &tc); if (!rt && !ts->get_pendown_state) { /* * If pressure reported is 0 and we don't have * callback to check pendown state, we have to * assume that pen was lifted up. */ break; } if (rt <= ts->max_rt) { dev_dbg(&ts->client->dev, "DOWN point(%4d,%4d), resistance (%4u)\n", tc.x, tc.y, rt); rt = ts->max_rt - rt; input_report_key(input, BTN_TOUCH, 1); input_report_abs(input, ABS_X, tc.x); input_report_abs(input, ABS_Y, tc.y); input_report_abs(input, ABS_PRESSURE, rt); input_sync(input); } else { /* * Sample found inconsistent by debouncing or pressure is * beyond the maximum. Don't report it to user space, * repeat at least once more the measurement. */ dev_dbg(&ts->client->dev, "ignored pressure %d\n", rt); } wait_event_timeout(ts->wait, ts->stopped, ts->poll_period); } dev_dbg(&ts->client->dev, "UP\n"); input_report_key(input, BTN_TOUCH, 0); input_report_abs(input, ABS_PRESSURE, 0); input_sync(input); if (ts->clear_penirq) ts->clear_penirq(); return IRQ_HANDLED; } static irqreturn_t tsc2007_hard_irq(int irq, void *handle) { struct tsc2007 *ts = handle; if (tsc2007_is_pen_down(ts)) return IRQ_WAKE_THREAD; if (ts->clear_penirq) ts->clear_penirq(); return IRQ_HANDLED; } static void tsc2007_stop(struct tsc2007 *ts) { ts->stopped = true; mb(); wake_up(&ts->wait); disable_irq(ts->irq); } static int tsc2007_open(struct input_dev *input_dev) { struct tsc2007 *ts = input_get_drvdata(input_dev); int err; ts->stopped = false; mb(); enable_irq(ts->irq); /* Prepare for touch readings - power down ADC and enable PENIRQ */ err = tsc2007_xfer(ts, PWRDOWN); if (err < 0) { tsc2007_stop(ts); return err; } return 0; } static void tsc2007_close(struct input_dev *input_dev) { struct tsc2007 *ts = input_get_drvdata(input_dev); tsc2007_stop(ts); } #ifdef CONFIG_OF static int tsc2007_get_pendown_state_gpio(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct tsc2007 *ts = i2c_get_clientdata(client); return !gpio_get_value(ts->gpio); } static int tsc2007_probe_dt(struct i2c_client *client, struct tsc2007 *ts) { struct device_node *np = client->dev.of_node; u32 val32; u64 val64; if (!np) { dev_err(&client->dev, "missing device tree data\n"); return -EINVAL; } if (!of_property_read_u32(np, "ti,max-rt", &val32)) ts->max_rt = val32; else ts->max_rt = MAX_12BIT; if (!of_property_read_u32(np, "ti,fuzzx", &val32)) ts->fuzzx = val32; if (!of_property_read_u32(np, "ti,fuzzy", &val32)) ts->fuzzy = val32; if (!of_property_read_u32(np, "ti,fuzzz", &val32)) ts->fuzzz = val32; if (!of_property_read_u64(np, "ti,poll-period", &val64)) ts->poll_period = msecs_to_jiffies(val64); else ts->poll_period = msecs_to_jiffies(1); if (!of_property_read_u32(np, "ti,x-plate-ohms", &val32)) { ts->x_plate_ohms = val32; } else { dev_err(&client->dev, "missing ti,x-plate-ohms devicetree property."); return -EINVAL; } ts->gpio = of_get_gpio(np, 0); if (gpio_is_valid(ts->gpio)) ts->get_pendown_state = tsc2007_get_pendown_state_gpio; else dev_warn(&client->dev, "GPIO not specified in DT (of_get_gpio returned %d)\n", ts->gpio); return 0; } #else static int tsc2007_probe_dt(struct i2c_client *client, struct tsc2007 *ts) { dev_err(&client->dev, "platform data is required!\n"); return -EINVAL; } #endif static int tsc2007_probe_pdev(struct i2c_client *client, struct tsc2007 *ts, const struct tsc2007_platform_data *pdata, const struct i2c_device_id *id) { ts->model = pdata->model; ts->x_plate_ohms = pdata->x_plate_ohms; ts->max_rt = pdata->max_rt ? : MAX_12BIT; ts->poll_period = msecs_to_jiffies(pdata->poll_period ? : 1); ts->get_pendown_state = pdata->get_pendown_state; ts->clear_penirq = pdata->clear_penirq; ts->fuzzx = pdata->fuzzx; ts->fuzzy = pdata->fuzzy; ts->fuzzz = pdata->fuzzz; if (pdata->x_plate_ohms == 0) { dev_err(&client->dev, "x_plate_ohms is not set up in platform data"); return -EINVAL; } return 0; } static void tsc2007_call_exit_platform_hw(void *data) { struct device *dev = data; const struct tsc2007_platform_data *pdata = dev_get_platdata(dev); pdata->exit_platform_hw(); } static int tsc2007_probe(struct i2c_client *client, const struct i2c_device_id *id) { const struct tsc2007_platform_data *pdata = dev_get_platdata(&client->dev); struct tsc2007 *ts; struct input_dev *input_dev; int err; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) return -EIO; ts = devm_kzalloc(&client->dev, sizeof(struct tsc2007), GFP_KERNEL); if (!ts) return -ENOMEM; if (pdata) err = tsc2007_probe_pdev(client, ts, pdata, id); else err = tsc2007_probe_dt(client, ts); if (err) return err; input_dev = devm_input_allocate_device(&client->dev); if (!input_dev) return -ENOMEM; i2c_set_clientdata(client, ts); ts->client = client; ts->irq = client->irq; ts->input = input_dev; init_waitqueue_head(&ts->wait); mutex_init(&ts->mlock); snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(&client->dev)); input_dev->name = "TSC2007 Touchscreen"; input_dev->phys = ts->phys; input_dev->id.bustype = BUS_I2C; input_dev->open = tsc2007_open; input_dev->close = tsc2007_close; input_set_drvdata(input_dev, ts); input_set_capability(input_dev, EV_KEY, BTN_TOUCH); input_set_abs_params(input_dev, ABS_X, 0, MAX_12BIT, ts->fuzzx, 0); input_set_abs_params(input_dev, ABS_Y, 0, MAX_12BIT, ts->fuzzy, 0); input_set_abs_params(input_dev, ABS_PRESSURE, 0, MAX_12BIT, ts->fuzzz, 0); if (pdata) { if (pdata->exit_platform_hw) { err = devm_add_action(&client->dev, tsc2007_call_exit_platform_hw, &client->dev); if (err) { dev_err(&client->dev, "Failed to register exit_platform_hw action, %d\n", err); return err; } } if (pdata->init_platform_hw) pdata->init_platform_hw(); } err = devm_request_threaded_irq(&client->dev, ts->irq, tsc2007_hard_irq, tsc2007_soft_irq, IRQF_ONESHOT, client->dev.driver->name, ts); if (err) { dev_err(&client->dev, "Failed to request irq %d: %d\n", ts->irq, err); return err; } tsc2007_stop(ts); /* power down the chip (TSC2007_SETUP does not ACK on I2C) */ err = tsc2007_xfer(ts, PWRDOWN); if (err < 0) { dev_err(&client->dev, "Failed to setup chip: %d\n", err); return err; /* chip does not respond */ } err = input_register_device(input_dev); if (err) { dev_err(&client->dev, "Failed to register input device: %d\n", err); return err; } err = tsc2007_iio_configure(ts); if (err) { dev_err(&client->dev, "Failed to register with IIO: %d\n", err); return err; } return 0; } static const struct i2c_device_id tsc2007_idtable[] = { { "tsc2007", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, tsc2007_idtable); #ifdef CONFIG_OF static const struct of_device_id tsc2007_of_match[] = { { .compatible = "ti,tsc2007" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, tsc2007_of_match); #endif static struct i2c_driver tsc2007_driver = { .driver = { .name = "tsc2007", .of_match_table = of_match_ptr(tsc2007_of_match), }, .id_table = tsc2007_idtable, .probe = tsc2007_probe, }; module_i2c_driver(tsc2007_driver); MODULE_AUTHOR("Kwangwoo Lee <kwlee@mtekvision.com>"); MODULE_DESCRIPTION("TSC2007 TouchScreen Driver"); MODULE_LICENSE("GPL");
[ "wangcong15@mails.tsinghua.edu.cn" ]
wangcong15@mails.tsinghua.edu.cn
410e96a20777ccc7675a38a36e4e81c51ea60afc
ec59f447a7ea27f3370a1eea8277cecaa1f1fb46
/rtmp01/FFLv2-lib-master/source/thread/FFL_thread.c
8d5f8521712fe5a359f6585870ba13d2a72ee646
[]
no_license
lianhuaren/cocoa
1f1da889b0f6ac3352c15fcbd4b2b42df58fe0cd
04e46392d51018ed589e46d5114079d6ed3e3946
refs/heads/master
2021-06-04T04:33:41.733428
2021-01-21T08:20:26
2021-01-21T08:20:26
4,923,423
2
0
null
null
null
null
UTF-8
C
false
false
5,347
c
/* * This file is part of FFL project. * * The MIT License (MIT) * Copyright (C) 2017-2018 zhufeifei All rights reserved. * * FFL_Thread.c * Created by zhufeifei(34008081@qq.com) on 2017/08/12 * https://github.com/zhenfei2016/FFLv2-lib.git * 线程,主要移植于SDL库 * */ #include <FFL_Thread.h> #include <FFL_Mutex.h> #include "FFL_thread_sys.h" typedef struct { int (FFL_CALL * func) (void *); void *data; FFL_Thread *info; FFL_sem *wait; } thread_args; /* 线程函数, 进行一些初始化操作的 */ static int FFL_CALL RunThread_loop(void *data) { thread_args *args = (thread_args *) data; int ( FFL_CALL * userfunc) (void *) = args->func; void *userdata = args->data; FFL_Thread *thread = args->info; int *statusloc = &thread->status; //设置线程名称 // FFL_SYS_SetThreadName(thread->name); //获取线程id // thread->threadid = FFL_SYS_ThreadID(); //通知一下已经开始执行了 // FFL_SemPost(args->wait); /* 外部指定的线程函数 */ *statusloc = userfunc(userdata); if (!FFL_atomicCmpxchg(&thread->state, FFL_THREAD_STATE_ALIVE, FFL_THREAD_STATE_ZOMBIE)) {/* 如果结束前调用了 FFL_DetachThread,则进这里面.*/ if (FFL_atomicCmpxchg(&thread->state, FFL_THREAD_STATE_DETACHED, FFL_THREAD_STATE_CLEANED)) { if (thread->name) { FFL_free(thread->name); thread->name=0; } FFL_free(thread); } } return 0; } /* 创建一个线程,并且等待线程已经开始执行了 */ static FFL_Thread * FFL_CreateThreadWithStackSize(int ( FFL_CALL * fn) (void *),const char *name, const size_t stacksize, void *data) { FFL_Thread *thread; thread_args *args; int ret; thread = (FFL_Thread *) FFL_mallocz(sizeof(*thread)); if (thread == NULL) { FFL_outofmemory(); return (NULL); } thread->status=-1; FFL_atomicInit(&thread->state, FFL_THREAD_STATE_ALIVE); /* 保存线程名称 */ if (name != NULL&&name[0]!=0) { thread->name = FFL_strdup(name); if (thread->name == NULL) { FFL_outofmemory(); FFL_free(thread); return (NULL); } } /* 保存线程上线文参数 */ args = (thread_args *) FFL_malloc(sizeof(*args)); if (args == NULL) { FFL_outofmemory(); if (thread->name) { FFL_free(thread->name); thread->name=0; } FFL_free(thread); return (NULL); } args->func = fn; args->data = data; args->info = thread; /* 创建信号,用于通知线程已经起来了 */ args->wait = FFL_CreateSemaphore(0); if (args->wait == NULL) { if (thread->name) { FFL_free(thread->name); } FFL_free(thread); FFL_free(args); return (NULL); } thread->stacksize = stacksize; ret = FFL_SYS_CreateThread(thread, args, RunThread_loop); if (ret >= 0) { FFL_SemWait(args->wait); } else { if (thread->name) { FFL_free(thread->name); } FFL_free(thread); thread = NULL; } FFL_DestroySemaphore(args->wait); FFL_free(args); return (thread); } /* 对外的创建线程函数 */ FFL_Thread * FFL_CALL FFL_CreateThread(FFL_ThreadFunction fn,const char *name, void *data) { size_t stacksize = 0; return FFL_CreateThreadWithStackSize(fn, name, stacksize, data); } /* 获取线程名称 */ const char * FFL_CALL FFL_GetThreadName(FFL_Thread * thread) { if (thread) { return thread->name; } else { return NULL; } } FFL_ThreadID FFL_CALL FFL_CurrentThreadID(void) { return FFL_SYS_ThreadID(); } /*获取线程*/ FFL_ThreadID FFL_GetThreadID(FFL_Thread * thread) { FFL_ThreadID id; if (thread) { id = thread->threadid; } else { id = FFL_CurrentThreadID(); } return id; } /* 设置线程优先级 */ int FFL_SetThreadPriority(FFL_ThreadPriority priority) { return FFL_SYS_SetThreadPriority(priority); } /* 等待线程结束 */ void FFL_WaitThread(FFL_Thread * thread, int *status) { if (thread) { FFL_SYS_WaitThread(thread); if (status) { *status = thread->status; } if (thread->name) { FFL_free(thread->name); thread->name=0; } FFL_free(thread); } } /* 结束线程 */ void FFL_DetachThread(FFL_Thread * thread) { if (!thread) { return; } /* Grab dibs if the state is alive+joinable. */ if (FFL_atomicCmpxchg(&thread->state, FFL_THREAD_STATE_ALIVE, FFL_THREAD_STATE_DETACHED)) { FFL_SYS_DetachThread(thread); } else { /* all other states are pretty final, see where we landed. */ const int thread_state = FFL_atomicValueGet(&thread->state); if ((thread_state == FFL_THREAD_STATE_DETACHED) || (thread_state == FFL_THREAD_STATE_CLEANED)) { return; /* already detached (you shouldn't call this twice!) */ } else if (thread_state == FFL_THREAD_STATE_ZOMBIE) { FFL_WaitThread(thread, NULL); /* already done, clean it up. */ } else { FFL_ASSERT_LOG(0 , "Unexpected thread state"); return; } } }
[ "libb@bairuitech.com" ]
libb@bairuitech.com
7c6ce842ffa38098c68ad52b2af503994406191e
913fbc48b13cd7352ace806789b85dd07841e6dc
/Comunicaciones/Task4_CanTransmitFunctions/source/infrastructure/bsp/libboard_samv7-ek/include/s25fl1.h
98f6c2cc2b982c53410b4058aeb806837de92eb4
[]
no_license
Shaiduck/embedded
858a168542819d4854b6feaaaccf96f63df6fe18
bc57d19f5dd5a766c6aac44d21e55f674eafe55a
refs/heads/master
2020-03-27T14:50:11.562679
2019-05-09T04:07:26
2019-05-09T04:07:26
146,681,865
1
2
null
2019-04-10T03:54:28
2018-08-30T01:59:32
C
UTF-8
C
false
false
9,253
h
/* ---------------------------------------------------------------------------- * SAM Software Package License * ---------------------------------------------------------------------------- * Copyright (c) 2013, Atmel Corporation * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the disclaimer below. * * Atmel's name may not be used to endorse or promote products derived from * this software without specific prior written permission. * * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ---------------------------------------------------------------------------- */ /** * \file * * Interface for the S25fl1 Serial Flash driver. * */ #ifndef S25FL1_H #define S25FL1_H #define USE_QSPI_DMA /*---------------------------------------------------------------------------- * Macros *----------------------------------------------------------------------------*/ #define Size(pAt25) ((pAt25)->pDesc->size) #define PageSize(pAt25) ((pAt25)->pDesc->pageSize) #define BlockSize(pAt25) ((pAt25)->pDesc->blockSize) #define Name(pAt25) ((pAt25)->pDesc->name) #define ManId(pAt25) (((pAt25)->pDesc->jedecId) & 0xFF) #define PageNumber(pAt25) (Size(pAt25) / PageSize(pAt25)) #define BlockNumber(pAt25) (Size(pAt25) / BlockSize(pAt25)) #define PagePerBlock(pAt25) (BlockSize(pAt25) / PageSize(pAt25)) #define BlockEraseCmd(pAt25) ((pAt25)->pDesc->blockEraseCmd) /*---------------------------------------------------------------------------- * Local definitions *----------------------------------------------------------------------------*/ /** Device is protected, operation cannot be carried out. */ #define ERROR_PROTECTED 1 /** Device is busy executing a command. */ #define ERROR_BUSY 2 /** There was a problem while trying to program page data. */ #define ERROR_PROGRAM 3 /** There was an SPI communication error. */ #define ERROR_SPI 4 /** Device ready/busy status bit. */ #define STATUS_RDYBSY (1 << 0) /** Device is ready. */ #define STATUS_RDYBSY_READY (0 << 0) /** Device is busy with internal operations. */ #define STATUS_RDYBSY_BUSY (1 << 0) /** Write enable latch status bit. */ #define STATUS_WEL (1 << 1) /** Device is not write enabled. */ #define STATUS_WEL_DISABLED (0 << 1) /** Device is write enabled. */ #define STATUS_WEL_ENABLED (1 << 1) /** Software protection status bit-field. */ #define STATUS_SWP (3 << 2) /** All sectors are software protected. */ #define STATUS_SWP_PROTALL (3 << 2) /** Some sectors are software protected. */ #define STATUS_SWP_PROTSOME (1 << 2) /** No sector is software protected. */ #define STATUS_SWP_PROTNONE (0 << 2) /** Write protect pin status bit. */ #define STATUS_WPP (1 << 4) /** Write protect signal is not asserted. */ #define STATUS_WPP_NOTASSERTED (0 << 4) /** Write protect signal is asserted. */ #define STATUS_WPP_ASSERTED (1 << 4) /** Erase/program error bit. */ #define STATUS_EPE (1 << 5) /** Erase or program operation was successful. */ #define STATUS_EPE_SUCCESS (0 << 5) /** Erase or program error detected. */ #define STATUS_EPE_ERROR (1 << 5) /** Sector protection registers locked bit. */ #define STATUS_SPRL (1 << 7) /** Sector protection registers are unlocked. */ #define STATUS_SPRL_UNLOCKED (0 << 7) /** Sector protection registers are locked. */ #define STATUS_SPRL_LOCKED (1 << 7) /** Quad enable bit */ #define STATUS_QUAD_ENABLE (1 << 1) /** Quad enable bit */ #define STATUS_WRAP_ENABLE (0 << 4) /** Latency control bits */ #define STATUS_LATENCY_CTRL (0xF << 0) #define STATUS_WRAP_BYTE (1 << 5) #define BLOCK_PROTECT_Msk (7 << 2) #define TOP_BTM_PROTECT_Msk (1 << 5) #define SEC_PROTECT_Msk (1 << 6) #define CHIP_PROTECT_Msk (0x1F << 2) /** Read array command code. */ #define READ_ARRAY 0x0B /** Read array (low frequency) command code. */ #define READ_ARRAY_LF 0x03 /** Fast Read array command code. */ #define READ_ARRAY_DUAL 0x3B /** Fast Read array command code. */ #define READ_ARRAY_QUAD 0x6B /** Fast Read array command code. */ #define READ_ARRAY_DUAL_IO 0xBB /** Fast Read array command code. */ #define READ_ARRAY_QUAD_IO 0xEB /** Block erase command code (4K block). */ #define BLOCK_ERASE_4K 0x20 /** Block erase command code (32K block). */ #define BLOCK_ERASE_32K 0x52 /** Block erase command code (64K block). */ #define BLOCK_ERASE_64K 0xD8 /** Chip erase command code 1. */ #define CHIP_ERASE_1 0x60 /** Chip erase command code 2. */ #define CHIP_ERASE_2 0xC7 /** Byte/page program command code. */ #define BYTE_PAGE_PROGRAM 0x02 /** Sequential program mode command code 1. */ #define SEQUENTIAL_PROGRAM_1 0xAD /** Sequential program mode command code 2. */ #define SEQUENTIAL_PROGRAM_2 0xAF /** Write enable command code. */ #define WRITE_ENABLE 0x06 /** Write disable command code. */ #define WRITE_DISABLE 0x04 /** Protect sector command code. */ #define PROTECT_SECTOR 0x36 /** Unprotected sector command code. */ #define UNPROTECT_SECTOR 0x39 /** Read sector protection registers command code. */ #define READ_SECTOR_PROT 0x3C /** Read status register command code. */ #define READ_STATUS_1 0x05 /** Read status register command code. */ #define READ_STATUS_2 0x35 /** Read status register command code. */ #define READ_STATUS_3 0x33 /** Write status register command code. */ #define WRITE_STATUS 0x01 /** Read manufacturer and device ID command code. */ #define READ_JEDEC_ID 0x9F /** Deep power-down command code. */ #define DEEP_PDOWN 0xB9 /** Resume from deep power-down command code. */ #define RES_DEEP_PDOWN 0xAB /** Resume from deep power-down command code. */ #define SOFT_RESET_ENABLE 0x66 /** Resume from deep power-down command code. */ #define SOFT_RESET 0x99 /** Resume from deep power-down command code. */ #define WRAP_ENABLE 0x77 /** Continuous Read Mode Reset command code. */ #define CONT_MODE_RESET 0xFF /** SPI Flash Manufacturer JEDEC ID */ #define ATMEL_SPI_FLASH 0x1F #define ST_SPI_FLASH 0x20 #define WINBOND_SPI_FLASH 0xEF #define MACRONIX_SPI_FLASH 0xC2 #define SST_SPI_FLASH 0xBF /*---------------------------------------------------------------------------- * Exported functions *----------------------------------------------------------------------------*/ uint32_t S25FL1D_ReadJedecId(void); void S25FL1D_InitFlashInterface(uint8_t Mode); void S25FL1D_SoftReset(void); void S25FL1D_ContReadModeReset(void); unsigned char S25FL1D_Unprotect(void); unsigned char S25FL1D_Protect(uint32_t StartAddr, uint32_t Size); void S25FL1D_QuadMode(uint8_t Enable); void S25FL1D_EnableWrap(uint8_t ByetAlign); void S25FL1D_SetReadLatencyControl(uint8_t Latency); unsigned char S25FL1D_EraseChip(void); unsigned char S25FL1D_EraseSector( unsigned int address); unsigned char S25FL1D_Erase64KBlock( unsigned int address); unsigned char S25FL1D_Write( uint32_t *pData, uint32_t size, uint32_t address, uint8_t Secure); extern unsigned char S25FL1D_Read( uint32_t *pData, uint32_t size, uint32_t address); extern unsigned char S25FL1D_ReadDual( uint32_t *pData, uint32_t size, uint32_t address); extern unsigned char S25FL1D_ReadQuad( uint32_t *pData, uint32_t size, uint32_t address); extern unsigned char S25FL1D_ReadDualIO( uint32_t *pData, uint32_t size, uint32_t address, uint8_t ContMode, uint8_t Secure); extern unsigned char S25FL1D_ReadQuadIO( uint32_t *pData, uint32_t size, uint32_t address, uint8_t ContMode, uint8_t Secure); #endif // #ifndef S25FL1_H
[ "cristian.shaidt@gmail.com" ]
cristian.shaidt@gmail.com
74f6242012a2369e41d2743af007baa8dacfaf3f
2f48d7f3655e8481006672ada477a9b66126b18a
/test/config/autogen/fill_2_2_1.i.c
e9a42a232718ba7766d4f6781a29ba4623b2d55d
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
DanielSchuette/re2c
0b8befd7faf5f7cb2a11bb037a3685271b3f598e
5ecfafc27728b5450fa26b0d93a3a3e007e11236
refs/heads/master
2022-07-13T09:17:46.173500
2020-05-19T20:29:59
2020-05-19T20:29:59
null
0
0
null
null
null
null
UTF-8
C
false
false
288
c
/* Generated by re2c */ // re2c:define:YYFILL = "fill(need);"; // re2c:define:YYFILL@len = need; // re2c:yyfill:check = 0; { YYCTYPE yych; fill(1);(1); yych = *YYCURSOR; switch (yych) { case 'a': goto yy4; default: goto yy2; } yy2: ++YYCURSOR; { x } yy4: ++YYCURSOR; { a } }
[ "skvadrik@gmail.com" ]
skvadrik@gmail.com
c830173a5e8282e636cee4f1e70fe67f2aa8b767
bfb30eec5563cd267676c505fac621d2158a568f
/codechef/chefgr.c
4db8d84bdb2b60a6f674e12f771184b28b997aa6
[]
no_license
ismnitesh/Codes
fe98b40f6e434f29aafe971249b1c51232c3bb30
1232387848458ce48d8eaf280726ffd482bf52b7
refs/heads/master
2021-01-18T21:19:45.978804
2016-03-28T13:47:12
2016-03-28T13:47:12
30,146,054
0
1
null
null
null
null
UTF-8
C
false
false
434
c
#include<stdio.h> int main() { int t,n,m,a[105],i,max,count; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); max=0; for(i=0;i<n;i++) { scanf("%d",&a[i]); if(a[i]>max) max=a[i]; } count=0; for(i=0;i<n;i++) { count=count+max-a[i]; } if(m>=count) { if((m-count)%n==0) printf("Yes\n"); else printf("No\n"); } else printf("No\n"); } return 0; }
[ "nkagrawal14@gmail.com" ]
nkagrawal14@gmail.com
dabb12dcdf2d4af2336516c7b1da75b62c4aae1b
d876a40f73a852105f92205ff676a9dbda3277ef
/DUMP/TBP_ContextualHelp_RangedWeapon_FireMode_classes.h
ae4cffceadacc89a0a263c53ec430b60908da78b
[]
no_license
xkp95175333/Bloodhunt_SDK_15_9_21
b1aacd07984425e57210843e9b62d247f7cf0de6
f39061d5932b5184951d40423674059a8837534b
refs/heads/main
2023-08-02T13:48:08.544313
2021-09-15T12:54:27
2021-09-15T12:54:27
406,763,953
2
0
null
null
null
null
UTF-8
C
false
false
1,274
h
// BlueprintGeneratedClass TBP_ContextualHelp_RangedWeapon_FireMode.TBP_ContextualHelp_RangedWeapon_FireMode_C // Size: 0xd0 (Inherited: 0xc4) struct UTBP_ContextualHelp_RangedWeapon_FireMode_C : UTBP_ContextualHelpBase_C { char pad_C4[0x4]; // 0xc4(0x04) struct FPointerToUberGraphFrame UberGraphFrame; // 0xc8(0x08) void OnPlayerSpawned(struct ATigerPlayer* InTigerPlayer); // Function TBP_ContextualHelp_RangedWeapon_FireMode.TBP_ContextualHelp_RangedWeapon_FireMode_C.OnPlayerSpawned // (Event|Public|BlueprintEvent) // @ game+0x16c0340 void RangedWeaponPickedUp(); // Function TBP_ContextualHelp_RangedWeapon_FireMode.TBP_ContextualHelp_RangedWeapon_FireMode_C.RangedWeaponPickedUp // (BlueprintCallable|BlueprintEvent) // @ game+0x16c0340 void ItemPickedUp(struct UTigerItemAsset* Item, int32_t Count); // Function TBP_ContextualHelp_RangedWeapon_FireMode.TBP_ContextualHelp_RangedWeapon_FireMode_C.ItemPickedUp // (BlueprintCallable|BlueprintEvent) // @ game+0x16c0340 void ExecuteUbergraph_TBP_ContextualHelp_RangedWeapon_FireMode(int32_t EntryPoint); // Function TBP_ContextualHelp_RangedWeapon_FireMode.TBP_ContextualHelp_RangedWeapon_FireMode_C.ExecuteUbergraph_TBP_ContextualHelp_RangedWeapon_FireMode // (Final|UbergraphFunction) // @ game+0x16c0340 };
[ "68745798+xkp95175333@users.noreply.github.com" ]
68745798+xkp95175333@users.noreply.github.com
22473b87478782a7e9c2c727c0621dac29be22d4
e6525346cfb15da999c186d6037cd280c2ba488e
/Satish_Karnekota/25jan_2021/conditional_statement/conditional_statement.c
a64c1fa66d1cd2b794c9fac21aff539bbcf74d3b
[]
no_license
srivalli-project/TS_Team
dbac1713ccb927e42f6863a3b50c719b4fc87fa6
144a7a1a1cf567557f17d0f62b7d221b294b968d
refs/heads/master
2023-02-25T12:02:52.225132
2021-01-28T11:34:31
2021-01-28T11:34:31
331,626,583
0
1
null
null
null
null
UTF-8
C
false
false
1,429
c
#include <assert.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char* readline(); int main() { char* n_endptr; char* n_str = readline(); int n = strtol(n_str, &n_endptr, 10); if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } // Write Your Code Here const char *numbers[]={"one","two","three","four","five","six","seven","eight","nine"}; if(n>=1 && n<=9)printf("%s",numbers[n-1]); else printf("Greater than 9 \n"); return 0; } char* readline() { size_t alloc_length = 1024; size_t data_length = 0; char* data = malloc(alloc_length); while (true) { char* cursor = data + data_length; char* line = fgets(cursor, alloc_length - data_length, stdin); if (!line) { break; } data_length += strlen(cursor); if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } size_t new_length = alloc_length << 1; data = realloc(data, new_length); if (!data) { break; } alloc_length = new_length; } if (data[data_length - 1] == '\n') { data[data_length - 1] = '\0'; } data = realloc(data, data_length); return data; } /* results: input: 5 output: five input : 8 output: eight input:44 output: greater than 9 */
[ "sksatishkumar133@gmail.com" ]
sksatishkumar133@gmail.com
94e7594339baec934a50c7ed254c29d3665fc10b
0d81ed70d6a445a489baaf96f240f1b328fcd1ce
/Pods/Headers/Public/TXIMSDK_TUIKit_iOS_Professional/TNaviBarIndicatorView.h
387891adb9a0f551d546707b2ff89b7067756830
[]
no_license
mb18738140150/huijushangxueyuan
e5dd220ed15b4f9cd07d17b08c1f3ea8ba7e95ae
d444ea0312856eb4665befb06d253d91f96fd14d
refs/heads/master
2023-01-31T12:51:12.179954
2020-12-15T09:20:09
2020-12-15T09:20:09
304,179,089
0
1
null
null
null
null
UTF-8
C
false
false
100
h
../../../TXIMSDK_TUIKit_iOS_Professional/TUIKit/Classes/Section/Conversation/TNaviBarIndicatorView.h
[ "ytx123013@gmail.com" ]
ytx123013@gmail.com
9f3d819cf1ddde0483b33a1f7afec5207863095a
67e1d6b442293fbff3e5e30f07b434260c635aa7
/sensor/main.c
47f76f7da01baed34680d285737120a92e827547
[]
no_license
zeyugao/atmega8a
f92c5476fd791c904118020ab1233816ffc68550
05c2191510e88c58be48ee77a51294ad4d5e78e7
refs/heads/master
2020-05-04T15:30:24.886564
2019-05-12T08:42:35
2019-05-12T08:42:35
179,243,801
0
0
null
null
null
null
UTF-8
C
false
false
1,204
c
#ifndef F_CPU #define F_CPU 8000000UL #endif #include <util/delay.h> #include <stdlib.h> #include "../module/usart.h" #include "../module/dht11.h" #include "../module/i2c_lcd1602.h" #include "../module/adc.h" #define DHT11 1 #define LIGHT 2 #include <avr/io.h> #ifndef BUILD #include <avr/iom8a.h> #endif int main() { I2C_LCD1602_Init(); usart_init(MYUBRR); unsigned char command = 3; unsigned char success = 0; unsigned char data[4]; unsigned int distance; unsigned char len; char buffer[10]; adc_init(0); while (1) { command = usart_receive(); I2C_LCD1602_WriteChar(0, 10, command + '0'); switch (command) { case DHT11: read_dht11(data); for (int i = 0; i < 4; i++) { I2C_LCD1602_WriteChar(0, 3 - i, data[i] + '0'); } usart_send_array(data, 4); break; case LIGHT: read_adc(&data[0], &data[1]); itoa(data[0], buffer, 10); I2C_LCD1602_WriteString(0, 0, " "); I2C_LCD1602_WriteString(0, 0, buffer); itoa(data[1], buffer, 10); I2C_LCD1602_WriteString(1, 0, " "); I2C_LCD1602_WriteString(1, 0, buffer); usart_send_array(data, 2); default: break; } } }
[ "zeyugao@outlook.com" ]
zeyugao@outlook.com
fd846cdb3b57673cdb93b92c18d2f73528cf9291
ec2301ba138dba3cc8cd370e0a2618b4ff1df141
/src/ft_strjoin.c
dde7882197859aef722772b69e9a6d3c915b9f5b
[]
no_license
ARhony/Libft
d5a1bcefac93153eda7206bd15fdd065b61d52f4
7890d7766072a119ba66426738480907a25f4d83
refs/heads/master
2023-06-08T17:29:05.419994
2023-05-29T05:46:48
2023-05-29T05:46:48
102,402,921
0
0
null
null
null
null
UTF-8
C
false
false
1,354
c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strjoin.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aramon <aramon@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/02/04 12:37:21 by aramon #+# #+# */ /* Updated: 2023/02/15 23:42:21 by aramon ### ########.fr */ /* */ /* ************************************************************************** */ #include "../inc/libft.h" char *ft_strjoin(const char *s1, const char *s2) { int i; int s1len; int s2len; char *new; s1len = ft_strlen(s1); s2len = ft_strlen(s2); new = (char *)malloc(sizeof(char) * (s1len + s2len + 1)); if (new == NULL && s1len + s2len + 1 > 0) return (NULL); i = 0; while (i < s1len) { new[i] = (char)s1[i]; i++; } while (i < s2len + s1len) { new[i] = (char)s2[i - s1len]; i++; } new[i] = '\0'; return (new); }
[ "aramon@student.42perpignan.fr" ]
aramon@student.42perpignan.fr
82d9b2d2d63fde977a7c25f279182be7a8565f37
74a6914d408e2d437f82bf9213dccea9700d9f87
/tests/test_buffer_new.c
71a7d9299e91cd0011c7b27f1af8814bcad35eef
[ "Apache-2.0" ]
permissive
adsr/mlbuf
19008aa99ceb7a789adf8b4c6ac80bffac684c86
48f2c5ce7a929ac1c3dd2059b73d730486a6f68c
refs/heads/master
2020-05-21T05:53:08.113192
2018-12-21T02:09:18
2018-12-21T02:09:18
27,909,890
5
1
Apache-2.0
2018-02-26T17:24:23
2014-12-12T07:19:10
C
UTF-8
C
false
false
68
c
#include "test.h" MAIN("hello\nworld", ASSERT("yes", 1, 1); )
[ "saponara@gmail.com" ]
saponara@gmail.com