hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
e29cb2e64a68996e0cdcd87c591546f745db20fe
3,333
h
C
rtp_rtcp/RtcRtpsource/rtp_format_h264.h
jjzhang166/KKPlayer2
6af2e2e0f7bfba88b30df250c60211368a08dd84
[ "MIT" ]
2
2018-08-10T03:10:47.000Z
2020-06-02T23:30:23.000Z
rtp_rtcp/RtcRtpsource/rtp_format_h264.h
jjzhang166/KKPlayer
b963cb9e2474cff94de1cec41994428fdbe1a0f5
[ "MIT" ]
null
null
null
rtp_rtcp/RtcRtpsource/rtp_format_h264.h
jjzhang166/KKPlayer
b963cb9e2474cff94de1cec41994428fdbe1a0f5
[ "MIT" ]
5
2017-09-29T04:02:20.000Z
2022-03-18T01:08:05.000Z
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_FORMAT_H264_H_ #define WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_FORMAT_H264_H_ #include <queue> #include <string> #include "rtp_format.h" namespace webrtc { class RtpPacketizerH264 : public RtpPacketizer { public: // Initialize with payload from encoder. // The payload_data must be exactly one encoded H264 frame. RtpPacketizerH264(FrameType frame_type, size_t max_payload_len); virtual ~RtpPacketizerH264(); virtual void SetPayloadData( const uint8_t* payload_data, size_t payload_size, const RTPFragmentationHeader* fragmentation) OVERRIDE; // Get the next payload with H264 payload header. // buffer is a pointer to where the output will be written. // bytes_to_send is an output variable that will contain number of bytes // written to buffer. The parameter last_packet is true for the last packet of // the frame, false otherwise (i.e., call the function again to get the // next packet). // Returns true on success or false if there was no payload to packetize. virtual bool NextPacket(uint8_t* buffer, size_t* bytes_to_send, bool* last_packet) OVERRIDE; virtual ProtectionType GetProtectionType() OVERRIDE; virtual StorageType GetStorageType(uint32_t retransmission_settings) OVERRIDE; virtual std::string ToString() OVERRIDE; private: struct Packet { Packet(size_t offset, size_t size, bool first_fragment, bool last_fragment, bool aggregated, uint8_t header) : offset(offset), size(size), first_fragment(first_fragment), last_fragment(last_fragment), aggregated(aggregated), header(header) {} size_t offset; size_t size; bool first_fragment; bool last_fragment; bool aggregated; uint8_t header; }; typedef std::queue<Packet> PacketQueue; void GeneratePackets(); void PacketizeFuA(size_t fragment_offset, size_t fragment_length); int PacketizeStapA(size_t fragment_index, size_t fragment_offset, size_t fragment_length); void NextAggregatePacket(uint8_t* buffer, size_t* bytes_to_send); void NextFragmentPacket(uint8_t* buffer, size_t* bytes_to_send); const uint8_t* payload_data_; size_t payload_size_; const size_t max_payload_len_; RTPFragmentationHeader fragmentation_; PacketQueue packets_; FrameType frame_type_; DISALLOW_COPY_AND_ASSIGN(RtpPacketizerH264); }; // Depacketizer for H264. class RtpDepacketizerH264 : public RtpDepacketizer { public: virtual ~RtpDepacketizerH264() {} virtual bool Parse(ParsedPayload* parsed_payload, const uint8_t* payload_data, size_t payload_data_length) OVERRIDE; }; } // namespace webrtc #endif // WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_FORMAT_H264_H_
32.048077
80
0.716772
5b0a3e4b5320298adee22fb573569452cba7355a
690
h
C
DeviceMatrix.h
achintya-kumar/Decentralized-State-Estimation-using-Nvidia-CUDA
78648c61538b0b059df539ac29b8516aa4bc20b2
[ "Apache-2.0" ]
null
null
null
DeviceMatrix.h
achintya-kumar/Decentralized-State-Estimation-using-Nvidia-CUDA
78648c61538b0b059df539ac29b8516aa4bc20b2
[ "Apache-2.0" ]
null
null
null
DeviceMatrix.h
achintya-kumar/Decentralized-State-Estimation-using-Nvidia-CUDA
78648c61538b0b059df539ac29b8516aa4bc20b2
[ "Apache-2.0" ]
null
null
null
#pragma once #include <iterator> #include <iostream> #include <fstream> #include <sstream> // 5 possible types of matrices. Currently in use are Double and ComplexZ. Both are Double precision Floating Point and Complex Numbers // Int was later introduced for storage of index-matrices. enum Dtype { Int, Float, Double, ComplexC, ComplexZ }; // Class representing the matrix allocation on GPU, its dimensions and data-type. class DeviceMatrix { public: int id; void* device_pointer; int width; int height; Dtype dtype; DeviceMatrix(); DeviceMatrix(void* matrix_device_pointer, int matrix_width, int matrix_height, Dtype matrix_dtype); DeviceMatrix(int id); ~DeviceMatrix(); };
25.555556
135
0.763768
8552d2482b8c13c6f9e777f67a517cbf946996d9
180
h
C
convbuf.h
aiquie/base64io
2cf5e93e58f3d42ece6cac6dc8c1dd2909dd99dd
[ "MIT" ]
null
null
null
convbuf.h
aiquie/base64io
2cf5e93e58f3d42ece6cac6dc8c1dd2909dd99dd
[ "MIT" ]
null
null
null
convbuf.h
aiquie/base64io
2cf5e93e58f3d42ece6cac6dc8c1dd2909dd99dd
[ "MIT" ]
null
null
null
#ifndef CONVBUF_H #define CONVBUF_H struct convbuf { char * p; int sz; }; extern struct convbuf const encbuf; extern struct convbuf const decbuf; #endif // CONVBUF_H
12.857143
35
0.705556
8bce107be4e53cb0940d70913649b4097ef3cef6
9,864
c
C
M051SeriesBSP/SampleCode/Driver/FMC/main.c
lazhartel/tinythread
a43be5c9047470375aae8d140b604aaea162b4ad
[ "MIT" ]
14
2015-08-20T14:10:57.000Z
2021-07-08T10:17:50.000Z
M051SeriesBSP/SampleCode/Driver/FMC/main.c
lazhartel/tinythread
a43be5c9047470375aae8d140b604aaea162b4ad
[ "MIT" ]
null
null
null
M051SeriesBSP/SampleCode/Driver/FMC/main.c
lazhartel/tinythread
a43be5c9047470375aae8d140b604aaea162b4ad
[ "MIT" ]
5
2015-03-27T01:53:46.000Z
2021-11-08T06:35:55.000Z
/**************************************************************************//** * @file Smpl_DrvFMC.c * @version V2.00 * $Revision: 4 $ * $Date: 12/04/23 7:41p $ * @brief M051 Series Flash Memory Controller Driver Sample Code * * @note * Copyright (C) 2011 Nuvoton Technology Corp. All rights reserved. * ******************************************************************************/ #include <stdio.h> #include "M051Series.h" #define PLLCON_SETTING SYSCLK_PLLCON_50MHz_XTAL #define PLL_CLOCK 50000000 #define KEY_ADDR 0x20000FFC /* The location of signature */ #define SIGNATURE 0x21557899 /* The signature word is used by AP code to check if simple LD is finished */ extern uint32_t loaderImageBase; extern uint32_t loaderImageLimit; uint32_t g_u32ImageSize; void SYS_Init(void) { /*---------------------------------------------------------------------------------------------------------*/ /* Init System Clock */ /*---------------------------------------------------------------------------------------------------------*/ /* Unlock protected registers */ SYS_UnlockReg(); /* Enable External XTAL (4~24 MHz) */ SYSCLK->PWRCON |= SYSCLK_PWRCON_XTL12M_EN_Msk; SYSCLK->PLLCON = PLLCON_SETTING; /* Waiting for clock ready */ SYS_WaitingForClockReady(SYSCLK_CLKSTATUS_PLL_STB_Msk | SYSCLK_CLKSTATUS_XTL12M_STB_Msk); /* Switch HCLK clock source to PLL */ SYSCLK->CLKSEL0 = SYSCLK_CLKSEL0_HCLK_PLL; /* Enable IP clock */ SYSCLK->APBCLK = SYSCLK_APBCLK_UART0_EN_Msk; /* Select IP clock source */ SYSCLK->CLKSEL1 = SYSCLK_CLKSEL1_UART_PLL; /* Update System Core Clock */ /* User can use SystemCoreClockUpdate() to calculate PllClock, SystemCoreClock and CycylesPerUs automatically. */ //SystemCoreClockUpdate(); PllClock = PLL_CLOCK; // PLL SystemCoreClock = PLL_CLOCK / 1; // HCLK CyclesPerUs = PLL_CLOCK / 1000000; // For SYS_SysTickDelay() /*---------------------------------------------------------------------------------------------------------*/ /* Init I/O Multi-function */ /*---------------------------------------------------------------------------------------------------------*/ /* Set P3 multi-function pins for UART0 RXD and TXD */ SYS->P3_MFP = SYS_MFP_P30_RXD0 | SYS_MFP_P31_TXD0; /* Lock protected registers */ SYS_LockReg(); } void UART0_Init(void) { /*---------------------------------------------------------------------------------------------------------*/ /* Init UART */ /*---------------------------------------------------------------------------------------------------------*/ /* Reset IP */ SYS->IPRSTC2 |= SYS_IPRSTC2_UART0_RST_Msk; SYS->IPRSTC2 &= ~SYS_IPRSTC2_UART0_RST_Msk; /* Configure UART0 and set UART0 Baudrate */ UART0->BAUD = UART_BAUD_MODE2 | UART_BAUD_DIV_MODE2(PLL_CLOCK, 115200); _UART_SET_DATA_FORMAT(UART0, UART_WORD_LEN_8 | UART_PARITY_NONE | UART_STOP_BIT_1); } void FMC_LDROM_Test(void) { int32_t i32Err; uint32_t u32Data, i, j, *pu32Loader; /* Enable LDROM Update */ _FMC_ENABLE_LD_UPDATE(); printf(" Erase LD ROM ............................... "); /* Page Erase LDROM */ for (i = 0; i < FMC_LDROM_SIZE; i += FMC_FLASH_PAGE_SIZE) FMC_Erase(FMC_LDROM_BASE + i); /* Erase Verify */ i32Err = 0; for (i = FMC_LDROM_BASE; i < (FMC_LDROM_BASE+FMC_LDROM_SIZE); i += 4) { u32Data = FMC_Read(i); if (u32Data != 0xFFFFFFFF) { i32Err = 1; } } if (i32Err) printf("[FAIL]\n"); else printf("[OK]\n"); printf(" Program LD ROM test ........................ "); /* Program LDROM and read out data to compare it */ for(i = FMC_LDROM_BASE; i < (FMC_LDROM_BASE+FMC_LDROM_SIZE); i += 4) { FMC_Write(i, i); } i32Err = 0; for(i = FMC_LDROM_BASE; i < (FMC_LDROM_BASE+FMC_LDROM_SIZE); i += 4) { u32Data = FMC_Read(i); if (u32Data != i) { i32Err = 1; } } if (i32Err) printf("[FAIL]\n"); else printf("[OK]\n"); printf(" Program Simple LD Code ..................... "); pu32Loader = (uint32_t *)&loaderImageBase; for (i=0;i<g_u32ImageSize;i+=FMC_FLASH_PAGE_SIZE) { FMC_Erase(FMC_LDROM_BASE + i); for (j=0;j<FMC_FLASH_PAGE_SIZE;j+=4) { FMC_Write(FMC_LDROM_BASE + i + j, pu32Loader[(i + j) / 4]); } } /* Verify loader */ i32Err = 0; for (i=0;i<g_u32ImageSize;i+=FMC_FLASH_PAGE_SIZE) { for (j=0;j<FMC_FLASH_PAGE_SIZE;j+=4) { u32Data = FMC_Read(FMC_LDROM_BASE + i + j); if (u32Data != pu32Loader[(i+j)/4]) i32Err = 1; if (i + j >= g_u32ImageSize) break; } } if (i32Err) { printf("[FAIL]\n"); } else { printf("[OK]\n"); /* Reset CPU to boot to LD mode */ printf("\n >>> Reset to LD mode <<<\n"); /* Make sure message has printed out */ _UART_WAIT_TX_EMPTY(UART0); FMC->ISPCON |= FMC_ISPCON_BS_LDROM; /* CPU Reset */ _SYS_RESET_CPU(); } } /*---------------------------------------------------------------------------------------------------------*/ /* Main Function */ /*---------------------------------------------------------------------------------------------------------*/ int32_t main (void) { uint8_t ch; uint32_t u32Data; /* Init System, IP clock and multi-function I/O */ SYS_Init(); /* Init UART0 for printf */ UART0_Init(); /* Unlock protected registers for ISP function */ SYS_UnlockReg(); /* Enable ISP function */ FMC->ISPCON |= FMC_ISPCON_ISPEN_Msk; /* Check the signature to check if Simple LD code is finished or not */ if (inp32(KEY_ADDR) == SIGNATURE) { /* Just clear SIGNATURE and finish the sample code if Simple LD code has been executed. */ outp32(KEY_ADDR, 0); /* Read BS */ printf(" Boot Mode .................................. "); if ((FMC->ISPCON & FMC_ISPCON_BS_Msk) == FMC_ISPCON_BS_APROM) printf("[APROM]\n"); else { printf("[LDROM]\n"); printf(" WARNING: The driver sample code must execute in AP mode!\n"); } goto lexit; } /* This sample code will demo some function about FMC: 1. Check if CPU boots from APROM 2. Read 96-bit UID 3. Erase LDROM, program LD sample code to LDROM, and verify LD sample code 4. Select next booting from LDROM and run LD sample code */ printf("\n\n"); printf("+--------------------------------------------------------+\n"); printf("| M05xx Flash Memory Controller Driver Sample Code |\n"); printf("+--------------------------------------------------------+\n"); printf("\nCPU @ %dHz\n\n", SystemCoreClock); /* Read BS */ printf(" Boot Mode .................................. "); if ((FMC->ISPCON & FMC_ISPCON_BS_Msk) == FMC_ISPCON_BS_APROM) printf("[APROM]\n"); else { printf("[LDROM]\n"); printf(" WARNING: The driver sample code must execute in AP mode!\n"); goto lexit; } /* Read UID */ printf(" UID[ 0:31] ................................. [0x%x]\n", FMC_ReadUID(0)); printf(" UID[32:63] ................................. [0x%x]\n", FMC_ReadUID(1)); printf(" UID[64:95] ................................. [0x%x]\n", FMC_ReadUID(2)); /* Read Data Flash base address */ printf(" Data Flash Base Address .................... [0x%x]\n", FMC->DFBADR); /* Check the data in LD ROM to avoid overwrite them */ u32Data = FMC_Read(FMC_LDROM_BASE); if (u32Data != 0xFFFFFFFF) { printf("\n WARNING: There is code in LD ROM.\n If you proceed, the code in LD ROM will be corrupted.\n"); printf(" Continue? [y/n]:"); ch = getchar(); putchar(ch); if (ch != 'y') goto lexit; printf("\n\n"); } /* Check LD image size */ g_u32ImageSize = (uint32_t)&loaderImageLimit - (uint32_t)&loaderImageBase; if (g_u32ImageSize == 0) { printf(" ERROR: Loader Image is 0 bytes!\n"); goto lexit; } if (g_u32ImageSize > FMC_LDROM_SIZE) { printf(" ERROR: Loader Image is larger than 4KBytes!\n"); goto lexit; } /* Erase LDROM, program LD sample code to LDROM, and verify LD sample code */ /* The chip will boot from LDROM and run LD sample code if LD sample code is downloaded successfully */ FMC_LDROM_Test(); lexit: /* Disable ISP function */ FMC->ISPCON &= ~FMC_ISPCON_ISPEN_Msk; /* Lock protected registers */ SYS_LockReg(); printf("\nFMC Sample Code Completed.\n"); }
31.615385
118
0.452149
8f78d86e6ff5d6f03b2ec495c87a3c7ede141c31
8,402
c
C
arch/arm/src/stm32/LWIP/lwip_app/lwip_comm/lwip_comm.c
MirrShad/NuttxSpace-nuttx
1b220792c91c5a5ef3aa738caaaa56ecfd21122a
[ "Zlib" ]
null
null
null
arch/arm/src/stm32/LWIP/lwip_app/lwip_comm/lwip_comm.c
MirrShad/NuttxSpace-nuttx
1b220792c91c5a5ef3aa738caaaa56ecfd21122a
[ "Zlib" ]
null
null
null
arch/arm/src/stm32/LWIP/lwip_app/lwip_comm/lwip_comm.c
MirrShad/NuttxSpace-nuttx
1b220792c91c5a5ef3aa738caaaa56ecfd21122a
[ "Zlib" ]
1
2021-05-03T09:34:24.000Z
2021-05-03T09:34:24.000Z
#include "lwip_comm.h" #include "netif/etharp.h" #include "lwip/dhcp.h" #include "lwip/mem.h" #include "lwip/memp.h" #include "lwip/init.h" #include "ethernetif.h" #include "lwip/timers.h" #include "lwip/tcp_impl.h" #include "lwip/ip_frag.h" #include "lwip/tcpip.h" #include <stdio.h> #include "Console.h" ////////////////////////////////////////////////////////////////////////////////// //本程序只供学习使用,未经作者许可,不得用于其它任何用途 //ALIENTEK STM32F407开发板 //lwip通用驱动 代码 //正点原子@ALIENTEK //技术论坛:www.openedv.com //创建日期:2014/8/15 //版本:V1.0 //版权所有,盗版必究。 //Copyright(C) 广州市星翼电子科技有限公司 2009-2019 //All rights reserved //******************************************************************************* //修改信息 //无 ////////////////////////////////////////////////////////////////////////////////// __lwip_dev lwipdev; //lwip控制结构体 struct netif lwip_netif; //定义一个全局的网络接口 //extern u32 memp_get_memorysize(void); //在memp.c里面定义 //extern u8_t *memp_memory; //在memp.c里面定义. //extern u8_t *ram_heap; //在mem.c里面定义. u32 TCPTimer=0; //TCP查询计时器 u32 ARPTimer=0; //ARP查询计时器 u32 lwip_localtime; //lwip本地时间计数器,单位:ms #if LWIP_DHCP u32 DHCPfineTimer=0; //DHCP精细处理计时器 u32 DHCPcoarseTimer=0; //DHCP粗糙处理计时器 #endif //lwip中mem和memp的内存申请 //返回值:0,成功; // 其他,失败 u8 lwip_comm_mem_malloc(void) { // u32 mempsize; // u32 ramheapsize; // mempsize=memp_get_memorysize(); //得到memp_memory数组大小 // memp_memory = (uint8_t*)mymalloc(SRAMIN,mempsize); //为memp_memory申请内存 // ramheapsize=LWIP_MEM_ALIGN_SIZE(MEM_SIZE)+2*LWIP_MEM_ALIGN_SIZE(4*3)+MEM_ALIGNMENT;//得到ram heap大小 // ram_heap = (uint8_t*)mymalloc(SRAMIN,ramheapsize); //为ram_heap申请内存 // if(!memp_memory||!ram_heap)//有申请失败的 // { // lwip_comm_mem_free(); // return 1; // } return 0; } //lwip中mem和memp内存释放 void lwip_comm_mem_free(void) { // myfree(SRAMIN,memp_memory); // myfree(SRAMIN,ram_heap); } //lwip 默认IP设置 //lwipx:lwip控制结构体指针 void lwip_comm_default_ip_set(__lwip_dev *lwipx) { u32 sn0; sn0=*(vu32*)(0x1FFF7A10);//获取STM32的唯一ID的前24位作为MAC地址后三字节 //默认远端IP为:192.168.1.100 lwipx->remoteip[0]=192; lwipx->remoteip[1]=168; lwipx->remoteip[2]=192; lwipx->remoteip[3]=104; //MAC地址设置(高三字节固定为:2.0.0,低三字节用STM32唯一ID) lwipx->mac[0]=2;//高三字节(IEEE称之为组织唯一ID,OUI)地址固定为:2.0.0 lwipx->mac[1]=0; lwipx->mac[2]=0; lwipx->mac[3]=(sn0>>16)&0XFF;//低三字节用STM32的唯一ID lwipx->mac[4]=(sn0>>8)&0XFFF;; lwipx->mac[5]=sn0&0XFF; //默认本地IP为:192.168.1.30 lwipx->ip[0]=192; lwipx->ip[1]=168; lwipx->ip[2]=192; lwipx->ip[3]=4; //默认子网掩码:255.255.255.0 lwipx->netmask[0]=255; lwipx->netmask[1]=255; lwipx->netmask[2]=255; lwipx->netmask[3]=0; //默认网关:192.168.1.1 lwipx->gateway[0]=192; lwipx->gateway[1]=168; lwipx->gateway[2]=192; lwipx->gateway[3]=15; lwipx->dhcpstatus=0;//没有DHCP } //LWIP初始化(LWIP启动的时候使用) //返回值:0,成功 // 1,内存错误 // 2,物理层芯片初始化失败 // 3,网卡添加失败. u8 lwip_comm_init(void) { struct netif *Netif_Init_Flag; //调用netif_add()函数时的返回值,用于判断网络初始化是否成功 struct ip_addr ipaddr; //ip地址 struct ip_addr netmask; //子网掩码 struct ip_addr gw; //默认网关 if(ETH_Mem_Malloc())return 1; //内存申请失败 // if(lwip_comm_mem_malloc())return 1; //内存申请失败 lwip_init(); //初始化LWIP内核 lwip_comm_default_ip_set(&lwipdev); //设置默认IP等信息 #if LWIP_DHCP //使用动态IP ipaddr.addr = 0; netmask.addr = 0; gw.addr = 0; #else //使用静态IP IP4_ADDR(&ipaddr,lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]); IP4_ADDR(&netmask,lwipdev.netmask[0],lwipdev.netmask[1] ,lwipdev.netmask[2],lwipdev.netmask[3]); IP4_ADDR(&gw,lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]); Console::Instance()->printf("Mac address: %d.%d.%d.%d.%d.%d\r\n",lwipdev.mac[0],lwipdev.mac[1],lwipdev.mac[2],lwipdev.mac[3],lwipdev.mac[4],lwipdev.mac[5]); Console::Instance()->printf("IP address: %d.%d.%d.%d\r\n",lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]); Console::Instance()->printf("Netmask: %d.%d.%d.%d\r\n",lwipdev.netmask[0],lwipdev.netmask[1],lwipdev.netmask[2],lwipdev.netmask[3]); Console::Instance()->printf("Default Gateway: %d.%d.%d.%d\r\n",lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]); #endif Netif_Init_Flag=netif_add(&lwip_netif,&ipaddr,&netmask,&gw,NULL,&ethernetif_init,&ethernet_input);//向网卡列表中添加一个网口 #if LWIP_DHCP //如果使用DHCP的话 lwipdev.dhcpstatus=0; //DHCP标记为0 dhcp_start(&lwip_netif); //开启DHCP服务 #endif if(Netif_Init_Flag == NULL) return -6;//网卡添加失败 else//网口添加成功后,设置netif为默认值,并且打开netif网口 { netif_set_default(&lwip_netif); //设置netif为默认网口 netif_set_up(&lwip_netif); //打开netif网口 } return 0;//操作OK. } //当接收到数据后调用 void lwip_pkt_handle(void) { //从网络缓冲区中读取接收到的数据包并将其发送给LWIP处理 ethernetif_input(&lwip_netif); } //LWIP轮询任务 void lwip_periodic_handle() { #if LWIP_TCP //每250ms调用一次tcp_tmr()函数 if (lwip_localtime - TCPTimer >= TCP_TMR_INTERVAL) { TCPTimer = lwip_localtime; tcp_tmr(); } #endif //ARP每5s周期性调用一次 if ((lwip_localtime - ARPTimer) >= ARP_TMR_INTERVAL) { ARPTimer = lwip_localtime; etharp_tmr(); } #if LWIP_DHCP //如果使用DHCP的话 //每500ms调用一次dhcp_fine_tmr() if (lwip_localtime - DHCPfineTimer >= DHCP_FINE_TIMER_MSECS) { DHCPfineTimer = lwip_localtime; dhcp_fine_tmr(); if ((lwipdev.dhcpstatus != 2)&&(lwipdev.dhcpstatus != 0XFF)) { lwip_dhcp_process_handle(); //DHCP处理 } } //每60s执行一次DHCP粗糙处理 if (lwip_localtime - DHCPcoarseTimer >= DHCP_COARSE_TIMER_MSECS) { DHCPcoarseTimer = lwip_localtime; dhcp_coarse_tmr(); } #endif } //如果使能了DHCP #if LWIP_DHCP //DHCP处理任务 void lwip_dhcp_process_handle(void) { u32 ip=0,netmask=0,gw=0; switch(lwipdev.dhcpstatus) { case 0: //开启DHCP dhcp_start(&lwip_netif); lwipdev.dhcpstatus = 1; //等待通过DHCP获取到的地址 Console::Instance()->printf("正在查找DHCP服务器,请稍等...........\r\n"); break; case 1: //等待获取到IP地址 { ip=lwip_netif.ip_addr.addr; //读取新IP地址 netmask=lwip_netif.netmask.addr;//读取子网掩码 gw=lwip_netif.gw.addr; //读取默认网关 if(ip!=0) //正确获取到IP地址的时候 { lwipdev.dhcpstatus=2; //DHCP成功 Console::Instance()->printf("网卡en的MAC地址为:................%d.%d.%d.%d.%d.%d\r\n",lwipdev.mac[0],lwipdev.mac[1],lwipdev.mac[2],lwipdev.mac[3],lwipdev.mac[4],lwipdev.mac[5]); //解析出通过DHCP获取到的IP地址 lwipdev.ip[3]=(uint8_t)(ip>>24); lwipdev.ip[2]=(uint8_t)(ip>>16); lwipdev.ip[1]=(uint8_t)(ip>>8); lwipdev.ip[0]=(uint8_t)(ip); Console::Instance()->printf("通过DHCP获取到IP地址..............%d.%d.%d.%d\r\n",lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]); //解析通过DHCP获取到的子网掩码地址 lwipdev.netmask[3]=(uint8_t)(netmask>>24); lwipdev.netmask[2]=(uint8_t)(netmask>>16); lwipdev.netmask[1]=(uint8_t)(netmask>>8); lwipdev.netmask[0]=(uint8_t)(netmask); Console::Instance()->printf("通过DHCP获取到子网掩码............%d.%d.%d.%d\r\n",lwipdev.netmask[0],lwipdev.netmask[1],lwipdev.netmask[2],lwipdev.netmask[3]); //解析出通过DHCP获取到的默认网关 lwipdev.gateway[3]=(uint8_t)(gw>>24); lwipdev.gateway[2]=(uint8_t)(gw>>16); lwipdev.gateway[1]=(uint8_t)(gw>>8); lwipdev.gateway[0]=(uint8_t)(gw); Console::Instance()->printf("通过DHCP获取到的默认网关..........%d.%d.%d.%d\r\n",lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]); }else if(lwip_netif.dhcp->tries>LWIP_MAX_DHCP_TRIES) //通过DHCP服务获取IP地址失败,且超过最大尝试次数 { lwipdev.dhcpstatus=0XFF;//DHCP超时失败. //使用静态IP地址 IP4_ADDR(&(lwip_netif.ip_addr),lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]); IP4_ADDR(&(lwip_netif.netmask),lwipdev.netmask[0],lwipdev.netmask[1],lwipdev.netmask[2],lwipdev.netmask[3]); IP4_ADDR(&(lwip_netif.gw),lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]); Console::Instance()->printf("DHCP服务超时,使用静态IP地址!\r\n"); Console::Instance()->printf("网卡en的MAC地址为:................%d.%d.%d.%d.%d.%d\r\n",lwipdev.mac[0],lwipdev.mac[1],lwipdev.mac[2],lwipdev.mac[3],lwipdev.mac[4],lwipdev.mac[5]); Console::Instance()->printf("静态IP地址........................%d.%d.%d.%d\r\n",lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]); Console::Instance()->printf("子网掩码..........................%d.%d.%d.%d\r\n",lwipdev.netmask[0],lwipdev.netmask[1],lwipdev.netmask[2],lwipdev.netmask[3]); Console::Instance()->printf("默认网关..........................%d.%d.%d.%d\r\n",lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]); } } break; default : break; } } #endif
29.377622
175
0.653178
df20678520a47a10fdbe8eca5c1eb1578bf457d7
1,864
h
C
gen_nxsscriptcontrol/resource.h
saivert/winamp-plugins
5dae16e80bb63e3de258b4279c444bf2434de564
[ "MIT" ]
3
2019-06-14T12:03:23.000Z
2022-02-12T18:15:38.000Z
gen_nxsscriptcontrol/resource.h
saivert/winamp-plugins
5dae16e80bb63e3de258b4279c444bf2434de564
[ "MIT" ]
null
null
null
gen_nxsscriptcontrol/resource.h
saivert/winamp-plugins
5dae16e80bb63e3de258b4279c444bf2434de564
[ "MIT" ]
null
null
null
//{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by gen_nxsscriptcontrol.rc // #define IDS_EXECUTE 1 #define IDS_HALT 2 #define IDS_EXAMPLE1 3 #define IDS_TIPABOUTPAGE 4 #define IDS_TIPSCRIPTPAGE 5 #define IDS_TIPGENERALPAGE 6 #define IDS_EXAMPLE2 7 #define IDS_EXAMPLE3 8 #define IDS_EXAMPLE4 9 #define IDD_CONFIGPAGE 103 #define IDD_ABOUT 107 #define IDD_TITLEFORMAT 108 #define IDD_SCRIPT 108 #define IDD_GENERAL 109 #define IDC_SCRIPTEDIT 1000 #define IDC_RUNSCRIPT 1001 #define IDC_CLEARSCRIPT 1002 #define IDC_SAVETOFILE 1003 #define IDC_LOADFROMFILE 1004 #define IDC_AUTHOR 1005 #define IDC_LOGLIST 1006 #define IDC_URLBUTTON 1007 #define IDC_HOMEPAGE 1007 #define IDC_LINKTOPAGE 1007 #define IDC_HOMEPAGE2 1008 #define IDC_SCLANGCOMBO 1009 #define IDC_HOMEPAGE3 1009 #define IDC_SCLANG 1010 #define IDC_LOADSAMPLE 1011 #define IDC_VERSION 1012 #define IDC_SAMPLECOMBO 1012 #define IDC_TAB1 1023 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 104 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1013 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
38.833333
54
0.539163
0e762bf53f772ea1a8433b5142ecd1e7b11b2a14
2,704
h
C
build/qCC/ui_sensorComputeDistancesDlg.h
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
build/qCC/ui_sensorComputeDistancesDlg.h
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
build/qCC/ui_sensorComputeDistancesDlg.h
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
1
2019-02-03T12:19:42.000Z
2019-02-03T12:19:42.000Z
/******************************************************************************** ** Form generated from reading UI file 'sensorComputeDistancesDlg.ui' ** ** Created by: Qt User Interface Compiler version 5.11.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_SENSORCOMPUTEDISTANCESDLG_H #define UI_SENSORCOMPUTEDISTANCESDLG_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QCheckBox> #include <QtWidgets/QDialog> #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QVBoxLayout> QT_BEGIN_NAMESPACE class Ui_sensorComputeDistancesDlg { public: QVBoxLayout *verticalLayout; QCheckBox *checkSquaredDistance; QDialogButtonBox *buttonBox; void setupUi(QDialog *sensorComputeDistancesDlg) { if (sensorComputeDistancesDlg->objectName().isEmpty()) sensorComputeDistancesDlg->setObjectName(QStringLiteral("sensorComputeDistancesDlg")); sensorComputeDistancesDlg->resize(178, 67); verticalLayout = new QVBoxLayout(sensorComputeDistancesDlg); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); checkSquaredDistance = new QCheckBox(sensorComputeDistancesDlg); checkSquaredDistance->setObjectName(QStringLiteral("checkSquaredDistance")); verticalLayout->addWidget(checkSquaredDistance); buttonBox = new QDialogButtonBox(sensorComputeDistancesDlg); buttonBox->setObjectName(QStringLiteral("buttonBox")); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); verticalLayout->addWidget(buttonBox); retranslateUi(sensorComputeDistancesDlg); QObject::connect(buttonBox, SIGNAL(accepted()), sensorComputeDistancesDlg, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), sensorComputeDistancesDlg, SLOT(reject())); QMetaObject::connectSlotsByName(sensorComputeDistancesDlg); } // setupUi void retranslateUi(QDialog *sensorComputeDistancesDlg) { sensorComputeDistancesDlg->setWindowTitle(QApplication::translate("sensorComputeDistancesDlg", "Sensor range computation", nullptr)); checkSquaredDistance->setText(QApplication::translate("sensorComputeDistancesDlg", "Squared distances", nullptr)); } // retranslateUi }; namespace Ui { class sensorComputeDistancesDlg: public Ui_sensorComputeDistancesDlg {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_SENSORCOMPUTEDISTANCESDLG_H
38.628571
142
0.697115
b8a5a01c878544c922838e80ec9f6da0d07bd678
16,567
h
C
MVMFirmwareUnitTests/mvm_fw_unit_test_config.h
fmselab/mvm-firmware
e11af30e47749e3b2505892172878e89f396b986
[ "Apache-2.0" ]
1
2021-02-13T14:11:22.000Z
2021-02-13T14:11:22.000Z
MVMFirmwareUnitTests/mvm_fw_unit_test_config.h
fmselab/mvm-firmware
e11af30e47749e3b2505892172878e89f396b986
[ "Apache-2.0" ]
1
2020-05-04T22:46:32.000Z
2020-05-05T07:21:26.000Z
MVMFirmwareUnitTests/mvm_fw_unit_test_config.h
fmselab/mvm-firmware
e11af30e47749e3b2505892172878e89f396b986
[ "Apache-2.0" ]
1
2020-05-09T15:25:07.000Z
2020-05-09T15:25:07.000Z
// // File: mvm_fw_unit_test_config.h // // Author: Francesco Prelz (Francesco.Prelz@mi.infn.it) // // Revision history: // 24-Apr-2020 Initial version. // 29-Apr-2020 Timeline of text commands added. // 18-May-2020 Added possibility to include other config files. // // Description: // Moved here the methods to access the JSON configuration file, // with a static instance of the config handle, as this seems so fashionable // around this project. // #ifndef _MVM_FW_TEST_CONFIG_H #define _MVM_FW_TEST_CONFIG_H #include <string> #include <vector> #include <iostream> #ifdef JSON_INSTEAD_OF_YAML #include <rapidjson/document.h> #include <rapidjson/error/en.h> #include <rapidjson/istreamwrapper.h> #else #include <yaml-cpp/yaml.h> #endif #include <cerrno> #include <cstring> // strerror() #include "SystemStatus.h" #include "quantity_timelines.hpp" struct sim_i2c_devaddr; class system_error { public: // We do this in the C way to keep to C++98 standard. system_error(): m_errs(::strerror(errno)) {} ~system_error() {} const std::string &get_err() const { return m_errs; } private: std::string m_errs; }; std::ostream& operator<< (std::ostream &os, const system_error &serr); const std::string MVM_FM_confattr_LogFile("LogFile"); const std::string MVM_FM_confattr_SerialTTY("SerialTTY"); const std::string MVM_FM_confattr_SerialPollTimeout("serial_port_timeout"); const std::string MVM_FM_confattr_StartTick("start_tick"); const std::string MVM_FM_confattr_EndTick("end_tick"); const std::string MVM_FM_confattr_EndMs("end_ms"); const std::string MVM_FM_confattr_CmdTimeline("command_timeline"); const std::string MVM_FM_confattr_MsScaleFactor("ms_scale_factor"); const std::string MVM_FM_confattr_UsWaitPerTick("us_wait_per_tick"); const std::string MVM_FM_confattr_DebugLevel("debug_level"); typedef std::map<qtl_tick_t, std::string> mvm_fw_test_cmds_t; extern mvm_fw_test_cmds_t FW_TEST_command_timeline; class mvm_fw_unit_test_config { public: #ifdef JSON_INSTEAD_OF_YAML typedef rapidjson::Document mvm_fw_test_config_t; #else typedef YAML::Node mvm_fw_test_config_t; #endif typedef std::vector<mvm_fw_unit_test_config> otherf_container; mvm_fw_unit_test_config(): m_valid(false), m_time_started(false) {} mvm_fw_unit_test_config(const std::string &conf_file): m_valid(false), m_time_started(false) { load_config(conf_file); } ~mvm_fw_unit_test_config() {} bool get_string(const std::string &name, std::string &value) const { if (!m_valid) return false; const char *cname=name.c_str(); #ifdef JSON_INSTEAD_OF_YAML if (m_conf.HasMember(cname)) { const rapidjson::Value& v(m_conf[cname]); if (!v.IsString()) return false; value = v.GetString(); #else YAML::Node v; if (v=m_conf[cname]) { if (!v.IsScalar()) return false; value = v.as<std::string>(); #endif return true; } else { otherf_container::const_iterator oit; otherf_container::const_iterator oend = m_other_confs.end(); for (oit = m_other_confs.begin(); oit != oend; ++oit) { if (oit->get_string(name, value)) return true; } } return false; } template<typename TNUM> bool get_number(const std::string &name, TNUM &value) const { if (!m_valid) return false; const char *cname=name.c_str(); #ifdef JSON_INSTEAD_OF_YAML if (m_conf.HasMember(cname)) { const rapidjson::Value& v(m_conf[cname]); if (!v.IsNumber()) return false; value = v.Get<TNUM>(); #else YAML::Node v; if (v = m_conf[cname]) { if (!v.IsScalar()) return false; value = v.as<TNUM>(); #endif return true; } else { otherf_container::const_iterator oit; otherf_container::const_iterator oend = m_other_confs.end(); for (oit = m_other_confs.begin(); oit != oend; ++oit) { if (oit->get_number(name, value)) return true; } } return false; } template<typename TNUM> bool get_num_array(const std::string &name, TNUM *value, int size) const { if (!m_valid) return false; const char *cname=name.c_str(); #ifdef JSON_INSTEAD_OF_YAML if (m_conf.HasMember(cname)) { const rapidjson::Value& a(m_conf[cname]); if (!a.IsArray()) return false; for (rapidjson::SizeType i = 0; ((i < a.Size())&&(i < size)); i++) { const rapidjson::Value& v(a[i]); if (!(v.IsNumber())) #else YAML::Node a; if (a = m_conf[cname]) { if (!a.IsSequence()) return false; for (std::size_t i = 0; ((i < a.size())&&(i < size)); i++) { YAML::Node v = a[i]; if (!(v.IsScalar())) #endif { value[i] = 0; continue; } #ifdef JSON_INSTEAD_OF_YAML value[i] = v.Get<TNUM>(); #else value[i] = v.as<TNUM>(); #endif } return true; } else { otherf_container::const_iterator oit; otherf_container::const_iterator oend = m_other_confs.end(); for (oit = m_other_confs.begin(); oit != oend; ++oit) { if (oit->get_num_array(name, value, size)) return true; } } return false; } bool get_ushort_array(const std::string &name, uint16_t *value, int size) const { // It seems that no template classes can be instantiated for // uint16_t's. if (!m_valid) return false; const char *cname=name.c_str(); #ifdef JSON_INSTEAD_OF_YAML if (m_conf.HasMember(cname)) { const rapidjson::Value& a(m_conf[cname]); if (!a.IsArray()) return false; for (rapidjson::SizeType i = 0; ((i < a.Size())&&(i < size)); i++) { const rapidjson::Value& v(a[i]); if (!(v.IsNumber())) #else YAML::Node a; if (a = m_conf[cname]) { if (!a.IsSequence()) return false; for (std::size_t i = 0; ((i < a.size())&&(i < size)); i++) { YAML::Node v = a[i]; if (!(v.IsScalar())) #endif { value[i] = 0; continue; } #ifdef JSON_INSTEAD_OF_YAML value[i] = static_cast<uint16_t>(v.GetInt()); #else value[i] = v.as<uint16_t>(); #endif } return true; } else { otherf_container::const_iterator oit; otherf_container::const_iterator oend = m_other_confs.end(); for (oit = m_other_confs.begin(); oit != oend; ++oit) { if (oit->get_ushort_array(name, value, size)) return true; } } return false; } bool get_bool(const std::string &name, bool &value) const { if (!m_valid) return false; const char *cname=name.c_str(); #ifdef JSON_INSTEAD_OF_YAML if (m_conf.HasMember(cname)) { const rapidjson::Value& v(m_conf[cname]); if (!v.IsBool()) return false; value = v.GetBool(); #else YAML::Node v; if (v = m_conf[cname]) { if (!v.IsScalar()) return false; value = v.as<bool>(); #endif return true; } else { otherf_container::const_iterator oit; otherf_container::const_iterator oend = m_other_confs.end(); for (oit = m_other_confs.begin(); oit != oend; ++oit) { if (oit->get_bool(name, value)) return true; } } return false; } bool load_config(const char *conf_file); bool load_config(const std::string &conf_file) { return load_config(conf_file.c_str()); } const mvm_fw_test_config_t &get_conf() const { return m_conf; } const std::string &get_error_string() const { return m_error_string; } int load_command_timeline(mvm_fw_test_cmds_t &ctl, const std::string &name=MVM_FM_confattr_CmdTimeline) const; template<typename TNUM> void initialize_qtl(quantity_timelines<TNUM> &qtl, const std::string &name=default_head_el) const { otherf_container::const_iterator oit; otherf_container::const_iterator oend = m_other_confs.end(); for (oit = m_other_confs.begin(); oit != oend; ++oit) { oit->initialize_qtl(qtl, name); } qtl.initialize(m_conf, name.c_str(), mvm_fw_unit_test_dirname(m_conf_file)); } void start_time() { if (!get_number<double>(MVM_FM_confattr_MsScaleFactor, m_time_scale)) { m_time_scale = 1.; } ::clock_gettime(CLOCK_REALTIME, &m_start_time); m_time_started = true; } timespec get_current_rt() { timespec now, ret; ::clock_gettime(CLOCK_REALTIME, &now); if (!m_time_started) return now; ret.tv_sec = now.tv_sec - m_start_time.tv_sec; int nsec_d = now.tv_nsec - m_start_time.tv_nsec; if (nsec_d < 0) { --(ret.tv_sec); ret.tv_nsec = nsec_d + 1000000000; } else ret.tv_nsec = nsec_d; return ret; } double get_scale_factor() const { return m_time_scale; } qtl_ms_t get_scaled_ms() { timespec cr=get_current_rt(); qtl_ms_t ret = (cr.tv_sec * 1000) + (cr.tv_nsec/1000000); ret *= m_time_scale; return ret; } const otherf_container &get_other_confs() const { return m_other_confs; } void clear_other_confs () { m_other_confs.clear(); } private: std::string m_conf_file; std::string m_error_string; bool m_valid; //WARNING: const methods to *read* the configuration will try to // change the YAML node state. Has to stay mutable. mutable mvm_fw_test_config_t m_conf; bool m_time_started; double m_time_scale; timespec m_start_time; otherf_container m_other_confs; }; extern quantity_timelines<double> FW_TEST_qtl_double; extern qtl_tick_t FW_TEST_tick; extern qtl_ms_t FW_TEST_ms; extern t_SystemStatus *FW_TEST_peek_system_status; extern mvm_fw_unit_test_config FW_TEST_main_config; class mvm_fw_gpio_devs { public: mvm_fw_gpio_devs() { uint32_t pv1_init; // RapidJSON doesn't handle 16-bit types. if (!FW_TEST_main_config.get_number<uint32_t>("PV1_init", pv1_init)) { m_pv1_value = 0; // Default: start w/ valve closed. } else m_pv1_value = static_cast<uint16_t>(pv1_init); uint32_t gpio_init; // Default: valves open, no LED. if (!FW_TEST_main_config.get_number<uint32_t>("GPIO_init", gpio_init)) { gpio_init = 0; // Default: valves open, no LEDs. } for (int i = 0; i<LAST_REG; ++i) { if (gpio_init & (1<<i)) m_devs[i] = true; else m_devs[i] = false; } } ~mvm_fw_gpio_devs() {} enum mvm_fw_bool_regs { BREATHE, OUT_VALVE, BUZZER, ALARM_LED, ALARM_RELAY, LAST_REG }; bool set(mvm_fw_bool_regs dev, bool value) { double enable, override; bool ret = false; enable = FW_TEST_qtl_double.value(std::string(m_names[dev])+"_enable", FW_TEST_ms); override = FW_TEST_qtl_double.value(std::string(m_names[dev])+"_override", FW_TEST_ms); timespec now; ::clock_gettime(CLOCK_REALTIME, &now); bool old_value = m_devs[dev]; m_msg.str(""); m_msg.clear(); m_msg << "GPIO - DEVS" << " - " << m_names[dev] << " - " << now.tv_sec << ":" << now.tv_nsec/1000000 << " - ms (scaled):" << FW_TEST_ms << " - tick:" << FW_TEST_tick << " - Alarms: " << std::hex << std::showbase << FW_TEST_peek_system_status->ALARM_FLAG << " - Warnings: " << FW_TEST_peek_system_status->WARNING_FLAG << " - " << std::dec << std::noshowbase ; if (std::isnan(enable) || (!std::isnan(enable) && (enable != 0))) { if (!std::isnan(override)) { if (override != 0) value = false; else value = true; m_msg << " value forced to " << value << " by configuration -"; } m_devs[dev] = value; m_msg << " value set to " << value; ret = true; if (m_devs[dev] == old_value) { // Don't log too verbosely. m_msg.str(""); m_msg.clear(); } } else { m_msg << "device disabled in config. NOT set to " << value << " - current value is " << m_devs[dev]; } if (m_msg.str().length() > 0) m_msg << std::endl; return ret; } bool set_pv1(uint16_t value) { double enable, override; bool ret = false; enable = FW_TEST_qtl_double.value("PV1_enable", FW_TEST_ms); override = FW_TEST_qtl_double.value("PV1_override", FW_TEST_ms); timespec now; ::clock_gettime(CLOCK_REALTIME, &now); uint16_t old_pv1_value = m_pv1_value; m_msg.str(""); m_msg.clear(); m_msg << "GPIO - DEVS - PV1 - " << now.tv_sec << ":" << now.tv_nsec/1000000 << " - ms (scaled):" << FW_TEST_ms << " - tick:" << FW_TEST_tick << " - "; if (std::isnan(enable) || (!std::isnan(enable) && (enable != 0))) { if (!std::isnan(override)) { value = static_cast<uint16_t>(override); m_msg << " value forced to " << value << " by configuration -"; } m_pv1_value = value; m_msg << "value set to " << value; ret = true; if (m_pv1_value == old_pv1_value) { // Don't log too verbosely. m_msg.str(""); m_msg.clear(); } } else { m_msg << "device disabled in config. NOT set to " << value << " - current value is " << m_pv1_value; } if (m_msg.str().length() > 0) m_msg << std::endl; return ret; } const std::string &get_error_msg() { m_msg_str = m_msg.str(); return m_msg_str; } bool operator[](mvm_fw_bool_regs dev) const { return m_devs[dev]; } uint16_t get_pv1() const { return m_pv1_value; } double get_pv1_fraction() const { // Fraction of *opening* of the valve. Zero is valve *closed* // (confirmed on 20200506) - which is also the initial valve status. return ((static_cast<double>(m_pv1_value) / 0xffff)); } private: bool m_devs[LAST_REG]; std::ostringstream m_msg; std::string m_msg_str; uint16_t m_pv1_value; const char *m_names[LAST_REG] = { "BREATHE", "OUT_VALVE", "BUZZER", "ALARM_LED", "ALARM_RELAY" }; }; extern mvm_fw_gpio_devs FW_TEST_gdevs; class mvm_fw_unit_test_pflow { public: mvm_fw_unit_test_pflow(): m_inited(false) {} ~mvm_fw_unit_test_pflow() {} void init(); double p_value(const std::string &name, qtl_ms_t t); double in_f_value(qtl_ms_t t); double v_f_value(qtl_ms_t t); double get_venturi_linear_coefficient() const { return m_venturi_flow_at_1_psi_drop; } enum p_sensors { PI3, PI2, PI1, LAST_PS }; private: bool m_inited; qtl_ms_t m_last_ms; void m_evolve(qtl_tick_t t); double m_m_resistance, m_in_v_resistance, m_out_v_resistance; double m_overpressure, m_peep; double m_capacity, m_lung_max_capacity, m_lung_k; double m_gas, m_gas_rest, m_gas_old; double m_in_flow, m_v_flow; double m_cur_p, m_old_c; double m_venturi_flow_at_1_psi_drop; double m_p[LAST_PS]; }; extern mvm_fw_unit_test_pflow FW_TEST_pflow; /* Hardware map */ enum FW_TEST_devices { TEST_TE_MS5525DSO, TEST_SENSIRION_SFM3019, TEST_TI_ADS1115, TEST_TCA_I2C_MULTIPLEXER, TEST_XXX_SUPERVISOR }; typedef std::map<sim_i2c_devaddr, std::pair<FW_TEST_devices, std::string> > test_hardware_t; extern test_hardware_t FW_TEST_hardware; extern qtl_tick_t FW_TEST_last_watchdog_reset; extern int FW_TEST_debug_level; extern int FW_TEST_serial_poll_timeout; #endif /* defined _MVM_FW_TEST_CONFIG_H */
28.319658
92
0.590391
8ff1e5c57f04f0742171a9506499794cf5a07f8d
250
c
C
src/pbhelper/pbhelper_DrawCylinder.c
D-a-n-i-l-o/raylib-purebasic
ef8cafa7be2fab4a742ab8bc4ec4e33d2d4e7cac
[ "Zlib" ]
15
2020-05-07T16:55:13.000Z
2022-03-06T10:52:54.000Z
src/pbhelper/pbhelper_DrawCylinder.c
D-a-n-i-l-o/raylib-purebasic
ef8cafa7be2fab4a742ab8bc4ec4e33d2d4e7cac
[ "Zlib" ]
null
null
null
src/pbhelper/pbhelper_DrawCylinder.c
D-a-n-i-l-o/raylib-purebasic
ef8cafa7be2fab4a742ab8bc4ec4e33d2d4e7cac
[ "Zlib" ]
2
2020-05-07T09:43:17.000Z
2021-09-24T03:19:31.000Z
#include "raylib_pb_helper.h" void pbhelper_DrawCylinder(Vector3* position, float radiusTop, float radiusBottom, float height, int slices, Color color) { if( position ) DrawCylinder(*position, radiusTop, radiusBottom, height, slices, color); }
41.666667
123
0.772
dee830e12324b517da042022574950b37e7fb5fe
321
h
C
src/c99/gfx.h
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
null
null
null
src/c99/gfx.h
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
null
null
null
src/c99/gfx.h
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
null
null
null
#ifndef ARI_GFX_H #define ARI_GFX_H #include "macros.h" #include "core.h" // Texture CARI_HANDLE(TextureHandle) CARI_API bool IsValidTexture(uint32_t& _handle); CARI_API TextureHandle LoadTexture(char* _path); // SubMesh CARI_HANDLE(SubMeshHandle) CARI_API bool IsValidSubMesh(uint32_t& _handle); #endif // ARI_GFX_H
18.882353
48
0.794393
729f14088f0af797211c037b765fbaa6d96ffe68
399
c
C
PartTwo/col08/q8_7_11a.c
sujimodern/Programming-Pearls
354c6d4e3b7149b1b0fdac442610b7d3776f1131
[ "MIT" ]
null
null
null
PartTwo/col08/q8_7_11a.c
sujimodern/Programming-Pearls
354c6d4e3b7149b1b0fdac442610b7d3776f1131
[ "MIT" ]
null
null
null
PartTwo/col08/q8_7_11a.c
sujimodern/Programming-Pearls
354c6d4e3b7149b1b0fdac442610b7d3776f1131
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> enum { num_tolls = 7 }; int main(int argc, char* argv[argc+1]) { size_t tolls[num_tolls] = {500, 300, 120, 600, 750, 250, 80}; size_t begin = 1; size_t end = 6; size_t total = 0; for (size_t i = 0; i < num_tolls; ++i) { if (begin <= i && i <= end) { total += tolls[i]; } } printf("toll = %lu\n", total); return EXIT_SUCCESS; }
21
63
0.558897
6971c84c4f9ccf96a435f76b8e2af3573f51f229
122
h
C
include/lspe/contact.h
ZYMelaii/LSP-Engine
675ce5340152e23d9f23c857c99027cd733ef575
[ "MIT" ]
1
2021-09-23T09:25:32.000Z
2021-09-23T09:25:32.000Z
include/lspe/contact.h
ZYMelaii/LSP-Engine
675ce5340152e23d9f23c857c99027cd733ef575
[ "MIT" ]
null
null
null
include/lspe/contact.h
ZYMelaii/LSP-Engine
675ce5340152e23d9f23c857c99027cd733ef575
[ "MIT" ]
null
null
null
#pragma once namespace lspe { class ContactInfo { public: ContactInfo(); ~ContactInfo(); protected: private: }; }
6.421053
17
0.680328
e65c60bd165c07f095882f24a823e50725c23faf
630
h
C
Turn Touch Mac/Modes/Nest/TTModeNestSetTempOptions.h
samuelclay/turntouch-app
da23df56bdf27e7c665313dcbc39adc10794f916
[ "MIT" ]
13
2019-01-06T15:38:06.000Z
2021-12-07T12:39:54.000Z
Turn Touch Mac/Modes/Nest/TTModeNestSetTempOptions.h
samuelclay/turntouch-app
da23df56bdf27e7c665313dcbc39adc10794f916
[ "MIT" ]
16
2019-04-24T17:32:58.000Z
2021-02-22T22:20:43.000Z
Turn Touch Mac/Modes/Nest/TTModeNestSetTempOptions.h
samuelclay/turntouch-app
da23df56bdf27e7c665313dcbc39adc10794f916
[ "MIT" ]
4
2019-01-04T22:48:39.000Z
2021-02-27T17:56:58.000Z
// // TTModeNestSetTemperatureOptions.h // Turn Touch Remote // // Created by Samuel Clay on 1/19/16. // Copyright © 2016 Turn Touch. All rights reserved. // #import "TTOptionsDetailViewController.h" @interface TTModeNestSetTempOptions : TTOptionsDetailViewController @property (nonatomic) IBOutlet NSPopUpButton *thermostatPopup; @property (nonatomic) IBOutlet NSTextField *labelTemp; @property (nonatomic) IBOutlet NSSlider *sliderTemp; @property (nonatomic) IBOutlet TTSegmentedControl *heatControl; @property (nonatomic) IBOutlet NSLayoutConstraint *heatControlWidth; - (IBAction)didChangeThermostat:(id)sender; @end
28.636364
68
0.796825
0a667b20597e60f733d15281912397cbcd40e460
983
c
C
Examene/1c2019/1/2(strings).c
RiedelNicolas/Final-Taller-7542-CursoVeiga
05fc8a2acc7de2db622111cb9398a44efe074742
[ "MIT" ]
null
null
null
Examene/1c2019/1/2(strings).c
RiedelNicolas/Final-Taller-7542-CursoVeiga
05fc8a2acc7de2db622111cb9398a44efe074742
[ "MIT" ]
null
null
null
Examene/1c2019/1/2(strings).c
RiedelNicolas/Final-Taller-7542-CursoVeiga
05fc8a2acc7de2db622111cb9398a44efe074742
[ "MIT" ]
null
null
null
/*Escriba una función ISO C llamada Replicar que reciba 1 cadena (S), dos índices (I1 e I2) y una cantidad (Q). La función debe retornar una copia de S salvo los caracteres que se encuentran entre los índices I1 e I2 que serán duplicados Q veces. Ej. replicar(“Hola”, 1, 2, 3) retorna “Hololola”. */ #include <stdio.h> char* replicar (const char* S, size_t I1, size_t I2, size_t Q) { if(I1>=strlen(S) || I2>=strlen(S) || I2 < I1){ fprintf(stderr, "Parametros incorrectos pai."); return NULL; } size_t len = (strlen(S) + ((Q-1)*(I1-I2+1)) +1); char* replicado = (char*) malloc(sizeof(char)*len); size_t j = 0; for (size_t i = 0; i < strlen(S); i++) { if (i < I1 || i> I2) { replicado[j] = S[i]; j++; continue; } while (Q>0) { for (size_t k = I1; i <= I2; i++) { replicado[j]=S[k]; j++; } } Q--; } }
31.709677
91
0.513733
f8a47f43a07a6171e5c5fd5c35e594da673b9345
252
h
C
src/address_interpreter.h
YVEF/CLRPEPatcher
dc3fc848f2253a00c133b8644813b5b6d713f356
[ "MIT" ]
1
2021-02-08T14:06:03.000Z
2021-02-08T14:06:03.000Z
src/address_interpreter.h
YVEF/CLRPEPatcher
dc3fc848f2253a00c133b8644813b5b6d713f356
[ "MIT" ]
null
null
null
src/address_interpreter.h
YVEF/CLRPEPatcher
dc3fc848f2253a00c133b8644813b5b6d713f356
[ "MIT" ]
null
null
null
#pragma once #include <windows.h> class address_interpreter { public: static DWORD to_rva(const IMAGE_SECTION_HEADER* pSectionHeader, const DWORD& virt_addr); static DWORD to_va(const IMAGE_SECTION_HEADER* section_header, const DWORD& rva); };
28
92
0.785714
0a21e067afd6a00a3385bec23ce642109b462659
1,159
h
C
MassiveCompute/Schedulers/EqualBlockScheduler.h
sssr33/Raytracer
b06dff8f81f7c0f5ead4dee0be4186a7bfe5cb44
[ "MIT" ]
2
2020-07-02T16:21:56.000Z
2020-11-04T19:39:51.000Z
MassiveCompute/Schedulers/EqualBlockScheduler.h
sssr33/Raytracer
b06dff8f81f7c0f5ead4dee0be4186a7bfe5cb44
[ "MIT" ]
null
null
null
MassiveCompute/Schedulers/EqualBlockScheduler.h
sssr33/Raytracer
b06dff8f81f7c0f5ead4dee0be4186a7bfe5cb44
[ "MIT" ]
null
null
null
#pragma once #include "../Image.h" #include "../BaseFunctor.h" #include <functional> namespace MassiveCompute { class EqualBlockScheduler { public: void operator()(Image& img, BaseFunctor functor); private: class ThreadFunctor { public: ThreadFunctor(Image& img, BaseFunctor functor, size_t y, size_t height); void operator()(); private: Block block; BaseFunctor functor; }; // Determines height of the block considering <residualHeight>. // <residualHeight> is a height that is left after dividing image height equaly between threads. // EXAMPLE // For 4 thread cpu and image.Height == 7 each of 4 threads gets 1 row and <residualHeight> == 3. // If we will give last thread all of the left rows then row distribution will be // th1: 1row th2: 1row th3: 1row th4: 4rows // this distribution gives 4th thread 4 times more rows than 1 - 3 thread gets. // This method takes into account <residualHeight> == 3 and distributes it to each thread which gives: // th1: 2rows th2: 2rows th3: 2rows th4: 1row static size_t GetHeightForThread(size_t threadIdx, size_t heightPerThread, size_t residualHeight); }; }
29.717949
104
0.722174
92f628486deb13153c700f89d260f884672c0be3
167,333
c
C
library/ssl_tls13_server.c
eembc/mbedtls
32bb4a3fe388e46f6734b3056525561c77886437
[ "Apache-2.0" ]
null
null
null
library/ssl_tls13_server.c
eembc/mbedtls
32bb4a3fe388e46f6734b3056525561c77886437
[ "Apache-2.0" ]
null
null
null
library/ssl_tls13_server.c
eembc/mbedtls
32bb4a3fe388e46f6734b3056525561c77886437
[ "Apache-2.0" ]
null
null
null
/* * TLSv1.3 server-side functions * * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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. * * This file is part of mbed TLS ( https://tls.mbed.org ) */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) #if defined(MBEDTLS_SSL_SRV_C) #include "mbedtls/debug.h" #include "mbedtls/ssl.h" #include "mbedtls/ssl_internal.h" #include "ssl_tls13_keys.h" #include <string.h> #if defined(MBEDTLS_ECP_C) #include "mbedtls/ecp.h" #endif /* MBEDTLS_ECP_C */ #include "mbedtls/hkdf.h" #if defined(MBEDTLS_SSL_NEW_SESSION_TICKET) #include "mbedtls/ssl_ticket.h" #endif /* MBEDTLS_SSL_NEW_SESSION_TICKET */ #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif /* MBEDTLS_PLATFORM_C */ #if defined(MBEDTLS_HAVE_TIME) #include <time.h> #endif /* MBEDTLS_HAVE_TIME */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) static int ssl_write_sni_server_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t buflen, size_t *olen ) { unsigned char *p = buf; *olen = 0; if( ( ssl->handshake->extensions_present & SERVERNAME_EXTENSION ) == 0 ) { return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding server_name extension" ) ); if( buflen < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } /* Write extension header */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME ) & 0xFF ); /* Write total extension length */ *p++ = 0; *p++ = 0; *olen = 4; return( 0 ); } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ /* Key Shares Extension enum { obsolete_RESERVED( 1..22 ), secp256r1( 23 ), secp384r1( 24 ), secp521r1( 25 ), obsolete_RESERVED( 26..28 ), x25519( 29 ), x448( 30 ), ffdhe2048( 256 ), ffdhe3072( 257 ), ffdhe4096( 258 ), ffdhe6144( 259 ), ffdhe8192( 260 ), ffdhe_private_use( 0x01FC..0x01FF ), ecdhe_private_use( 0xFE00..0xFEFF ), obsolete_RESERVED( 0xFF01..0xFF02 ), ( 0xFFFF ) } NamedGroup; struct { NamedGroup group; opaque key_exchange<1..2^16-1>; } KeyShareEntry; struct { select ( role ) { case client: KeyShareEntry client_shares<0..2^16-1>; case server: KeyShareEntry server_share; } } KeyShare; */ #if ( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ) static int ssl_write_key_shares_ext( mbedtls_ssl_context *ssl, unsigned char* buf, unsigned char* end, size_t* olen ) { unsigned char *p = buf + 4; unsigned char *header = buf; /* Pointer where the header has to go. */ size_t len; int ret; const mbedtls_ecp_curve_info *info = NULL; /* const mbedtls_ecp_group_id *grp_id; */ *olen = 0; /* TBD: Can we say something about the smallest number of bytes needed for the ecdhe parameters */ if( end < p || ( end - p ) < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } if( ssl->conf->curve_list == NULL ) { /* This should never happen since we previously checked the * server-supported curves against the client-provided curves. * We should have returned a HelloRetryRequest instead. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "server key share extension: empty curve list" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding key share extension" ) ); /* Fetching the agreed curve. */ info = mbedtls_ecp_curve_info_from_grp_id( ssl->handshake->ecdh_ctx[ssl->handshake->ecdh_ctx_selected].grp.id ); if( info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "server key share extension: fetching agreed curve failed" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDHE curve: %s", info->name ) ); if( ( ret = mbedtls_ecp_group_load( &ssl->handshake->ecdh_ctx[ssl->handshake->ecdh_ctx_selected].grp, info->grp_id ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecp_group_load", ret ); return( ret ); } if( ( ret = mbedtls_ecdh_make_params( &ssl->handshake->ecdh_ctx[ssl->handshake->ecdh_ctx_selected], &len, p, end-buf, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_params", ret ); return( ret ); } p += len; MBEDTLS_SSL_DEBUG_ECP( 3, "ECDHE: Q ", &ssl->handshake->ecdh_ctx[ssl->handshake->ecdh_ctx_selected].Q ); /* Write extension header */ *header++ = (unsigned char)( ( MBEDTLS_TLS_EXT_KEY_SHARES >> 8 ) & 0xFF ); *header++ = (unsigned char)( ( MBEDTLS_TLS_EXT_KEY_SHARES ) & 0xFF ); /* Write total extension length */ *header++ = (unsigned char)( ( ( len ) >> 8 ) & 0xFF ); *header++ = (unsigned char)( ( ( len ) ) & 0xFF ); *olen = len + 4; /* 4 bytes for fixed header + length of key share */ return( 0 ); } #endif /* MBEDTLS_ECDH_C && MBEDTLS_ECDSA_C */ #if ( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ) /* TODO: Code for MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED missing */ static int check_ecdh_params( const mbedtls_ssl_context *ssl ) { const mbedtls_ecp_curve_info *curve_info; curve_info = mbedtls_ecp_curve_info_from_grp_id( ssl->handshake->ecdh_ctx[ssl->handshake->ecdh_ctx_selected].grp.id ); if( curve_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name ) ); #if defined(MBEDTLS_ECP_C) if( mbedtls_ssl_check_curve( ssl, ssl->handshake->ecdh_ctx[ssl->handshake->ecdh_ctx_selected].grp.id ) != 0 ) #else if( ssl->handshake->ecdh_ctx.grp.nbits < 163 || ssl->handshake->ecdh_ctx.grp.nbits > 521 ) #endif /* MBEDTLS_ECP_C */ return( -1 ); MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Qp", &ssl->handshake->ecdh_ctx[ssl->handshake->ecdh_ctx_selected].Qp ); return( 0 ); } #endif /* MBEDTLS_ECDH_C || ( MBEDTLS_ECDSA_C */ #if ( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ) /* mbedtls_ssl_parse_supported_groups_ext( ) processes the received supported groups extension and copies the client provided groups into ssl->handshake->curves. Possible response values are: - MBEDTLS_ERR_SSL_BAD_HS_SUPPORTED_GROUPS - MBEDTLS_ERR_SSL_ALLOC_FAILED */ int mbedtls_ssl_parse_supported_groups_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_size, our_size; const unsigned char *p; const mbedtls_ecp_curve_info *curve_info, **curves; MBEDTLS_SSL_DEBUG_BUF( 3, "Received supported groups", buf, len ); list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( list_size + 2 != len || list_size % 2 != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad supported groups extension" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SUPPORTED_GROUPS ); } /* Should never happen unless client duplicates the extension */ /* if( ssl->handshake->curves != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad supported groups extension" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SUPPORTED_GROUPS ); } */ /* Don't allow our peer to make us allocate too much memory, * and leave room for a final 0 */ our_size = list_size / 2 + 1; if( our_size > MBEDTLS_ECP_DP_MAX ) our_size = MBEDTLS_ECP_DP_MAX; if( ( curves = mbedtls_calloc( our_size, sizeof( *curves ) ) ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_calloc failed" ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } ssl->handshake->curves = curves; p = buf + 2; while ( list_size > 0 && our_size > 1 ) { curve_info = mbedtls_ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] ); /* mbedtls_ecp_curve_info_from_tls_id( ) uses the mbedtls_ecp_curve_info data structure ( defined in ecp.c ), which only includes the list of curves implemented. Hence, we only add curves that are also supported and implemented by the server. */ if( curve_info != NULL ) { *curves++ = curve_info; MBEDTLS_SSL_DEBUG_MSG( 5, ( "supported curve: %s", curve_info->name ) ); our_size--; } list_size -= 2; p += 2; } return( 0 ); } #endif /* MBEDTLS_ECDH_C || ( MBEDTLS_ECDSA_C */ #if ( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ) /* TODO: Code for MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED missing */ /* ssl_parse_key_shares_ext( ) verifies whether the information in the extension is correct and stores the provided key shares. Whether this is an acceptable key share depends on the selected ciphersuite. Possible return values are: - 0: Successful processing of the client provided key share extension. - MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE: The key share provided by the client does not match a group supported by the server. A HelloRetryRequest will be needed. MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_SHARE: Problem encountered with the key share provided by the client. */ static int ssl_parse_key_shares_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = 0, final_ret = 0, extensions_available = 1; unsigned char *end = (unsigned char*)buf + len; unsigned char *start = (unsigned char*)buf; unsigned char *old; #if !defined(MBEDTLS_SSL_TLS13_CTLS) size_t n; unsigned int ks_entry_size; #endif /* MBEDTLS_SSL_TLS13_CTLS */ int match_found = 0; const mbedtls_ecp_group_id *gid; /* Is there a key share available at the server config? */ /* if( ssl->conf->keyshare_ctx == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no key share context" ) ); if( ( ret = mbedtls_ssl_send_fatal_handshake_failure( ssl ) ) != 0 ) return( ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } */ /* With CTLS there is only one key share */ #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_DO_NOT_USE ) #endif /* MBEDTLS_SSL_TLS13_CTLS */ { /* Pick the first KeyShareEntry */ n = ( buf[0] << 8 ) | buf[1]; if( n + 2 > len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad key share extension in client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_SHARE ); } start += 2; /* We try to find a suitable key share entry and copy it to the * handshake context. Later, we have to find out whether we can do * something with the provided key share or whether we have to * dismiss it and send a HelloRetryRequest message. */ } /* * Ephemeral ECDH parameters: * * struct { * NamedGroup group; * opaque key_exchange<1..2^16-1>; * } KeyShareEntry; */ /* Jump over extension length field to the first KeyShareEntry by advancing buf+2 */ old = start; while ( extensions_available ) { if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx[ssl->handshake->ecdh_ctx_selected], ( const unsigned char ** )&start, end ) ) != 0 ) { /* For some reason we didn't recognize the key share. We jump * to the next one */ MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params failed " ), ret ); final_ret = MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_SHARE; goto skip_parsing_key_share_entry; } /* Does the provided key share match any of our supported groups */ for ( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ ) { /* Currently we only support a single key share */ /* Hence, we do not need a loop */ if( ssl->handshake->ecdh_ctx[ssl->handshake->ecdh_ctx_selected].grp.id == *gid ) { match_found = 1; ret = check_ecdh_params( ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "check_ecdh_params: %d" ), ret ); final_ret = MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_SHARE; goto skip_parsing_key_share_entry; } break; } } if( match_found == 0 ) { /* A HelloRetryRequest is needed */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "no matching curve for ECDHE" ) ); final_ret = MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE; } else { /* The key share matched our supported groups */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "Key share matched our supported group: %s", mbedtls_ecp_curve_info_from_grp_id( ssl->handshake->ecdh_ctx[ssl->handshake->ecdh_ctx_selected].grp.id )->name ) ); final_ret = 0; goto finish_key_share_parsing; } skip_parsing_key_share_entry: #if !defined(MBEDTLS_SSL_TLS13_CTLS) /* we jump to the next key share entry, if there is one */ ks_entry_size = ( ( old[2] << 8 ) | ( old[3] ) ); /* skip named group id + length field + key share entry length */ start = old + ( ks_entry_size + 4 ); old = start; if( start >= end ) { /* we reached the end */ final_ret = MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE; extensions_available = 0; } #else ( (void ) buf ); #endif /* MBEDTLS_SSL_TLS13_CTLS */ } finish_key_share_parsing: if( final_ret == 0 ) { /* we found a key share we like */ return ( 0 ); } else { ( (void ) buf ); return ( final_ret ); } } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */ #if defined(MBEDTLS_SSL_NEW_SESSION_TICKET) int mbedtls_ssl_parse_new_session_ticket_server( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len, mbedtls_ssl_ticket *ticket ) { int ret; unsigned char *ticket_buffer; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) ); if( ssl->conf->f_ticket_parse == NULL || ssl->conf->f_ticket_write == NULL ) { return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", len ) ); if( len == 0 ) return( 0 ); /* We create a copy of the encrypted ticket since decrypting * it into the same buffer will wipe-out the original content. * We do, however, need the original buffer for computing the * psk binder value. */ ticket_buffer = mbedtls_calloc( len,1 ); if( ticket_buffer == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return ( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } else memcpy( ticket_buffer, buf, len ); if( ( ret = ssl->conf->f_ticket_parse( ssl->conf->p_ticket, ticket, ticket_buffer, len ) ) != 0 ) { mbedtls_platform_zeroize( &ticket, sizeof( mbedtls_ssl_ticket ) ); mbedtls_free( ticket_buffer ); if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is not authentic" ) ); else if( ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is expired" ) ); else MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_parse", ret ); return( ret ); } /* We delete the temporary buffer */ mbedtls_free( ticket_buffer ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_NEW_SESSION_TICKET */ /* ssl_calc_binder( ): 0 | v PSK -> HKDF-Extract | v Early Secret | | +------> Derive-Secret( ., | "ext binder" | | "res binder", | "" ) | = binder_key */ static int ssl_calc_binder( mbedtls_ssl_context *ssl, unsigned char *psk, size_t psk_len, const mbedtls_md_info_t *md, const mbedtls_ssl_ciphersuite_t *suite_info, unsigned char *buffer, size_t blen, unsigned char *computed_binder ) { int ret = 0; int hash_length; /* TBD: With dynamic memory allocations or a different hash function API * we could make a more efficient memory allocation. * Currently, we always allocate 64 bytes ( 512 bits ) even if we only need * 48 bytes ( 384 bits ) as needed by a SHA384 hash function. */ unsigned char salt[MBEDTLS_MD_MAX_SIZE]; unsigned char padbuf[MBEDTLS_MD_MAX_SIZE]; unsigned char hash[MBEDTLS_MD_MAX_SIZE]; /* unsigned char early_secret[MBEDTLS_MD_MAX_SIZE]; */ unsigned char binder_key[MBEDTLS_MD_MAX_SIZE]; unsigned char finished_key[MBEDTLS_MD_MAX_SIZE]; #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_context sha256; #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_context sha512; #endif /* MBEDTLS_SHA512_C */ hash_length = mbedtls_hash_size_for_ciphersuite( suite_info ); if( hash_length == -1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_hash_size_for_ciphersuite == -1, ssl_calc_binder failed" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* Compute Early Secret with HKDF-Extract( 0, PSK ) */ memset( salt, 0x0, hash_length ); ret = mbedtls_hkdf_extract( md, salt, hash_length, psk, psk_len, ssl->handshake->early_secret ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_hkdf_extract( ) with early_secret", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 5, ( "HKDF Extract -- early_secret" ) ); MBEDTLS_SSL_DEBUG_BUF( 5, "Salt", salt, hash_length ); MBEDTLS_SSL_DEBUG_BUF( 5, "Input", psk, psk_len ); MBEDTLS_SSL_DEBUG_BUF( 5, "Output", ssl->handshake->early_secret, hash_length ); /* Compute binder_key with Derive-Secret( early_secret, "ext binder" | "res binder","" ) */ /* Create hash of empty message first. * TBD: replace by constant. * * For SHA256 the constant is * e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 * * For SHA384 the constant is * 38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b */ if( suite_info->mac == MBEDTLS_MD_SHA256 ) { #if defined(MBEDTLS_SHA256_C) mbedtls_sha256( (const unsigned char*)"", 0, hash, 0 ); #else MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_ssl_tls1_3_derive_master_secret: Unknow hash function." ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); #endif /* MBEDTLS_SHA256_C */ } else if( suite_info->mac == MBEDTLS_MD_SHA384 ) { #if defined(MBEDTLS_SHA512_C) mbedtls_sha512( (const unsigned char*)"", 0, hash, 1 /* for SHA384 */ ); #else MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_ssl_tls1_3_derive_master_secret: Unknow hash function." ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); #endif /* MBEDTLS_SHA512_C */ } #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) && defined(MBEDTLS_SSL_NEW_SESSION_TICKET) if( ( ssl->handshake->resume == 1 ) || ( ssl->conf->resumption_mode == 1 ) ) { ret = mbedtls_ssl_tls1_3_derive_secret( mbedtls_md_get_type( md ), ssl->handshake->early_secret, hash_length, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( res_binder ), NULL, 0, MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED, binder_key, hash_length ); MBEDTLS_SSL_DEBUG_MSG( 5, ( "Derive Early Secret with 'res binder'" ) ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL && MBEDTLS_SSL_NEW_SESSION_TICKET */ { ret = mbedtls_ssl_tls1_3_derive_secret( mbedtls_md_get_type( md ), ssl->handshake->early_secret, hash_length, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( ext_binder ), NULL, 0, MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED, binder_key, hash_length ); MBEDTLS_SSL_DEBUG_MSG( 5, ( "Derive Early Secret with 'ext binder'" ) ); } if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_tls1_3_derive_secret( ) with binder_key: Error", ret ); return( ret ); } if( suite_info->mac == MBEDTLS_MD_SHA256 ) { #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_init( &sha256 ); if( ( ret = mbedtls_sha256_starts_ret( &sha256, 0 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha256_starts_ret", ret ); goto exit; } MBEDTLS_SSL_DEBUG_BUF( 5, "finished sha256 state", (unsigned char *) sha256.state, sizeof( sha256.state ) ); /*mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 ); */ MBEDTLS_SSL_DEBUG_BUF( 5, "input buffer for psk binder", buffer, blen ); if( ( ret = mbedtls_sha256_update_ret( &sha256, buffer, blen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha256_update_ret", ret ); goto exit; } if( ( ret = mbedtls_sha256_finish_ret( &sha256, padbuf ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha256_finish_ret", ret ); goto exit; } MBEDTLS_SSL_DEBUG_BUF( 5, "handshake hash for psk binder", padbuf, 32 ); #else MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_ssl_tls1_3_derive_master_secret: Unknow hash function." ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); #endif /* MBEDTLS_SHA256_C */ } else if( suite_info->mac == MBEDTLS_MD_SHA384 ) { #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_init( &sha512 ); if( ( ret = mbedtls_sha512_starts_ret( &sha512, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha512_starts_ret", ret ); goto exit; } MBEDTLS_SSL_DEBUG_BUF( 5, "finished sha384 state", ( unsigned char * )sha512.state, 48 ); /*mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 ); */ MBEDTLS_SSL_DEBUG_BUF( 5, "input buffer for psk binder", buffer, blen ); if( ( ret = mbedtls_sha512_update_ret( &sha512, buffer, blen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha512_update_ret", ret ); goto exit; } if( ( ret = mbedtls_sha512_finish_ret( &sha512, padbuf ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha512_finish_ret", ret ); goto exit; } MBEDTLS_SSL_DEBUG_BUF( 5, "handshake hash for psk binder", padbuf, 48 ); #else MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_ssl_tls1_3_derive_master_secret: Unknow hash function." ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); #endif /* MBEDTLS_SHA512_C */ } /* * finished_key = * HKDF-Expand-Label( BaseKey, "finished", "", Hash.length ) * * The binding_value is computed in the same way as the Finished message * but with the BaseKey being the binder_key. */ ret = mbedtls_ssl_tls1_3_hkdf_expand_label( suite_info->mac, binder_key, hash_length, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( finished ), NULL, 0, finished_key, hash_length ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 2, "Creating the finished_key failed", ret ); goto exit; } MBEDTLS_SSL_DEBUG_BUF( 3, "finished_key", finished_key, hash_length ); /* compute mac and write it into the buffer */ ret = mbedtls_md_hmac( md, finished_key, hash_length, padbuf, hash_length, computed_binder ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_hmac", ret ); goto exit; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "verify_data of psk binder" ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Input", padbuf, hash_length ); MBEDTLS_SSL_DEBUG_BUF( 3, "Key", finished_key, hash_length ); MBEDTLS_SSL_DEBUG_BUF( 3, "Output", computed_binder, hash_length ); exit: #if defined(MBEDTLS_SHA256_C) if( suite_info->mac == MBEDTLS_MD_SHA256 ) { mbedtls_sha256_free( &sha256 ); } else #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) if( suite_info->mac == MBEDTLS_MD_SHA384 ) { mbedtls_sha512_free( &sha512 ); } else #endif /* MBEDTLS_SHA512_C */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_ssl_tls1_3_derive_master_secret: Unknow hash function." ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } mbedtls_platform_zeroize( finished_key, hash_length ); return( ret ); } #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) int mbedtls_ssl_parse_client_psk_identity_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = 0; unsigned char *truncated_clienthello_end, *truncated_clienthello_start = ssl->in_msg; unsigned int item_array_length, item_length, sum, length_so_far; unsigned char server_computed_binder[MBEDTLS_MD_MAX_SIZE]; uint32_t obfuscated_ticket_age; mbedtls_ssl_ticket ticket; const unsigned char *psk = NULL; size_t psk_len = 0; #if defined(MBEDTLS_HAVE_TIME) time_t now; int64_t diff; #endif /* MBEDTLS_HAVE_TIME */ /* if( ssl->conf->f_psk == NULL && ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL || ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no pre-shared key configured" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } */ /* Read length of array of identities */ item_array_length = ( buf[0] << 8 ) | buf[1]; length_so_far = item_array_length + 2; buf += 2; if( length_so_far > len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad psk_identity extension in client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } sum = 2; while ( sum < item_array_length+2 ) { /* Read to psk identity length */ item_length = ( buf[0] << 8 ) | buf[1]; sum = sum + 2 + item_length; if( sum > len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk_identity length mismatch" ) ); if( ( ret = mbedtls_ssl_send_fatal_handshake_failure( ssl ) ) != 0 ) return( ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Extract pre-shared key identity provided by the client */ /* jump to identity value itself */ buf += 2; MBEDTLS_SSL_DEBUG_BUF( 3, "received psk identity", buf, item_length ); if( ssl->conf->f_psk != NULL ) { if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, buf, item_length ) != 0 ) ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } else { /* Identity is not a big secret since clients send it in the clear, * but treat it carefully anyway, just in case */ if( item_length != ssl->conf->psk_identity_len || mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, buf, item_length ) != 0 ) { ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } else { /* skip obfuscated ticket age */ /* TBD: Process obfuscated ticket age ( zero for externally configured PSKs?! ) */ buf = buf + item_length + 4; /* 4 for obfuscated ticket age */; goto psk_parsing_successful; } #if defined(MBEDTLS_SSL_NEW_SESSION_TICKET) /* Check the ticket cache if previous lookup was unsuccessful */ if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ) { /* copy ticket since it acts as the psk_identity */ if( ssl->session_negotiate->ticket != NULL ) { mbedtls_free( ssl->session_negotiate->ticket ); } ssl->session_negotiate->ticket = mbedtls_calloc( 1, item_length ); if( ssl->session_negotiate->ticket == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed ( %d bytes )", item_length ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } memcpy( ssl->session_negotiate->ticket, buf, item_length ); ssl->session_negotiate->ticket_len = item_length; ret = mbedtls_ssl_parse_new_session_ticket_server( ssl, ssl->session_negotiate->ticket, item_length, &ticket ); if( ret == 0 ) { /* found a match in the ticket cache; everything is OK */ ssl->handshake->resume = 1; /* We put the resumption_master_secret into the handshake->psk * * Note: The key in the ticket is already the final PSK, * i.e., the HKDF-Expand-Label( resumption_master_secret, "resumption", ticket_nonce, Hash.length ) * function has already been applied. */ mbedtls_ssl_set_hs_psk( ssl, ticket.key, ticket.key_len ); MBEDTLS_SSL_DEBUG_BUF( 5, "ticket: key", ticket.key, ticket.key_len ); /* obfuscated ticket age follows the identity field, which is item_length long, containing the ticket */ memcpy( &obfuscated_ticket_age, buf+item_length, 4 ); MBEDTLS_SSL_DEBUG_BUF( 5, "ticket: obfuscated_ticket_age", ( const unsigned char * ) &obfuscated_ticket_age, 4 ); /* * A server MUST validate that the ticket age for the selected PSK identity * is within a small tolerance of the time since the ticket was issued. */ #if defined(MBEDTLS_HAVE_TIME) now = time( NULL ); /* Check #1: * Is the time when the ticket was issued later than now? */ if( now < ticket.start ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Ticket expired: now=%d, ticket.start=%d",now, ticket.start ) ); ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED; } /* Check #2: * Is the ticket expired already? */ if( now - ticket.start > ticket.ticket_lifetime ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Ticket expired ( now - ticket.start=%d, ticket.ticket_lifetime=%d", now - ticket.start, ticket.ticket_lifetime ) ); ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED; } /* Check #3: * Is the ticket age for the selected PSK identity ( computed by subtracting ticket_age_add from PskIdentity.obfuscated_ticket_age modulo 2^32 ) * within a small tolerance of the time since the ticket was issued? */ diff = ( now - ticket.start ) - ( obfuscated_ticket_age - ticket.ticket_age_add ); if( diff > MBEDTLS_SSL_TICKET_AGE_TOLERANCE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Ticket age outside tolerance window ( diff=%d )", diff ) ); ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED; } #if defined(MBEDTLS_ZERO_RTT) if( ssl->conf->early_data == MBEDTLS_SSL_EARLY_DATA_ENABLED ) { if( diff <= MBEDTLS_SSL_EARLY_DATA_MAX_DELAY ) { ssl->session_negotiate->process_early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED; } else { ssl->session_negotiate->process_early_data = MBEDTLS_SSL_EARLY_DATA_DISABLED; ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED; } } #endif /* MBEDTLS_ZERO_RTT */ #endif /* MBEDTLS_HAVE_TIME */ /* TBD: check ALPN, ciphersuite and SNI as well */ /* * If the check failed, the server SHOULD proceed with the handshake but * reject 0-RTT, and SHOULD NOT take any other action that assumes that * this ClientHello is fresh. */ /* Disable 0-RTT */ if( ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED ) { #if defined(MBEDTLS_ZERO_RTT) if( ssl->conf->early_data == MBEDTLS_SSL_EARLY_DATA_ENABLED ) { ssl->session_negotiate->process_early_data = MBEDTLS_SSL_EARLY_DATA_DISABLED; } #else ( ( void )buf ); #endif /* MBEDTLS_ZERO_RTT */ } } } #endif /* MBEDTLS_SSL_NEW_SESSION_TICKET */ } /* skip the processed identity field and the obfuscated ticket age field */ buf += item_length; buf += 4; sum = sum + 4; } if( ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Neither PSK nor ticket found." ) ); if( ( ret = mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY ) ) != 0 ) { return( ret ); } return( ret ); } if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ) { MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", buf, item_length ); if( ( ret = mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY ) ) != 0 ) { return( ret ); } return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ); } if( length_so_far != sum ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad psk_identity extension in client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } psk_parsing_successful: /* Store this pointer since we need it to compute * the psk binder. */ truncated_clienthello_end = (unsigned char*) buf; /* read length of psk binder array */ item_array_length = ( buf[0] << 8 ) | buf[1]; length_so_far += item_array_length; buf += 2; sum = 0; while ( sum < item_array_length ) { /* Read to psk binder length */ item_length = buf[0]; sum = sum + 1 + item_length; buf += 1; if( sum > item_array_length ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk binder length mismatch" ) ); if( ( ret = mbedtls_ssl_send_fatal_handshake_failure( ssl ) ) != 0 ) return( ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "ssl_calc_binder computed over ", truncated_clienthello_start, truncated_clienthello_end - truncated_clienthello_start ); if( ssl->handshake->resume == 1 ) { /* Case 1: We are using the PSK from a ticket */ ret = ssl_calc_binder( ssl, ssl->handshake->psk, ssl->handshake->psk_len, mbedtls_md_info_from_type( ssl->handshake->ciphersuite_info->mac ), ssl->handshake->ciphersuite_info, truncated_clienthello_start, truncated_clienthello_end - truncated_clienthello_start, server_computed_binder ); } else { /* Case 2: We are using a static PSK, or a dynamic PSK if one is defined */ if( ( ret = mbedtls_ssl_get_psk( ssl, &psk, &psk_len ) ) != 0 ) return( ret ); ret = ssl_calc_binder( ssl, (unsigned char *) psk, psk_len, mbedtls_md_info_from_type( ssl->handshake->ciphersuite_info->mac ), ssl->handshake->ciphersuite_info, truncated_clienthello_start, truncated_clienthello_end - truncated_clienthello_start, server_computed_binder ); } /* We do not check for multiple binders */ if( ret != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Psk binder calculation failed." ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "psk binder ( computed ): ", server_computed_binder, item_length ); MBEDTLS_SSL_DEBUG_BUF( 3, "psk binder ( received ): ", buf, item_length ); if( mbedtls_ssl_safer_memcmp( server_computed_binder, buf, item_length ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Received psk binder does not match computed psk binder." ) ); if( ( ret = mbedtls_ssl_send_fatal_handshake_failure( ssl ) ) != 0 ) return( ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } buf += item_length; return( 0 ); } /* no valid psk binder value found */ MBEDTLS_SSL_DEBUG_RET( 1, "create_binder in ssl_parse_pre_shared_key_ext failed:", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED*/ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) /* * struct { * select ( Handshake.msg_type ) { * case client_hello: * PskIdentity identities<6..2^16-1>; * * case server_hello: * uint16 selected_identity; * } * } PreSharedKeyExtension; */ static int ssl_write_server_pre_shared_key_ext( mbedtls_ssl_context *ssl, unsigned char* buf, unsigned char* end, size_t* olen ) { unsigned char *p = (unsigned char*)buf; size_t selected_identity; int ret=0; *olen = 0; /* Are we using any PSK at all? */ if( mbedtls_ssl_get_psk( ssl, NULL, NULL ) != 0 ) ret = MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED; /* Are we using resumption? */ if( ssl->handshake->resume == 0 && ret == MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "No pre-shared-key available." ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding pre_shared_key extension" ) ); if( end < p || ( end - p ) < 6 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } /* Extension Type */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_PRE_SHARED_KEY >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_PRE_SHARED_KEY ) & 0xFF ); /* Extension Length */ *p++ = (unsigned char)( ( 2 >> 8 ) & 0xFF ); *p++ = (unsigned char)( 2 & 0xFF ); /* retrieve selected_identity */ selected_identity = 0; /* Write selected_identity */ *p++ = (unsigned char)( ( selected_identity >> 8 ) & 0xFF ); *p++ = (unsigned char)( selected_identity & 0xFF ); *olen = 6; MBEDTLS_SSL_DEBUG_MSG( 5, ( "sent selected_identity: %d", selected_identity ) ); return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_SSL_COOKIE_C) int mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl, const unsigned char *info, size_t ilen ) { if( ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); mbedtls_free( ssl->cli_id ); if( ( ssl->cli_id = mbedtls_calloc( 1, ilen ) ) == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( ssl->cli_id, info, ilen ); ssl->cli_id_len = ilen; return( 0 ); } #endif /* MBEDTLS_SSL_COOKIE_C */ #if defined(MBEDTLS_SSL_COOKIE_C) void mbedtls_ssl_conf_cookies( mbedtls_ssl_config *conf, mbedtls_ssl_cookie_write_t *f_cookie_write, mbedtls_ssl_cookie_check_t *f_cookie_check, void *p_cookie, unsigned int rr_config ) { conf->f_cookie_write = f_cookie_write; conf->f_cookie_check = f_cookie_check; conf->p_cookie = p_cookie; conf->rr_config = rr_config; } #endif /* MBEDTLS_SSL_COOKIE_C */ #if defined(MBEDTLS_SSL_COOKIE_C) && defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) static int ssl_parse_cookie_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = 0; /* size_t servername_list_size , hostname_len; */ /* const unsigned char *p; */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "parse cookie extension" ) ); if( ssl->conf->f_cookie_check != NULL ) { MBEDTLS_SSL_DEBUG_BUF( 3, "Received cookie", buf, len ); if( ssl->conf->f_cookie_check( ssl->conf->p_cookie, buf, len, ssl->cli_id, ssl->cli_id_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification failed" ) ); ssl->handshake->verify_cookie_len = 1; ret = MBEDTLS_ERR_SSL_BAD_HS_COOKIE_EXT; } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification passed" ) ); ssl->handshake->verify_cookie_len = 0; } } else { /* TBD: Check under what cases this is appropriate */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification skipped" ) ); } return( ret ); } #endif /* MBEDTLS_SSL_COOKIE_C && MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) static int ssl_parse_servername_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret; size_t servername_list_size, hostname_len; const unsigned char *p; if( ssl->conf->p_sni == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "No SNI callback configured. Skip SNI parsing." ) ); return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "Parse ServerName extension" ) ); servername_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( servername_list_size + 2 != len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } p = buf + 2; while ( servername_list_size > 0 ) { hostname_len = ( ( p[1] << 8 ) | p[2] ); if( hostname_len + 3 > servername_list_size ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( p[0] == MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) { ret = ssl->conf->f_sni( ssl->conf->p_sni, ssl, p + 3, hostname_len ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_sni_wrapper", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } return( 0 ); } servername_list_size -= hostname_len + 3; p += hostname_len + 3; } if( servername_list_size != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } return( 0 ); } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_ZERO_RTT) /* static int ssl_parse_early_data_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { ( ( void* )ssl ); ( ( void* )buf ); return( 0 ); } */ #endif /* MBEDTLS_ZERO_RTT */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->session_negotiate->mfl_code = buf[0]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "Maximum fragment length = %d", buf[0] ) ); return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) /* * ssl_parse_key_exchange_modes_ext( ) structure: * * enum { psk_ke( 0 ), psk_dhe_ke( 1 ), ( 255 ) } PskKeyExchangeMode; * * struct { * PskKeyExchangeMode ke_modes<1..255>; * } PskKeyExchangeModes; */ static int ssl_parse_key_exchange_modes_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = 0; /* Length has to be either 1 or 2 based on the currently defined psk key exchange modes */ if( len < 2 || len >3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad psk key exchange modes extension in client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* We check for the allowed combinations and set the key_exchange_modes variable accordingly */ if( buf[0] == 2 ) { if( ( buf[1] == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_KE || buf[1] == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_DHE_KE ) && ( buf[2] == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_KE || buf[2] == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_DHE_KE ) ) { ssl->session_negotiate->key_exchange_modes = MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_ALL; } else ret = MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO; } else if( buf[0] == 1 ) { switch ( buf[1] ) { case 0: ssl->session_negotiate->key_exchange_modes = MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_KE; break; case 1: ssl->session_negotiate->key_exchange_modes = MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_DHE_KE; break; default: ret = MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO; } } else ret = MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO; if( ret != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad psk key exchange modes extension in client hello message" ) ); return( ret ); } return ( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ /* * ssl_write_supported_version_ext( ): * ( as sent by server ) * * case server_hello: * ProtocolVersion selected_version; */ static int ssl_write_supported_version_ext( mbedtls_ssl_context *ssl, unsigned char* buf, unsigned char* end, size_t* olen ) { unsigned char *p = buf; *olen = 0; if( ssl->handshake->extensions_present & SUPPORTED_VERSION_EXTENSION ) { return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding supported version extension" ) ); if( end < p || (size_t)( end - p ) < 6 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS ) & 0xFF ); /* length */ *p++ = 0x00; *p++ = 2; /* For TLS 1.3 and for DTLS 1.3 we use 0x0304 */ *p++ = 0x03; *p++ = 0x04; MBEDTLS_SSL_DEBUG_MSG( 3, ( "version [%d:%d]", *( p-2 ), *( p-1 ) ) ); *olen = 6; return( 0 ); } static int ssl_parse_supported_versions_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_len; int major_ver, minor_ver; if( len < 3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ssl_parse_supported_versions_ext: Incorrect length" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SUPPORTED_VERSIONS_EXT ); } while ( len > 0 ) { /* list_len = ( buf[0] << 8 ) | buf[1]; */ list_len = buf[0]; /* length has to be at least 2 bytes long */ if( list_len < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ssl_parse_supported_versions_ext: Incorrect length" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SUPPORTED_VERSIONS_EXT ); } /* skip length field */ buf++; mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, buf ); /* In this implementation we only support TLS 1.3 and DTLS 1.3. */ if( major_ver == ( int )0x03 && minor_ver == ( int )0x04 ) { /* we found a supported version */ goto found_version; } else { /* if no match found, check next entry */ buf += 2; len -= 3; } } /* If we got here then we have no version in common */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "Unsupported version of TLS. Supported is [%d:%d]", ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); found_version: MBEDTLS_SSL_DEBUG_MSG( 1, ( "Negotiated version. Supported is [%d:%d]", major_ver, minor_ver ) ); /* version in common */ ssl->major_ver = major_ver; ssl->minor_ver = minor_ver; ssl->handshake->max_major_ver = ssl->major_ver; ssl->handshake->max_minor_ver = ssl->minor_ver; return( 0 ); } #if defined(MBEDTLS_SSL_ALPN) static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_len, cur_len, ours_len; const unsigned char *theirs, *start, *end; const char **ours; /* If ALPN not configured, just ignore the extension */ if( ssl->conf->alpn_list == NULL ) return( 0 ); /* * opaque ProtocolName<1..2^8-1>; * * struct { * ProtocolName protocol_name_list<2..2^16-1> * } ProtocolNameList; */ /* Min length is 2 ( list_len ) + 1 ( name_len ) + 1 ( name ) */ if( len < 4 ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); list_len = ( buf[0] << 8 ) | buf[1]; if( list_len != len - 2 ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); /* * Use our order of preference */ start = buf + 2; end = buf + len; for ( ours = ssl->conf->alpn_list; *ours != NULL; ours++ ) { ours_len = strlen( *ours ); for ( theirs = start; theirs != end; theirs += cur_len ) { /* If the list is well formed, we should get equality first */ if( theirs > end ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); cur_len = *theirs++; /* Empty strings MUST NOT be included */ if( cur_len == 0 ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); if( cur_len == ours_len && memcmp( theirs, *ours, cur_len ) == 0 ) { ssl->alpn_chosen = *ours; return( 0 ); } } } /* If we get there, no match was found */ mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_NEW_SESSION_TICKET) /* This function creates a NewSessionTicket message in the following format. * The ticket inside the NewSessionTicket is an encrypted container carrying * the necessary information so that the server is later able to restore the * required parameters. * * struct { * uint32 ticket_lifetime; * uint32 ticket_age_add; * opaque ticket_nonce<0..255>; * opaque ticket<1..2^16-1>; * Extension extensions<0..2^16-2>; * } NewSessionTicket; * * The following fields are populated in the ticket: * * - creation time ( start ) * - flags ( flags ) * - lifetime ( ticket_lifetime ) * - age add ( ticket_age_add ) * - key ( key ) * - key length ( key_len ) * - ciphersuite ( ciphersuite ) * - certificate of the peer ( peer_cert ) * */ static int ssl_write_new_session_ticket( mbedtls_ssl_context *ssl ) { int ret; size_t tlen; size_t ext_len = 0; mbedtls_ssl_ciphersuite_t *suite_info; int hash_length; mbedtls_ssl_ticket ticket; mbedtls_ssl_ticket_context *ctx = ssl->conf->p_ticket; /* Check whether the use of session tickets is enabled */ if( ssl->conf->session_tickets == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use of tickets disabled." ) ); return ( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write NewSessionTicket msg" ) ); /* Do we have space for the fixed length part of the ticket */ if( MBEDTLS_SSL_MAX_CONTENT_LEN < ( 16 + MBEDTLS_SSL_TICKET_NONCE_LENGTH ) ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_new_session_ticket: not enough space", ret ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_NEW_SESSION_TICKET; if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, (unsigned char*) &ticket.ticket_age_add, 4 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "Generating the ticket_age_add failed", ret ); return( ret ); } suite_info = ( mbedtls_ssl_ciphersuite_t * ) ssl->handshake->ciphersuite_info; hash_length = mbedtls_hash_size_for_ciphersuite( suite_info ); if( hash_length == -1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_hash_size_for_ciphersuite == -1, ssl_write_new_session_ticket failed" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_HAVE_TIME) /* Store time when ticket was created. */ ticket.start = time( NULL ); #endif /* MBEDTLS_HAVE_TIME */ ticket.flags = ctx->flags; ticket.ticket_lifetime = ctx->ticket_lifetime; /* In this code the psk key length equals the length of the hash */ ticket.key_len = hash_length; ticket.ciphersuite = ssl->handshake->ciphersuite_info->id; #if defined(MBEDTLS_X509_CRT_PARSE_C) /* Check whether the client provided a certificate during the exchange */ if( ssl->session->peer_cert != NULL ) ticket.peer_cert = ssl->session->peer_cert; else ticket.peer_cert = NULL; #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* * HKDF-Expand-Label( resumption_master_secret, * "resumption", ticket_nonce, Hash.length ) */ /* Compute nonce ( and write it already into the outgoing NewSessionTicket message */ if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, &ssl->out_msg[13], MBEDTLS_SSL_TICKET_NONCE_LENGTH ) ) != 0 ) return( ret ); MBEDTLS_SSL_DEBUG_BUF( 3, "resumption_master_secret", ssl->session->resumption_master_secret, hash_length ); MBEDTLS_SSL_DEBUG_BUF( 3, "ticket_nonce:", &ssl->out_msg[13], MBEDTLS_SSL_TICKET_NONCE_LENGTH ); ret = mbedtls_ssl_tls1_3_hkdf_expand_label( suite_info->mac, ssl->session->resumption_master_secret, hash_length, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( resumption ), (const unsigned char *) &ssl->out_msg[13], MBEDTLS_SSL_TICKET_NONCE_LENGTH, ticket.key, hash_length ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 2, "Creating the ticket-resumed PSK failed", ret ); return ( ret ); } MBEDTLS_SSL_DEBUG_BUF( 3, "Ticket-resumed PSK", ticket.key, ticket.key_len ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket->key_len: %d", ticket.key_len ) ); /* Ticket */ if( ( ret = ssl->conf->f_ticket_write( ssl->conf->p_ticket, &ticket, &ssl->out_msg[15+ MBEDTLS_SSL_TICKET_NONCE_LENGTH], ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN, &tlen, &ticket.ticket_lifetime, &ticket.flags ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ticket->mbedtls_ssl_ticket_write", ret ); /* tlen = 0; */ return ( ret ); } /* Ticket Lifetime */ ssl->out_msg[4] = ( ticket.ticket_lifetime >> 24 ) & 0xFF; ssl->out_msg[5] = ( ticket.ticket_lifetime >> 16 ) & 0xFF; ssl->out_msg[6] = ( ticket.ticket_lifetime >> 8 ) & 0xFF; ssl->out_msg[7] = ( ticket.ticket_lifetime ) & 0xFF; MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket->ticket_lifetime: %d", ticket.ticket_lifetime ) ); /* Ticket Age Add */ ssl->out_msg[8] = ( ticket.ticket_age_add >> 24 ) & 0xFF; ssl->out_msg[9] = ( ticket.ticket_age_add >> 16 ) & 0xFF; ssl->out_msg[10] = ( ticket.ticket_age_add >> 8 ) & 0xFF; ssl->out_msg[11] = ( ticket.ticket_age_add ) & 0xFF; MBEDTLS_SSL_DEBUG_BUF( 3, "ticket->ticket_age_add:", ( const unsigned char * )&ticket.ticket_age_add, 4 ); /* Nonce Length */ ssl->out_msg[12] = MBEDTLS_SSL_TICKET_NONCE_LENGTH; MBEDTLS_SSL_DEBUG_MSG( 3, ( "NewSessionTicket ( nonce length ): %d", MBEDTLS_SSL_TICKET_NONCE_LENGTH ) ); /* Ticket Length */ ssl->out_msg[13+ MBEDTLS_SSL_TICKET_NONCE_LENGTH] = (unsigned char)( ( tlen >> 8 ) & 0xFF ); ssl->out_msg[14+ MBEDTLS_SSL_TICKET_NONCE_LENGTH] = (unsigned char)( ( tlen ) & 0xFF ); /* no extensions for now -> set length to zero */ ssl->out_msg[15+ MBEDTLS_SSL_TICKET_NONCE_LENGTH +tlen] = ( ext_len >> 8 ) & 0xFF; ssl->out_msg[16+ MBEDTLS_SSL_TICKET_NONCE_LENGTH +tlen] = ( ext_len ) & 0xFF; ssl->out_msglen = 17+ MBEDTLS_SSL_TICKET_NONCE_LENGTH + tlen; MBEDTLS_SSL_DEBUG_MSG( 3, ( "NewSessionTicket ( extension_length ): %d", ext_len ) ); /* MBEDTLS_SSL_DEBUG_BUF( 3, "NewSessionTicket ( extension ):", extensions, ext_len ); */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "NewSessionTicket ( ticket length ): %d", tlen ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "NewSessionTicket ( ticket dump ):", &ssl->out_msg[15 + MBEDTLS_SSL_TICKET_NONCE_LENGTH], tlen ); if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write new session ticket" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_NEW_SESSION_TICKET */ /* * * STATE HANDLING: Parse End-of-Early Data * */ /* * Overview */ #if defined(MBEDTLS_ZERO_RTT) /* Main state-handling entry point; orchestrates the other functions. */ int ssl_read_end_of_early_data_process( mbedtls_ssl_context* ssl ); static int ssl_read_end_of_early_data_preprocess( mbedtls_ssl_context* ssl ); /* There is no parse function for the end_of_early_data message. */ /* Update the state after handling the incoming end of early data message. */ static int ssl_read_end_of_early_data_postprocess( mbedtls_ssl_context* ssl ); /* * Implementation */ int ssl_read_end_of_early_data_process( mbedtls_ssl_context* ssl ) { int ret; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse end_of_early_data" ) ); MBEDTLS_SSL_PROC_CHK( ssl_read_end_of_early_data_preprocess( ssl ) ); /* Fetching step */ if ( (ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); goto cleanup; } if ( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE || ssl->in_msg[0] != MBEDTLS_SSL_HS_END_OF_EARLY_DATA ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad end_of_early_data message" ) ); ret = MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE; goto cleanup; } /* Postprocessing step: Update state machine */ MBEDTLS_SSL_PROC_CHK( ssl_read_end_of_early_data_postprocess( ssl ) ); cleanup: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse end_of_early_data" ) ); return( ret ); } static int ssl_read_end_of_early_data_preprocess( mbedtls_ssl_context* ssl ) { int ret; mbedtls_ssl_key_set traffic_keys; ret = mbedtls_ssl_early_data_key_derivation( ssl, &traffic_keys ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_early_data_key_derivation", ret ); return( ret ); } mbedtls_ssl_transform_free( ssl->transform_negotiate ); ret = mbedtls_set_traffic_key( ssl, &traffic_keys, ssl->transform_negotiate, 0 ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_set_traffic_key", ret ); return ( ret ); } return( 0 ); } static int ssl_read_end_of_early_data_postprocess( mbedtls_ssl_context* ssl ) { mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_CLIENT_FINISHED ); return ( 0 ); } #endif /* MBEDTLS_ZERO_RTT */ /* * * STATE HANDLING: Parse Early Data * */ /* * Overview */ #if defined(MBEDTLS_ZERO_RTT) /* Main state-handling entry point; orchestrates the other functions. */ int ssl_read_early_data_process( mbedtls_ssl_context* ssl ); static int ssl_read_early_data_preprocess( mbedtls_ssl_context* ssl ); /* Parse early data send by the peer. */ static int ssl_read_early_data_parse( mbedtls_ssl_context* ssl, unsigned char const* buf, size_t buflen ); /* Update the state after handling the incoming early data message. */ static int ssl_read_early_data_postprocess( mbedtls_ssl_context* ssl ); /* * Implementation */ int ssl_read_early_data_process( mbedtls_ssl_context* ssl ) { int ret; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse early data" ) ); MBEDTLS_SSL_PROC_CHK( ssl_read_early_data_preprocess( ssl ) ); /* Fetching step */ if ( (ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); goto cleanup; } /* Check whether there is early data */ if ( ssl->in_msg != NULL && ssl->in_msglen > 0 ) { /* Parsing step */ MBEDTLS_SSL_PROC_CHK( ssl_read_early_data_parse( ssl, ssl->in_msg, ssl->in_msglen ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "No early data received!" ) ); ret = MBEDTLS_ERR_SSL_BAD_EARLY_DATA; goto cleanup; } /* Postprocessing step: Update state machine */ MBEDTLS_SSL_PROC_CHK( ssl_read_early_data_postprocess( ssl ) ); cleanup: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse early data" ) ); return( ret ); } static int ssl_read_early_data_preprocess( mbedtls_ssl_context* ssl ) { int ret; mbedtls_ssl_key_set traffic_keys; ret = mbedtls_ssl_early_data_key_derivation( ssl, &traffic_keys ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_early_data_key_derivation", ret ); return( ret ); } mbedtls_ssl_transform_free( ssl->transform_negotiate ); ret = mbedtls_set_traffic_key( ssl, &traffic_keys, ssl->transform_negotiate, 0 ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_set_traffic_key", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) /* epoch value( 1 ) is used for messages protected using keys derived * from early_traffic_secret. */ ssl->in_epoch = 1; ssl->out_epoch = 1; #endif /* MBEDTLS_SSL_PROTO_DTLS */ return( 0 ); } static int ssl_read_early_data_parse( mbedtls_ssl_context* ssl, unsigned char const* buf, size_t buflen ) { /* Check whether we have enough buffer space */ if ( buflen <= ssl->conf->early_data_len ) { /* copy data to staging area */ memcpy( ssl->conf->early_data_buf, buf, buflen ); /* execute callback to process application data */ ssl->conf->early_data_callback( ssl, (unsigned char*)ssl->conf->early_data_buf, buflen ); } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer too small ( received early data size = %d, buffer size = %d", buflen, ssl->conf->early_data_len ) ); return ( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } return( 0 ); } static int ssl_read_early_data_postprocess( mbedtls_ssl_context* ssl ) { mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_SERVER_HELLO ); return ( 0 ); } #endif /* MBEDTLS_ZERO_RTT */ /* * * STATE HANDLING: ClientHello * */ /* ssl_parse_client_hello( ) processes the first message provided by the client. The function may return: 0: Successful processing of the ClientHello MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO: Generic parsing failure with the ClientHello MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE: A feature is not available that prevents further processing. MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION: Version negotiation problem MBEDTLS_ERR_SSL_INTERNAL_ERROR Furthermore, there are various errors in parsing extensions: MBEDTLS_ERR_SSL_BAD_HS_SERVERNAME_EXT MBEDTLS_ERR_SSL_BAD_HS_PRE_SHARED_KEY_EXT MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE MBEDTLS_ERR_SSL_BAD_HS_MAX_FRAGMENT_LENGTH_EXT MBEDTLS_ERR_SSL_BAD_HS_SUPPORTED_GROUPS MBEDTLS_ERR_SSL_BAD_HS_ALPN_EXT MBEDTLS_ERR_SSL_BAD_HS_MISSING_COOKIE_EXT */ /* * Overview */ /* Main entry point from the state machine; orchestrates the otherfunctions. */ static int ssl_client_hello_process( mbedtls_ssl_context* ssl ); static int ssl_client_hello_fetch( mbedtls_ssl_context* ssl, unsigned char** buf, size_t* buflen ); static int ssl_client_hello_parse( mbedtls_ssl_context* ssl, unsigned char* buf, size_t buflen ); /* Update the handshake state machine */ /* TODO: At the moment, this doesn't update the state machine - why? */ static int ssl_client_hello_postprocess( mbedtls_ssl_context* ssl, int ret ); /* * Implementation */ static int ssl_client_hello_process( mbedtls_ssl_context* ssl ) { int ret; unsigned char* buf = NULL; size_t buflen = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello" ) ); MBEDTLS_SSL_PROC_CHK( ssl_client_hello_fetch( ssl, &buf, &buflen ) ); MBEDTLS_SSL_PROC_CHK( ssl_client_hello_parse( ssl, buf, buflen ) ); MBEDTLS_SSL_PROC_CHK( ssl_client_hello_postprocess( ssl, ret ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_recv_flight_completed( ssl ); #endif /* MBEDTLS_SSL_PROTO_DTLS */ cleanup: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello" ) ); return( ret ); } static int ssl_client_hello_fetch( mbedtls_ssl_context* ssl, unsigned char** dst, size_t* dstlen ) { int ret; unsigned char* buf; size_t msg_len; #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) read_record_header: #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ if( ( ret = mbedtls_ssl_fetch_input( ssl, 5 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } buf = ssl->in_hdr; MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, mbedtls_ssl_hdr_len( ssl, MBEDTLS_SSL_DIRECTION_IN, ssl->transform_negotiate ) ); /* * TLS Client Hello * * Record layer: * 0 . 0 message type * 1 . 2 protocol version * 3 . 11 DTLS: epoch + record sequence number * 3 . 4 message length */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, message type: %d", buf[0] ) ); if( buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE ) { #if defined(MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE) if( buf[0] == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) { msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1]; if( msg_len != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad CCS message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "CCS, message len.: %d", msg_len ) ); if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl, MBEDTLS_SSL_DIRECTION_IN, ssl->transform_negotiate ) + msg_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC ); } if( ssl->in_msg[0] == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Change Cipher Spec message received and ignoring it." ) ); /* Done reading this record, get ready for the next one */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->next_record_offset = msg_len + mbedtls_ssl_hdr_len( ssl, MBEDTLS_SSL_DIRECTION_IN ); } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ { ssl->in_left = 0; } return ( MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC ); } else { if( ( ret = mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ) ) != 0 ) { return( ret ); } return ( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } } else #endif /* MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Spurious message ( maybe alert message )" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, message len.: %d", ( ssl->in_len[0] << 8 ) | ssl->in_len[1] ) ); /* For DTLS if this is the initial handshake, remember the client sequence * number to use it in our next message ( RFC 6347 4.2.1 ) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Epoch should be 0 for initial handshakes */ if( ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } memcpy( ssl->out_ctr + 2, ssl->in_ctr + 2, 6 ); #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record, discarding" ) ); ssl->next_record_offset = 0; ssl->in_left = 0; goto read_record_header; } /* No MAC to check yet, so we can update right now */ mbedtls_ssl_dtls_replay_update( ssl ); #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ } #endif /* MBEDTLS_SSL_PROTO_DTLS */ msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1]; if( msg_len > MBEDTLS_SSL_MAX_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl, MBEDTLS_SSL_DIRECTION_IN, ssl->transform_in ) + msg_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Done reading this record, get ready for the next one */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->next_record_offset = msg_len + mbedtls_ssl_hdr_len( ssl, MBEDTLS_SSL_DIRECTION_IN, ssl->transform_in ); } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ { ssl->in_left = 0; } buf = ssl->in_msg; MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, msg_len ); /* * Handshake layer: * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 5 DTLS only: message seqence number * 6 . 8 DTLS only: fragment offset * 9 . 11 DTLS only: fragment length */ if( msg_len < mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake type: %d", buf[0] ) ); if( buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake len.: %d", ( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3] ) ); /* We don't support fragmentation of ClientHello ( yet? ) */ if( buf[1] != 0 || msg_len != mbedtls_ssl_hs_hdr_len( ssl ) + ( ( buf[2] << 8 ) | buf[3] ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* * Copy the client's handshake message_seq on initial handshakes, * check sequence number on renego. */ { unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; ssl->handshake->out_msg_seq = cli_msg_seq; ssl->handshake->in_msg_seq = cli_msg_seq + 1; } /* * For now we don't support fragmentation, so make sure * fragment_offset == 0 and fragment_length == length */ if( ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 || memcmp( ssl->in_msg + 1, ssl->in_msg + 9, 3 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ClientHello fragmentation not supported" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ *dst = ssl->in_msg; *dstlen = msg_len; return( 0 ); } static int ssl_client_hello_parse( mbedtls_ssl_context* ssl, unsigned char* buf, size_t buflen ) { int ret, final_ret = 0, got_common_suite; size_t i, j; size_t comp_len, sess_len; size_t orig_msg_len, ciph_len, ext_len, ext_len_psk_ext = 0; unsigned char *orig_buf, *end = buf + buflen; unsigned char *ciph_offset; #if defined(MBEDTLS_SSL_COOKIE_C) && defined(MBEDTLS_SSL_PROTO_DTLS) size_t cookie_offset, cookie_len; #endif /* MBEDTLS_SSL_COOKIE_C && MBEDTLS_SSL_PROTO_DTLS */ unsigned char* p, * ext, * ext_psk_ptr = NULL; #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_context sha256; #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_context sha512; #endif /* MBEDTLS_SHA512_C */ const int* ciphersuites; const mbedtls_ssl_ciphersuite_t* ciphersuite_info; ssl->handshake->extensions_present = NO_EXTENSION; ssl->session_negotiate->key_exchange = MBEDTLS_KEY_EXCHANGE_NONE; /* TBD: Refactor */ orig_buf = buf; orig_msg_len = mbedtls_ssl_hs_hdr_len( ssl ) + ( ( ssl->in_msg[2] << 8 ) | ssl->in_msg[3] ); /* * ClientHello layer: * 0 . 1 protocol version * 2 . 33 random bytes ( starting with 4 bytes of Unix time ) * 34 . 35 session id length ( 1 byte ) * 35 . 34+x session id * 35+x . 35+x DTLS only: cookie length ( 1 byte ) * 36+x . .. DTLS only: cookie * .. . .. ciphersuite list length ( 2 bytes ) * .. . .. ciphersuite list * .. . .. compression alg. list length ( 1 byte ) * .. . .. compression alg. list * .. . .. extensions length ( 2 bytes, optional ) * .. . .. extensions ( optional ) */ buf += mbedtls_ssl_hs_hdr_len( ssl ); buflen -= mbedtls_ssl_hs_hdr_len( ssl ); /* TBD: Needs to be updated due to mandatory extensions * Minimal length ( with everything empty and extensions ommitted ) is * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can * read at least up to session id length without worrying. */ if( buflen < 38 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * We ignore the version field in the ClientHello. * We use the version field in the extension. */ #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_USE ) { buf += 1; /* skip version */ } else #endif /* MBEDTLS_SSL_TLS13_CTLS */ { buf += 2; /* skip version */ } /* * Save client random */ #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_USE ) { MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", buf, 16 ); memcpy( &ssl->handshake->randbytes[0], buf, 16 ); buf += 16; /* skip random bytes */ } else #endif /* MBEDTLS_SSL_TLS13_CTLS */ { MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", buf, 32 ); memcpy( &ssl->handshake->randbytes[0], buf, 32 ); buf += 32; /* skip random bytes */ } #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_DO_NOT_USE ) #endif /* MBEDTLS_SSL_TLS13_CTLS */ { /* * Parse session ID */ sess_len = buf[0]; buf++; /* skip session id length */ if( sess_len > 32 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->session_negotiate->id_len = sess_len; /* Note that this field is echoed even if * the client�s value corresponded to a cached pre-TLS 1.3 session * which the server has chosen not to resume. A client which * receives a legacy_session_id_echo field that does not match what * it sent in the ClientHello MUST abort the handshake with an * "illegal_parameter" alert. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id length ( %d )", sess_len ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf, sess_len ); memcpy( &ssl->session_negotiate->id[0], buf, sess_len ); /* write session id */ buf += sess_len; } /* * Check the cookie length and content */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { cookie_len = buf[0]; /* Length check */ if( buf + cookie_len > msg_end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } buf++; /* skip cookie length */ MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie", buf, cookie_len ); #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) if( ssl->conf->f_cookie_check != NULL ) { if( ssl->conf->f_cookie_check( ssl->conf->p_cookie, buf, cookie_len, ssl->cli_id, ssl->cli_id_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification failed" ) ); ssl->handshake->verify_cookie_len = 1; } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification passed" ) ); ssl->handshake->verify_cookie_len = 0; } } else #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ { /* We know we didn't send a cookie, so it should be empty */ if( cookie_len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification skipped" ) ); } /* skip cookie length */ buf += cookie_len; } #endif /* MBEDTLS_SSL_PROTO_DTLS */ ciph_len = ( buf[0] << 8 ) | ( buf[1] ); /* Length check */ if( buf + ciph_len > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* store pointer to ciphersuite list */ ciph_offset = buf; /* skip cipher length */ buf += 2; MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist", buf, ciph_len ); /* skip ciphersuites for now */ buf += ciph_len; #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_DO_NOT_USE ) #endif /* MBEDTLS_SSL_TLS13_CTLS */ { /* * For TLS 1.3 we are not using compression. */ comp_len = buf[0]; if( buf + comp_len > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } buf++; /* skip compression length */ MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, compression", buf, comp_len ); /* Determine whether we are indeed using null compression */ if( ( comp_len != 1 ) && ( buf[1] == 0 ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* skip compression */ buf++; } /* * Check the extension length */ if( buf+2 > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ext_len = ( buf[0] << 8 ) | ( buf[1] ); if( ( ext_len > 0 && ext_len < 4 ) || buf + 2 + ext_len > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } buf += 2; ext = buf; MBEDTLS_SSL_DEBUG_BUF( 3, "client hello extensions", ext, ext_len ); while ( ext_len != 0 ) { unsigned int ext_id = ( ( ext[0] << 8 ) | ( ext[1] ) ); unsigned int ext_size = ( ( ext[2] << 8 ) | ( ext[3] ) ); if( ext_size + 4 > ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } switch ( ext_id ) { #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) case MBEDTLS_TLS_EXT_SERVERNAME: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ServerName extension" ) ); ret = ssl_parse_servername_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_parse_servername_ext", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVERNAME_EXT ); } ssl->handshake->extensions_present += SERVERNAME_EXTENSION; break; #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_CID) case MBEDTLS_TLS_EXT_CID: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found CID extension" ) ); if( ssl->conf->cid == MBEDTLS_CID_CONF_DISABLED ) break; ret = ssl_parse_cid_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) { final_ret = MBEDTLS_ERR_SSL_BAD_HS_CID_EXT; } else if( ret == 0 ) /* cid extension present and processed succesfully */ { ssl->handshake->extensions_present += CID_EXTENSION; } break; #endif /* MBEDTLS_CID */ #if defined(MBEDTLS_SSL_COOKIE_C) case MBEDTLS_TLS_EXT_COOKIE: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found cookie extension" ) ); ret = ssl_parse_cookie_ext( ssl, ext + 4, ext_size ); /* if cookie verification failed then we return a hello retry message */ if( ret == MBEDTLS_ERR_SSL_BAD_HS_COOKIE_EXT ) { final_ret = MBEDTLS_ERR_SSL_BAD_HS_COOKIE_EXT; } else if( ret == 0 ) /* cookie extension present and processed succesfully */ { ssl->handshake->extensions_present += COOKIE_EXTENSION; } break; #endif /* MBEDTLS_SSL_COOKIE_C */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) case MBEDTLS_TLS_EXT_PRE_SHARED_KEY: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found pre_shared_key extension" ) ); /* Delay processing of the PSK identity once we have * found out which algorithms to use. We keep a pointer * to the buffer and the size for later processing. */ ext_len_psk_ext = ext_size; ext_psk_ptr = ext + 4; ssl->handshake->extensions_present += PRE_SHARED_KEY_EXTENSION; break; #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_ZERO_RTT) case MBEDTLS_TLS_EXT_EARLY_DATA: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found early_data extension" ) ); /* There is nothing really to process with this extension. ret = ssl_parse_early_data_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_parse_supported_groups_ext", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_SUPPORTED_GROUPS ); } */ ssl->handshake->extensions_present += EARLY_DATA_EXTENSION; break; #endif /* MBEDTLS_ZERO_RTT */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) case MBEDTLS_TLS_EXT_SUPPORTED_GROUPS: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported group extension" ) ); /* Supported Groups Extension * * When sent by the client, the "supported_groups" extension * indicates the named groups which the client supports, * ordered from most preferred to least preferred. */ ret = mbedtls_ssl_parse_supported_groups_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_parse_supported_groups_ext", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_SUPPORTED_GROUPS ); } ssl->handshake->extensions_present += SUPPORTED_GROUPS_EXTENSION; break; #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) case MBEDTLS_TLS_EXT_PSK_KEY_EXCHANGE_MODES: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found psk key exchange modes extension" ) ); ret = ssl_parse_key_exchange_modes_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_parse_key_exchange_modes_ext", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_PSK_KEY_EXCHANGE_MODES_EXT ); } ssl->handshake->extensions_present += PSK_KEY_EXCHANGE_MODES_EXTENSION; break; #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if ( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ) case MBEDTLS_TLS_EXT_KEY_SHARES: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found key share extension" ) ); /* * Key Share Extension * * When sent by the client, the "key_share" extension * contains the endpoint's cryptographic parameters for * ECDHE/DHE key establishment methods. */ ret = ssl_parse_key_shares_ext( ssl, ext + 4, ext_size ); if( ret == MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_SHARE ) { /* We parsed the extension incorrectly */ MBEDTLS_SSL_DEBUG_RET( 1, "ssl_parse_key_shares_ext", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_SHARE ); break; } else if( ret == MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE ) { /* We need to send a HelloRetryRequest message * but we still have to determine the ciphersuite. * Note: We got the key share - we just didn't like * the content of it. */ final_ret = MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE; ssl->handshake->extensions_present += KEY_SHARE_EXTENSION; break; } ssl->handshake->extensions_present += KEY_SHARE_EXTENSION; break; #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max fragment length extension" ) ); ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_max_fragment_length_ext" ), ret ); return( MBEDTLS_ERR_SSL_BAD_HS_MAX_FRAGMENT_LENGTH_EXT ); } ssl->handshake->extensions_present += MAX_FRAGMENT_LENGTH_EXTENSION; break; #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ case MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported versions extension" ) ); ret = ssl_parse_supported_versions_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_supported_versions_ext" ), ret ); return( MBEDTLS_ERR_SSL_BAD_HS_SUPPORTED_VERSIONS_EXT ); } ssl->handshake->extensions_present += SUPPORTED_VERSION_EXTENSION; break; #if defined(MBEDTLS_SSL_ALPN) case MBEDTLS_TLS_EXT_ALPN: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) ); ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_alpn_ext" ), ret ); return( MBEDTLS_ERR_SSL_BAD_HS_ALPN_EXT ); } ssl->handshake->extensions_present += ALPN_EXTENSION; break; #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) case MBEDTLS_TLS_EXT_SIG_ALG: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found signature_algorithms extension" ) ); ret = mbedtls_ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ssl_parse_supported_signature_algorithms_server_ext ( %d )", ret ) ); return( ret ); } ssl->handshake->extensions_present += SIGNATURE_ALGORITHM_EXTENSION; break; #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ default: MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d ( ignoring )", ext_id ) ); } ext_len -= 4 + ext_size; ext += 4 + ext_size; if( ext_len > 0 && ext_len < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } /* * Search for a matching ciphersuite */ got_common_suite = 0; ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver]; ciphersuite_info = NULL; #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE) for ( j = 0, p = ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) { for ( i = 0; ciphersuites[i] != 0; i++ ) #else for ( i = 0; ciphersuites[i] != 0; i++ ) { for ( j = 0, p = ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) #endif /* MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE */ { if( p[0] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) || p[1] != ( ( ciphersuites[i] ) & 0xFF ) ) continue; got_common_suite = 1; ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] ); if( ciphersuite_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_ssl_ciphersuite_from_id: should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } goto have_ciphersuite; /* if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i], &ciphersuite_info ) ) != 0 ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); if( ciphersuite_info != NULL ) goto have_ciphersuite; */ } } if( got_common_suite ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, but none of them usable" ) ); /*mbedtls_ssl_send_fatal_handshake_failure( ssl ); */ return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE ); } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) ); /*mbedtls_ssl_send_fatal_handshake_failure( ssl ); */ return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); } have_ciphersuite: MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) ); ssl->session_negotiate->ciphersuite = ciphersuites[i]; ssl->handshake->ciphersuite_info = ciphersuite_info; /* List all the extensions we have received */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Extensions:" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "- KEY_SHARE_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & KEY_SHARE_EXTENSION ) > 0 ) ? "TRUE" : "FALSE" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "- PSK_KEY_EXCHANGE_MODES_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & PSK_KEY_EXCHANGE_MODES_EXTENSION ) > 0 ) ? "TRUE" : "FALSE" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "- PRE_SHARED_KEY_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & PRE_SHARED_KEY_EXTENSION ) > 0 ) ? "TRUE" : "FALSE" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "- SIGNATURE_ALGORITHM_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & SIGNATURE_ALGORITHM_EXTENSION ) >0 ) ? "TRUE" : "FALSE" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "- SUPPORTED_GROUPS_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & SUPPORTED_GROUPS_EXTENSION ) >0 ) ? "TRUE" : "FALSE" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "- SUPPORTED_VERSION_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & SUPPORTED_VERSION_EXTENSION ) > 0 ) ? "TRUE" : "FALSE" ) ); #if defined(MBEDTLS_CID) MBEDTLS_SSL_DEBUG_MSG( 3, ( "- CID_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & CID_EXTENSION ) > 0 ) ? "TRUE" : "FALSE" ) ); #endif /* MBEDTLS_CID */ #if defined ( MBEDTLS_SSL_SERVER_NAME_INDICATION ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "- SERVERNAME_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & SERVERNAME_EXTENSION ) > 0 ) ? "TRUE" : "FALSE" ) ); #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined ( MBEDTLS_SSL_ALPN ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "- ALPN_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & ALPN_EXTENSION ) > 0 ) ? "TRUE" : "FALSE" ) ); #endif /* MBEDTLS_SSL_ALPN */ #if defined ( MBEDTLS_SSL_MAX_FRAGMENT_LENGTH ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "- MAX_FRAGMENT_LENGTH_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & MAX_FRAGMENT_LENGTH_EXTENSION ) > 0 ) ? "TRUE" : "FALSE" ) ); #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined ( MBEDTLS_SSL_COOKIE_C ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "- COOKIE_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & COOKIE_EXTENSION ) >0 ) ? "TRUE" : "FALSE" ) ); #endif /* MBEDTLS_SSL_COOKIE_C */ #if defined(MBEDTLS_ZERO_RTT) MBEDTLS_SSL_DEBUG_MSG( 3, ( "- EARLY_DATA_EXTENSION ( %s )", ( ( ssl->handshake->extensions_present & EARLY_DATA_EXTENSION ) >0 ) ? "TRUE" : "FALSE" ) ); #endif /* MBEDTLS_ZERO_RTT*/ /* Determine key exchange algorithm to use. There are three types of key exchanges * supported in TLS 1.3, namely ( EC )DH with ECDSA, ( EC )DH with PSK, and plain PSK. * Additionally, we need to consider the ZeroRTT exchange as well. */ #if defined(MBEDTLS_ZERO_RTT) /* * 0 ) Zero-RTT Exchange / Early Data * It requires early_data extension, at least key_exchange_modes and * the pre_shared_key extension. It may additionally provide key share * and supported_groups. */ if( ssl->handshake->extensions_present & EARLY_DATA_EXTENSION ) { /* Pure PSK mode */ if( ( ssl->conf->early_data == MBEDTLS_SSL_EARLY_DATA_ENABLED ) && ( ssl->handshake->extensions_present & PRE_SHARED_KEY_EXTENSION ) && ( ssl->handshake->extensions_present & PSK_KEY_EXCHANGE_MODES_EXTENSION ) ) { /* Test whether we are allowed to use this mode ( server-side check ) */ if( ( ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_KE ) || ( ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_ALL ) || ( ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_ALL ) ) { /* Test whether we are allowed to use this mode ( client-side check ) */ if( ( ssl->session_negotiate->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_KE ) || ( ssl->session_negotiate->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_ALL ) ) { ret = mbedtls_ssl_parse_client_psk_identity_ext( ssl, ext_psk_ptr, ext_len_psk_ext ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "Using a PSK key exchange" ) ); ssl->session_negotiate->key_exchange = MBEDTLS_KEY_EXCHANGE_PSK; ssl->handshake->early_data = MBEDTLS_SSL_EARLY_DATA_ON; goto end_client_hello; } } } /* ECDHE-PSK mode */ if( ( ssl->conf->early_data == MBEDTLS_SSL_EARLY_DATA_ENABLED ) && ( ssl->handshake->extensions_present & PRE_SHARED_KEY_EXTENSION ) && ( ssl->handshake->extensions_present & KEY_SHARE_EXTENSION ) && ( ssl->handshake->extensions_present & PSK_KEY_EXCHANGE_MODES_EXTENSION ) ) { /* Test whether we are allowed to use this mode ( server-side check ) */ if( ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_DHE_KE || ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_ALL || ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_ALL ) { /* Test whether we are allowed to use this mode ( client-side check ) */ if( ssl->session_negotiate->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_DHE_KE || ssl->session_negotiate->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_ALL ) { ret = mbedtls_ssl_parse_client_psk_identity_ext( ssl, ext_psk_ptr, ext_len_psk_ext ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "Using a ECDHE-PSK key exchange" ) ); ssl->session_negotiate->key_exchange = MBEDTLS_KEY_EXCHANGE_ECDHE_PSK; ssl->handshake->early_data = MBEDTLS_SSL_EARLY_DATA_ON; goto end_client_hello; } } } } #endif /* MBEDTLS_ZERO_RTT*/ /* The order of preference is * 1 ) Plain PSK Mode * 2 ) ( EC )DHE-PSK Mode * 3 ) Certificate Mode * * Currently, the preference order is hard-coded - not configurable. */ /* * 1 ) Plain PSK-based key exchange * Requires key_exchange_modes and the pre_shared_key extension * */ if( ( ssl->handshake->extensions_present & PRE_SHARED_KEY_EXTENSION ) && ( ssl->handshake->extensions_present & PSK_KEY_EXCHANGE_MODES_EXTENSION ) ) { /* Test whether we are allowed to use this mode ( server-side check ) */ if( ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_KE || ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_ALL || ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_ALL ) { /* Test whether we are allowed to use this mode ( client-side check ) */ if( ssl->session_negotiate->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_KE || ssl->session_negotiate->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_ALL ) { if( ( ret = mbedtls_ssl_parse_client_psk_identity_ext( ssl, ext_psk_ptr, ext_len_psk_ext ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "Using a PSK key exchange" ) ); ssl->session_negotiate->key_exchange = MBEDTLS_KEY_EXCHANGE_PSK; goto end_client_hello; } } } /* * 2 ) ( EC )DHE-PSK-based key exchange * Requires key share, supported_groups, key_exchange_modes and * the pre_shared_key extension. */ if( ( ssl->handshake->extensions_present & PRE_SHARED_KEY_EXTENSION ) && ( ssl->handshake->extensions_present & KEY_SHARE_EXTENSION ) && ( ssl->handshake->extensions_present & PSK_KEY_EXCHANGE_MODES_EXTENSION ) ) { /* Test whether we are allowed to use this mode ( server-side check ) */ if( ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_DHE_KE || ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_ALL || ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_ALL ) { /* Test whether we are allowed to use this mode ( client-side check ) */ if( ssl->session_negotiate->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_DHE_KE || ssl->session_negotiate->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_PSK_ALL ) { if( ( ret = mbedtls_ssl_parse_client_psk_identity_ext( ssl, ext_psk_ptr, ext_len_psk_ext ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "Using a ECDHE-PSK key exchange" ) ); ssl->session_negotiate->key_exchange = MBEDTLS_KEY_EXCHANGE_ECDHE_PSK; goto end_client_hello; } } } /* * 3 ) Certificate-based key exchange * It requires supported_groups, supported_signature extensions, and key share * */ if( ( ssl->handshake->extensions_present & SUPPORTED_GROUPS_EXTENSION ) && ( ssl->handshake->extensions_present & SIGNATURE_ALGORITHM_EXTENSION ) && ( ssl->handshake->extensions_present & KEY_SHARE_EXTENSION ) ) { /* Test whether we are allowed to use this mode ( server-side check ) */ if( ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_ECDHE_ECDSA || ssl->conf->key_exchange_modes == MBEDTLS_SSL_TLS13_KEY_EXCHANGE_MODE_ALL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Using a ECDSA-ECDHE key exchange" ) ); ssl->session_negotiate->key_exchange = MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA; goto end_client_hello; } } /* If we previously determined that an HRR is needed then * we will send it now. */ if( final_ret == MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE ) return( MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE ); /* if( ssl->session_negotiate->key_exchange == 0 ) { */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "ClientHello message misses mandatory extensions." ) ); return( MBEDTLS_ERR_SSL_BAD_HS_MISSING_EXTENSION_EXT ); /* } */ end_client_hello: #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_recv_flight_completed( ssl ); #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_COOKIE_C) /* If we failed to see a cookie extension, and we required it through the * configuration settings ( rr_config ), then we need to send a HRR msg. * Conceptually, this is similiar to having received a cookie that failed * the verification check. */ if( ( ssl->conf->rr_config == MBEDTLS_SSL_FORCE_RR_CHECK_ON ) && !( ssl->handshake->extensions_present & COOKIE_EXTENSION ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Cookie extension missing. Need to send a HRR." ) ); final_ret = MBEDTLS_ERR_SSL_BAD_HS_MISSING_COOKIE_EXT; } #endif /* MBEDTLS_SSL_COOKIE_C */ if( final_ret == MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE || final_ret == MBEDTLS_ERR_SSL_BAD_HS_MISSING_COOKIE_EXT ) { /* create stateless transcript hash for HRR */ unsigned char transcript[MBEDTLS_MD_MAX_SIZE + 4]; /* used to store the ClientHello1 msg */ int hash_length; MBEDTLS_SSL_DEBUG_MSG( 5, ( "--- Checksum ( ssl_parse_client_hello, stateless transcript hash for HRR )" ) ); /* * Transcript-Hash( ClientHello1, HelloRetryRequest, ... MN ) = * Hash( message_hash || * 00 00 Hash.length || * Hash( ClientHello1 ) || * HelloRetryRequest ... MN ) * */ transcript[0] = MBEDTLS_SSL_HS_MESSAGE_HASH; transcript[1] = 0; transcript[2] = 0; hash_length = mbedtls_hash_size_for_ciphersuite( ssl->handshake->ciphersuite_info ); if( hash_length == -1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_hash_size_for_ciphersuite == -1" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } transcript[3] = ( uint8_t )hash_length; if( ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA256 ) { #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_init( &sha256 ); if( ( ret = mbedtls_sha256_starts_ret( &sha256, 0 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha256_starts_ret", ret ); final_ret = ret; goto cleanup; } /* Hash ClientHello message */ if( ( ret = mbedtls_sha256_update_ret( &sha256, orig_buf, orig_msg_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha256_update_ret", ret ); final_ret = ret; goto cleanup; } if( ( ret = mbedtls_sha256_finish_ret( &sha256, &transcript[4]) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha256_finish_ret", ret ); final_ret = ret; goto cleanup; } MBEDTLS_SSL_DEBUG_BUF( 5, "Transcript-Hash( ClientHello1, HelloRetryRequest, ... MN )", &transcript[0], 32+4 ); #else MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_ssl_tls1_3_derive_master_secret: Unknow hash function." ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); #endif /* MBEDTLS_SHA256_C */ } else if( ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) { #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_init( &sha512 ); if( ( ret = mbedtls_sha512_starts_ret( &sha512, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha512_starts_ret", ret ); final_ret = ret; goto cleanup; } /* Hash ClientHello message */ if( ( ret = mbedtls_sha512_update_ret( &sha512, orig_buf, orig_msg_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha512_update_ret", ret ); final_ret = ret; goto cleanup; } if( ( ret = mbedtls_sha512_finish_ret( &sha512, &transcript[4] ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha512_finish_ret", ret ); goto cleanup; } MBEDTLS_SSL_DEBUG_BUF( 5, "Transcript-Hash( ClientHello1, HelloRetryRequest, ... MN )", &transcript[0], 48+4 ); #else MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_ssl_tls1_3_derive_master_secret: Unknow hash function." ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); #endif /* MBEDTLS_SHA512_C */ } else if( ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA512 ) { #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_init( &sha512 ); if( ( ret = mbedtls_sha512_starts_ret( &sha512, 0 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha512_starts_ret", ret ); final_ret = ret; goto cleanup; } /* Hash ClientHello message */ if( ( ret = mbedtls_sha512_update_ret( &sha512, orig_buf, orig_msg_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha512_update_ret", ret ); final_ret = ret; goto cleanup; } if( ( ret = mbedtls_sha512_finish_ret( &sha512, &transcript[4] ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha512_finish_ret", ret ); final_ret = ret; goto cleanup; } MBEDTLS_SSL_DEBUG_BUF( 5, "ClientHello hash", &transcript[4], 64 ); } else { #else MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_ssl_tls1_3_derive_master_secret: Unknow hash function." ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); #endif /* MBEDTLS_SHA512_C */ } ssl->handshake->update_checksum( ssl, &transcript[0], hash_length + 4 ); } else { /* create normal transcript hash */ MBEDTLS_SSL_DEBUG_MSG( 5, ( "--- Checksum ( ssl_parse_client_hello, normal transcript hash )" ) ); ssl->handshake->update_checksum( ssl, orig_buf, orig_msg_len ); } mbedtls_ssl_optimize_checksum( ssl, ssl->handshake->ciphersuite_info ); cleanup: #if defined(MBEDTLS_SHA256_C) if( ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA256 ) { mbedtls_sha256_free( &sha256 ); } else #endif #if defined(MBEDTLS_SHA512_C) if( ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA384 || ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA512 ) { mbedtls_sha512_free( &sha512 ); } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_ssl_tls1_3_derive_master_secret: Unknow hash function." ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } return( final_ret ); } static int ssl_client_hello_postprocess( mbedtls_ssl_context* ssl, int ret ) { ( (void ) ssl ); ( (void ) ret ); return ( 0 ); } #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; *olen = 0; if( ( ssl->handshake->extensions_present & MAX_FRAGMENT_LENGTH_EXTENSION ) == 0 ) { return( 0 ); } if( ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) { return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, max_fragment_length extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF ); *p++ = 0x00; *p++ = 1; *p++ = ssl->session_negotiate->mfl_code; *olen = 5; } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_ALPN) static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { *olen = 0; if( ( ssl->handshake->extensions_present & ALPN_EXTENSION ) == 0 || ssl->alpn_chosen == NULL ) { return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding alpn extension" ) ); /* * 0 . 1 ext identifier * 2 . 3 ext length * 4 . 5 protocol list length * 6 . 6 protocol name length * 7 . 7+n protocol name */ buf[0] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF ); buf[1] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF ); *olen = 7 + strlen( ssl->alpn_chosen ); buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF ); buf[3] = (unsigned char)( ( *olen - 4 ) & 0xFF ); buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF ); buf[5] = (unsigned char)( ( *olen - 6 ) & 0xFF ); buf[6] = (unsigned char)( ( *olen - 7 ) & 0xFF ); memcpy( buf + 7, ssl->alpn_chosen, *olen - 7 ); } #endif /* MBEDTLS_SSL_ALPN */ /* * * EncryptedExtensions message * * The EncryptedExtensions message contains any extensions which * should be protected, i.e., any which are not needed to establish * the cryptographic context. */ /* * Overview */ /* Main entry point; orchestrates the other functions */ static int ssl_encrypted_extensions_process( mbedtls_ssl_context* ssl ); static int ssl_encrypted_extensions_prepare( mbedtls_ssl_context* ssl ); static int ssl_encrypted_extensions_write( mbedtls_ssl_context* ssl, unsigned char* buf, size_t buflen, size_t* olen ); static int ssl_encrypted_extensions_postprocess( mbedtls_ssl_context* ssl ); static int ssl_encrypted_extensions_process( mbedtls_ssl_context* ssl ) { int ret; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write encrypted extension" ) ); /* Make sure we can write a new message. */ MBEDTLS_SSL_PROC_CHK( mbedtls_ssl_flush_output( ssl ) ); MBEDTLS_SSL_PROC_CHK( ssl_encrypted_extensions_prepare( ssl ) ); MBEDTLS_SSL_PROC_CHK( ssl_encrypted_extensions_write( ssl, ssl->out_msg, MBEDTLS_SSL_MAX_CONTENT_LEN, &ssl->out_msglen ) ); ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_ENCRYPTED_EXTENSION; MBEDTLS_SSL_DEBUG_BUF( 3, "EncryptedExtensions", ssl->out_msg, ssl->out_msglen ); /* Update state */ MBEDTLS_SSL_PROC_CHK( ssl_encrypted_extensions_postprocess( ssl ) ); /* Dispatch message */ MBEDTLS_SSL_PROC_CHK( mbedtls_ssl_write_record( ssl ) ); /* NOTE: For the new messaging layer, the postprocessing step * might come after the dispatching step if the latter * doesn't send the message immediately. * At the moment, we must do the postprocessing * prior to the dispatching because if the latter * returns WANT_WRITE, we want the handshake state * to be updated in order to not enter * this function again on retry. */ cleanup: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write encrypted extension" ) ); return( ret ); } static int ssl_encrypted_extensions_prepare( mbedtls_ssl_context* ssl ) { int ret; mbedtls_ssl_key_set traffic_keys; ret = mbedtls_ssl_key_derivation( ssl, &traffic_keys ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_key_derivation", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Remember current sequence number / epoch settings for resending */ ssl->handshake->alt_transform_out = ssl->transform_out; memcpy( ssl->handshake->alt_out_ctr, ssl->out_ctr, 8 ); } #endif ssl->transform_out = ssl->transform_negotiate; ssl->session_out = ssl->session_negotiate; mbedtls_ssl_transform_free( ssl->transform_negotiate ); ret = mbedtls_set_traffic_key( ssl, &traffic_keys, ssl->transform_negotiate, 0 ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_set_traffic_key", ret ); return( ret ); } /* * Set the out_msg pointer to the correct location based on IV length */ ssl->out_msg = ssl->out_iv; /* * Switch to our negotiated transform and session parameters for outbound * data. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Remember current sequence number / epoch settings for resending */ /*ssl->handshake->alt_transform_out = ssl->transform_out; */ /*memcpy( ssl->handshake->alt_out_ctr, ssl->out_ctr, 8 ); */ /* Set sequence_number of record layer to zero */ memset( ssl->out_ctr + 2, 0, 6 ); /* TODO: Why is this commented out? Check! */ /* unsigned char i; for ( i = 2; i > 0; i-- ) if( ++ssl->out_ctr[i - 1] != 0 ) break; if( i == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) ); return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } */ } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ { memset( ssl->out_ctr, 0, 8 ); } /* Set sequence number used at the handshake header to zero */ memset( ssl->transform_out->sequence_number_enc, 0x0, 12 ); #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_activate != NULL ) { if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) /* epoch value ( 2 ) is used for messages protected * using keys derived from the handshake_traffic_secret. */ ssl->in_epoch = 2; ssl->out_epoch = 2; #endif /* MBEDTLS_SSL_PROTO_DTLS */ return( 0 ); } static int ssl_encrypted_extensions_write( mbedtls_ssl_context* ssl, unsigned char* buf, size_t buflen, size_t* olen ) { int ret; size_t n; unsigned char *p, *end; /* If all extensions are disabled then olen is 0. */ *olen = 0; end = buf + buflen; if( buflen < ( 4 ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } /* Skip HS header */ p = buf + 4; /* * struct { * Extension extensions<0..2 ^ 16 - 1>; * } EncryptedExtensions; * */ /* Skip extension length; first write extensions, then update length */ p += 2; #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) ret = ssl_write_sni_server_ext( ssl, p, end - p, &n ); if( ret != 0 ) return( ret ); p += n; #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_SSL_ALPN) ret = ssl_write_alpn_ext( ssl, p, end - p, &n ); if( ret != 0 ) return( ret ); p += n; #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) ret = ssl_write_max_fragment_length_ext( ssl, p, end - p, &n ); if( ret != 0 ) return( ret ); p += n; #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_ZERO_RTT) ret = mbedtls_ssl_write_early_data_ext( ssl, p, (size_t)( end - p ), &n ); if( ret != 0 ) return( ret ); p += n; #endif /* MBEDTLS_ZERO_RTT */ *olen = p - buf; *( buf + 4 ) = (unsigned char)( ( ( *olen - 4 - 2 ) >> 8 ) & 0xFF ); *( buf + 5 ) = (unsigned char)( ( *olen - 4 - 2 ) & 0xFF ); return( 0 ); } static int ssl_encrypted_extensions_postprocess( mbedtls_ssl_context* ssl ) { mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_CERTIFICATE_REQUEST ); return( 0 ); } /* ssl_write_hello_retry_request( ) to transmit a HelloRetryRequest message * * Servers send this message in response to a ClientHello message when * the server was able to find an acceptable set of algorithms and groups * that are mutually supported, but the client's KeyShare did not contain * an acceptable offer. * * We also send this message with DTLS 1.3 to perform a return-routability * check ( and we include a cookie ). */ static int ssl_write_hello_retry_request( mbedtls_ssl_context *ssl ) { int ret; unsigned char *p = ssl->out_msg + 4; unsigned char *ext_len_byte; int ext_length, total_ext_len = 0; unsigned char *extension_start; const char magic_hrr_string[32] = { 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91, 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33 ,0x9C }; #if defined(MBEDTLS_ECDH_C) const mbedtls_ecp_group_id *gid; const mbedtls_ecp_curve_info **curve = NULL; #endif /* MBEDTLS_ECDH_C */ /*const mbedtls_ssl_ciphersuite_t *ciphersuite_info; */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello retry request" ) ); /* * struct { * ProtocolVersion legacy_version = 0x0303; * Random random ( with magic value ); * opaque legacy_session_id_echo<0..32>; * CipherSuite cipher_suite; * uint8 legacy_compression_method = 0; * Extension extensions<0..2^16-1>; * } ServerHello; --- aka HelloRetryRequest */ /* For TLS 1.3 we use the legacy version number {0x03, 0x03} * instead of the true version number. * * For DTLS 1.3 we use the legacy version number * {254,253}. * * In cTLS the version number is elided. */ #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_DO_NOT_USE ) #endif /* MBEDTLS_SSL_TLS13_CTLS */ { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { *p++ = 0xfe; /* 254 */ *p++ = 0xfd; /* 253 */ MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p - 2, 2 ); } else #else { *p++ = 0x03; *p++ = 0x03; MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p - 2, 2 ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ } if( ssl->transform_negotiate == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ssl_write_hello_retry_request: ssl->transform_negotiate == NULL" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /*ciphersuite_info = ssl->handshake->ciphersuite_info; */ /* write magic string ( as a replacement for the random value ) */ memcpy( p, &magic_hrr_string[0], 32 ); MBEDTLS_SSL_DEBUG_BUF( 3, "random bytes", p, 32 ); p += 32; /* write legacy_session_id_echo */ *p++ = (unsigned char) ssl->session_negotiate->id_len; memcpy( p, &ssl->session_negotiate->id[0], ssl->session_negotiate->id_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "session id", p, ssl->session_negotiate->id_len ); p += ssl->session_negotiate->id_len; /* write ciphersuite ( 2 bytes ) */ *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite >> 8 ); *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite ); MBEDTLS_SSL_DEBUG_BUF( 3, "ciphersuite", p-2, 2 ); /* write legacy_compression_method ( 0 ) */ *p++ = 0x0; MBEDTLS_SSL_DEBUG_MSG( 3, ( "legacy compression method: [%d]", *( p-1 ) ) ); /* write extensions */ extension_start = p; /* Extension starts with a 2 byte length field; we skip it and write it later */ p += 2; #if defined(MBEDTLS_SSL_COOKIE_C) /* Cookie Extension * * struct { * opaque cookie<0..2^16-1>; * } Cookie; * */ /* Write extension header */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_COOKIE >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_COOKIE ) & 0xFF ); /* Write total extension length * ( Skip it for now till we know the length ) */ ext_len_byte = p; p = p + 2; /* If we get here, f_cookie_check is not null */ if( ssl->conf->f_cookie_write == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "inconsistent cookie callbacks" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( ( ret = ssl->conf->f_cookie_write( ssl->conf->p_cookie, &p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN, ssl->cli_id, ssl->cli_id_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "f_cookie_write", ret ); return( ret ); } ext_length = ( p - ( ext_len_byte + 2 ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Cookie", ext_len_byte + 2, ext_length ); /* Write length */ *ext_len_byte++ = (unsigned char)( ( ext_length >> 8 ) & 0xFF ); *ext_len_byte = (unsigned char)( ext_length & 0xFF ); total_ext_len += ext_length + 4 /* 2 bytes for extension_type and 2 bytes for length field */; #endif /* MBEDTLS_SSL_COOKIE_C */ #if defined(MBEDTLS_ECDH_C) /* key_share Extension * * struct { * select ( Handshake.msg_type ) { * case client_hello: * KeyShareEntry client_shares<0..2^16-1>; * * case hello_retry_request: * NamedGroup selected_group; * * case server_hello: * KeyShareEntry server_share; * }; * } KeyShare; * */ /* For a pure PSK-based ciphersuite there is no key share to declare. * Hence, we focus on ECDHE-EDSA and ECDHE-PSK. */ if( ssl->session_negotiate->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA || ssl->session_negotiate->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { /* Write extension header */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_KEY_SHARES >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_KEY_SHARES ) & 0xFF ); ext_len_byte = p; /* Write length */ *p++ = 0; *p++ = 2; ext_length = 2; for ( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ ) { for ( curve = ssl->handshake->curves; *curve != NULL; curve++ ) { if( ( *curve )->grp_id == *gid ) goto curve_matching_done; } } curve_matching_done: if( curve == NULL || *curve == NULL ) { /* This case should not happen */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "no matching named group found" ) ); return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); } /* Write selected group */ *p++ = ( *curve )->tls_id >> 8; *p++ = ( *curve )->tls_id & 0xFF; MBEDTLS_SSL_DEBUG_MSG( 3, ( "NamedGroup in HRR: %s", ( *curve )->name ) ); } total_ext_len += ext_length + 4 /* 2 bytes for extension_type and 2 bytes for length field */; #endif /* MBEDTLS_ECDH_C */ *extension_start++ = (unsigned char)( ( total_ext_len >> 8 ) & 0xFF ); *extension_start++ = (unsigned char)( ( total_ext_len ) & 0xFF ); ssl->out_msglen = p - ssl->out_msg; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_HELLO; if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello retry request" ) ); return( 0 ); } /* * * STATE HANDLING: ServerHello * */ /* * Overview */ /* Main entry point; orchestrates the other functions */ static int ssl_server_hello_process( mbedtls_ssl_context* ssl ); /* ServerHello handling sub-routines */ static int ssl_server_hello_prepare( mbedtls_ssl_context* ssl ); static int ssl_server_hello_write( mbedtls_ssl_context* ssl, unsigned char* buf, size_t buflen, size_t* olen ); static int ssl_server_hello_postprocess( mbedtls_ssl_context* ssl ); static int ssl_server_hello_process( mbedtls_ssl_context* ssl ) { int ret = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello" ) ); /* Coordination */ /* Preprocessing */ /* This might lead to ssl_process_server_hello( ) being called multiple * times. The implementation of ssl_process_server_hello_preprocess( ) * must either be safe to be called multiple times, or we need to add * state to omit this call once we're calling ssl_process_server_hello( ) * multiple times. */ MBEDTLS_SSL_PROC_CHK( ssl_server_hello_prepare( ssl ) ); /* Writing */ /* Make sure we can write a new message. */ MBEDTLS_SSL_PROC_CHK( mbedtls_ssl_flush_output( ssl ) ); MBEDTLS_SSL_PROC_CHK( ssl_server_hello_write( ssl, ssl->out_msg, MBEDTLS_SSL_MAX_CONTENT_LEN, &ssl->out_msglen ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) ); ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_HELLO; /* Postprocess */ MBEDTLS_SSL_PROC_CHK( ssl_server_hello_postprocess( ssl ) ); /* Dispatch */ MBEDTLS_SSL_PROC_CHK( mbedtls_ssl_write_record( ssl ) ); /* NOTE: For the new messaging layer, the postprocessing step * might come after the dispatching step if the latter * doesn't send the message immediately. * At the moment, we must do the postprocessing * prior to the dispatching because if the latter * returns WANT_WRITE, we want the handshake state * to be updated in order to not enter * this function again on retry. */ cleanup: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) ); return( ret ); } /* IMPORTANT: This function can currently be called multiple times * in case the call to mbedtls_ssl_flush_output( ) that * follows it in ssl_process_server_hello( ) fails. * * Make sure that the preparations in this function * can safely be repeated multiple times, or add logic * to ssl_process_server_hello( ) to never call it twice. */ static int ssl_server_hello_prepare( mbedtls_ssl_context* ssl ) { int ret; #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_USE ) { if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->handshake->randbytes + 16, 16 ) ) != 0 ) return( ret ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", ssl->handshake->randbytes + 16, 16 ); } else #endif /* MBEDTLS_SSL_TLS13_CTLS */ { if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->handshake->randbytes + 32, 32 ) ) != 0 ) return( ret ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", ssl->handshake->randbytes + 32, 32 ); } #if defined(MBEDTLS_HAVE_TIME) ssl->session_negotiate->start = time( NULL ); #endif /* MBEDTLS_HAVE_TIME */ /* Check for session resumption * <TBD> */ return( 0 ); } static int ssl_server_hello_write( mbedtls_ssl_context* ssl, unsigned char* buf, size_t buflen, size_t* olen ) { int ret=0; /* Extensions */ /* extension_start * Used during extension writing where the * buffer pointer to the beginning of the * extension list must be kept to write * the total extension list size in the end. */ unsigned char* extension_start; size_t cur_ext_len; /* Size of the current extension */ size_t total_ext_len; /* Size of list of extensions */ size_t rand_bytes_len; /* Buffer management */ unsigned char* start = buf; unsigned char* end = buf + buflen; #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_USE ) { rand_bytes_len = MBEDTLS_SSL_TLS13_CTLS_RANDOM_MAX_LENGTH; } else #endif /* MBEDTLS_SSL_TLS13_CTLS */ { rand_bytes_len = 32; } /* Ensure we have enough room for ServerHello * up to but excluding the extensions. */ if( buflen < ( 4+32+2+2+1+ssl->session_negotiate->id_len+1+1 ) ) /* TBD: FIXME */ { return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } /* * TLS 1.3 * 0 . 0 handshake type * 1 . 3 handshake length * * cTLS * 0 . 0 handshake type * * The header is set by ssl_write_record. * For DTLS 1.3 the other fields are adjusted. */ #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_USE ) { buf++; /* skip handshake type */ buflen--; } else #endif /* MBEDTLS_SSL_TLS13_CTLS */ { buf += 4; /* skip handshake type + length */ buflen -=4; } /* Version */ #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_DO_NOT_USE ) { #endif /* MBEDTLS_SSL_TLS13_CTLS */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { *buf++ = (unsigned char) 0xfe; *buf++ = (unsigned char) 0xfd; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen version: [0xfe:0xfd]" ) ); } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ { *buf++ = (unsigned char)0x3; *buf++ = (unsigned char)0x3; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen version: [0x3:0x3]" ) ); } buflen -= 2; #if defined(MBEDTLS_SSL_TLS13_CTLS) } #endif /* MBEDTLS_SSL_TLS13_CTLS */ /* Write random bytes */ memcpy( buf, ssl->handshake->randbytes + 32, rand_bytes_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf, rand_bytes_len ); buf += rand_bytes_len; buflen -= rand_bytes_len; #if defined(MBEDTLS_HAVE_TIME) ssl->session_negotiate->start = time( NULL ); #endif /* MBEDTLS_HAVE_TIME */ /* Write legacy session id */ #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_DO_NOT_USE ) #endif /* MBEDTLS_SSL_TLS13_CTLS */ { *buf++ = (unsigned char)ssl->session_negotiate->id_len; buflen--; memcpy( buf, &ssl->session_negotiate->id[0], ssl->session_negotiate->id_len ); buf += ssl->session_negotiate->id_len; MBEDTLS_SSL_DEBUG_MSG( 3, ( "session id length ( %d )", ssl->session_negotiate->id_len ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "session id", ssl->session_negotiate->id, ssl->session_negotiate->id_len ); buflen -= ssl->session_negotiate->id_len; } /* write selected ciphersuite ( 2 bytes ) */ *buf++ = (unsigned char)( ssl->session_negotiate->ciphersuite >> 8 ); *buf++ = (unsigned char)( ssl->session_negotiate->ciphersuite ); buflen -= 2; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s ( id=%d )", mbedtls_ssl_get_ciphersuite_name( ssl->session_negotiate->ciphersuite ), ssl->session_negotiate->ciphersuite ) ); #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_DO_NOT_USE ) #endif /* MBEDTLS_SSL_TLS13_CTLS */ { /* write legacy_compression_method ( 0 ) */ *buf++ = 0x0; buflen--; } /* First write extensions, then the total length */ extension_start = buf; total_ext_len = 0; buf += 2; #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) /* Only add the pre_shared_key extension if the client provided it in the ClientHello * and if the key exchange supports PSK */ if( ssl->handshake->extensions_present & PRE_SHARED_KEY_EXTENSION && ( ssl->session_negotiate->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || ssl->session_negotiate->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ) ) { ssl_write_server_pre_shared_key_ext( ssl, buf, end, &cur_ext_len ); total_ext_len += cur_ext_len; buf += cur_ext_len; } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if ( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ) /* Only add the key_share extension if the client provided it in the ClientHello * and if the appropriate key exchange mechanism was selected */ if( ssl->handshake->extensions_present & KEY_SHARE_EXTENSION && ( ssl->session_negotiate->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || ssl->session_negotiate->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ) ) { if( ( ret = ssl_write_key_shares_ext( ssl, buf, end, &cur_ext_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_key_shares_ext", ret ); return( ret ); } total_ext_len += cur_ext_len; buf += cur_ext_len; } #endif /* ( MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */ /* Add supported_version extension */ if( ( ret = ssl_write_supported_version_ext( ssl, buf, end, &cur_ext_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_supported_version_ext", ret ); return( ret ); } total_ext_len += cur_ext_len; buf += cur_ext_len; #if defined(MBEDTLS_CID) if( ssl->handshake->extensions_present & CID_EXTENSION ) { if( ( ret = ssl_write_cid_ext( ssl, buf, end, &cur_ext_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_cid_ext", ret ); return( ret ); } total_ext_len += cur_ext_len; buf += cur_ext_len; } #endif /* MBEDTLS_CID */ MBEDTLS_SSL_DEBUG_BUF( 4, "server hello extensions", extension_start, total_ext_len ); /* Write length information */ *extension_start++ = (unsigned char)( ( total_ext_len >> 8 ) & 0xFF ); *extension_start++ = (unsigned char)( ( total_ext_len ) & 0xFF ); buflen -= 2 + total_ext_len; *olen = buf - start; MBEDTLS_SSL_DEBUG_BUF( 3, "server hello", start, *olen ); return( ret ); } static int ssl_server_hello_postprocess( mbedtls_ssl_context* ssl ) { int ret = 0; ( (void ) ssl ); return( ret ); } /* * * STATE HANDLING: CertificateRequest * */ /* Main entry point; orchestrates the other functions */ static int ssl_certificate_request_process( mbedtls_ssl_context* ssl ); /* Coordination: * Check whether a CertificateRequest message should be written. * Returns a negative error code on failure, or one of * - SSL_CERTIFICATE_REQUEST_EXPECT_WRITE or * - SSL_CERTIFICATE_REQUEST_SKIP * indicating if the writing of the CertificateRequest * should be skipped or not. */ #define SSL_CERTIFICATE_REQUEST_SEND 0 #define SSL_CERTIFICATE_REQUEST_SKIP 1 static int ssl_certificate_request_coordinate( mbedtls_ssl_context* ssl ); #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) static int ssl_certificate_request_write( mbedtls_ssl_context* ssl, unsigned char* buf, size_t buflen, size_t* olen ); #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ static int ssl_certificate_request_postprocess( mbedtls_ssl_context* ssl ); /* * Implementation */ static int ssl_certificate_request_process( mbedtls_ssl_context* ssl ) { int ret = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) ); /* Coordination step: Check if we need to send a CertificateRequest */ MBEDTLS_SSL_PROC_CHK( ssl_certificate_request_coordinate( ssl ) ); #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) if( ret == SSL_CERTIFICATE_REQUEST_SEND ) { /* Make sure we can write a new message. */ MBEDTLS_SSL_PROC_CHK( mbedtls_ssl_flush_output( ssl ) ); /* Prepare CertificateRequest message in output buffer. */ MBEDTLS_SSL_PROC_CHK( ssl_certificate_request_write( ssl, ssl->out_msg, MBEDTLS_SSL_MAX_CONTENT_LEN, &ssl->out_msglen ) ); ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST; /* Update state */ MBEDTLS_SSL_PROC_CHK( ssl_certificate_request_postprocess( ssl ) ); /* Dispatch message */ MBEDTLS_SSL_PROC_CHK( mbedtls_ssl_write_record( ssl ) ); /* NOTE: With the new messaging layer, the postprocessing * step might come after the dispatching step if the * latter doesn't send the message immediately. * At the moment, we must do the postprocessing * prior to the dispatching because if the latter * returns WANT_WRITE, we want the handshake state * to be updated in order to not enter * this function again on retry. * * Further, once the two calls can be re-ordered, the two * calls to ssl_certificate_request_postprocess( ) can be * consolidated. */ } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ if( ret == SSL_CERTIFICATE_REQUEST_SKIP ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) ); /* Update state */ MBEDTLS_SSL_PROC_CHK( ssl_certificate_request_postprocess( ssl ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } cleanup: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate request" ) ); return( ret ); } static int ssl_certificate_request_coordinate( mbedtls_ssl_context* ssl ) { int authmode; if( ( ssl->session_negotiate->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ssl->session_negotiate->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) ) return( SSL_CERTIFICATE_REQUEST_SKIP ); #if !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ( ( void )authmode ); MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); #else #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET ) authmode = ssl->handshake->sni_authmode; else #endif authmode = ssl->conf->authmode; if( authmode == MBEDTLS_SSL_VERIFY_NONE ) return( SSL_CERTIFICATE_REQUEST_SKIP ); return( SSL_CERTIFICATE_REQUEST_SEND ); #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ } static int ssl_certificate_request_write( mbedtls_ssl_context* ssl, unsigned char* buf, size_t buflen, size_t* olen ) { int ret; unsigned char* p; unsigned char* end = buf + buflen; size_t const tls_hs_hdr_len = 4; /* Skip over handshake header. * * NOTE: * Even for DTLS, we are skipping 4 bytes for the TLS handshake * header. The actual DTLS handshake header is inserted in * the record writing routine mbedtls_ssl_write_record( ). */ p = buf + tls_hs_hdr_len; if( p + tls_hs_hdr_len + 1 + 2 > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return ( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } /* * * struct { * opaque certificate_request_context<0..2^8-1>; * Extension extensions<2..2^16-1>; * } CertificateRequest; * */ /* * Write certificate_request_context */ /* * We use a zero length context for the normal handshake * messages. For post-authentication handshake messages * this request context would be set to a non-zero value. */ #if defined(MBEDTLS_SSL_TLS13_CTLS) if( ssl->handshake->ctls == MBEDTLS_SSL_TLS13_CTLS_DO_NOT_USE ) #endif /* MBEDTLS_SSL_TLS13_CTLS */ { *p++ = 0x0; } /* * Write extensions */ /* The extensions must contain the signature_algorithms. */ /* Currently we don't use any other extension */ ret = mbedtls_ssl_write_signature_algorithms_ext( ssl, p+2, end, olen ); if( ret != 0 ) return( ret ); /* length field for all extensions */ *p++ = (unsigned char)( ( *olen >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( *olen ) & 0xFF ); p += *olen; *olen = p - buf; return( ret ); } static int ssl_certificate_request_postprocess( mbedtls_ssl_context* ssl ) { /* next state */ mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_SERVER_CERTIFICATE ); return( 0 ); } /* * TLS and DTLS 1.3 State Maschine -- server side */ int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl ) { int ret = 0; mbedtls_ssl_key_set traffic_keys; if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "server state: %d", ssl->state ) ); if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) return( ret ); } #endif switch ( ssl->state ) { /* start state */ case MBEDTLS_SSL_HELLO_REQUEST: ssl->handshake->hello_retry_requests_sent = 0; mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_CLIENT_HELLO ); #if defined(MBEDTLS_SSL_PROTO_DTLS) /* epoch value ( 0 ) is used with unencrypted messages */ ssl->out_epoch = 0; ssl->in_epoch = 0; #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE) ssl->handshake->ccs_sent = 0; #endif /* MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE */ break; /* ----- READ CLIENT HELLO ----*/ case MBEDTLS_SSL_CLIENT_HELLO: /* Reset pointers to buffers */ #if defined(MBEDTLS_SSL_PROTO_DTLS) && defined(MBEDTLS_CID) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->out_hdr = ssl->out_buf; ssl->out_ctr = ssl->out_buf + 3; ssl->out_len = ssl->out_buf + 11; ssl->out_iv = ssl->out_buf + 13; ssl->out_msg = ssl->out_buf + 13; ssl->in_hdr = ssl->in_buf; ssl->in_ctr = ssl->in_buf + 3; ssl->in_len = ssl->in_buf + 11; ssl->in_iv = ssl->in_buf + 13; ssl->in_msg = ssl->in_buf + 13; } #endif /* MBEDTLS_CID && MBEDTLS_SSL_PROTO_DTLS */ ret = ssl_client_hello_process( ssl ); /*ret = MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE; // for testing purposes */ switch ( ret ) { case 0: #if defined(MBEDTLS_SSL_COOKIE_C) && defined(MBEDTLS_SSL_PROTO_DTLS) /* If we use DTLS 1.3 then we may need to send a HRR instead of a ClientHello * to do a return-routability check. We use the ssl->conf->rr_config * variable for determining the preference to use the RR-check. */ if( ssl->handshake->hello_retry_requests_sent == 0 && ssl->conf->rr_config == MBEDTLS_SSL_FORCE_RR_CHECK_ON ) { /* Transmit Hello Retry Request */ mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_HELLO_RETRY_REQUEST ); } else #endif /* MBEDTLS_SSL_COOKIE_C && MBEDTLS_SSL_PROTO_DTLS */ { #if defined(MBEDTLS_ZERO_RTT) if( ssl->handshake->early_data == MBEDTLS_SSL_EARLY_DATA_ON ) { mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_EARLY_APP_DATA ); } else #endif /* MBEDTLS_ZERO_RTT */ { mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_SERVER_HELLO ); } } break; #if ( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ) case MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE: /* Wrong key share --> send HRR */ mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_HELLO_RETRY_REQUEST ); ret = 0; break; case MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_SHARE: /* Failed to parse the key share correctly --> send HRR */ mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_HELLO_RETRY_REQUEST ); ret = 0; break; #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */ case MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION: mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); break; case MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN: mbedtls_ssl_send_fatal_handshake_failure( ssl ); break; case MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE: mbedtls_ssl_send_fatal_handshake_failure( ssl ); break; #if defined(MBEDTLS_SSL_COOKIE_C) case MBEDTLS_ERR_SSL_BAD_HS_COOKIE_EXT: /* Cookie verification failed. This case is conceptually similar * to MBEDTLS_ERR_SSL_BAD_HS_WRONG_KEY_SHARE with the exception * that we are definitely going to include a cookie. --> Send HRR */ mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_HELLO_RETRY_REQUEST ); ret = 0; break; case MBEDTLS_ERR_SSL_BAD_HS_MISSING_COOKIE_EXT: /* Cookie extension missing. Send HRR */ mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_HELLO_RETRY_REQUEST ); ret = 0; break; #endif /* MBEDTLS_SSL_COOKIE_C */ case MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO: /* We have encountered a problem parsing the ClientHello */ /* Let us jump back to the initial state */ mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_HELLO_REQUEST ); ret = 0; break; case MBEDTLS_ERR_SSL_BAD_HS_MISSING_EXTENSION_EXT: mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_MISSING_EXTENSION ); return ( MBEDTLS_ERR_SSL_BAD_HS_MISSING_EXTENSION_EXT ); break; case MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE: return ( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); break; #if defined(MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE) case MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO_CCS: mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_CLIENT_HELLO ); ret = 0; break; #endif /* MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE */ default: /* Something went wrong and we jump back to initial state */ mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_HELLO_REQUEST ); /* TBD: Should we rather return an error here -- return ( ret )? */ ret = 0; } break; /* ----- WRITE EARLY APP DATA ----*/ #if defined(MBEDTLS_ZERO_RTT) case MBEDTLS_SSL_EARLY_APP_DATA: ret = ssl_read_early_data_process( ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_read_early_data_process", ret ); return ( ret ); } break; #endif /* MBEDTLS_ZERO_RTT */ /* ----- WRITE HELLO RETRY REQUEST ----*/ case MBEDTLS_SSL_HELLO_RETRY_REQUEST: if( ssl->handshake->hello_retry_requests_sent > 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Too many HRRs" ) ); return ( MBEDTLS_ERR_SSL_BAD_HS_TOO_MANY_HRR ); } ret = ssl_write_hello_retry_request( ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_hello_retry_request", ret ); return( ret ); } ssl->handshake->hello_retry_requests_sent++; #if defined(MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE) mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_SERVER_CCS_AFTER_HRR ); #else mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_CLIENT_HELLO ); #endif /* MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE */ break; /* ----- WRITE CHANGE CIPHER SPEC ----*/ #if defined(MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE) case MBEDTLS_SSL_SERVER_CCS_AFTER_HRR: ret = mbedtls_ssl_write_change_cipher_spec_process( ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_change_cipher_spec_process", ret ); return( ret ); } break; #endif /* MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE */ /* ----- READ 2nd CLIENT HELLO ----*/ case MBEDTLS_SSL_SECOND_CLIENT_HELLO: ret = ssl_client_hello_process( ssl ); switch ( ret ) { case 0: mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_SERVER_HELLO ); break; case MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION: mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); break; case MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN: mbedtls_ssl_send_fatal_handshake_failure( ssl ); break; case MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE: mbedtls_ssl_send_fatal_handshake_failure( ssl ); break; case MBEDTLS_ERR_SSL_BAD_HS_MISSING_EXTENSION_EXT: mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_MISSING_EXTENSION ); return ( MBEDTLS_ERR_SSL_BAD_HS_MISSING_EXTENSION_EXT ); break; case MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC: /* Stay in this state */ mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_SECOND_CLIENT_HELLO ); ret = 0; break; default: return( ret ); } break; /* ----- WRITE SERVER HELLO ----*/ case MBEDTLS_SSL_SERVER_HELLO: ret = ssl_server_hello_process( ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_server_hello_process", ret ); return( ret ); } #if defined(MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE) if( ssl->handshake->ccs_sent > 1 ) { mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_SERVER_CCS_AFTER_SERVER_HELLO ); } else { mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_ENCRYPTED_EXTENSIONS ); } #else mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_ENCRYPTED_EXTENSIONS ); #endif /* MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE */ break; /* ----- WRITE CHANGE CIPHER SPEC ----*/ #if defined(MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE) case MBEDTLS_SSL_SERVER_CCS_AFTER_SERVER_HELLO: ret = mbedtls_ssl_write_change_cipher_spec_process(ssl); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_change_cipher_spec_process", ret ); return( ret ); } break; #endif /* MBEDTLS_SSL_TLS13_COMPATIBILITY_MODE */ /* ----- WRITE ENCRYPTED EXTENSIONS ----*/ case MBEDTLS_SSL_ENCRYPTED_EXTENSIONS: ret = ssl_encrypted_extensions_process( ssl ); break; /* ----- WRITE CERTIFICATE REQUEST ----*/ case MBEDTLS_SSL_CERTIFICATE_REQUEST: ret = ssl_certificate_request_process( ssl ); break; /* ----- WRITE SERVER CERTIFICATE ----*/ case MBEDTLS_SSL_SERVER_CERTIFICATE: ret = mbedtls_ssl_write_certificate_process( ssl ); break; /* ----- WRITE SERVER CERTIFICATE VERIFY ----*/ case MBEDTLS_SSL_CERTIFICATE_VERIFY: ret = mbedtls_ssl_certificate_verify_process( ssl ); break; /* ----- WRITE FINISHED ----*/ case MBEDTLS_SSL_SERVER_FINISHED: ret = mbedtls_ssl_finished_out_process( ssl ); break; /* ----- READ CLIENT CERTIFICATE ----*/ case MBEDTLS_SSL_CLIENT_CERTIFICATE: ret = mbedtls_ssl_read_certificate_process( ssl ); break; /* ----- READ CLIENT CERTIFICATE VERIFY ----*/ case MBEDTLS_SSL_CLIENT_CERTIFICATE_VERIFY: ret = mbedtls_ssl_read_certificate_verify_process( ssl ); break; #if defined(MBEDTLS_ZERO_RTT) case MBEDTLS_SSL_EARLY_DATA: ret = ssl_read_end_of_early_data_process( ssl ); break; #endif /* MBEDTLS_ZERO_RTT */ /* ----- READ FINISHED ----*/ case MBEDTLS_SSL_CLIENT_FINISHED: #if defined(MBEDTLS_ZERO_RTT) if( ssl->handshake->early_data == MBEDTLS_SSL_EARLY_DATA_ON ) { ret = mbedtls_ssl_key_derivation( ssl, &traffic_keys ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_key_derivation", ret ); return( ret ); } mbedtls_ssl_transform_free( ssl->transform_negotiate ); ret = mbedtls_set_traffic_key( ssl, &traffic_keys, ssl->transform_negotiate,0 ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_set_traffic_key", ret ); return( ret ); } } #endif /* MBEDTLS_ZERO_RTT */ ret = mbedtls_ssl_generate_application_traffic_keys( ssl, &traffic_keys ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_generate_application_traffic_keys", ret ); return( ret ); } ret = mbedtls_ssl_finished_in_process( ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_finished_in_process", ret ); return( ret ); } /* Compute resumption_master_secret */ ret = mbedtls_ssl_generate_resumption_master_secret( ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_generate_resumption_master_secret ", ret ); return( ret ); } mbedtls_ssl_transform_free( ssl->transform_negotiate ); ret = mbedtls_set_traffic_key( ssl, &traffic_keys, ssl->transform_negotiate, 0 ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_set_traffic_key", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) /* epoch value ( 3 ) is used for payloads protected * using keys derived from the initial traffic_secret_0. */ ssl->in_epoch = 3; ssl->out_epoch = 3; #endif /* MBEDTLS_SSL_PROTO_DTLS */ if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_HANDSHAKE_FINISH_ACK ); else mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_HANDSHAKE_WRAPUP ); break; #if defined(MBEDTLS_SSL_PROTO_DTLS) case MBEDTLS_SSL_HANDSHAKE_FINISH_ACK: /* The server needs to reply with an ACK message after parsing * the Finish message from the client. */ ret = mbedtls_ssl_write_ack( ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_ack", ret ); return( ret ); } mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_HANDSHAKE_WRAPUP ); break; #endif /* MBEDTLS_SSL_PROTO_DTLS */ case MBEDTLS_SSL_HANDSHAKE_WRAPUP: MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) ); mbedtls_ssl_handshake_wrapup( ssl ); mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_HANDSHAKE_OVER ); #if defined(MBEDTLS_SSL_NEW_SESSION_TICKET) ret = ssl_write_new_session_ticket( ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_new_session_ticket ", ret ); return( ret ); } #endif /* MBEDTLS_SSL_NEW_SESSION_TICKET */ break; default: MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } mbedtls_ssl_handle_pending_alert( ssl ); return( ret ); } #endif /* MBEDTLS_SSL_SRV_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
34.630174
233
0.593589
a1fe6590cd4406cfc9cdd19d1d94abfd358b39c5
1,602
c
C
sources/utils.c
nicolasvienot/wolf-3d
309311db408d32b2fd5cd6dd7aaf36d3ce762f9e
[ "MIT" ]
5
2019-04-28T00:10:55.000Z
2019-10-08T19:36:15.000Z
sources/utils.c
nicolasvienot/wolf3d
309311db408d32b2fd5cd6dd7aaf36d3ce762f9e
[ "MIT" ]
null
null
null
sources/utils.c
nicolasvienot/wolf3d
309311db408d32b2fd5cd6dd7aaf36d3ce762f9e
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nvienot <nvienot@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/22 18:05:31 by nvienot #+# #+# */ /* Updated: 2019/05/22 18:11:50 by nvienot ### ########.fr */ /* */ /* ************************************************************************** */ #include "wolf3d.h" int secure_tex_x(int tex_x, int surface_w) { if (tex_x < 0) tex_x = 1; else if (tex_x > surface_w) tex_x = surface_w; return (tex_x); } int secure_tex_y(int tex_y, int surface_h) { if (tex_y < 0) tex_y = 1; else if (tex_y > surface_h) tex_y = surface_h; return (tex_y); } int check_map(t_win *win) { int i; int j; j = 0; while (win->map[j]) { i = 0; while (win->map[j][i]) { if ((win->map[j][i]) == '0') { win->pos_y = (double)j + 0.5; win->pos_x = (double)i + 0.5; return (1); } i++; } j++; } return (0); } void put_map(char **map) { int i; i = 0; ft_putendl("MAP :"); while (map[i]) { ft_putendl(map[i]); i++; } }
23.217391
80
0.297129
8737b51f94e6b3ec6cc75b3e5e0281f7756fb29b
819
h
C
include/digipots.h
michaelansel/ns1nanosynth
961aadc0cb50816b8a3de3673aa1589da5949730
[ "Unlicense" ]
null
null
null
include/digipots.h
michaelansel/ns1nanosynth
961aadc0cb50816b8a3de3673aa1589da5949730
[ "Unlicense" ]
null
null
null
include/digipots.h
michaelansel/ns1nanosynth
961aadc0cb50816b8a3de3673aa1589da5949730
[ "Unlicense" ]
null
null
null
#include "main.h" #ifdef USE_MOZZI_TWI #include "twi_nonblock.h" #else #include "Wire.h" // i2c for digipots #endif // Main i2c address #define MCP4451_I2C_ADDR 0b0101100 // 0b01011 + A0(0) + A1(0) // 4-bit memory addresses #define MCP4451_TCON0 0x4 #define MCP4451_TCON1 0xa #define MCP4451_WIPER0 0x0 #define MCP4451_WIPER1 0x1 #define MCP4451_WIPER2 0x6 #define MCP4451_WIPER3 0x7 // 2 bit commands #define MCP4451_WRITE 0b00 #define MCP4451_INCREMENT 0b01 #define MCP4451_DECREMENT 0b10 #define MCP4451_READ 0b11 // Command byte = 4bit address + 2bit command + 2bit (MSB) of 10bit data (0x00) #define MCP4451_COMMAND(address, command, data) (address << 4 | command << 2 | data) const char digipotNames[] = {'A','B','C','D'}; void DigipotInit(); void DigipotWrite(byte pot, byte val); void DigipotTestSweep();
24.818182
84
0.748474
f502e10a01f0d4c036856b4683c20651d2b69a75
33,365
c
C
src/extlib/kxnet.c
Kray-G/kinx
b2ef0e40fb49e9497f71eaa13fe5e456522fc37d
[ "MIT" ]
241
2019-11-28T01:20:38.000Z
2022-02-04T08:12:22.000Z
src/extlib/kxnet.c
Kray-G/kinx
b2ef0e40fb49e9497f71eaa13fe5e456522fc37d
[ "MIT" ]
89
2020-01-26T02:48:15.000Z
2022-01-06T01:58:17.000Z
src/extlib/kxnet.c
Kray-G/kinx
b2ef0e40fb49e9497f71eaa13fe5e456522fc37d
[ "MIT" ]
15
2020-05-20T12:15:14.000Z
2021-09-09T23:26:41.000Z
#if defined(_WIN32) || defined(_WIN64) #include <winsock2.h> #include <ws2tcpip.h> #endif #include <dbg.h> #include <ctype.h> #define KX_DLL #include <kinx.h> #include <kxthread.h> #include <kxnet.h> KX_DECL_MEM_ALLOCATORS(); #define CURL_STATICLIB #include "libmodules/libs/libcurl/include/curl/curl.h" static size_t Net_headerCallback(void *ptr, size_t size, size_t nmemb, void *userp); static size_t Net_writeCallback(void *ptr, size_t size, size_t nmemb, void *userp); static int Net_debugCallback(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr); #define KX_NET_GET_CURLINFO(r, obj) \ kx_curl_info_t *r = NULL; \ if (obj) { \ kx_val_t *val = NULL; \ KEX_GET_PROP(val, obj, "_curl"); \ if (!val || val->type != KX_ANY_T) { \ KX_THROW_BLTIN_EXCEPTION("NetException", "Invalid Net object"); \ } \ r = (kx_curl_info_t *)(val->value.av->p); \ } \ /**/ #define KX_NET_GET_IS_RUNNING(r, obj) \ int r = 0; \ if (obj) { \ kx_val_t *val = NULL; \ KEX_GET_PROP(val, obj, "isRunning"); \ if (val && val->type == KX_INT_T) { \ r = (int)val->value.iv; \ } \ } \ /**/ #define KX_NET_GET_DEBUG_DETAIL(r, obj) \ int r = 0; \ if (obj) { \ kx_val_t *val = NULL; \ KEX_GET_PROP(val, obj, "debugDetail"); \ if (val && val->type == KX_INT_T) { \ r = (int)val->value.iv; \ } \ } \ /**/ #define KX_NET_GET_BUFFER(r, obj, name) \ kstr_t *r = 0; \ if (obj) { \ kx_val_t *val = NULL; \ KEX_GET_PROP(val, obj, name); \ if (val && val->type == KX_STR_T) { \ r = val->value.sv; \ } \ } \ /**/ #define KX_NET_GET_BIN_BUFFER(r, obj, name) \ kx_bin_t *r = 0; \ if (obj) { \ kx_val_t *val = NULL; \ KEX_GET_PROP(val, obj, name); \ if (val && val->type == KX_BIN_T) { \ r = val->value.bn; \ } \ } \ /**/ #define KX_NET_GET_BUFFER_AS_CSTR(r, obj, name) \ const char *r = 0; \ if (obj) { \ kx_val_t *val = NULL; \ KEX_GET_PROP(val, obj, name); \ if (val && val->type == KX_CSTR_T) { \ r = val->value.pv; \ } \ } \ /**/ #define KX_NET_RESET_STR_BUFFER(vname, obj, name) \ KX_NET_GET_BUFFER(vname, obj, name); \ if (!vname) { \ KX_NET_GET_BUFFER_AS_CSTR(cstr, obj, name); \ if (cstr) { \ KEX_SET_PROP_CSTR(obj, name, cstr); \ } else { \ KEX_SET_PROP_CSTR(obj, name, ""); \ } \ KX_NET_GET_BUFFER(vname, obj, name); \ } \ /**/ typedef struct kx_curl_info_ { CURLM *mh; CURL *eh; struct curl_slist *sl; char *cr; } kx_curl_info_t; static void net_initialize(void) { curl_global_init(CURL_GLOBAL_DEFAULT & ~CURL_GLOBAL_WIN32); } static void net_finalize(void) { curl_global_cleanup(); } static kx_curl_info_t *new_ci(void) { kx_curl_info_t *ci = (kx_curl_info_t *)kx_calloc(1, sizeof(kx_curl_info_t)); ci->mh = curl_multi_init(); ci->sl = NULL; ci->eh = curl_easy_init(); ci->cr = NULL; curl_multi_add_handle(ci->mh, ci->eh); return ci; } static void free_ci(void *obj) { kx_curl_info_t *ci = (kx_curl_info_t *)obj; curl_multi_remove_handle(ci->mh, ci->eh); curl_easy_cleanup(ci->eh); curl_multi_cleanup(ci->mh); if (ci->sl) { curl_slist_free_all(ci->sl); } if (ci->cr) { kx_free(ci->cr); } kx_free(ci); } /* main functions */ int Net_setupHandler(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_NET_GET_CURLINFO(ci, obj); curl_multi_remove_handle(ci->mh, ci->eh); curl_multi_add_handle(ci->mh, ci->eh); KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Net_resetHandler(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_NET_GET_CURLINFO(ci, obj); curl_easy_reset(ci->eh); curl_easy_setopt(ci->eh, CURLOPT_WRITEFUNCTION, Net_writeCallback); curl_easy_setopt(ci->eh, CURLOPT_WRITEDATA, obj); curl_easy_setopt(ci->eh, CURLOPT_DEBUGFUNCTION, Net_debugCallback); curl_easy_setopt(ci->eh, CURLOPT_DEBUGDATA, obj); KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Net_setOptionInt(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_NET_GET_CURLINFO(ci, obj); if (args != 3) { KX_THROW_BLTIN_EXCEPTION("NetException", "Needs two arguments"); } int optcode = get_arg_int(2, args, ctx); int data = get_arg_int(3, args, ctx); int r = curl_easy_setopt(ci->eh, optcode, data); if (r == CURLE_UNKNOWN_OPTION) { KX_THROW_BLTIN_EXCEPTION("NetException", "Unknown option code"); } if (r > 0) { KX_THROW_BLTIN_EXCEPTION("NetException", static_format("%s", curl_easy_strerror(r))); } if (optcode == CURLOPT_HEADER && !data) { curl_easy_setopt(ci->eh, CURLOPT_HEADERFUNCTION, Net_headerCallback); curl_easy_setopt(ci->eh, CURLOPT_HEADERDATA, obj); } KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Net_setOptionString(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_NET_GET_CURLINFO(ci, obj); if (args != 3) { KX_THROW_BLTIN_EXCEPTION("NetException", "Needs two arguments"); } int optcode = get_arg_int(2, args, ctx); const char *data = get_arg_str(3, args, ctx); if (!data) { KX_THROW_BLTIN_EXCEPTION("NetException", "Failed because no string data"); } int r; if (optcode == CURLOPT_CUSTOMREQUEST) { ci->cr = kx_strdup(data); r = curl_easy_setopt(ci->eh, CURLOPT_CUSTOMREQUEST, ci->cr); } else { r = curl_easy_setopt(ci->eh, optcode, data); } if (r == CURLE_UNKNOWN_OPTION) { KX_THROW_BLTIN_EXCEPTION("NetException", "Unknown option code"); } if (r > 0) { KX_THROW_BLTIN_EXCEPTION("NetException", static_format("%s", curl_easy_strerror(r))); } KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Net_setOptionSlist(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_NET_GET_CURLINFO(ci, obj); if (args != 2) { KX_THROW_BLTIN_EXCEPTION("NetException", "Needs an option code"); } int optcode = get_arg_int(2, args, ctx); int r = curl_easy_setopt(ci->eh, optcode, ci->sl); if (r == CURLE_UNKNOWN_OPTION) { KX_THROW_BLTIN_EXCEPTION("NetException", "Unknown option code"); } if (r > 0) { KX_THROW_BLTIN_EXCEPTION("NetException", static_format("%s", curl_easy_strerror(r))); } KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Net_appendSlist(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_NET_GET_CURLINFO(ci, obj); const char *data = get_arg_str(2, args, ctx); if (!data) { KX_THROW_BLTIN_EXCEPTION("NetException", "Failed because no string data"); } struct curl_slist *temp = curl_slist_append(ci->sl, data); if (!temp) { KX_THROW_BLTIN_EXCEPTION("NetException", "Failed to append data"); } ci->sl = temp; KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Net_wait(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_NET_GET_CURLINFO(ci, obj); int timout = get_arg_int(2, args, ctx); int numfds; CURLMcode mc = curl_multi_wait(ci->mh, NULL, 0, timout <= 0 ? 1 : timout, &numfds); if (mc > 0) { KX_THROW_BLTIN_EXCEPTION("NetException", static_format("%s", curl_multi_strerror(mc))); } KX_ADJST_STACK(); push_i(ctx->stack, numfds); return 0; } int Net_poll(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_NET_GET_CURLINFO(ci, obj); int timout = get_arg_int(2, args, ctx); int numfds; CURLMcode mc = curl_multi_poll(ci->mh, NULL, 0, timout <= 0 ? 1 : timout, &numfds); if (mc > 0) { KX_THROW_BLTIN_EXCEPTION("NetException", static_format("%s", curl_multi_strerror(mc))); } KX_ADJST_STACK(); push_i(ctx->stack, numfds); return 0; } int Net_perform(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_NET_GET_CURLINFO(ci, obj); KX_NET_GET_IS_RUNNING(still_running, obj); KX_NET_RESET_STR_BUFFER(hd, obj, "header"); KX_NET_RESET_STR_BUFFER(sv, obj, "received"); KX_NET_RESET_STR_BUFFER(sd, obj, "debugInfo"); CURLMcode mc = curl_multi_perform(ci->mh, &still_running); if (mc > 0) { KX_THROW_BLTIN_EXCEPTION("NetException", static_format("%s", curl_multi_strerror(mc))); } KEX_SET_PROP_INT(obj, "isRunning", still_running); int q = 0; CURLMsg *msg = NULL; while ((msg = curl_multi_info_read(ci->mh, &q)) != NULL) { if (msg->msg == CURLMSG_DONE) { CURLcode r = msg->data.result; if (r > 0) { KX_THROW_BLTIN_EXCEPTION("NetException", static_format("%s", curl_easy_strerror(r))); } } } KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Net_perfromEnd(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_NET_GET_CURLINFO(ci, obj); if (ci->sl) { curl_slist_free_all(ci->sl); ci->sl = NULL; curl_easy_setopt(ci->eh, CURLOPT_HTTPHEADER, NULL); } if (ci->cr) { kx_free(ci->cr); ci->cr = NULL; curl_easy_setopt(ci->eh, CURLOPT_CUSTOMREQUEST, NULL); } KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } static size_t Net_headerCallback(void *ptr, size_t size, size_t nmemb, void *userp) { kx_obj_t *obj = (kx_obj_t *)userp; size_t bufsz = size * nmemb; KX_NET_GET_BUFFER(sv, obj, "header"); KX_NET_GET_BUFFER(ct, obj, "contentType"); if (!sv) { return bufsz; } ks_append_n(sv, (char *)ptr, bufsz); const char *p = strstr(ks_string(sv), "Content-Type: "); if (p) { p += strlen("Content-Type: "); const char *e = strchr(p, ';'); if (!e) { e = strchr(p, '\r'); if (!e) { e = strchr(p, '\n'); } } if (e) { kstr_t *s = ks_new(); ks_append_n(s, (char *)p, e - p); if (!ks_equals(s, ct)) { ks_clear(ct); ks_append_n(ct, (char *)p, e - p); KX_NET_GET_BUFFER(ctt, obj, "isContentTypeText"); // If a user sets it already, there's no change here. // '*a' means a user did no mode change at the moment. if (ks_string(ctt)[1] == 'a') { ks_clear(ctt); if (strcmp(ks_string(ct), "application/json") == 0 || strncmp(ks_string(ct), "text/", 5) == 0) { ks_append(ctt, "1a"); } else { ks_append(ctt, "0a"); } } } ks_free(s); } } return bufsz; } static size_t Net_writeCallback(void *ptr, size_t size, size_t nmemb, void *userp) { kx_obj_t *obj = (kx_obj_t *)userp; size_t bufsz = size * nmemb; int is_bin; KX_NET_GET_BUFFER(ctt, obj, "isContentTypeText"); if (ks_string(ctt)[0] == '1') { is_bin = 0; } else { is_bin = 1; } if (is_bin) { KX_NET_GET_BIN_BUFFER(bin, obj, "receivedbin"); char *p = (char *)ptr; int sz = bufsz; while (sz--) { *kv_pushp(uint8_t, bin->bin) = *p++; } } else { KX_NET_GET_BUFFER(sv, obj, "received"); if (!sv) { return bufsz; } ks_append_n(sv, (char *)ptr, bufsz); } return bufsz; } static void dump_detail(const char *text, kstr_t *sd, unsigned char *ptr, size_t size, int nohex) { size_t i; size_t c; unsigned int width = 0x10; if (nohex) { width = 0x40; } ks_appendf(sd, "%s, %10.10lu bytes (0x%8.8lx)\n", text, (unsigned long)size, (unsigned long)size); for (i = 0; i<size; i += width) { ks_appendf(sd, "%4.4lx: ", (unsigned long)i); if (!nohex) { for (c = 0; c < width; c++) { if (i + c < size) ks_appendf(sd, "%02x ", ptr[i + c]); else ks_append(sd, " "); } } for (c = 0; (c < width) && (i + c < size); c++) { if (nohex && (i + c + 1 < size) && ptr[i + c] == 0x0D && ptr[i + c + 1] == 0x0A) { i += (c + 2 - width); break; } ks_appendf(sd, "%c", (ptr[i + c] >= 0x20) && (ptr[i + c] < 0x80) ? ptr[i + c] : '.'); if (nohex && (i + c + 2 < size) && ptr[i + c + 1] == 0x0D && ptr[i + c + 2] == 0x0A) { i += (c + 3 - width); break; } } ks_append(sd, "\n"); } } static void try_append_data_in_text(kstr_t *sd, char *data, size_t size) { char buf[128] = {0}; int p = 0; for (int i = 0; i < size; ++i) { if (i % 128 == 127) { ks_append(sd, buf); memset(buf, 0, 128); p = 0; } if (*data == '\r') { ++data; continue; } if (isprint(*data) || *data == '\n') { buf[p++] = *data++; } else { buf[p++] = '.'; ++data; } } if (p > 0) { ks_append(sd, buf); } } static int Net_debugCallback(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { kx_obj_t *obj = (kx_obj_t *)userptr; KX_NET_GET_DEBUG_DETAIL(debug_detail, obj); KX_NET_GET_BUFFER(sd, obj, "debugInfo"); if (!sd) { return 0; } int nohex = (debug_detail & 0x02) != 0x02; switch (type) { case CURLINFO_TEXT: ks_append(sd, "* "); ks_append_n(sd, data, size); break; case CURLINFO_HEADER_OUT: ks_append(sd, "> "); try_append_data_in_text(sd, data, size); break; case CURLINFO_DATA_OUT: if (debug_detail) { ks_append(sd, "> "); dump_detail("Send data", sd, data, size, nohex); } break; case CURLINFO_SSL_DATA_OUT: if (debug_detail) { ks_append(sd, "> "); dump_detail("Send SSL data", sd, data, size, nohex); } break; case CURLINFO_HEADER_IN: ks_append(sd, "< "); try_append_data_in_text(sd, data, size); break; case CURLINFO_DATA_IN: if (debug_detail) { ks_append(sd, "> "); dump_detail("Recv data", sd, data, size, nohex); } break; case CURLINFO_SSL_DATA_IN: if (debug_detail) { ks_append(sd, "> "); dump_detail("Recv SSL data", sd, data, size, nohex); } break; } return 0; } int Net_createCurlHandler(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_curl_info_t *ci = new_ci(); kx_any_t *info = allocate_any(ctx); info->p = ci; info->any_free = free_ci; kx_obj_t *obj = allocate_obj(ctx); KEX_SET_PROP_ANY(obj, "_curl", info); KEX_SET_PROP_INT(obj, "isRunning", 0); KEX_SET_PROP_CSTR(obj, "header", ""); KEX_SET_PROP_CSTR(obj, "contentType", ""); KEX_SET_PROP_CSTR(obj, "isContentTypeText", "0a"); KEX_SET_PROP_CSTR(obj, "received", ""); KEX_SET_PROP_BIN(obj, "receivedbin", allocate_bin(ctx)); KEX_SET_PROP_CSTR(obj, "debugInfo", ""); curl_easy_setopt(ci->eh, CURLOPT_WRITEFUNCTION, Net_writeCallback); curl_easy_setopt(ci->eh, CURLOPT_WRITEDATA, obj); curl_easy_setopt(ci->eh, CURLOPT_DEBUGFUNCTION, Net_debugCallback); curl_easy_setopt(ci->eh, CURLOPT_DEBUGDATA, obj); KEX_SET_METHOD("setupHandler", obj, Net_setupHandler); KEX_SET_METHOD("resetHandler", obj, Net_resetHandler); KEX_SET_METHOD("setOptionInt", obj, Net_setOptionInt); KEX_SET_METHOD("setOptionString", obj, Net_setOptionString); KEX_SET_METHOD("setOptionSlist", obj, Net_setOptionSlist); KEX_SET_METHOD("appendSlist", obj, Net_appendSlist); KEX_SET_METHOD("wait", obj, Net_wait); KEX_SET_METHOD("poll", obj, Net_poll); KEX_SET_METHOD("perform", obj, Net_perform); KEX_SET_METHOD("perfromEnd", obj, Net_perfromEnd); KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } /* Socket */ #define KX_NET_BACKLOG 5 #define KX_NET_R 0 #define KX_NET_W 1 #define KX_NET_RW 2 #define KX_NET_READABLE(x) (((x) & 0x01) == 0x01) #define KX_NET_WRITABLE(x) (((x) & 0x02) == 0x02) #define KX_GET_NETINFO(r, obj) KX_GET_RAW(kx_netinfo_t, "_socket", r, obj, "SocketException", "Invalid Socket object") typedef struct kx_netinfo_ { int soc; struct addrinfo *ai; } kx_netinfo_t; static int select_socket(kx_netinfo_t *p, int direction, int msec) { int r = -1; switch (direction) { case KX_NET_R: { fd_set fdr; FD_ZERO(&fdr); FD_SET(p->soc, &fdr); struct timeval tv = {0}; tv.tv_sec = (unsigned int)msec / 1000; tv.tv_usec = (unsigned int)(msec % 1000) * 1000; r = select(p->soc + 1, &fdr, NULL, NULL, &tv); if (r > 0) { if (FD_ISSET(p->soc, &fdr)) { r = 0x01; } } break; } case KX_NET_W: { fd_set fdw; FD_ZERO(&fdw); FD_SET(p->soc, &fdw); struct timeval tv = {0}; tv.tv_sec = (unsigned int)msec / 1000; tv.tv_usec = (unsigned int)(msec % 1000) * 1000; r = select(p->soc + 1, NULL, &fdw, NULL, &tv); if (r > 0) { if (FD_ISSET(p->soc, &fdw)) { r = 0x02; } } break; } case KX_NET_RW: { fd_set fdr; fd_set fdw; FD_ZERO(&fdr); FD_SET(p->soc, &fdr); FD_ZERO(&fdw); FD_SET(p->soc, &fdw); struct timeval tv = {0}; tv.tv_sec = (unsigned int)msec / 1000; tv.tv_usec = (unsigned int)(msec % 1000) * 1000; r = select(p->soc + 1, &fdr, &fdw, NULL, &tv); if (r > 0) { r = 0x00; if (FD_ISSET(p->soc, &fdr)) { r = 0x01; } if (FD_ISSET(p->soc, &fdw)) { r |= 0x02; } } break; } default: break; } return r; } static void free_netinfo(void *obj) { kx_netinfo_t *p = (kx_netinfo_t *)obj; if (p->ai) { freeaddrinfo(p->ai); } if (p->soc >= 0) { closesocket(p->soc); } kx_free(p); } int Socket_bind(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_GET_NETINFO(p, obj) if (!p->ai || p->soc < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Invalid Socket object"); } if (bind(p->soc, p->ai->ai_addr, p->ai->ai_addrlen) < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Socket_listen(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_GET_NETINFO(p, obj) if (!p->ai || p->soc < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Invalid Socket object"); } if (listen(p->soc, KX_NET_BACKLOG) < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } #if defined(_WIN32) || defined(_WIN64) unsigned long block = 1; if (ioctlsocket(p->soc, FIONBIO, &block) == SOCKET_ERROR) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Failed to ioctlsocket"); } #else if (fcntl(p->soc, F_SETFL, O_NONBLOCK) < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } #endif freeaddrinfo(p->ai); p->ai = NULL; KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Socket_close(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_GET_NETINFO(p, obj) if (p->soc >= 0) { closesocket(p->soc); p->soc = -1; } KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Socket_select(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_GET_NETINFO(p, obj) int d = get_arg_int(2, args, ctx); int m = get_arg_int(3, args, ctx); int r = select_socket(p, d, m); if (r < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } KX_ADJST_STACK(); push_i(ctx->stack, r); return 0; } int Socket_recv(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_GET_NETINFO(p, obj) kstr_t *sv = allocate_str(ctx); char buf[2048] = {0}; int n = recv(p->soc, buf, 2047, 0); if (n > 0) { ks_append(sv, buf); } KX_ADJST_STACK(); push_sv(ctx->stack, sv); return 0; } int Socket_send(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_GET_NETINFO(p, obj) if (p->soc < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Invalid Socket object"); } const char *sp = get_arg_str(2, args, ctx); if (!sp) { KX_THROW_BLTIN_EXCEPTION("SocketException", "No message to send"); } size_t len = strlen(sp); while (len > 0) { int res = send(p->soc, sp, len, 0); if (res < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { KX_ADJST_STACK(); push_i(ctx->stack, res); return 0; } else { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } } len -= res; sp += res; } KX_ADJST_STACK(); push_i(ctx->stack, 0); return 0; } int Socket_recvfrom(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_GET_NETINFO(p, obj) if (p->soc < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Invalid Socket object"); } struct sockaddr_storage sa = {0}; char buf[2048] = {0}; int len = sizeof(sa); int rc = recvfrom(p->soc, buf, 2047, 0, (struct sockaddr*)&sa, &len); if (rc < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Failed to recvfrom"); } char hoststr[NI_MAXHOST] = {0}; char portstr[NI_MAXSERV] = {0}; rc = getnameinfo((struct sockaddr *)&sa, len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); if (rc < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Failed to get a client address and port"); } kx_obj_t *cobj = allocate_obj(ctx); KEX_SET_PROP_CSTR(cobj, "message", buf); KEX_SET_PROP_CSTR(cobj, "address", hoststr); KEX_SET_PROP_CSTR(cobj, "port", portstr); KX_ADJST_STACK(); push_obj(ctx->stack, cobj); return 0; } int Socket_sendto(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_GET_NETINFO(p, obj) if (p->soc < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Invalid Socket object"); } const char *sp = get_arg_str(2, args, ctx); if (!sp) { KX_THROW_BLTIN_EXCEPTION("SocketException", "No message to send"); } size_t len = strlen(sp); while (len > 0) { int res = sendto(p->soc, sp, len, 0, p->ai->ai_addr, p->ai->ai_addrlen); if (res < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { KX_ADJST_STACK(); push_i(ctx->stack, res); return 0; } else { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } } len -= res; sp += res; } KX_ADJST_STACK(); push_i(ctx->stack, 0); return 0; } int Socket_accept(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { kx_obj_t *obj = get_arg_obj(1, args, ctx); KX_GET_NETINFO(p, obj) if (p->soc < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Invalid Socket object"); } struct sockaddr_storage sa = {0}; socklen_t len = sizeof(sa); int csoc = accept(p->soc, (struct sockaddr*)&sa, &len); if (csoc < 0) { #if defined(_WIN32) || defined(_WIN64) int e = WSAGetLastError(); int err = e == WSAEWOULDBLOCK ? EAGAIN : e; #else int err = errno; #endif kx_obj_t *cobj = allocate_obj(ctx); KEX_SET_PROP_INT(cobj, "value", csoc); KEX_SET_PROP_INT(cobj, "errno", (err == EWOULDBLOCK ? EAGAIN : err)); KX_ADJST_STACK(); push_obj(ctx->stack, cobj); return 0; } #if defined(_WIN32) || defined(_WIN64) unsigned long block = 1; if (ioctlsocket(csoc, FIONBIO, &block) == SOCKET_ERROR) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Failed to ioctlsocket"); } #else if (fcntl(csoc, F_SETFL, O_NONBLOCK) < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } #endif kx_netinfo_t *cp = kx_calloc(1, sizeof(kx_netinfo_t)); cp->soc = csoc; kx_any_t *info = allocate_any(ctx); info->p = cp; info->any_free = free_netinfo; char hoststr[NI_MAXHOST] = {0}; char portstr[NI_MAXSERV] = {0}; int rc = getnameinfo((struct sockaddr *)&sa, len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); if (rc < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Failed to get a client address and port"); } kx_obj_t *cobj = allocate_obj(ctx); KEX_SET_PROP_ANY(cobj, "_socket", info); KEX_SET_PROP_CSTR(cobj, "address", hoststr); KEX_SET_PROP_CSTR(cobj, "port", portstr); KEX_SET_METHOD("close", cobj, Socket_close); KEX_SET_METHOD("send", cobj, Socket_send); KEX_SET_METHOD("recv", cobj, Socket_recv); KEX_SET_METHOD("select", cobj, Socket_select); KX_ADJST_STACK(); push_obj(ctx->stack, cobj); return 0; } int Net_createTcpServerSocket(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { const char *service = get_arg_str(1, args, ctx); struct addrinfo hints = {0}; struct addrinfo *res = NULL; hints.ai_family = AF_INET6; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE|AI_V4MAPPED; int err = getaddrinfo(NULL, service, &hints, &res); if (err != 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_gai_strerror(err)); } int soc = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (soc < 0) { freeaddrinfo(res); KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } int on = 1; if (setsockopt(soc, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof(on)) < 0) { freeaddrinfo(res); KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } on = 0; if (setsockopt(soc, IPPROTO_IPV6, IPV6_V6ONLY, (const void *)&on, sizeof(on)) < 0) { freeaddrinfo(res); KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } kx_netinfo_t *p = kx_calloc(1, sizeof(kx_netinfo_t)); p->soc = soc; p->ai = res; kx_any_t *info = allocate_any(ctx); info->p = p; info->any_free = free_netinfo; kx_obj_t *obj = allocate_obj(ctx); KEX_SET_PROP_ANY(obj, "_socket", info); KEX_SET_METHOD("bind", obj, Socket_bind); KEX_SET_METHOD("listen", obj, Socket_listen); KEX_SET_METHOD("accept", obj, Socket_accept); KEX_SET_METHOD("close", obj, Socket_close); KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Net_createTcpClientSocket(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { const char *host = get_arg_str(1, args, ctx); const char *service = get_arg_str(2, args, ctx); int timeout = get_arg_int(3, args, ctx); struct addrinfo hints = {0}; struct addrinfo *res = NULL; struct addrinfo *ai; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; int err = getaddrinfo(host, service, &hints, &res); if (err != 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_gai_strerror(err)); } int soc; for (ai = res; ai; ai = ai->ai_next) { soc = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (soc < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_gai_strerror(err)); } if (connect_with_timeout(soc, ai->ai_addr, ai->ai_addrlen, timeout) < 0) { closesocket(soc); soc = -1; continue; } break; } if (soc < 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", "Connection failed"); } kx_netinfo_t *p = kx_calloc(1, sizeof(kx_netinfo_t)); p->soc = soc; p->ai = ai; kx_any_t *info = allocate_any(ctx); info->p = p; info->any_free = free_netinfo; kx_obj_t *cobj = allocate_obj(ctx); KEX_SET_PROP_ANY(cobj, "_socket", info); KEX_SET_METHOD("bind", cobj, Socket_bind); KEX_SET_METHOD("close", cobj, Socket_close); KEX_SET_METHOD("send", cobj, Socket_send); KEX_SET_METHOD("recv", cobj, Socket_recv); KEX_SET_METHOD("select", cobj, Socket_select); KX_ADJST_STACK(); push_obj(ctx->stack, cobj); return 0; } int Net_createUdpServerSocket(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { const char *service = get_arg_str(1, args, ctx); struct addrinfo hints = {0}; struct addrinfo *res = NULL; hints.ai_family = AF_INET6; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = AI_PASSIVE|AI_V4MAPPED; int err = getaddrinfo(NULL, service, &hints, &res); if (err != 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_gai_strerror(err)); } int soc = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (soc < 0) { freeaddrinfo(res); KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } int on = 1; if (setsockopt(soc, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof(on)) < 0) { freeaddrinfo(res); KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } on = 0; if (setsockopt(soc, IPPROTO_IPV6, IPV6_V6ONLY, (const void *)&on, sizeof(on)) < 0) { freeaddrinfo(res); KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } kx_netinfo_t *p = kx_calloc(1, sizeof(kx_netinfo_t)); p->soc = soc; p->ai = res; kx_any_t *info = allocate_any(ctx); info->p = p; info->any_free = free_netinfo; kx_obj_t *obj = allocate_obj(ctx); KEX_SET_PROP_ANY(obj, "_socket", info); KEX_SET_METHOD("bind", obj, Socket_bind); KEX_SET_METHOD("close", obj, Socket_close); KEX_SET_METHOD("sendto", obj, Socket_sendto); KEX_SET_METHOD("recvfrom", obj, Socket_recvfrom); KEX_SET_METHOD("select", obj, Socket_select); KX_ADJST_STACK(); push_obj(ctx->stack, obj); return 0; } int Net_createUdpClientSocket(int args, kx_frm_t *frmv, kx_frm_t *lexv, kx_context_t *ctx) { const char *host = get_arg_str(1, args, ctx); const char *service = get_arg_str(2, args, ctx); int timeout = get_arg_int(3, args, ctx); struct addrinfo hints = {0}; struct addrinfo *res = NULL; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; int err = getaddrinfo(host, service, &hints, &res); if (err != 0) { KX_THROW_BLTIN_EXCEPTION("SocketException", kx_gai_strerror(err)); } int soc = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (soc < 0) { freeaddrinfo(res); KX_THROW_BLTIN_EXCEPTION("SocketException", kx_strerror(errno)); } kx_netinfo_t *p = kx_calloc(1, sizeof(kx_netinfo_t)); p->soc = soc; p->ai = res; kx_any_t *info = allocate_any(ctx); info->p = p; info->any_free = free_netinfo; kx_obj_t *cobj = allocate_obj(ctx); KEX_SET_PROP_ANY(cobj, "_socket", info); KEX_SET_METHOD("bind", cobj, Socket_bind); KEX_SET_METHOD("close", cobj, Socket_close); KEX_SET_METHOD("sendto", cobj, Socket_sendto); KEX_SET_METHOD("recvfrom", cobj, Socket_recvfrom); KEX_SET_METHOD("select", cobj, Socket_select); KX_ADJST_STACK(); push_obj(ctx->stack, cobj); return 0; } static kx_bltin_def_t kx_bltin_info[] = { { "createCurlHandler", Net_createCurlHandler }, { "createTcpServerSocket", Net_createTcpServerSocket }, { "createTcpClientSocket", Net_createTcpClientSocket }, { "createUdpServerSocket", Net_createUdpServerSocket }, { "createUdpClientSocket", Net_createUdpClientSocket }, }; KX_DLL_DECL_FNCTIONS(kx_bltin_info, net_initialize, net_finalize);
29.396476
139
0.596254
0b7803b6194ec44bf30febec9acd05e3662e5b7e
1,254
h
C
usr/libexec/gamed/GKFriendPlayerInternal.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
4
2019-08-27T18:03:47.000Z
2021-09-18T06:29:00.000Z
usr/libexec/gamed/GKFriendPlayerInternal.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
null
null
null
usr/libexec/gamed/GKFriendPlayerInternal.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
null
null
null
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Jun 10 2020 10:03:13). // // Copyright (C) 1997-2019 Steve Nygard. // #import "GKFamiliarPlayerInternal.h" @class GKGameInternal, NSDate, NSString; @interface GKFriendPlayerInternal : GKFamiliarPlayerInternal { NSString *_status; // 112 = 0x70 NSDate *_lastPlayedDate; // 120 = 0x78 GKGameInternal *_lastPlayedGame; // 128 = 0x80 } + (id)secureCodedPropertyKeys; // IMP=0x0000000100105e2c + (_Bool)supportsSecureCoding; // IMP=0x0000000100105da0 + (int)familiarity; // IMP=0x0000000100118ed4 + (id)propertiesToFetch; // IMP=0x0000000100118d84 - (void)setLastPlayedGame:(id)arg1; // IMP=0x0000000100106018 - (id)lastPlayedGame; // IMP=0x0000000100106008 - (void)setLastPlayedDate:(id)arg1; // IMP=0x0000000100105ffc - (id)lastPlayedDate; // IMP=0x0000000100105fec - (void)setStatus:(id)arg1; // IMP=0x0000000100105fe0 - (id)status; // IMP=0x0000000100105fd0 - (int)defaultFamiliarity; // IMP=0x0000000100105fc8 - (_Bool)isFriend; // IMP=0x0000000100105fc0 - (void)dealloc; // IMP=0x0000000100105da8 - (void)updateWithProperties:(id)arg1; // IMP=0x0000000100118edc - (void)updateWithCacheObject:(id)arg1; // IMP=0x0000000100118cf8 @end
34.833333
120
0.750399
3cc5a4a1bb2d2400b5bd0de09b4c6dd510317656
872
h
C
include/function/variable_instruction.h
giovgiac/cassio
b673c8fe082609057904befce9a099fa64077986
[ "Apache-2.0" ]
null
null
null
include/function/variable_instruction.h
giovgiac/cassio
b673c8fe082609057904befce9a099fa64077986
[ "Apache-2.0" ]
null
null
null
include/function/variable_instruction.h
giovgiac/cassio
b673c8fe082609057904befce9a099fa64077986
[ "Apache-2.0" ]
null
null
null
/** * @file variable_instruction.h * @brief * * @copyright Copyright (c) 2018 All Rights Reserved. * */ #ifndef FUNCTION_VARIABLE_INSTRUCTION_H_ #define FUNCTION_VARIABLE_INSTRUCTION_H_ #include <core/child.h> #include <expressions/expression.h> #include <function/instruction.h> namespace cassio { /** * @enum VariableInstructionType * @brief * * ... * */ enum class VariableInstructionType { ASSIGNMENT, FUNCTION_CALL }; /** * @class VariableInstruction * @brief * * ... * */ class VariableInstruction : public Instruction { public: static std::unique_ptr<Instruction> Construct(std::list<Token> &tokens); std::string Generate() override; void Semanticate() override; private: VariableInstructionType type_; std::unique_ptr<Child> variable_; std::unique_ptr<Expression> value_; }; } #endif // FUNCTION_VARIABLE_INSTRUCTION_H_
16.769231
74
0.722477
a71732aed016d24122a76343a994cf5c078372b7
343
h
C
source/Utils/Timer.h
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
21
2020-12-08T20:06:01.000Z
2022-02-13T22:52:02.000Z
source/Utils/Timer.h
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
9
2020-12-20T03:54:55.000Z
2022-03-31T19:30:04.000Z
source/Utils/Timer.h
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
5
2021-04-25T18:47:17.000Z
2022-01-23T02:37:30.000Z
#if !defined(TIME_H) #define TIME_H #include "../Utils/Utils.h" class CTimer { public: CTimer() {} virtual ~CTimer() {} void StartMeasuringTime(); double ElapsedTime(); #if defined(_PLATFORM_WIN_) || defined(_PLATFORM_LINUX_) long int m_tStartTime; #else time_t m_t0; #endif }; #endif // !defined(TIME_H)
15.590909
57
0.64723
717ba0b658288662d52185e9f5337e07ce68837a
397
h
C
Cheetah_mPaaSSDK/Frameworks/mPaas.framework/Headers/mPaas.h
hyissogood/Cheetah_mPaaSSDK
30f6c22fa051ba702028b5bbc814baf957b53a26
[ "MIT" ]
232
2019-08-16T03:07:29.000Z
2020-11-18T06:10:19.000Z
Cheetah_mPaaSSDK/Frameworks/mPaas.framework/Headers/mPaas.h
hyissogood/Cheetah_mPaaSSDK
30f6c22fa051ba702028b5bbc814baf957b53a26
[ "MIT" ]
42
2019-08-20T11:44:51.000Z
2020-11-06T00:37:15.000Z
mpaas_nebula_demo/mpaas_nebula_demo_ios/MPaaS/Frameworks/mPaas.framework/Headers/mPaas.h
alipay/mpaas-demo
3efc4e383913a11d1bf231f63bb7be0c0decccdf
[ "Apache-2.0" ]
41
2019-08-16T07:30:31.000Z
2020-11-13T01:56:03.000Z
// // mPaas.h // mPaas // // Created by shenmo on 10/23/15. // Copyright © 2015 Alibaba. All rights reserved. // #import <UIKit/UIKit.h> #import "MPaaSInterface.h" #import "APMPaaS.h" #import "MobileFoundation.h" #import "APMobileFoundation.h" #import "MPJSONKit.h" #import "DTDeviceInfo.h" #import "MPUnification.h" #import "MPCryptKit.h" #import "MPZipKit.h" #import "MPThreadManager.h"
17.26087
50
0.70529
292a35f61fdcb64afd9837c9319a47ad324e6354
2,104
h
C
src/objective-c/RxLibrary/GRXWriter+Immediate.h
txl0591/grpc
8b732dc466fb8a567c1bca9dbb84554d29087395
[ "Apache-2.0" ]
117
2017-10-02T21:34:35.000Z
2022-03-02T01:49:03.000Z
src/objective-c/RxLibrary/GRXWriter+Immediate.h
txl0591/grpc
8b732dc466fb8a567c1bca9dbb84554d29087395
[ "Apache-2.0" ]
22
2016-10-15T06:34:17.000Z
2018-04-10T14:16:13.000Z
Pods/gRPC-RxLibrary/src/objective-c/RxLibrary/GRXWriter+Immediate.h
touyou/GirlsHackShinokiChildren
4e48e9656198ce29c57415faf56b4999139b8d67
[ "MIT" ]
54
2016-10-07T12:13:53.000Z
2021-12-23T11:17:33.000Z
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #import "GRXWriter.h" @interface GRXWriter (Immediate) /** * Returns a writer that pulls values from the passed NSEnumerator instance and pushes them to * its writeable. The NSEnumerator is released when it finishes. */ + (instancetype)writerWithEnumerator:(NSEnumerator *)enumerator; /** * Returns a writer that pushes to its writeable the successive values returned by the passed * block. When the block first returns nil, it is released. */ + (instancetype)writerWithValueSupplier:(id (^)())block; /** * Returns a writer that iterates over the values of the passed container and pushes them to * its writeable. The container is released when the iteration is over. * * Note that the usual speed gain of NSFastEnumeration over NSEnumerator results from not having to * call one method per element. Because GRXWriteable instances accept values one by one, that speed * gain doesn't happen here. */ + (instancetype)writerWithContainer:(id<NSFastEnumeration>)container; /** * Returns a writer that sends the passed value to its writeable and then finishes (releasing the * value). */ + (instancetype)writerWithValue:(id)value; /** * Returns a writer that, as part of its start method, sends the passed error to the writeable * (then releasing the error). */ + (instancetype)writerWithError:(NSError *)error; /** * Returns a writer that, as part of its start method, finishes immediately without sending any * values to its writeable. */ + (instancetype)emptyWriter; @end
32.875
99
0.746198
5d9384a87eb703b431837f35998a91c80b43301c
9,655
h
C
copasi/model/CProcessQueue.h
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/model/CProcessQueue.h
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/model/CProcessQueue.h
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
// Copyright (C) 2010 - 2014 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #ifndef COPASI_CProcessQueue #define COPASI_CProcessQueue #include <map> #include <set> #include "copasi/utilities/CVector.h" #include "copasi/model/CEvent.h" class CExpression; class CMathModel; class CMathEvent; class CProcessQueue { private: class CKey { friend std::ostream &operator<<(std::ostream &os, const CProcessQueue & o); // Operations public: /** * Default constructor */ CKey(); /** * Copy constructor * @param const CKey & src */ CKey(const CKey & src); /** * Specific constructor * @param const C_FLOAT64 & executionTime * @param const bool & equality * @param const size_t & cascadingLevel */ CKey(const C_FLOAT64 & executionTime, const bool & equality, const size_t & cascadingLevel); /** * Destructor */ ~CKey(); /** * A less than sort operator for sorting the entries in the queue * @param const CKey & rhs * @return bool lessThan */ bool operator < (const CKey & rhs) const; /** * Retrieve the execution time. * @return const C_FLOAT64 & executionTime */ inline const C_FLOAT64 & getExecutionTime() const {return mExecutionTime;} friend std::ostream &operator<<(std::ostream &os, const CKey & o); // Attributes private: /** * The time the entry is scheduled to be executed. */ C_FLOAT64 mExecutionTime; /** * Cascading level */ size_t mCascadingLevel; /** * A Boolean value indication whether we have equality or inequality. * Equalities have to be handled prior to inequalities */ bool mEquality; }; friend std::ostream &operator<<(std::ostream &os, const CKey & o); class CAction { public: enum Type { Calculation = 0, Assignment, Callback }; // Operations private: /** * Default constructor (hidden) */ CAction(); public: /** * Copy constructor * @param const CAction & src */ CAction(const CAction & src); /** * Specific constructor * @param CMathEvent * pEvent * @param CProcessQueue * pProcessQueue */ CAction(CMathEvent * pEvent, CProcessQueue * pProcessQueue); /** * Specific constructor * @param const CVector< C_FLOAT64 > & values * @param CMathEvent * pEvent * @param CProcessQueue * pProcessQueue */ CAction(const CVector< C_FLOAT64 > & values, CMathEvent * pEvent, CProcessQueue * pProcessQueue); /** * Destructor (hidden) */ ~CAction(); /** * Process the action * @return bool stateChanged */ bool process(); /** * Retrieve the event id * @return CMathEvent * pEvent */ inline CMathEvent * getEvent() const {return mpEvent;} /** * Retrieve the type of action * @return const Type & type */ const Type & getType() const; friend std::ostream &operator<<(std::ostream &os, const CAction & o); // Attributes public: /** * The type of the actions */ Type mType; /** * The new value if the entry is an assignment. */ CVector< C_FLOAT64 > mValues; /** * The event associated with this action */ CMathEvent * mpEvent; /** * A pointer to the process queue to which a subsequent assignment must be added if * the entry is a calculation. */ CProcessQueue * mpProcessQueue; }; friend std::ostream &operator<<(std::ostream &os, const CAction & o); // Type definitions public: typedef std::multimap< CKey, CAction >::iterator iterator; typedef std::pair < std::multimap< CKey, CAction >::iterator, std::multimap< CKey, CAction >::iterator > range; typedef iterator(*resolveSimultaneousAssignments)(const std::multimap< CKey, CAction > & /* assignments */, const C_FLOAT64 & /* time */, const bool & /* equality */, const size_t & /* cascadingLevel */); /** * This is the type for an event call back function */ typedef void (*EventCallBack)(void*, CEvent::Type type); // Operations public: /** * Default constructor */ CProcessQueue(); /** * Copy constructor */ CProcessQueue(const CProcessQueue & src); /** * Destructor */ ~CProcessQueue(); /** * Add an assignment to the process queue. * @param const C_FLOAT64 & executionTime * @param const bool & equality * @param const CVector< C_FLOAT64 > & values * @param CMathEvent * pEvent * @return bool success */ bool addAssignment(const C_FLOAT64 & executionTime, const bool & equality, const CVector< C_FLOAT64 > & values, CMathEvent * pEvent); /** * Add a calculation to the process queue. * @param const C_FLOAT64 & executionTime * @param const bool & equality * @param CMathEvent * pEvent * @return bool success */ bool addCalculation(const C_FLOAT64 & executionTime, const bool & equality, CMathEvent * pEvent); /** * Clear the process queue. * @param CMathModel * pMathModel */ void initialize(CMathModel * pMathModel); /** * Process the queue. * @param const C_FLOAT64 & time * @param const bool & priorToOutput * @param resolveSimultaneousAssignments pResolveSimultaneousAssignments * @return bool stateChanged */ bool process(const C_FLOAT64 & time, const bool & priorToOutput, resolveSimultaneousAssignments pResolveSimultaneousAssignments); /** * Retrieve the next execution time scheduled in the process queue * @return const C_FLOAT64 & processQueueExecutionTime */ const C_FLOAT64 & getProcessQueueExecutionTime() const; /** * Set whether to continue on simultaneous events * @param const bool & continueSimultaneousEvents */ void setContinueSimultaneousEvents(const bool & continueSimultaneousEvents); /** * Retrieve whether to continue on simultaneous events. * @return const bool & continueSimultaneousEvents */ const bool & getContinueSimultaneousEvents() const; /** * Sets an event call back. The call back function must be a static function * that receives a "this" pointer as first argument. * The function is called when the actual assignment takes place, * or when the assignment would take place in case the event * has no assignment. * The function is called with an integer argument: * 1: An assignment has happened * 2: A cut plane was crossed */ void setEventCallBack(void* pTask, EventCallBack ecb); /** * This prints debugging info to stdout */ void printDebug() const {std::cout << *this; }; friend std::ostream &operator<<(std::ostream &os, const CProcessQueue & o); private: /** * Destroy a unique eventId * @@param const size_t & eventId; */ void destroyEventId(const size_t & eventId); /** * Retrieve the currently pending actions * @return CProcessQueue::iterator itAction */ iterator getAction(); /** * Execute the actions * @param CProcessQueue::iterator itAction * @return bool stateChanged */ bool executeAction(CProcessQueue::iterator itAction); /** * Check whether the executions of assignment lead to newly found roots * @return bool rootsFound */ bool rootsFound(); /** * Check whether a range is not empty * @param const range & range * bool notEmpty */ static bool notEmpty(const range & range); // Attributes private: /** * An ordered list of calculations in the queue. */ std::multimap< CKey, CAction > mActions; /** * The limit of execution steps allowed for call to process */ size_t mExecutionLimit; /** * A counter of the execution steps for the current process */ size_t mExecutionCounter; /** * The current time */ C_FLOAT64 mTime; /** * Indicate whether we processing equality or inequality */ bool mEquality; /** * The cascading level of events */ size_t mCascadingLevel; /** * A flag indicating that simultaneous assignments have been found. */ bool mSimultaneousAssignmentsFound; /** * A set of currently active event ids */ std::set< size_t > mEventIdSet; /** * A pointer to the math model the process queue belongs to. */ CMathModel * mpMathModel; /** * */ CVector< C_INT > mRootsFound; /** * */ CVector< C_FLOAT64 > mRootValues1; /** * */ CVector< C_FLOAT64 > mRootValues2; /** * */ CVector< C_FLOAT64 > * mpRootValuesBefore; /** * */ CVector< C_FLOAT64 > * mpRootValuesAfter; /** * A pointer to a call back method for resolving simultaneous event assignments */ resolveSimultaneousAssignments mpResolveSimultaneousAssignments; /** * A flag indicating to continue when simultaneous events are encountered. */ bool mContinueSimultaneousEvents; /** * the object to which the call back function belongs */ void * mpCallbackTask; /** * the pointer to the call back function */ EventCallBack mpEventCallBack; }; #endif // COPASI_CProcessQueue
22.664319
113
0.636044
5dc85dce719220f47a7e8c4768cb34a6247912ca
10,560
h
C
okl4_kernel/okl4_2.1.1-patch.9/libs/b_plus_tree/include/b_plus_tree.h
CyberQueenMara/baseband-research
e1605537e10c37e161fff1a3416b908c9894f204
[ "MIT" ]
77
2018-12-31T22:12:09.000Z
2021-12-31T22:56:13.000Z
okl4_kernel/okl4_2.1.1-patch.9/libs/b_plus_tree/include/b_plus_tree.h
CyberQueenMara/baseband-research
e1605537e10c37e161fff1a3416b908c9894f204
[ "MIT" ]
null
null
null
okl4_kernel/okl4_2.1.1-patch.9/libs/b_plus_tree/include/b_plus_tree.h
CyberQueenMara/baseband-research
e1605537e10c37e161fff1a3416b908c9894f204
[ "MIT" ]
24
2019-01-20T15:51:52.000Z
2021-12-25T18:29:13.000Z
/* * Copyright (c) 1995-2004, University of New South Wales * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (c) 2007 Open Kernel Labs, Inc. (Copyright Holder). * All rights reserved. * * 1. Redistribution and use of OKL4 (Software) in source and binary * forms, with or without modification, are permitted provided that the * following conditions are met: * * (a) Redistributions of source code must retain this clause 1 * (including paragraphs (a), (b) and (c)), clause 2 and clause 3 * (Licence Terms) and the above copyright notice. * * (b) Redistributions in binary form must reproduce the above * copyright notice and the Licence Terms in the documentation and/or * other materials provided with the distribution. * * (c) Redistributions in any form must be accompanied by information on * how to obtain complete source code for: * (i) the Software; and * (ii) all accompanying software that uses (or is intended to * use) the Software whether directly or indirectly. Such source * code must: * (iii) either be included in the distribution or be available * for no more than the cost of distribution plus a nominal fee; * and * (iv) be licensed by each relevant holder of copyright under * either the Licence Terms (with an appropriate copyright notice) * or the terms of a licence which is approved by the Open Source * Initative. For an executable file, "complete source code" * means the source code for all modules it contains and includes * associated build and other files reasonably required to produce * the executable. * * 2. THIS SOFTWARE IS PROVIDED ``AS IS'' AND, TO THE EXTENT PERMITTED BY * LAW, ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED. WHERE ANY WARRANTY IS * IMPLIED AND IS PREVENTED BY LAW FROM BEING DISCLAIMED THEN TO THE * EXTENT PERMISSIBLE BY LAW: (A) THE WARRANTY IS READ DOWN IN FAVOUR OF * THE COPYRIGHT HOLDER (AND, IN THE CASE OF A PARTICIPANT, THAT * PARTICIPANT) AND (B) ANY LIMITATIONS PERMITTED BY LAW (INCLUDING AS TO * THE EXTENT OF THE WARRANTY AND THE REMEDIES AVAILABLE IN THE EVENT OF * BREACH) ARE DEEMED PART OF THIS LICENCE IN A FORM MOST FAVOURABLE TO * THE COPYRIGHT HOLDER (AND, IN THE CASE OF A PARTICIPANT, THAT * PARTICIPANT). IN THE LICENCE TERMS, "PARTICIPANT" INCLUDES EVERY * PERSON WHO HAS CONTRIBUTED TO THE SOFTWARE OR WHO HAS BEEN INVOLVED IN * THE DISTRIBUTION OR DISSEMINATION OF THE SOFTWARE. * * 3. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR ANY OTHER PARTICIPANT 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. */ /* * Description: B+ tree include file. * * Authors: Daniel Potts <danielp@cse.unsw.edu.au> - ported to kenge */ /* * B+ tree implementation. * * Written by Ruth Kurniawati, Oct/Nov 1995. Adapted by Jerry Vochteloo in * April 1996. Adapted by Gernot Heiser <G.Heiser@unsw.edu.au> on 97-02-08: - * handle intervals in B-tree code - completely separate object handling */ /* * This implementation does not care what the objects are, these are completely * under user control (who might, for example, maintain a secondary access * structure such as a linked list). Hence all allocation/deallocation of * objects is left to the user. * * The user is also given full control over storage allocation for actual B-tree * nodes. This is done by using the alloc_page, free_page functions, and a "page * pool" pointer as part of the B-tree datastructure. * * The B-tree can operate as usual, storing objects identified by a single key * value. Alternatively, it can be set up for storing non-overlapping interval * objects, i.e. each object occupying an interval of key space. * * In order to use this B+ tree implementation, you'll need to (in * btree_conf.h): - define a type "BTkey", which is the type of the keys to the * B+ tree. - define "BT_ORDER" as the maximum spread of the B-tree. Must be * odd. - Define the following macros for dealing with keys: BTGetObjKey(object) * returns the key to object BTKeyLT(key1, key2) key1 < key2 BTKeyGT(key1, key2) * key1 > key2 BTKeyEQ(key1, key2) key1 == key2 If you want the B+ tree to store * objects taking up an interval of key space (rather than just a single value), * define BTGetObjLim(object) returns upper limit key value (i.e. the next value * available as key for another object) BTObjMatch(obj, key) key IN obj (if the * key lies within the object, i.e. obj->key <= key < obj->limit) * BTOverlaps(obj1, obj2) objects overlap. For normal B+-trees, leave those * undefined. - define a type "GBTObject", which should be a pointer to a struct * containing the data to be indexed. It is the pointer values which will be * stored in the B+ tree. - provide a (possibly empty) function void * BTPrintObj(GBTObject const obj); which will be used for printing your objects * by "BTPrint". - defined a type "PagePool". Pointers to this type are contained * in B+ tree references. This ensures that pages are allocated from the correct * pool, in case several B+ trees are used - define functions struct sBTPage * *alloc_page(PagePool *pool); void free_page(PagePool *pool, struct sBTPage * *page); for (de)allocating pages for the B+ tree. */ #ifndef _BTREE_H_ #define _BTREE_H_ struct sBTPage *EXPORT(AllocPage) (PagePool *pool); void EXPORT(FreePage) (PagePool *pool, struct sBTPage * page); #define BT_MAXKEY (BT_ORDER - 1) #define BT_MINKEY (BT_MAXKEY >> 1) #if !defined BTObjMatch && !defined BTGetObjLim && !defined BTOverlaps # define BTObjMatch(obj,key) (BTKeyEQ(BTGetObjKey((obj)),key)) # define BTGetObjLim(obj) BTGetObjKey(obj) # define BTOverlaps(o1,o2) (BTKeyEQ(BTGetObjKey(o1),BTGetObjKey(o2))) # undef BT_HAVE_INTERVALS #else # define BT_HAVE_INTERVALS #endif typedef int BTKeyCount; /* one B-Tree page */ struct sBTPage { BTKeyCount count; /* number of keys used */ int isleaf; /* true if this is a leaf page */ BTKey key[BT_MAXKEY]; /* child[i]<key[i]<=child[i+1] */ struct sBTPage *child[BT_ORDER]; /* Child (or object) pointers */ }; typedef struct sBTPage BTPage; typedef struct { int depth; /* depth of tree (incl root) */ BTPage *root; /* root page of B-tree */ PagePool *pool; /* pointer to B-tree's page pool */ } BTree_S; typedef BTree_S BTree; typedef BTree_S *GBTree; /* b+tree operations */ void EXPORT(BTPrint) (GBTree const); /* Print a B-tree */ int EXPORT(BTSearch) (GBTree const, BTKey const key, GBTObject *obj); /* * Search "key" in "GBTree", return object through "obj". Returns BT_FOUND if * successfull, BT_INVALID if invalid "GBTree", BT_NOT_FOUND if key not in * B-tree. */ int EXPORT(BTModify) (GBTree const, BTKey const key, GBTObject **obj); /* * Used for replacing an object in the B+ tree. Search "key" in "GBTree", * return object handle through "obj", which can then be used to replace the * pointer to the object in the index strucutre. WARNING: the new object MUST * have the same key values! Returns BT_FOUND if successfull, BT_INVALID if * invalid "GBTree", BT_NOT_FOUND if key not in B-tree. */ int EXPORT(BTIns) (GBTree const, GBTObject const obj, GBTObject *ngb); /* * Insert "obj" in "GBTree". Returns, through "ngb", one of the new object's * neighbours in the tree. Whether the right or left neighbour is returned is * undefined. NULL is returned iff the new object is the first one in the tree. * Returning the neighbour allows the user to maintain a secondary access * structure to their objects. Returns BT_FOUND if successful, BT_INVALID if * invalid "GBTree", BT_ALLOC_fail if out of memory, BT_DUPLICATE if "key" * already exists in B-tree, BT_OVERLAP if new object overlaps existing one. */ int EXPORT(BTDel) (GBTree const, BTKey const key, GBTObject *obj); /* * Delete object with "key" in "GBTree". A pointer to the actual object is * returned so that the caller can then deallocate its storage. Only an object * with an excatly matching key will be deleted (i.e. "key IN obj" is not good * enough). Returns BT_FOUND if successfull, BT_INVALID if invalid "GBTree", * BT_NOT_FOUND if key does not match ank key in B-tree. */ /* possible return values */ #define BT_FOUND 0 #define BT_OK 0 #define BT_INVALID 1 #define BT_NOT_FOUND 2 #define BT_DUPLICATE 3 #define BT_OVERLAP 4 #define BT_ALLOC_fail 5 /* running out of memory */ /* Internal return codes: */ #define BT_PROMOTION 6 /* place the promoted key */ #define BT_LESS_THAN_MIN 7 /* redistribute key from child */ #endif /* !_BTREE_H_ */
45.517241
81
0.720076
42aaa083fb45eca4a69784732a717ec7663870b7
9,304
c
C
Data structors in c/Binary Tree/basic AVL tree.c
ikaushikpal/C-practice
abab8a186eaf38b434811755833a32306cd47d64
[ "MIT" ]
null
null
null
Data structors in c/Binary Tree/basic AVL tree.c
ikaushikpal/C-practice
abab8a186eaf38b434811755833a32306cd47d64
[ "MIT" ]
null
null
null
Data structors in c/Binary Tree/basic AVL tree.c
ikaushikpal/C-practice
abab8a186eaf38b434811755833a32306cd47d64
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include "QueueSingly.h" struct AVLnode { struct AVLnode *lchild; int data; int height; struct AVLnode *rchild; }; typedef struct AVLnode AVLnode; AVLnode *createNode_AVL(int); AVLnode *Rinsert_AVL(AVLnode *, int); AVLnode *LLRotation_AVL(AVLnode *); AVLnode *RRRotation_AVL(AVLnode *); int nodeHeight_AVL(AVLnode *); int balanceFactor_AVL(AVLnode *); void clearAVL(AVLnode *); AVLnode *build_AVL(int *, int); AVLnode *Inoder_predecessor_BST(AVLnode *); AVLnode *Inoder_successor_BST(AVLnode *); AVLnode *Delete_AVLnode(AVLnode *, int); void preoderTraversal(AVLnode *); void preoderTraversalUtil(AVLnode *); void postoderTraversal(AVLnode *); void postoderTraversalUtil(AVLnode *); void inoderTraversal(AVLnode *); void inoderTraversalUtil(AVLnode *); void levelOrderTraversal(AVLnode *); int main() { int elements[] = {9, 5, 10, 0, 6, 11, -1, 1, 2}; int size = sizeof(elements) / sizeof(*elements); AVLnode *root = build_AVL(elements, size); preoderTraversal(root); postoderTraversal(root); inoderTraversal(root); levelOrderTraversal(root); printf("\n\n\n"); Delete_AVLnode(root, 10); preoderTraversal(root); postoderTraversal(root); inoderTraversal(root); levelOrderTraversal(root); clearAVL(root); return 0; } AVLnode *createNode(int data) { AVLnode *newNode = (AVLnode *)malloc(sizeof(AVLnode)); newNode->data = data; newNode->lchild = newNode->rchild = NULL; newNode->height = 1; return newNode; } void preoderTraversal(AVLnode *root) { printf("===============PREORDER TRAVERSAL===============\n"); preoderTraversalUtil(root); printf("\n================================================\n"); } void preoderTraversalUtil(AVLnode *root) { if (root) { printf("%d, ", root->data); preoderTraversalUtil(root->lchild); preoderTraversalUtil(root->rchild); } } void postoderTraversal(AVLnode *root) { { printf("==============POSTORDER TRAVERSAL===============\n"); postoderTraversalUtil(root); printf("\n================================================\n"); } } void postoderTraversalUtil(AVLnode *root) { if (root) { postoderTraversalUtil(root->lchild); postoderTraversalUtil(root->rchild); printf("%d, ", root->data); } } void inoderTraversal(AVLnode *root) { printf("===============INORDER TRAVERSAL================\n"); inoderTraversalUtil(root); printf("\n================================================\n"); } void inoderTraversalUtil(AVLnode *root) { if (root) { inoderTraversalUtil(root->lchild); printf("%d, ", root->data); inoderTraversalUtil(root->rchild); } } AVLnode *Rinsert_AVL(AVLnode *root, int data) { if (!root) return createNode(data); else if (root->data > data) root->lchild = Rinsert_AVL(root->lchild, data); else if (root->data < data) root->rchild = Rinsert_AVL(root->rchild, data); else return root; // updating each parent nodes height root->height = nodeHeight_AVL(root); int balanceFactor = balanceFactor_AVL(root); // case 1 : checking if it is lchild skewed(LL imbalanced),if yes then do LLRotation if (balanceFactor > 1 && data < root->lchild->data) return LLRotation_AVL(root); //case 2 : if it is rchild skewed(RR imbalanced), if yes then do RRRotation else if (balanceFactor < -1 && data > root->rchild->data) return RRRotation_AVL(root); //case 3 : if it is LR imbalanced, if yes then do LRRotation else if (balanceFactor > 1 && data > root->lchild->data) { // first need to do RR-rotaion on root->lchild then perform LL on root root->lchild = RRRotation_AVL(root->lchild); return LLRotation_AVL(root); } //case 3 : if it is RL imbalanced, if yes then do RLRotation else if (balanceFactor < -1 && data < root->rchild->data) { // first need to do LL-rotaion on root->rchild then perform RR on root root->rchild = LLRotation_AVL(root->rchild); return RRRotation_AVL(root); } // finally return root return root; } int nodeHeight_AVL(AVLnode *root) { int heightlchildSubTree, heightrchildSubTree; heightlchildSubTree = (root && root->lchild) ? root->lchild->height : 0; heightrchildSubTree = (root && root->rchild) ? root->rchild->height : 0; return (heightlchildSubTree > heightrchildSubTree) ? heightlchildSubTree + 1 : heightrchildSubTree + 1; } int balanceFactor_AVL(AVLnode *root) { int heightlchildSubTree, heightrchildSubTree; heightlchildSubTree = (root && root->lchild) ? root->lchild->height : 0; heightrchildSubTree = (root && root->rchild) ? root->rchild->height : 0; return heightlchildSubTree - heightrchildSubTree; } AVLnode *LLRotation_AVL(AVLnode *root) { AVLnode *LNode = root->lchild; AVLnode *LRNode = LNode->rchild; LNode->rchild = root; root->lchild = LRNode; root->height = nodeHeight_AVL(root); LNode->height = nodeHeight_AVL(LNode); return LNode; } AVLnode *RRRotation_AVL(AVLnode *root) { AVLnode *RNode = root->rchild; AVLnode *RLNode = RNode->lchild; RNode->lchild = root; root->rchild = RLNode; root->height = nodeHeight_AVL(root); RNode->height = nodeHeight_AVL(RNode); return RNode; } void clearAVL(AVLnode *root) { if (root) { clearAVL(root->lchild); clearAVL(root->rchild); free(root); } } AVLnode *build_AVL(int *arr, int n) { int i = 0; AVLnode *root = NULL; for (; i < n; i++) root = Rinsert_AVL(root, arr[i]); return root; } void levelOrderTraversal(AVLnode *root) { Queue_Singly queue; createQueue(&queue, sizeof(AVLnode *)); enQueue_Singly(&queue, &root); AVLnode **currNode = (AVLnode **)malloc(sizeof(AVLnode *)); unsigned int n = 1, copy_n; unsigned int level = 1; register int i = 0; printf("=============LEVEL ORDER TRAVERSAL==============\n"); while (isEmpty_Singly(&queue) != 1) { printf("%d level : ", level); copy_n = n; for (i = 0; i < copy_n; i++) { deQueue_Singly(&queue, currNode); n--; printf("%d, ", (*currNode)->data); if ((*currNode)->lchild) { enQueue_Singly(&queue, &((*currNode)->lchild)); n++; } if ((*currNode)->rchild) { enQueue_Singly(&queue, &((*currNode)->rchild)); n++; } } level++; if (isEmpty_Singly(&queue) == 0) printf("\n"); } free(currNode); clear_Singly(&queue); printf("\n===============================================\n"); } AVLnode *Inoder_predecessor_BST(AVLnode *root) { while (root && root->rchild) root = root->rchild; return root; } AVLnode *Inoder_successor_BST(AVLnode *root) { while (root && root->lchild) root = root->lchild; return root; } AVLnode *Delete_AVLnode(AVLnode *root, int key) { // if root is empty node then simply return null if (!root) return root; if (root->data > key) root->lchild = Delete_AVLnode(root->lchild, key); else if (root->data < key) root->rchild = Delete_AVLnode(root->rchild, key); else // now we found element { // node with only one child or no child if ((root->lchild == NULL) || (root->rchild == NULL)) { AVLnode *temp = root->lchild ? root->lchild : root->rchild; // No child case if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; // Copy the contents of // the non-empty child free(temp); } else { // node with two children: Get the inorder // successor (smallest in the rchild subtree) AVLnode *temp = Inoder_successor_BST(root->rchild); // Copy the inorder successor's data to this node root->data = temp->data; // Delete the inorder successor root->rchild = Delete_AVLnode(root->rchild, temp->data); } } if (root == NULL) return root; root->height = nodeHeight_AVL(root); int balance_factor = balanceFactor_AVL(root); //case 1 : do LL rotaion on root if (balance_factor > 1 && balanceFactor_AVL(root->lchild) >= 0) return LLRotation_AVL(root); //case 2:do LR rotaion else if (balance_factor > 1 && balanceFactor_AVL(root->lchild) < 0) { root->lchild = RRRotation_AVL(root->lchild); return LLRotation_AVL(root); } //case 3 : do RR Rotation on root else if (balance_factor < -1 && balanceFactor_AVL(root->rchild) <= 0) return RRRotation_AVL(root); // case 4 : do Rl rotaion else if (balance_factor < -1 && balanceFactor_AVL(root->rchild) > 0) { root->rchild = LLRotation_AVL(root->rchild); return RRRotation_AVL(root); } return root; }
28.193939
107
0.586307
09939fd3103370e177d3119c1049985e6b69150b
731
h
C
src/memory-api/close_buffer.h
DataManagementLab/dpi_library
79e55bdd5f82f64cfe4463df111c82ae877abb85
[ "Apache-2.0" ]
3
2019-01-28T10:43:39.000Z
2019-04-03T21:06:05.000Z
src/memory-api/close_buffer.h
DataManagementLab/dpi_library
79e55bdd5f82f64cfe4463df111c82ae877abb85
[ "Apache-2.0" ]
null
null
null
src/memory-api/close_buffer.h
DataManagementLab/dpi_library
79e55bdd5f82f64cfe4463df111c82ae877abb85
[ "Apache-2.0" ]
2
2019-01-15T12:49:27.000Z
2019-12-06T00:36:06.000Z
/** * @file close_buffer.h * @author cbinnig, lthostrup, tziegler * @date 2018-08-17 */ #pragma once #include <string> #include "context.h" #include "err_codes.h" #include "../utils/Config.h" /** * @brief DPI_Close_buffer indicates that the calling client does not wish to send more data to the buffer. Buffer is not remotely removed and can still be read from. * * @param name - name of the buffer * @param context - DPI_Context * @return int - error code */ inline int DPI_Close_buffer(string& name, DPI_Context& context) { if (context.registry_client == nullptr) return DPI_NOT_INITIALIZED; auto buffer_writer = context.buffer_writers[name]; buffer_writer->close(); return DPI_SUCCESS; }
25.206897
166
0.70725
abe10b9f640b66d4b6c28314ca9c441899c49730
5,825
c
C
physicalrobots/player/utils/playerv/pv_dev_sonar.c
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
physicalrobots/player/utils/playerv/pv_dev_sonar.c
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
physicalrobots/player/utils/playerv/pv_dev_sonar.c
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* * PlayerViewer * Copyright (C) Andrew Howard 2002 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ /*************************************************************************** * Desc: Sonar (fixed range finder) interface * Author: Andrew Howard * Date: 14 May 2002 * CVS: $Id: pv_dev_sonar.c 7807 2009-06-07 07:44:40Z thjc $ ***************************************************************************/ #include <assert.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "playerv.h" // Update the sonar configuration void sonar_update_config(sonar_t *sonar); // Draw the sonar scan void sonar_draw(sonar_t *sonar); // Dont draw the sonar scan void sonar_nodraw(sonar_t *sonar); // Update the geometry void sonar_update_geom(sonar_t *sonar); // Create a sonar device sonar_t *sonar_create(mainwnd_t *mainwnd, opt_t *opt, playerc_client_t *client, int index, const char *drivername, int subscribe) { char label[64]; char section[64]; sonar_t *sonar; sonar = malloc(sizeof(sonar_t)); sonar->proxy = playerc_sonar_create(client, index); sonar->drivername = strdup(drivername); sonar->datatime = 0; sonar->mainwnd = mainwnd; snprintf(section, sizeof(section), "sonar:%d", index); // Construct the menu snprintf(label, sizeof(label), "sonar:%d (%s)", index, sonar->drivername); sonar->menu = rtk_menu_create_sub(mainwnd->device_menu, label); sonar->subscribe_item = rtk_menuitem_create(sonar->menu, "Subscribe", 1); // Set the initial menu state // Set initial device state rtk_menuitem_check(sonar->subscribe_item, subscribe); sonar->fig_count = 0; sonar->scan_fig = NULL; return sonar; } void sonar_allocate_figures(sonar_t * sonar, int fig_count) { int i; if (fig_count <= sonar->fig_count) return; sonar->scan_fig = realloc(sonar->scan_fig,fig_count*sizeof(sonar->scan_fig[0])); // Construct figures for (i = sonar->fig_count; i < fig_count; i++) sonar->scan_fig[i] = rtk_fig_create(sonar->mainwnd->canvas, sonar->mainwnd->robot_fig, 1); sonar->fig_count = fig_count; } // Destroy a sonar device void sonar_destroy(sonar_t *sonar) { int i; if (sonar->proxy->info.subscribed) playerc_sonar_unsubscribe(sonar->proxy); playerc_sonar_destroy(sonar->proxy); for (i = 0; i < sonar->fig_count; i++) rtk_fig_destroy(sonar->scan_fig[i]); rtk_menuitem_destroy(sonar->subscribe_item); rtk_menu_destroy(sonar->menu); free(sonar->drivername); free(sonar); } // Update a sonar device void sonar_update(sonar_t *sonar) { // Update the device subscription if (rtk_menuitem_ischecked(sonar->subscribe_item)) { if (!sonar->proxy->info.subscribed) { if (playerc_sonar_subscribe(sonar->proxy, PLAYER_OPEN_MODE) != 0) PRINT_ERR1("subscribe failed : %s", playerc_error_str()); // Get the sonar geometry if (playerc_sonar_get_geom(sonar->proxy) != 0) PRINT_ERR1("get_geom failed : %s", playerc_error_str()); sonar_update_geom(sonar); } } else { if (sonar->proxy->info.subscribed) if (playerc_sonar_unsubscribe(sonar->proxy) != 0) PRINT_ERR1("unsubscribe failed : %s", playerc_error_str()); } rtk_menuitem_check(sonar->subscribe_item, sonar->proxy->info.subscribed); if (sonar->proxy->info.subscribed) { if (sonar->proxy->info.freshgeom) { sonar->proxy->info.freshgeom = 0; sonar_update_geom(sonar); } // Draw in the sonar scan if it has been changed. if (sonar->proxy->info.datatime != sonar->datatime) sonar_draw(sonar); sonar->datatime = sonar->proxy->info.datatime; } else { // Dont draw the sonar. sonar_nodraw(sonar); } } // update sonar geometry void sonar_update_geom(sonar_t *sonar) { int i; sonar_allocate_figures(sonar, sonar->proxy->pose_count); for (i = 0; i < sonar->proxy->pose_count; i++) rtk_fig_origin(sonar->scan_fig[i], sonar->proxy->poses[i].px, sonar->proxy->poses[i].py, sonar->proxy->poses[i].pyaw ); } // Draw the sonar scan void sonar_draw(sonar_t *sonar) { int i; double dr, da; double points[3][2]; for (i = 0; i < sonar->proxy->scan_count; i++) { rtk_fig_show(sonar->scan_fig[i], 1); rtk_fig_clear(sonar->scan_fig[i]); // Draw in the sonar itself rtk_fig_color_rgb32(sonar->scan_fig[i], COLOR_SONAR); rtk_fig_rectangle(sonar->scan_fig[i], 0, 0, 0, 0.01, 0.05, 0); // Draw in the range scan rtk_fig_color_rgb32(sonar->scan_fig[i], COLOR_SONAR_SCAN); dr = sonar->proxy->scan[i]; da = 20 * M_PI / 180 / 2; //rtk_fig_line(sonar->scan_fig[i], 0, 0, dr, 0); //rtk_fig_line(sonar->scan_fig[i], dr, -dr * da/2, dr, +dr * da/2); points[0][0] = 0; points[0][1] = 0; points[1][0] = dr * cos(-da); points[1][1] = dr * sin(-da); points[2][0] = dr * cos(+da); points[2][1] = dr * sin(+da); rtk_fig_polygon(sonar->scan_fig[i], 0, 0, 0, 3, points, 1); } } // Dont draw the sonar scan void sonar_nodraw(sonar_t *sonar) { int i; for (i = 0; i < sonar->proxy->scan_count; i++) rtk_fig_show(sonar->scan_fig[i], 0); }
27.093023
93
0.652704
8686a2435a1947449f495a69fdb8633381e89f23
4,282
h
C
src/imlib/scroller.h
jwrdegoede/abuse
77a34f69569815e73b95d99268fb7ba1cd64c17b
[ "WTFPL" ]
null
null
null
src/imlib/scroller.h
jwrdegoede/abuse
77a34f69569815e73b95d99268fb7ba1cd64c17b
[ "WTFPL" ]
null
null
null
src/imlib/scroller.h
jwrdegoede/abuse
77a34f69569815e73b95d99268fb7ba1cd64c17b
[ "WTFPL" ]
null
null
null
/* * Abuse - dark 2D side-scrolling platform game * Copyright (c) 1995 Crack dot Com * Copyright (c) 2005-2011 Sam Hocevar <sam@hocevar.net> * * This software was released into the Public Domain. As with most public * domain software, no warranty is made or implied by Crack dot Com, by * Jonathan Clark, or by Sam Hocevar. */ #ifndef _SCROLLER_HPP_ #define _SCROLLER_HPP_ #include "input.h" class scroller : public ifield { protected : int l,h,drag,vert,last_click; int bh(); int bw(); void drag_area(int &x1, int &y1, int &x2, int &y2); void dragger_area(int &x1, int &y1, int &x2, int &y2); int b1x() { if (vert) return m_pos.x+l; else return m_pos.x; } int b1y() { if (vert) return m_pos.y; else return m_pos.y+h; } int b2x() { if (vert) return m_pos.x+l; else return m_pos.x+l-bw(); } int b2y() { if (vert) return m_pos.y+h-bh(); else return m_pos.y+h; } unsigned char *b1(); unsigned char *b2(); void wig_area(int &x1, int &y1, int &x2, int &y2); int wig_x(); int darea() { return (l-bw()-2)-bw()-bw(); } void draw_widget(image *screen, int erase); int mouse_to_drag(int mx,int my); public : int t,sx; scroller(int X, int Y, int ID, int L, int H, int Vert, int Total_items, ifield *Next); virtual void area(int &x1, int &y1, int &x2, int &y2); virtual void draw_first(image *screen); virtual void draw(int active, image *screen); virtual void handle_event(Event &ev, image *screen, InputManager *im); virtual char *read() { return (char *)&sx; } virtual int activate_on_mouse_move() { return 1; } virtual void handle_inside_event(Event &ev, image *screen, InputManager *inm) { ; } virtual void scroll_event(int newx, image *screen); virtual void handle_up(image *screen, InputManager *inm); virtual void handle_down(image *screen, InputManager *inm); virtual void handle_left(image *screen, InputManager *inm); virtual void handle_right(image *screen, InputManager *inm); virtual void area_config() { ; } void set_size(int width, int height) { l=width; h=height; } virtual void set_x(int x, image *screen); } ; class spicker : public scroller { protected : int r,c,m,last_sel,cur_sel; uint8_t *select; public : spicker(int X, int Y, int ID, int Rows, int Cols, int Vert, int MultiSelect, ifield *Next); int vis() { if (vert) return r; else return c; } virtual void area_config(); void set_select(int x, int on); int get_select(int x); int first_selected(); virtual void scroll_event(int newx, image *screen); virtual void handle_inside_event(Event &ev, image *screen, InputManager *inm); // you should define \/ virtual void draw_background(image *screen); virtual void draw_item(image *screen, int x, int y, int num, int active) = 0; virtual int total() = 0; virtual int item_width() = 0; virtual int item_height() = 0; virtual void note_selection(image *screen, InputManager *inm, int x) { ; } virtual void note_new_current(image *screen, InputManager *inm, int x) { ; } virtual int ok_to_select(int num) { return 1; } virtual void handle_up(image *screen, InputManager *inm); virtual void handle_down(image *screen, InputManager *inm); virtual void handle_left(image *screen, InputManager *inm); virtual void handle_right(image *screen, InputManager *inm); virtual void set_x(int x, image *screen); void reconfigure(); // should be called by constructor after class is ready to take virtual calls ~spicker() { if (select) free(select); } } ; struct pick_list_item { char *name; int number; } ; class pick_list : public scroller { int last_sel,cur_sel,th,wid; pick_list_item *lis; char key_hist[20],key_hist_total; image *tex; public : pick_list(int X, int Y, int ID, int height, char **List, int num_entries, int start_yoffset, ifield *Next, image *texture=NULL); virtual void handle_inside_event(Event &ev, image *screen, InputManager *inm); virtual void scroll_event(int newx, image *screen); virtual char *read() { return (char *)this; } virtual void area_config(); virtual void handle_up(image *screen, InputManager *inm); virtual void handle_down(image *screen, InputManager *inm); int get_selection() { return lis[cur_sel].number; } ~pick_list() { free(lis); } } ; #endif
34.813008
101
0.694769
b68596012f4351025a33ddfb57175ed2a415395e
285
h
C
vitis_hls_examples/slxplugin_loopinterchange_demo/slxplugin/examples/dimension_reduction/reduce_2d_to_1d/code.h
viraphol/HLS
9de82acd6a8797b54038484e2bdd5a51dc133318
[ "Apache-2.0" ]
295
2021-02-27T08:42:52.000Z
2022-03-27T14:38:55.000Z
vitis_hls_examples/slxplugin_loopinterchange_demo/slxplugin/examples/dimension_reduction/reduce_2d_to_1d/code.h
viraphol/HLS
9de82acd6a8797b54038484e2bdd5a51dc133318
[ "Apache-2.0" ]
5
2021-03-09T17:00:12.000Z
2022-03-23T22:44:00.000Z
vitis_hls_examples/slxplugin_loopinterchange_demo/slxplugin/examples/dimension_reduction/reduce_2d_to_1d/code.h
viraphol/HLS
9de82acd6a8797b54038484e2bdd5a51dc133318
[ "Apache-2.0" ]
42
2021-02-26T07:49:39.000Z
2022-01-13T23:07:42.000Z
// Copyright (C) 2020, Silexica GmbH, Lichtstr. 25, Cologne, Germany // All rights reserved #ifndef _CODE_H_ #define _CODE_H_ typedef double IN_TYPE; typedef double OUT_TYPE; #define N 256 extern "C" { void reduce_2d_to_1d(IN_TYPE data[N][N], OUT_TYPE acc[N]); } #endif // _CODE_H_
19
68
0.736842
22b2631cbd595609efdb2ee28cf1ddd9c41c0527
9,024
h
C
MapSegmatation_5.2/mainwindow.h
JindingWang/-
1bd5c803a2a03be9cd3a4a4b89dde6e9402dcdb1
[ "Apache-2.0" ]
null
null
null
MapSegmatation_5.2/mainwindow.h
JindingWang/-
1bd5c803a2a03be9cd3a4a4b89dde6e9402dcdb1
[ "Apache-2.0" ]
null
null
null
MapSegmatation_5.2/mainwindow.h
JindingWang/-
1bd5c803a2a03be9cd3a4a4b89dde6e9402dcdb1
[ "Apache-2.0" ]
1
2021-12-31T05:55:57.000Z
2021-12-31T05:55:57.000Z
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QAction> #include <QString> #include <QLabel> #include <QCheckBox> #include <QEvent> #include <vector> #include <QLineEdit> #include <QPushButton> #include <QIntValidator> #include <QDoubleValidator> #include <queue> #include <utility> #include <QFile> #include <math.h> #include <dialog.h> //namespace Ui { //class MainWindow; //} struct color_node { unsigned int color_freq; unsigned int color_index; }; struct image_node { QString image_type="nullptr"; unsigned char * image_array=nullptr; }; struct cmp { bool operator()(color_node a, color_node b) { return a.color_freq < b.color_freq; } }; /*struct contour{ std::pair<int, int> seed_coor; int index = -1; int pixel_num = 0; contour(int a, int b, int c, int d) { seed_coor.first = a; seed_coor.second = b; index = c; pixel_num = d; } };*/ const int max_display_num_color = 80; const int max_history_step = 6; enum LineType{inLine, outLine}; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(int, int, int, int, QWidget *parent = nullptr); void change_setting(); void selected_colors_to_binary_array(unsigned char *, std::vector<int>, int, int, unsigned char); void generate_intergation_array(unsigned int *, unsigned char *, int, int); void median_filter(unsigned char *, unsigned char, int, int); void major_filter(unsigned char *, unsigned char, int, int); void dilate(unsigned char *, int, int, int, int); void erode(unsigned char *, int, int, int, int); void erase_select_area_with_main_color(unsigned char *, bool); void see_white_areas(); void on_OpenAction_triggered(); void on_SaveAction_triggered(); void autosave(QString); void on_median_3_3_triggered(); void on_median_5_5_triggered(); void on_median_7_7_triggered(); void on_median_9_9_triggered(); void on_median_11_11_triggered(); void on_major_3_3_triggered(); void on_major_5_5_triggered(); void on_major_7_7_triggered(); void on_major_9_9_triggered(); void on_major_11_11_triggered(); void on_major_13_13_triggered(); void on_major_15_15_triggered(); void on_FindColorAction_triggered(); void on_EraseColorByNearestColorAction_triggered(); void on_EraseSpecificColorAction_triggered(); void on_EraseAllBelowColorAction_triggered(); void on_EraseAllUnshowColorAction_triggered(); void on_ExtractColorAction_triggered(); void on_ConvertColorAction_triggered(); void on_EraseAllSmallContourAction_triggered(); void on_AddColorFromBinaryImageAction_triggered(); void on_disk_11_11_triggered(); // for filling white blank void on_disk_9_9_triggered(); void on_disk_7_7_triggered(); void on_disk_5_5_triggered(); void on_square_11_11_triggered(); void on_square_9_9_triggered(); void on_square_7_7_triggered(); void on_square_5_5_triggered(); void on_close_open_disk_5_5_triggered(); void on_close_open_disk_7_7_triggered(); void on_close_open_disk_9_9_triggered(); void on_open_disk_3_3_triggered(); void on_open_disk_5_5_triggered(); void on_open_disk_7_7_triggered(); void on_close_disk_3_3_triggered(); void on_close_disk_5_5_triggered(); void on_close_disk_7_7_triggered(); void on_open_square_3_3_triggered(); void on_open_square_5_5_triggered(); void on_open_square_7_7_triggered(); void on_close_square_3_3_triggered(); void on_close_square_5_5_triggered(); void on_close_square_7_7_triggered(); void on_ReturnAction_triggered(); void on_NextAction_triggered(); void on_SaveAllBinaryImageAction_triggered(); void on_SaveWithDilate3x3Action_triggered(); void on_SaveWithDilate5x5Action_triggered(); void on_BinaryToSvgAction_triggered(); void on_AllToSVGAction_triggered(); void on_AllToSHPAction_triggered(); void extractContourFromBinaryImg(unsigned char *, std::vector<std::vector<std::pair<float, float>>>& outContour, std::vector<std::vector<std::pair<float, float>>>& inContour, std::vector<std::vector<unsigned int>>& holeIndexs); double calCoutourArea(std::vector<std::pair<unsigned int, unsigned int>>&); void simplifyLine(std::vector<std::pair<unsigned int, unsigned int>>&, std::vector<std::pair<float, float>>&, LineType); void contourTwoSVG(std::vector<std::vector<std::pair<float, float>>>&, std::vector<std::vector<std::pair<float, float>>>&, std::vector<std::vector<unsigned int>>&, QFile&, QString, int); void getCoordinatePage(float* coor); ~MainWindow(); protected: //void changeEvent(QEvent * event); private: Dialog* getValue; bool first_find_color = false; int white_threshold = 224; short bit_mov_right = 4; unsigned int max_range_to_merge_color = 16; double min_color_area_ratio = 0.00002; //double min_main_color_ratio = 0.05; int current_image_index = -1; double min_area_ratio_to_replace = 0.15; int max_erase_win_size = 24; int notdilate = 0; int save_count = 0; int binary_save_count = 0; QAction *OpenAction; QAction *SaveAction; QAction *FindColorAction; QAction *ExtractColorAction; QAction *EraseColorAction; QAction *EraseColorByNearestColorAction; QAction *EraseSpecificColorAction; QAction *EraseAllBelowColorAction; QAction *EraseAllUnshowColorAction; QAction *ConvertColorAction; QAction *EraseAllSmallContourAction; QAction *AddColorFromBinaryImageAction; QAction *ReturnAction; QAction *NextAction; QAction *median_3_3; QAction *median_5_5; QAction *median_7_7; QAction *median_9_9; QAction *median_11_11; QAction *major_3_3; QAction *major_5_5; QAction *major_7_7; QAction *major_9_9; QAction *major_11_11; QAction *major_13_13; QAction *major_15_15; QAction *see_white; QAction *disk_5_5; QAction *disk_7_7; QAction *disk_9_9; QAction *disk_11_11; QAction *square_5_5; QAction *square_7_7; QAction *square_9_9; QAction *square_11_11; QAction *close_open_disk_5_5; QAction *close_open_disk_7_7; QAction *close_open_disk_9_9; QAction *open_disk_3_3; QAction *open_disk_5_5; QAction *open_disk_7_7; QAction *open_square_3_3; QAction *open_square_5_5; QAction *open_square_7_7; QAction *close_disk_3_3; QAction *close_disk_5_5; QAction *close_disk_7_7; QAction *close_square_3_3; QAction *close_square_5_5; QAction *close_square_7_7; QAction *BinaryToSVG; QAction *AllToSVG; QAction *AllToSHP; QAction *SaveAllBinaryImage; QAction *SaveWithDilate3x3; QAction *SaveWithDilate5x5; QLabel *ImageLabel; QImage *image = nullptr; QImage *bin_image = nullptr; QPixmap noneColor; QLabel *color[max_display_num_color]; QLabel *rgb[max_display_num_color]; QCheckBox *select[max_display_num_color]; QImage *SaveImage; QLabel *settingLabel; QLabel *minColorAreaRatioLabel; QLineEdit *minColorAreaRatio; QLabel * rightShiftNumLabel; QLineEdit* rightShiftNum; QLabel * maxRangeToMergeColorLabel; QLineEdit* maxRangeToMergeColor; QLabel * maxMainColorNumLabel; QLineEdit* maxMainColorNum; QPushButton* OK; QLabel *convertColorLabel; QLineEdit *convertColorR; QLineEdit *convertColorG; QLineEdit *convertColorB; QLabel *eraseColorLabel; QLineEdit *eraseColorR; QLineEdit *eraseColorG; QLineEdit *eraseColorB; QLabel *notDilateLabel; QLineEdit * notDilateNum; QString OpenFileName = ""; QString SaveFileName = ""; int display_num_color = 40; int display_per_row = 20; int need_sub16 = 1; int square_size = 64; int win_width = 0; int win_height = 0; int img_width = 0; int img_height = 0; int display_img_width = 0; int display_img_height = 0; unsigned char *ImgArray = nullptr; unsigned char *grayImgArray = nullptr; unsigned char *FilterImgArray = nullptr; unsigned int *color_histogram = nullptr; unsigned char *binary_img = nullptr; unsigned char *approximate_img = nullptr; unsigned char *erased_img = nullptr; std::vector<color_node> sorted_color[max_display_num_color]; image_node image_history[max_history_step]; double minContourArea = 5; short maxContourNum = 1000; }; #endif // MAINWINDOW_H
30.486486
102
0.683289
79cc8d83bc590c9824c040e13dabc4ef8086c855
596
h
C
dados.h
Joice-crypto/AEDS2
4d709c0c7eebafbd1b0a741d49c2e39377244143
[ "MIT" ]
null
null
null
dados.h
Joice-crypto/AEDS2
4d709c0c7eebafbd1b0a741d49c2e39377244143
[ "MIT" ]
null
null
null
dados.h
Joice-crypto/AEDS2
4d709c0c7eebafbd1b0a741d49c2e39377244143
[ "MIT" ]
null
null
null
#ifndef DADOS_H #define DADOS_H #define max 50 #include "grafos.h" #include <stdbool.h> typedef struct TGrafo Grafo; typedef struct TEvent { // evento que vai ficar no lugar do arquivo XML char mystate; char estado_vizinho; char acao; float prob; // probabilidade dele acontecer int t; bool repeat; // se o repeat for verdadeiro então ele vai inserir novamente na heap } Event; int Funinfeccao(Grafo *g, char estado, Event infec); int inicializaInf(Grafo *g, char estado, Event infec); int FunRecuperacao(Grafo *g, char estado, Event recup); #endif
23.84
89
0.706376
66cc3d3270d9e715631c4529e3bcf54b0c324371
5,106
c
C
linux-3.4/modules/rogue_km/services/shared/devices/rgx/rgx_compat_bvnc.c
xregist/v3s-linux-sdk
a2b013e3959662d65650a13fc23ec1cd503865eb
[ "Apache-2.0" ]
null
null
null
linux-3.4/modules/rogue_km/services/shared/devices/rgx/rgx_compat_bvnc.c
xregist/v3s-linux-sdk
a2b013e3959662d65650a13fc23ec1cd503865eb
[ "Apache-2.0" ]
null
null
null
linux-3.4/modules/rogue_km/services/shared/devices/rgx/rgx_compat_bvnc.c
xregist/v3s-linux-sdk
a2b013e3959662d65650a13fc23ec1cd503865eb
[ "Apache-2.0" ]
1
2020-01-31T10:27:07.000Z
2020-01-31T10:27:07.000Z
/*************************************************************************/ /*! @File @Title Functions for BVNC manipulating @Copyright Copyright (c) Imagination Technologies Ltd. All Rights Reserved @Description Utility functions used internally by device memory management code. @License Dual MIT/GPLv2 The contents of this file are subject to the MIT license as set out below. 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. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 ("GPL") in which case the provisions of GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of GPL, and not to allow others to use your version of this file under the terms of the MIT license, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by GPL as set out in the file called "GPL-COPYING" included in this distribution. If you do not delete the provisions above, a recipient may use your version of this file under the terms of either the MIT license or GPL. This License is also included in this distribution in the file called "MIT-COPYING". EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) 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; AND (B) 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. */ /**************************************************************************/ /****************************************************************************** * RGX Version packed into 24-bit (BNC) and string (V) to be used by Compatibility Check *****************************************************************************/ #include "rgx_compat_bvnc.h" IMG_VOID rgx_bvnc_packed(IMG_UINT32 *pui32OutBNC, IMG_CHAR *pszOutV, IMG_UINT32 ui32OutVMaxLen, IMG_UINT32 ui32B, IMG_CHAR *pszV, IMG_UINT32 ui32N, IMG_UINT32 ui32C) { #if 0 IMG_UINT32 i = ui32OutVMaxLen; #endif IMG_UINT32 ui32InVLen = 0; IMG_CHAR *pszPointer; IMG_UINT32 ui32V = 0; *pui32OutBNC = (((ui32B & 0xFF) << 16) | ((ui32N & 0xFF) << 8) | (ui32C & 0xFF)); /* Using dword accesses instead of byte accesses when forming V part of BVNC */ ui32OutVMaxLen = ui32OutVMaxLen; pszPointer = pszV; while (*pszPointer) { ui32InVLen++; pszPointer++; } if (ui32InVLen == 1) { ui32V = ((IMG_UINT32)pszV[0]) & 0xFF; } else if (ui32InVLen == 2) { ui32V = ((((IMG_UINT32)pszV[0]) & 0xFF) << 0) | ((((IMG_UINT32)pszV[1]) & 0xFF) << 8); } else if (ui32InVLen == 3) { ui32V = ((((IMG_UINT32)pszV[0]) & 0xFF) << 0) | ((((IMG_UINT32)pszV[1]) & 0xFF) << 8) | ((((IMG_UINT32)pszV[2]) & 0xFF) << 16); } *((IMG_UINT32 *)pszOutV) = ui32V; #if 0 for (i = 0; i < (ui32OutVMaxLen + 1); i++) pszOutV[i] = '\0'; while ((ui32OutVMaxLen > 0) && *pszV) { *pszOutV++ = *pszV++; ui32OutVMaxLen--; } #endif } IMG_VOID rgx_bvnc_pack_hw(IMG_UINT32 *pui32OutBNC, IMG_CHAR *pszOutV, IMG_UINT32 ui32OutVMaxLen, IMG_UINT32 ui32B, IMG_CHAR *pszFwV, IMG_UINT32 ui32V, IMG_UINT32 ui32N, IMG_UINT32 ui32C) { IMG_UINT32 i = ui32OutVMaxLen; IMG_CHAR *pszPointer; *pui32OutBNC = (((ui32B & 0xFF) << 16) | ((ui32N & 0xFF) << 8) | (ui32C & 0xFF)); for (i = 0; i < (ui32OutVMaxLen + 1); i++) pszOutV[i] = '\0'; /* find out whether pszFwV is integer number or not */ pszPointer = pszFwV; while (*pszPointer) { if ((*pszPointer < '0') || (*pszPointer > '9')) { break; } pszPointer++; } if (*pszPointer) { /* pszFwV is not a number, so taking V from it */ pszPointer = pszFwV; while ((ui32OutVMaxLen > 0) && *pszPointer) { *pszOutV++ = *pszPointer++; ui32OutVMaxLen--; } } else { /* pszFwV is a number, taking V from ui32V */ IMG_CHAR aszBuf[4]; pszPointer = aszBuf; if (ui32V > 99) pszPointer+=3; else if (ui32V > 9) pszPointer+=2; else pszPointer+=1; *pszPointer-- = '\0'; *pszPointer = '0'; while (ui32V > 0) { *pszPointer-- = (ui32V % 10) + '0'; ui32V /= 10; } pszPointer = aszBuf; while ((ui32OutVMaxLen > 0) && *pszPointer) { *pszOutV++ = *pszPointer++; ui32OutVMaxLen--; } } }
30.759036
129
0.648257
babc0e0edcc9e9b38276f27f1b30bafd03957ff4
1,025
c
C
meta.c
etale-cohomology/xcb
8974b070968ff37a46f7d5f763f1881510abde22
[ "Unlicense" ]
2
2019-03-14T12:16:07.000Z
2021-01-13T15:31:54.000Z
meta.c
etale-cohomology/xcb
8974b070968ff37a46f7d5f763f1881510abde22
[ "Unlicense" ]
null
null
null
meta.c
etale-cohomology/xcb
8974b070968ff37a46f7d5f763f1881510abde22
[ "Unlicense" ]
null
null
null
// gcc meta.c -o meta -lxcb && ./meta #include <mathisart.h> #include <xcb/xcb.h> // ------------------------------------------------------------------------------------------------ struct App{ xcb_connection_t* connection; xcb_screen_iterator_t screen_iter; }; void m_app_init(struct App* app){ puts("Connecting to the X server through XCB!"); app->connection = xcb_connect(NULL, NULL); app->screen_iter = xcb_setup_roots_iterator(xcb_get_setup(app->connection)); xcb_screen_t* screen = app->screen_iter.data; printf("root %u %ux%u:%u b %x w %x allowed_depths %u\n", screen->root, screen->width_in_pixels, screen->height_in_pixels, screen->root_depth, screen->black_pixel, screen->white_pixel,screen->allowed_depths_len); } void m_app_exit(struct App* app){ xcb_disconnect(app->connection); m_exit_success(); } // ------------------------------------------------------------------------------------------------ int main(){ struct App app; m_app_init(&app); m_app_exit(&app); }
26.282051
99
0.572683
a77364b28edff3304b2ef66f8cb7ed8d76d9e112
7,092
h
C
engine/include/Render/Animation.h
Vbif/geometric-diversity
6e9d5a923db68acb14a0a603bd2859f4772db201
[ "MIT" ]
null
null
null
engine/include/Render/Animation.h
Vbif/geometric-diversity
6e9d5a923db68acb14a0a603bd2859f4772db201
[ "MIT" ]
null
null
null
engine/include/Render/Animation.h
Vbif/geometric-diversity
6e9d5a923db68acb14a0a603bd2859f4772db201
[ "MIT" ]
null
null
null
//**************************************************************************************** // Класс Animation // // Реализует спрайтовую анимацию. Карта анимации должна располагаться в // файле BMP,GIF (не анимированный),TGA,JPG или PNG. Кадры в файле должны размещаться // начиная от левого верхнего угла текстуры (кадр 0) и далее слева направо построчно. // // Объекты описываются в xml-файле с помощью элемента <Animation id="Gobot" texture="#GobotTex">: // АТРИБУТЫ : // id - идентификатор объекта; // texture - идентификатор текстуры карты анимации (Текстура может быть также описана в ресурсах (элемент texture2D). // размеры текстуры ДОЛЖНЫ БЫТЬ степенью 2) // // Дочерние элеметы <Animation> // // 1. <frames width="73" height="81" count="6" first="1" last="5"/> // - width - ширина одного кадра // - height - высота одного кадра // - count - количество кадров // - first - номер первого проигрываемого кадра (при нереверсивном воспроизведении) // - last - номер последнего проигрываемого кадра (при нереверсивном проигрывании) // 2. <playback fps="5" play="1" loop="1" forward="0" pingpong="1"/> // - fps - скорость воспроизведения (кадров в секунду) // - play - воспроизводить анимацию? // - loop - зациклить проигрывание? // - forward - воспроизводить, начиная с кадра 0 (вперед)? // - pingpong - воспроизводить в стиле "пинг-понг"? //**************************************************************************************** #ifndef _RENDER_ANIMATION_H_ #define _RENDER_ANIMATION_H_ #define ANIM_FWD 0 #define ANIM_REV 1 #define ANIM_PINGPONG 2 #define ANIM_NOPINGPONG 0 #define ANIM_LOOP 4 #define ANIM_NOLOOP 0 #include "Render/Texture.h" #include "Render/Sheet.h" #include "Render/RenderFunc.h" #include "Core/Resource.h" namespace Render { typedef boost::intrusive_ptr<class Animation> AnimationPtr; /// Класс анимации. /// Задаётся в описании ресурсов в виде кода подобного следующему: /// \code /// <animation id="GearAnimation" texture="#GearTexture"> /// <frames width="32" height="32" count="8" first="0" last="7"/> /// <playback fps="24" play="1" loop="1" forward="0" pingpong="0"/> /// </animation> /// \endcode /// Данное описание подходит для анимации сложенной в текстуре и упорядоченной по размеру. /// Для анимации в виде отдельных кадров задаётся путь к файлам кадров, сами кадры упорядочиваются по алфавиту. /// \code /// <animation id="FishMoveAnimation" path="animations\fish_move"> /// <playback fps="24" play="1" loop="1" forward="1" pingpong="0"/> /// </animation> /// \endcode class Animation : public Resource { public: Animation(); explicit Animation(rapidxml::xml_node<>* elem); virtual Animation* Clone() const; const std::string& GetName() const { return _id; } size_t GetMemoryInUse() const; void Load(ResourceLoadMode load_mode); void Unload(ResourceLoadMode load_mode); void GroupLoad(ResourceLoadManager& glm); void GroupUnload(ResourceLoadManager& glm); void Upload(bool bCleanAfterUpload = true); void Bind(int channel = 0, int stageOp = 0); void setFilteringType(FilteringType type); void setAddressMode(AddressMode mode); void Draw(SpriteBatch* batch = nullptr); void Draw(const IPoint& position, SpriteBatch* batch = nullptr); void Update(float dt); void setCurrentFrame(int iFrame); void setFirstPlayedFrame(int iFrame); void setLastPlayedFrame(int iFrame); void setMode(int iMode); void setSpeed(float fFPS); void setPlayback(bool bPlayback); void setLoop(bool looped); /// Устанавливает режим смешивания текущего кадра со следующим. /// Поддерживаются режимы 0 (выкл.), 1, 2, 3 и, самое главное, 4. void setAlphaBlend(int blendMode) { _alphaBlend = blendMode; } bool IsPlaying() const { return _bIsPlaying; } bool IsFinished() const { return !_bIsPlaying || _isFinished; } int getMode() const { return _iMode; } float getSpeed() const { return 1.0f / _fSpeed; } int getCurrentFrame() const { return _iCurrentFrame; } int getFirstPlayedFrame() const { return _iFirstPlayedFrame; } int getLastPlayedFrame() const { return _iLastPlayedFrame; } int getFrameWidth() const { return _iFrameWidth; } int getFrameHeight() const { return _iFrameHeight; } int getFramesCount() const { return _iFramesCount; } FRect getFrameUV() const; void MoveTo(const IPoint& point); float getTimeSinceLastFrameChange() const { return _fSinceChangeTime; } /// идентификатор анимации, считанный из xml const std::string& GetId() const; bool GetMirrored() const; /// рисовать горизонтально отражённую анимацию /// влияет на Draw void SetMirrored(bool m); virtual bool isPixelTransparent(int x, int y); bool isPixelOpaque(int x, int y) { return !isPixelTransparent(x, y); } bool isPixelOpaque(const IPoint& p) { return !isPixelTransparent(p.x, p.y); } /// Указывает нужно ли трансформировать текстурные координаты. Если да, то необходимо вызвать TranslateUV перед отрисовкой. virtual bool needTranslate(); /// Трансформация текстурных координат. virtual void TranslateUV(FRect &rect, FRect &uv); void GetFrameUVRect(FRect& rect) const; void GetFrameTexRect(FRect& rect) const; Render::Texture* GetTexture() const; static AnimationPtr Spawn(const std::string& id); protected: /// Вспомогательные функции для инициализации. void InitFromTexture(const std::string& texId, EnginePixelType pixelType, bool useDithering); void InitFromSheet(const std::string& path, EnginePixelType pixelType, bool useDithering); void InitFromSheet(const std::string& sheetId); void InitFromPath(const std::string& path, const std::string& basename, EnginePixelType pixelType, bool useDithering); void setFirstFrame(int iFrame); void setLastFrame(int iFrame); protected: /// Если используется одна текстура Render::TexturePtr _texMap; /// Если используется путь, содержащий множество текстур (каждый кадр отдельно) std::vector<Render::TexturePtr> _texArray; /// Если используются кадры запакованные в полотнище Render::SheetPtr _sheet; /// Текущая текстура из полотнища Render::Texture *_sheet_texture, *_sheet_next_texture; IPoint _position; int _iFrameWidth; int _iFrameHeight; int _iFramesCount; int _iCurrentFrame; int _iFirstPlayedFrame; int _iLastPlayedFrame; int _iFirstFrame; int _iLastFrame; int _iAllFramesCount; bool _bIsPlaying; /// устанавливается в true при пересечении границы анимации bool _isFinished; float _fSpeed; /// время, прошедшее с последней смены кадра float _fSinceChangeTime; /// координаты кадра в текстуре FRect _uv, _uvNext; /// доля одного кадра в текстуре (ширина и высота) float _fXFramePerTex, _fYFramePerTex; /// направление воспроизведения int _iDelta; /// режим воспроизведения int _iMode; /// идентификатор анимации, считанный из xml std::string _id; std::string _group; /// рисовать горизонтально отражённую анимацию bool _mirrored; /// режим смешивания текущего кадра со следующим int _alphaBlend; }; } #endif
32.53211
125
0.710237
4418e5def5ed9d17ed313f08341b8a45ce37e592
101
h
C
test/SourceKit/Inputs/vfs/CModule/CModule.h
lwhsu/swift
e1e7a3fe75b4762d5e3d4d241f40b56946a03fdb
[ "Apache-2.0" ]
72,551
2015-12-03T16:45:13.000Z
2022-03-31T18:57:59.000Z
test/SourceKit/Inputs/vfs/CModule/CModule.h
lwhsu/swift
e1e7a3fe75b4762d5e3d4d241f40b56946a03fdb
[ "Apache-2.0" ]
39,352
2015-12-03T16:55:06.000Z
2022-03-31T23:43:41.000Z
test/SourceKit/Inputs/vfs/CModule/CModule.h
lwhsu/swift
e1e7a3fe75b4762d5e3d4d241f40b56946a03fdb
[ "Apache-2.0" ]
13,845
2015-12-03T16:45:13.000Z
2022-03-31T11:32:29.000Z
struct StructDefinedInCModule { int intFieldDefinedInCModule; }; void functionDefinedInCModule();
16.833333
32
0.821782
d55991ec6a0ed6c405b99f949966f13a5f275854
351
c
C
d/undead/rooms/weapon_storage.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/undead/rooms/weapon_storage.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/undead/rooms/weapon_storage.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#include <std.h>; #include "../undead.h" inherit "/d/darkwood/tabor/include/weapon_storage"; void create() { ::create(); set_name("Graez weaponsmith storage"); set_short("Graez weaponsmith storage"); set_long("Storage room for Graez's weaponsmith."); set_property("no teleport",1); set_exits(([ "out":TOWN"weapons", ])); }
21.9375
53
0.65812
170ee4a301c26a1f1a965e103a52204182a2a3d7
2,600
c
C
multiprocess_echo_server/src/echo_server.c
bishil06/echo_chat
4d5a164ecfac1027d780a0407ec7602f1c6de50f
[ "MIT" ]
null
null
null
multiprocess_echo_server/src/echo_server.c
bishil06/echo_chat
4d5a164ecfac1027d780a0407ec7602f1c6de50f
[ "MIT" ]
null
null
null
multiprocess_echo_server/src/echo_server.c
bishil06/echo_chat
4d5a164ecfac1027d780a0407ec7602f1c6de50f
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <sys/wait.h> #include <arpa/inet.h> #include <sys/socket.h> #include "validateInput.h" #define BUF_SIZE 1024 void error_handling(char *msg) { fprintf(stderr, "%s \n", msg); exit(1); } void endChildAction(int sig) { int status = 0; pid_t pid = waitpid(-1, &status, WNOHANG); if (WIFEXITED(status)) { printf("pid = %d child process success\n", pid); } else { printf("pid = %d child process fail\n", pid); } printf("child process return %d\n", WEXITSTATUS(status)); } int main(int argc, char *argv[]) { char *port = ""; bool check = validateInputServer(argc, argv, &port); if (check == false) { exit(1); } // 자식프로세스 처리 시그널 추가 struct sigaction act = { 0, }; act.sa_handler = endChildAction; act.sa_flags = 0; sigemptyset(&act.sa_mask); int state = sigaction(SIGCHLD, &act, 0); // 소켓 생성 int serv_sock = -1; serv_sock=socket(PF_INET, SOCK_STREAM, 0); if (serv_sock == -1) { error_handling("socket() error"); } // 소켓 주소 설정 struct sockaddr_in serv_addr = { 0, }; serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=htonl(INADDR_ANY); serv_addr.sin_port=htons(atoi(port)); if (bind(serv_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1) { error_handling("bind() error"); } if (listen(serv_sock, 5) == -1) { error_handling("listen() error"); } printf("server listenning %s port\n", port); while (true) { struct sockaddr_in clnt_addr = { 0, }; socklen_t clnt_addr_size = sizeof(clnt_addr); int clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_addr, &clnt_addr_size); if (clnt_sock == -1) { // fprintf(stderr, "accpet() error\n"); continue; } else { printf("new client connected ...\n"); } pid_t pid = fork(); if (pid == -1) { close(clnt_sock); continue; } if (pid == 0) { close(serv_sock); int str_len = 0; char buf[BUF_SIZE] = { 0, }; while (true) { str_len = read(clnt_sock, buf, BUF_SIZE); if (str_len == 0) { break; } write(clnt_sock, buf, str_len); } close(clnt_sock); printf("client disconnected ...\n"); return 0; } } return 0; }
25.490196
90
0.538846
3befbe50b9297f1e5f7140731b8bf130b42e2680
88
h
C
ext/hal/altera/include/sys/alt_debug.h
dmgerman/zephyrd3
b6a23cc9c5d534c352e33fd18fff7799ac3c2886
[ "Apache-2.0" ]
null
null
null
ext/hal/altera/include/sys/alt_debug.h
dmgerman/zephyrd3
b6a23cc9c5d534c352e33fd18fff7799ac3c2886
[ "Apache-2.0" ]
null
null
null
ext/hal/altera/include/sys/alt_debug.h
dmgerman/zephyrd3
b6a23cc9c5d534c352e33fd18fff7799ac3c2886
[ "Apache-2.0" ]
null
null
null
DECL|ALT_DEBUG_ASSERT|macro|ALT_DEBUG_ASSERT DECL|__ALT_DEBUG_H__|macro|__ALT_DEBUG_H__
29.333333
44
0.909091
f35bfc7f19046461a7b0264a8404a670c8471f5c
201
h
C
MyLiveProject/MyLiveProject/Classes/Helper/Tools/BRUserHelper.h
renboss/MyLiveProject
2a2dfcda5ce2c742bf82a75b8bac42bba88346f3
[ "Apache-2.0" ]
291
2017-02-10T02:15:47.000Z
2018-03-06T08:11:37.000Z
MyLiveProject/MyLiveProject/Classes/Helper/Tools/BRUserHelper.h
91renb/MyLiveProject
2a2dfcda5ce2c742bf82a75b8bac42bba88346f3
[ "Apache-2.0" ]
null
null
null
MyLiveProject/MyLiveProject/Classes/Helper/Tools/BRUserHelper.h
91renb/MyLiveProject
2a2dfcda5ce2c742bf82a75b8bac42bba88346f3
[ "Apache-2.0" ]
15
2018-03-11T13:19:54.000Z
2019-12-11T14:19:44.000Z
// // BRUserHelper.h // MyLiveProject // // Created by 任波 on 17/4/3. // Copyright © 2017年 RENB. All rights reserved. // #import <Foundation/Foundation.h> @interface BRUserHelper : NSObject @end
14.357143
48
0.681592
4a23d7e264f32d33ae6e8a1e9ef44c6f586274aa
1,802
h
C
upwork-devs/son-ha/c-icap/c-icap/include/hash.h
anejaalekh/s-k8-proxy-rebuild
bd690ece306ba8ae81ce027e5fb8ee933cce1748
[ "Apache-2.0" ]
null
null
null
upwork-devs/son-ha/c-icap/c-icap/include/hash.h
anejaalekh/s-k8-proxy-rebuild
bd690ece306ba8ae81ce027e5fb8ee933cce1748
[ "Apache-2.0" ]
null
null
null
upwork-devs/son-ha/c-icap/c-icap/include/hash.h
anejaalekh/s-k8-proxy-rebuild
bd690ece306ba8ae81ce027e5fb8ee933cce1748
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2004-2008 Christos Tsantilas * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. */ #ifndef __HASH_H #define __HASH_H #include "c-icap.h" #include "lookup_table.h" #include "mem.h" #ifdef __cplusplus extern "C" { #endif struct ci_hash_entry { unsigned int hash; const void *key; const void *val; struct ci_hash_entry *hnext; }; struct ci_hash_table { struct ci_hash_entry **hash_table; unsigned int hash_table_size; const ci_type_ops_t *ops; ci_mem_allocator_t *allocator; }; CI_DECLARE_FUNC(unsigned int) ci_hash_compute(unsigned long hash_max_value, const void *key, int len); CI_DECLARE_FUNC(struct ci_hash_table *) ci_hash_build(unsigned int hash_size, const ci_type_ops_t *ops, ci_mem_allocator_t *allocator); CI_DECLARE_FUNC(void) ci_hash_destroy(struct ci_hash_table *htable); CI_DECLARE_FUNC(const void *) ci_hash_search(struct ci_hash_table *htable,const void *key); CI_DECLARE_FUNC(void *) ci_hash_add(struct ci_hash_table *htable, const void *key, const void *val); #ifdef __cplusplus } #endif #endif
29.540984
102
0.743618
7d2efd63866d88e49230b088041c7a2696eabc07
771
c
C
tests/algorithm/check_node.c
benmandrew/c-networking
19cc83050b83ed2eeada5437022779c2c0d06e46
[ "MIT" ]
1
2021-12-08T22:48:45.000Z
2021-12-08T22:48:45.000Z
tests/algorithm/check_node.c
benmandrew/c-networking
19cc83050b83ed2eeada5437022779c2c0d06e46
[ "MIT" ]
null
null
null
tests/algorithm/check_node.c
benmandrew/c-networking
19cc83050b83ed2eeada5437022779c2c0d06e46
[ "MIT" ]
null
null
null
#include "test_inc.h" #include "algorithm/node_pi.h" START_TEST(test_node_init) { Node n; node_init(&n, 4); ck_assert_int_eq(n.n_neighbours, 4); } END_TEST START_TEST(test_node_local_alloc) { LocalNode n = node_local_alloc(1, 6, 5); ck_assert_int_eq(n.node.n_neighbours, 6); node_local_dealloc(&n); } END_TEST START_TEST(test_node_update_time) { Node n; node_init(&n, 1); struct timeval tv, res; gettimeofday(&tv, NULL); unsigned long long now = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000; node_update_time(&n); unsigned long long diff = n.timestamp - now; // Less than 3 millisecond difference // Chosen completely arbitrarily ck_assert_int_le(diff, 3); } END_TEST
20.837838
67
0.692607
a432023e599c67c9683b31cbc1b2ed814ddeed9f
3,418
h
C
uefi-sct/EMS/Src/EmsProtocol/EmsProtoArp.h
sunnywang-arm/edk2-test
475be9f7a70d012705eca64dd24a9eeaed643183
[ "BSD-2-Clause" ]
47
2018-10-15T02:34:39.000Z
2022-02-07T11:02:45.000Z
uefi-sct/EMS/Src/EmsProtocol/EmsProtoArp.h
sunnywang-arm/edk2-test
475be9f7a70d012705eca64dd24a9eeaed643183
[ "BSD-2-Clause" ]
null
null
null
uefi-sct/EMS/Src/EmsProtocol/EmsProtoArp.h
sunnywang-arm/edk2-test
475be9f7a70d012705eca64dd24a9eeaed643183
[ "BSD-2-Clause" ]
78
2018-10-08T01:17:19.000Z
2022-03-16T14:33:15.000Z
/** @file Copyright 2006 - 2010 Unified EFI, Inc.<BR> Copyright (c) 2010, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ /*++ Module Name: EmsProtoArp.h Abstract: Incude header files for protocol ARP --*/ #ifndef __EMS_ARP_H__ #define __EMS_ARP_H__ #define ARP_OPER_REQUEST 1 #define ARP_OPER_REPLY 2 #define ARP_OPER_REVREQUEST 3 #define ARP_OPER_REVREPLY 4 #define ARP_OPER_DRARP_REQUEST 5 #define ARP_OPER_DRARP_REPLY 6 #define ARP_OPER_DRARP_ERROR 7 #define ARP_OPER_INARP_REQUEST 8 #define ARP_OPER_INARP_REPLY 9 #define ARP_OPER_ARP_NAK 10 #define ARP_OPER_MARS_REQUEST 11 #define ARP_OPER_MARS_MULTI 12 #define ARP_OPER_MARS_MSERV 13 #define ARP_OPER_MARS_JOIN 14 #define ARP_OPER_MARS_LEAVE 15 #define ARP_OPER_MARS_UNSERV 16 #define ARP_OPER_MARS_SJOIN 17 #define ARP_OPER_MARS_SLEAVE 18 #define ARP_OPER_MARS_GRPLST_REQUEST 19 #define ARP_OPER_MARS_GRPLST_REPLY 20 #define ARP_OPER_MARS_GRPLST_MAP 21 #define ARP_OPER_MARS_REDIRECT_MAP 22 #define ARP_OPER_MAPOS_UNARP 23 #define ARP_HTYPE_ETHERNET 1 #define ARP_HTYPE_EXP_ETHERNET 2 #define ARP_HTYPE_AMATEUR_RADIO_AX25 3 #define ARP_HTYPE_PRONET_TOKEN_RING 4 #define ARP_HTYPE_CHAOS 5 #define ARP_HTYPE_IEEE802 6 #define ARP_HTYPE_ARCNET 7 #define ARP_HTYPE_HYPERCHANNEL 8 #define ARP_HTYPE_LANSTAR 9 #define ARP_HTYPE_AUTONET_SHORT_ADDR 10 #define ARP_HTYPE_LOCALTALK 11 #define ARP_HTYPE_LOCALNET 12 #define ARP_HTYPE_ULTRA_LINK 13 #define ARP_HTYPE_SMDS 14 #define ARP_HTYPE_FRAME_RELAY 15 #define ARP_HTYPE_ATM 16 #define ARP_HTYPE_HDLC 17 #define ARP_HTYPE_FIBRE_CHANNEL 18 #define ARP_HTYPE_ATM2 19 #define ARP_HTYPE_SERIAL_LINE 20 #define ARP_HTYPE_ATM3 21 #define ARP_HTYPE_MIL_STD 22 #define ARP_HTYPE_METRICOM 23 #define ARP_HTYPE_IEEE1394 24 #define ARP_HTYPE_MAPOS 25 #define ARP_HTYPE_TWINAXIAL 26 #define ARP_HTYPE_EUI_64 27 #define ARP_HTYPE_HIPARP 28 #define ARP_HTYPE_ISO7816_3 29 #define ARP_HTYPE_ARPSEC 30 #define ARP_HTYPE_IPSEC_TUNNEL 31 #define ARP_HTYPE_INFINIBAND 32 #define ARP_PTYPE_IP 0x0800 #define DEF_HTYPE ARP_HTYPE_ETHERNET #define DEF_PTYPE ARP_PTYPE_IP #define DEF_HLEN 6 #define DEF_PLEN 4 extern PROTOCOL_ENTRY_T ArpProtocol; typedef struct _ARP_HEADER { UINT16 HType; UINT16 PType; UINT8 HLen; UINT8 PLen; UINT16 Oper; UINT8 Sha[6]; UINT8 Spa[4]; UINT8 Tha[6]; UINT8 Tpa[4]; } ARP_HEADER; #endif
31.357798
85
0.664131
d12b0171bc60c7708f54f5cab6d94316975eb0e5
1,386
h
C
adventures-of-orchi/adventures-of-orchi/InfoPanel/InfoPanel.h
rmbernardi/game-project-stage-3
201cfd165281782de77b17d06fdfa95e068b7fcf
[ "Apache-2.0" ]
null
null
null
adventures-of-orchi/adventures-of-orchi/InfoPanel/InfoPanel.h
rmbernardi/game-project-stage-3
201cfd165281782de77b17d06fdfa95e068b7fcf
[ "Apache-2.0" ]
null
null
null
adventures-of-orchi/adventures-of-orchi/InfoPanel/InfoPanel.h
rmbernardi/game-project-stage-3
201cfd165281782de77b17d06fdfa95e068b7fcf
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016 Richard Bernardino 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. */ #pragma once #include "pch.h" #include "Constants.h" #include "Common\DeviceResources.h" #include "Common\DirectXHelper.h" using namespace DirectX; using namespace Microsoft::WRL; using namespace DX; using namespace std; using namespace Platform; class InfoPanel { public: void CreateText( String ^ text, float2 fWindowSize, const shared_ptr<DeviceResources>& deviceResources); void DrawText( float fLeft, float fTop, float fRight, const shared_ptr<DeviceResources>& deviceResources); void DrawBox( float fLeft, float fTop, float fRight, float fBottom, const shared_ptr<DeviceResources>& deviceResources); virtual void Render(const shared_ptr<DeviceResources>& deviceResources) = 0; protected: ComPtr<IDWriteTextLayout1> m_textLayout; DWRITE_TEXT_RANGE m_textRange; private: };
23.491525
77
0.776335
006b45b960054a90b8354382b708ba17f6397378
811
h
C
gadgets/epi/OneEncodingGadget.h
roopchansinghv/gadgetron
fb6c56b643911152c27834a754a7b6ee2dd912da
[ "MIT" ]
1
2022-02-22T21:06:36.000Z
2022-02-22T21:06:36.000Z
gadgets/epi/OneEncodingGadget.h
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
gadgets/epi/OneEncodingGadget.h
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
/** \file OneEncodingGadget.h \brief This is the class gadget to make sure EPI Flash Ref lines are in the same encoding space as the imaging lines. \author Hui Xue */ #ifndef ONEENCODINGGADGET_H #define ONEENCODINGGADGET_H #include "Gadget.h" #include "hoNDArray.h" #include "gadgetron_epi_export.h" #include <ismrmrd/ismrmrd.h> #include <complex> namespace Gadgetron { class EXPORTGADGETS_EPI OneEncodingGadget : public Gadget2<ISMRMRD::AcquisitionHeader, hoNDArray< std::complex<float> > > { public: OneEncodingGadget(); virtual ~OneEncodingGadget(); protected: virtual int process(GadgetContainerMessage< ISMRMRD::AcquisitionHeader>* m1, GadgetContainerMessage< hoNDArray< std::complex<float> > >* m2); }; } #endif // ONEENCODINGGADGET_H
26.16129
149
0.718866
00c6fc19c5aa36b60e39398cc683b3349b3d59ec
7,035
h
C
codegentemp/RS_485_Dir.h
glenn-edgar/POS4_MOISTURE_SENSOR
db35ebea352e51602212d6531abd24c907cd1981
[ "MIT" ]
null
null
null
codegentemp/RS_485_Dir.h
glenn-edgar/POS4_MOISTURE_SENSOR
db35ebea352e51602212d6531abd24c907cd1981
[ "MIT" ]
null
null
null
codegentemp/RS_485_Dir.h
glenn-edgar/POS4_MOISTURE_SENSOR
db35ebea352e51602212d6531abd24c907cd1981
[ "MIT" ]
null
null
null
/******************************************************************************* * File Name: RS_485_Dir.h * Version 2.20 * * Description: * This file contains Pin function prototypes and register defines * ******************************************************************************** * Copyright 2008-2015, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #if !defined(CY_PINS_RS_485_Dir_H) /* Pins RS_485_Dir_H */ #define CY_PINS_RS_485_Dir_H #include "cytypes.h" #include "cyfitter.h" #include "RS_485_Dir_aliases.h" /*************************************** * Data Struct Definitions ***************************************/ /** * \addtogroup group_structures * @{ */ /* Structure for sleep mode support */ typedef struct { uint32 pcState; /**< State of the port control register */ uint32 sioState; /**< State of the SIO configuration */ uint32 usbState; /**< State of the USBIO regulator */ } RS_485_Dir_BACKUP_STRUCT; /** @} structures */ /*************************************** * Function Prototypes ***************************************/ /** * \addtogroup group_general * @{ */ uint8 RS_485_Dir_Read(void); void RS_485_Dir_Write(uint8 value); uint8 RS_485_Dir_ReadDataReg(void); #if defined(RS_485_Dir__PC) || (CY_PSOC4_4200L) void RS_485_Dir_SetDriveMode(uint8 mode); #endif void RS_485_Dir_SetInterruptMode(uint16 position, uint16 mode); uint8 RS_485_Dir_ClearInterrupt(void); /** @} general */ /** * \addtogroup group_power * @{ */ void RS_485_Dir_Sleep(void); void RS_485_Dir_Wakeup(void); /** @} power */ /*************************************** * API Constants ***************************************/ #if defined(RS_485_Dir__PC) || (CY_PSOC4_4200L) /* Drive Modes */ #define RS_485_Dir_DRIVE_MODE_BITS (3) #define RS_485_Dir_DRIVE_MODE_IND_MASK (0xFFFFFFFFu >> (32 - RS_485_Dir_DRIVE_MODE_BITS)) /** * \addtogroup group_constants * @{ */ /** \addtogroup driveMode Drive mode constants * \brief Constants to be passed as "mode" parameter in the RS_485_Dir_SetDriveMode() function. * @{ */ #define RS_485_Dir_DM_ALG_HIZ (0x00u) /**< \brief High Impedance Analog */ #define RS_485_Dir_DM_DIG_HIZ (0x01u) /**< \brief High Impedance Digital */ #define RS_485_Dir_DM_RES_UP (0x02u) /**< \brief Resistive Pull Up */ #define RS_485_Dir_DM_RES_DWN (0x03u) /**< \brief Resistive Pull Down */ #define RS_485_Dir_DM_OD_LO (0x04u) /**< \brief Open Drain, Drives Low */ #define RS_485_Dir_DM_OD_HI (0x05u) /**< \brief Open Drain, Drives High */ #define RS_485_Dir_DM_STRONG (0x06u) /**< \brief Strong Drive */ #define RS_485_Dir_DM_RES_UPDWN (0x07u) /**< \brief Resistive Pull Up/Down */ /** @} driveMode */ /** @} group_constants */ #endif /* Digital Port Constants */ #define RS_485_Dir_MASK RS_485_Dir__MASK #define RS_485_Dir_SHIFT RS_485_Dir__SHIFT #define RS_485_Dir_WIDTH 1u /** * \addtogroup group_constants * @{ */ /** \addtogroup intrMode Interrupt constants * \brief Constants to be passed as "mode" parameter in RS_485_Dir_SetInterruptMode() function. * @{ */ #define RS_485_Dir_INTR_NONE ((uint16)(0x0000u)) /**< \brief Disabled */ #define RS_485_Dir_INTR_RISING ((uint16)(0x5555u)) /**< \brief Rising edge trigger */ #define RS_485_Dir_INTR_FALLING ((uint16)(0xaaaau)) /**< \brief Falling edge trigger */ #define RS_485_Dir_INTR_BOTH ((uint16)(0xffffu)) /**< \brief Both edge trigger */ /** @} intrMode */ /** @} group_constants */ /* SIO LPM definition */ #if defined(RS_485_Dir__SIO) #define RS_485_Dir_SIO_LPM_MASK (0x03u) #endif /* USBIO definitions */ #if !defined(RS_485_Dir__PC) && (CY_PSOC4_4200L) #define RS_485_Dir_USBIO_ENABLE ((uint32)0x80000000u) #define RS_485_Dir_USBIO_DISABLE ((uint32)(~RS_485_Dir_USBIO_ENABLE)) #define RS_485_Dir_USBIO_SUSPEND_SHIFT CYFLD_USBDEVv2_USB_SUSPEND__OFFSET #define RS_485_Dir_USBIO_SUSPEND_DEL_SHIFT CYFLD_USBDEVv2_USB_SUSPEND_DEL__OFFSET #define RS_485_Dir_USBIO_ENTER_SLEEP ((uint32)((1u << RS_485_Dir_USBIO_SUSPEND_SHIFT) \ | (1u << RS_485_Dir_USBIO_SUSPEND_DEL_SHIFT))) #define RS_485_Dir_USBIO_EXIT_SLEEP_PH1 ((uint32)~((uint32)(1u << RS_485_Dir_USBIO_SUSPEND_SHIFT))) #define RS_485_Dir_USBIO_EXIT_SLEEP_PH2 ((uint32)~((uint32)(1u << RS_485_Dir_USBIO_SUSPEND_DEL_SHIFT))) #define RS_485_Dir_USBIO_CR1_OFF ((uint32)0xfffffffeu) #endif /*************************************** * Registers ***************************************/ /* Main Port Registers */ #if defined(RS_485_Dir__PC) /* Port Configuration */ #define RS_485_Dir_PC (* (reg32 *) RS_485_Dir__PC) #endif /* Pin State */ #define RS_485_Dir_PS (* (reg32 *) RS_485_Dir__PS) /* Data Register */ #define RS_485_Dir_DR (* (reg32 *) RS_485_Dir__DR) /* Input Buffer Disable Override */ #define RS_485_Dir_INP_DIS (* (reg32 *) RS_485_Dir__PC2) /* Interrupt configuration Registers */ #define RS_485_Dir_INTCFG (* (reg32 *) RS_485_Dir__INTCFG) #define RS_485_Dir_INTSTAT (* (reg32 *) RS_485_Dir__INTSTAT) /* "Interrupt cause" register for Combined Port Interrupt (AllPortInt) in GSRef component */ #if defined (CYREG_GPIO_INTR_CAUSE) #define RS_485_Dir_INTR_CAUSE (* (reg32 *) CYREG_GPIO_INTR_CAUSE) #endif /* SIO register */ #if defined(RS_485_Dir__SIO) #define RS_485_Dir_SIO_REG (* (reg32 *) RS_485_Dir__SIO) #endif /* (RS_485_Dir__SIO_CFG) */ /* USBIO registers */ #if !defined(RS_485_Dir__PC) && (CY_PSOC4_4200L) #define RS_485_Dir_USB_POWER_REG (* (reg32 *) CYREG_USBDEVv2_USB_POWER_CTRL) #define RS_485_Dir_CR1_REG (* (reg32 *) CYREG_USBDEVv2_CR1) #define RS_485_Dir_USBIO_CTRL_REG (* (reg32 *) CYREG_USBDEVv2_USB_USBIO_CTRL) #endif /*************************************** * The following code is DEPRECATED and * must not be used in new designs. ***************************************/ /** * \addtogroup group_deprecated * @{ */ #define RS_485_Dir_DRIVE_MODE_SHIFT (0x00u) #define RS_485_Dir_DRIVE_MODE_MASK (0x07u << RS_485_Dir_DRIVE_MODE_SHIFT) /** @} deprecated */ #endif /* End Pins RS_485_Dir_H */ /* [] END OF FILE */
37.222222
113
0.59602
2e079ac91a8d0ad6f8604325df4ea710bf39864c
793
h
C
Visual Mercutio/zConversion/zConversionRes.h
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zConversion/zConversionRes.h
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zConversion/zConversionRes.h
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> zConversionRes ------------------------------------------------------* **************************************************************************** * Description : zConversion global resources file * * Developer : Processsoft * ****************************************************************************/ // next default values for new objects #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 28000 #define _APS_NEXT_COMMAND_VALUE 28000 #define _APS_NEXT_CONTROL_VALUE 28000 #define _APS_NEXT_SYMED_VALUE 28000 #endif #endif
46.647059
79
0.380832
44a83ccfc3e9c796ee186678156e5e0408e2488e
7,104
c
C
src/du_app/du_mgr_ex_ms.c
copslock/o-ran_o-du_l2
2e947aab8340b0f2cced69217f2378badeb716f2
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
src/du_app/du_mgr_ex_ms.c
copslock/o-ran_o-du_l2
2e947aab8340b0f2cced69217f2378badeb716f2
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
src/du_app/du_mgr_ex_ms.c
copslock/o-ran_o-du_l2
2e947aab8340b0f2cced69217f2378badeb716f2
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
/******************************************************************************* ################################################################################ # Copyright (c) [2017-2019] [Radisys] # # # # 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. # ################################################################################ *******************************************************************************/ /* This file contains message handling functionality for DU cell management */ #include "du_sctp.h" #include "f1ap_msg_hdl.h" extern S16 cmUnpkLkwCfgCfm(LkwCfgCfm func,Pst *pst, Buffer *mBuf); extern S16 cmUnpkLkwCntrlCfm(LkwCntrlCfm func,Pst *pst, Buffer *mBuf); extern S16 cmUnpkLrgCfgCfm(LrgCfgCfm func,Pst *pst, Buffer *mBuf); /************************************************************************** * @brief Task Initiation callback function. * * @details * * Function : duActvInit * * Functionality: * This function is supplied as one of parameters during DU APP's * task registration. SSI will invoke this function once, after * it creates and attaches this TAPA Task to a system task. * * @param[in] Ent entity, the entity ID of this task. * @param[in] Inst inst, the instance ID of this task. * @param[in] Region region, the region ID registered for memory * usage of this task. * @param[in] Reason reason. * @return ROK - success * RFAILED - failure ***************************************************************************/ S16 duActvInit(Ent entity, Inst inst, Region region, Reason reason) { duCb.init.procId = SFndProcId(); duCb.init.ent = entity; duCb.init.inst = inst; duCb.init.region = region; duCb.init.reason = reason; duCb.init.cfgDone = FALSE; duCb.init.pool = DU_POOL; duCb.init.acnt = FALSE; duCb.init.trc = FALSE; duCb.init.usta = TRUE; duCb.mem.region = DFLT_REGION; duCb.mem.pool = DU_POOL; duCb.sctpStatus = FALSE; duCb.f1Status = FALSE; duCb.duStatus = FALSE; SSetProcId(DU_PROC); return ROK; } /************************************************************************** * @brief Task Activation callback function. * * @details * * Function : duActvTsk * * Functionality: * Primitives invoked by DU APP's users/providers through * a loosely coupled interface arrive here by means of * SSI's message handling. This API is registered with * SSI during the Task Registration of DU APP. * * @param[in] Pst *pst, Post structure of the primitive. * @param[in] Buffer *mBuf, Packed primitive parameters in the * buffer. * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duActvTsk(Pst *pst, Buffer *mBuf) { S16 ret = ROK; switch(pst->srcEnt) { case ENTDUAPP: { switch(pst->event) { case EVTCFG: { duSendRlcUlCfg(); SPutMsg(mBuf); break; } default: { printf("\nInvalid event received at duActvTsk from ENTDUAPP"); SPutMsg(mBuf); ret = RFAILED; } } break; } case ENTKW: { switch(pst->event) { case LKW_EVT_CFG_CFM: { ret = cmUnpkLkwCfgCfm(duHdlRlcCfgComplete, pst, mBuf); break; } case LKW_EVT_CNTRL_CFM: { ret = cmUnpkLkwCntrlCfm(duHdlRlcCntrlCfgComplete, pst, mBuf); break; } case LKW_EVT_STA_IND: { break; } default: { printf("\nInvalid event %d received at duActvTsk from ENTKW", \ pst->event); SPutMsg(mBuf); ret = RFAILED; } } break; } case ENTRG: { switch(pst->event) { //Config complete case EVTCFG: { SPutMsg(mBuf); break; } case EVTLRGCFGCFM: { ret = cmUnpkLrgCfgCfm(duHdlMacCfgComplete, pst, mBuf); break; } case EVTLRGCNTRLCFM: { break; } default: { printf("\nInvalid event received at duActvTsk from ENTRG"); SPutMsg(mBuf); ret = RFAILED; } } break; } case ENTSCTP: { switch(pst->event) { case EVTSCTPDATA: { F1InmsgHdlr(mBuf); break; } case EVTSCTPNTFY: { ret = cmUnpkSctpNtfy(duSctpNtfyHdl, pst, mBuf); break; } default: { printf("\nInvalid event received at duActvTsk from ENTRG"); ret = RFAILED; } } SPutMsg(mBuf); break; } default: { printf("\n DU APP can not process message from Entity %d", pst->srcEnt); SPutMsg(mBuf); ret = RFAILED; } } SExitTsk(); return ret; } /********************************************************************** End of file **********************************************************************/
33.04186
84
0.400619
cd30cb7c61856446eb287031dd111a2166ff2c41
497
h
C
qqtw/qqheaders7.2/StackInfo.h
onezens/QQTweak
04b9efd1d93eba8ef8fec5cf9a20276637765777
[ "MIT" ]
5
2018-02-20T14:24:17.000Z
2020-08-06T09:31:21.000Z
qqtw/qqheaders7.2/StackInfo.h
onezens/QQTweak
04b9efd1d93eba8ef8fec5cf9a20276637765777
[ "MIT" ]
1
2020-06-10T07:49:16.000Z
2020-06-12T02:08:35.000Z
qqtw/qqheaders7.2/StackInfo.h
onezens/SmartQQ
04b9efd1d93eba8ef8fec5cf9a20276637765777
[ "MIT" ]
null
null
null
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @class NSArray; @interface StackInfo : NSObject { int invokeTimes; int _invokeTimes; NSArray *_stack; } - (void)dealloc; - (id)initWithStack:(id)arg1 invokeTimes:(int)arg2; @property int invokeTimes; // @synthesize invokeTimes=_invokeTimes; @property(retain, nonatomic) NSArray *stack; // @synthesize stack=_stack; @end
19.88
83
0.692153
ffb834ee3987f3eb407f1070c9a40a067a716f4f
17,642
h
C
en/device-dev/apis/usb/usbd_client.h
acidburn0zzz/openharmony
f19488de6f7635f3171b1ad19a25e4844c0a24df
[ "CC-BY-4.0" ]
null
null
null
en/device-dev/apis/usb/usbd_client.h
acidburn0zzz/openharmony
f19488de6f7635f3171b1ad19a25e4844c0a24df
[ "CC-BY-4.0" ]
null
null
null
en/device-dev/apis/usb/usbd_client.h
acidburn0zzz/openharmony
f19488de6f7635f3171b1ad19a25e4844c0a24df
[ "CC-BY-4.0" ]
null
null
null
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @addtogroup USB * @{ * * @brief Declares USB-related APIs, including the custom data types and functions * used to obtain descriptors, interface objects, and request objects, and to submit requests. * * @since 3.0 * @version 1.0 */ /** * @file usbd_client.h * * @brief Defines the usbd interface. * * @since 3.0 * @version 1.0 */ #ifndef USBD_CLIENT_H #define USBD_CLIENT_H #include "usb_param.h" #include "usbd_subscriber.h" namespace OHOS { namespace USB { class UsbdClient { public: /* * * @brief Opens a USB device to set up a connection. * * @param dev Indicates the USB device address. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t OpenDevice(const UsbDev &dev); /* * * @brief Closes a USB device to release all system resources related to the device. * * @param dev Indicates the USB device address. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t CloseDevice(const UsbDev &dev); /* * * @brief Obtains the USB device descriptor. * * @param dev Indicates the USB device address. * @param descriptor Indicates the USB device descriptor. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetDeviceDescriptor(const UsbDev &dev, std::vector<uint8_t> &decriptor); /* * * @brief Obtains the string descriptor of a USB device based on the specified string ID. * * @param dev Indicates the USB device address. * @param descId Indicates string descriptor ID. * @param descriptor Indicates the string descriptor of the USB device. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetStringDescriptor(const UsbDev &dev, uint8_t descId, std::vector<uint8_t> &decriptor); /* * * @brief Obtains the configuration descriptor of a USB device based on the specified config ID. * * @param dev Indicates the USB device address. * @param descId Indicates configuration descriptor ID. * @param descriptor Indicates the configuration descriptor of the USB device. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetConfigDescriptor(const UsbDev &dev, uint8_t descId, std::vector<uint8_t> &decriptor); /* * * @brief Obtains the raw descriptor. * * @param dev Indicates the USB device address. * @param descriptor Indicates the raw descriptor of the USB device. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetRawDescriptor(const UsbDev &dev, std::vector<uint8_t> &decriptor); /* * * @brief Sets the configuration information of a USB device. * * @param dev Indicates the USB device address. * @param configIndex Indicates the configuration information of the USB device. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t SetConfig(const UsbDev &dev, uint8_t configIndex); /* * * @brief Obtains the configuration information of a USB device. * * @param dev Indicates the USB device address. * @param configIndex Indicates the configuration information of the USB device. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetConfig(const UsbDev &dev, uint8_t &configIndex); /* * * @brief Claims a USB interface exclusively. This must be done before data transfer. * * @param dev Indicates the USB device address. * @param interfaceid Indicates the interface ID of the USB device. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t ClaimInterface(const UsbDev &dev, uint8_t interfaceid); /* * * @brief Releases a USB interface. This is usually done after data transfer. * * @param dev Indicates the USB device address. * @param interfaceid Indicates the interface ID of the USB device. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t ReleaseInterface(const UsbDev &dev, uint8_t interfaceid); /* * * @brief Sets the alternate settings for the specified USB interface. This allows you to switch between two interfaces with the same ID but different alternate settings. * * @param dev Indicates the USB device address. * @param interfaceid Indicates the interface ID of the USB device. * @param altIndex Indicates the alternate settings of the USB interface. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t SetInterface(const UsbDev &dev, uint8_t interfaceid, uint8_t altIndex); /* * * @brief Reads data on a specified endpoint during bulk transfer. The endpoint must be in the data reading direction. You can specify a timeout duration if needed. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * @param timeout Indicates the timeout duration. * @param data Indicates the read data. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkTransferRead(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, std::vector<uint8_t> &data); /* * * @brief Writes data on a specified endpoint during bulk transfer. The endpoint must be in the data writing direction. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * @param timeout Indicates the timeout duration. * @param data Indicates the written data. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkTransferWrite(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, const std::vector<uint8_t> &data); /* * * @brief Performs control transfer for endpoint 0 of the device. The data transfer direction is determined by the request type. If the result of <b>requestType</b>& * <b>USB_ENDPOINT_DIR_MASK</b> is USB_DIR_OUT, the endpoint is in the data writing direction; if the result is <b>USB_DIR_IN</b>, the endpoint is in the data reading direction. * * @param dev Indicates the USB device address. * @param ctrl Indicates the control data packet structure. * @param data Indicates the read data or written. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t ControlTransfer(const UsbDev &dev, const UsbCtrlTransfer &ctrl, std::vector<uint8_t> &data); /* * * @brief Reads data on a specified endpoint during interrupt transfer. The endpoint must be in the data reading direction. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * @param timeout Indicates the timeout duration. * @param data Indicates the read data. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t InterruptTransferRead(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, std::vector<uint8_t> &data); /* * * @brief Writes data on a specified endpoint during interrupt transfer. The endpoint must be in the data writing direction. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * @param timeout Indicates the timeout duration. * @param data Indicates the read data. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t InterruptTransferWrite(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, std::vector<uint8_t> &data); /* * * @brief Reads data on a specified endpoint during isochronous transfer. The endpoint must be in the data reading direction. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * @param timeout Indicates the timeout duration. * @param data Indicates the read data. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t IsoTransferRead(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, std::vector<uint8_t> &data); /* * * @brief Writes data on a specified endpoint during isochronous transfer. The endpoint must be in the data writing direction. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * @param timeout Indicates the timeout duration. * @param data Indicates the written data. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t IsoTransferWrite(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, std::vector<uint8_t> &data); /* * * @brief Sends or receives requests for isochronous transfer on a specified endpoint. The data transfer direction is determined by the endpoint direction. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * @param clientData Indicates the client data. * @param buffer Indicates the transferred data. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t RequestQueue(const UsbDev &dev, const UsbPipe &pipe, const std::vector<uint8_t> &clientData, const std::vector<uint8_t> &buffer); /* * * @brief Waits for the operation result of the requests for isochronous transfer in <b>RequestQueue</b>. * * @param dev Indicates the USB device address. * @param clientData Indicates the client data. * @param buffer Indicates the transferred data. * @param timeout Indicates the timeout duration. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t RequestWait(const UsbDev &dev, std::vector<uint8_t> &clientData, std::vector<uint8_t> &buffer, int32_t timeout); /* * * @brief Cancels the data transfer requests to be processed. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t RequestCancel(const UsbDev &dev, const UsbPipe &pipe); /* * * @brief Obtains the list of functions (represented by bit field) supported by the current device. * * @param funcs Indicates the list of functions supported by the current device. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetCurrentFunctions(int32_t &funcs); /* * * @brief Sets the list of functions (represented by bit field) supported by the current device. * * @param funcs Indicates the list of functions supported by the current device. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t SetCurrentFunctions(int32_t funcs); /* * * @brief Closes a USB device to release all system resources related to the device. * * @param portId Indicates the port ID of the USB interface. * @param powerRole Indicates the power role. * @param dataRole Indicates the data role. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); /* * * @brief Queries the current settings of a port. * * @param portId Indicates the port ID of the USB interface. * @param powerRole Indicates the power role. * @param dataRole Indicates the data role. * @param mode Indicates the mode. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t QueryPort(int32_t &portId, int32_t &powerRole, int32_t &dataRole, int32_t &mode); /* * * @brief Binds a subscriber. * * @param subscriber Indicates the subscriber. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static ErrCode BindUsbdSubscriber(const sptr<UsbdSubscriber> &subscriber); /* * * @brief Unbinds a subscriber. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static ErrCode UnbindUsbdSubscriber(); /* * * @brief Reads bulk data during isochronous transfer. This method is applicable to transfer of a huge amount of data. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * @param length Indicates the length of the data to read. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkRequstDataSize(const UsbDev &dev, const UsbPipe &pipe, uint32_t &length); /* * * @brief Obtains the data reading result. Use this method together with <b>BulkRequstDataSize</b>. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * @param data Indicates the read data. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkReadData(const UsbDev &dev, const UsbPipe &pipe, std::vector<uint8_t> &data); /* * * @brief Writes bulk data during isochronous transfer. This method is applicable to transfer of a huge amount of data. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * @param data Indicates the written data. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkWriteData(const UsbDev &dev, const UsbPipe &pipe, const std::vector<uint8_t> &data); /* * * @brief Obtains the data writing status based on <b>length</b>. Use this method together with <b>BulkWriteData</b>. * * @param dev Indicates the USB device address. * @param pipe Indicates the pipe of the USB device. * @param length Indicates the length of the written data. * * @return Returns <b>0</b> if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkGetWriteCompleteLength(const UsbDev &dev, const UsbPipe &pipe, uint32_t &length); private: static void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length); static int32_t SetDeviceMessage(MessageParcel &data, const UsbDev &dev); static int32_t SetBufferMessage(MessageParcel &data, const std::vector<uint8_t> &tdata); static int32_t GetBufferMessage(MessageParcel &data, std::vector<uint8_t> &tdata); static sptr<IRemoteObject> GetUsbdService(); static ErrCode DoDispatch(uint32_t cmd, MessageParcel &data, MessageParcel &reply); }; } // namespace USB } // namespace OHOS #endif // USBD_CLIENT_H
41.316159
181
0.673053
1a6e61571dcaf698a24e299ce808561170ba579c
57,760
c
C
src/rendering/vulkan.c
FrankvdStam/CVulkan
0419d867e8b8e7a4e210d113b1d8b8f472c1a829
[ "MIT" ]
null
null
null
src/rendering/vulkan.c
FrankvdStam/CVulkan
0419d867e8b8e7a4e210d113b1d8b8f472c1a829
[ "MIT" ]
null
null
null
src/rendering/vulkan.c
FrankvdStam/CVulkan
0419d867e8b8e7a4e210d113b1d8b8f472c1a829
[ "MIT" ]
null
null
null
// // Created by Frank on 10/07/2020. // #include "vulkan.h" #include <stddef.h> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" //======================================================================================================================================== //surface VkPhysicalDeviceMemoryProperties get_memory_properties(const application_t* application) { VkPhysicalDeviceMemoryProperties memory_properties; vkGetPhysicalDeviceMemoryProperties(application->vk_physical_device, &memory_properties); return memory_properties; } uint32_t find_memory_index(const application_t* application, uint32_t type_filter, VkMemoryPropertyFlags properties) { for (uint32_t i = 0; i < application->vk_memory_properties.memoryTypeCount; i++) { if ((type_filter & (1u << i)) && (application->vk_memory_properties.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } printf("Failed to get memory type."); exit(1); } VkSurfaceKHR get_vk_surface(const application_t* application) { VkSurfaceKHR vk_surface; if (glfwCreateWindowSurface(application->vk_instance, application->glfw_window, NULL, &vk_surface) != VK_SUCCESS) { printf("failed to create window surface\n"); exit(1); } printf("Successfully created window surface\n"); return vk_surface; } //======================================================================================================================================== //queue families queue_family_indices_t get_queue_family_indices(const application_t* application) { bool has_graphics_family_index = false; bool has_present_family_index = false; queue_family_indices_t indices; indices.graphics_family_index = 0; uint32_t queue_family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(application->vk_physical_device, &queue_family_count, NULL); VkQueueFamilyProperties* queue_family_properties = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * queue_family_count); vkGetPhysicalDeviceQueueFamilyProperties(application->vk_physical_device, &queue_family_count, queue_family_properties); for(size_t i = 0; i < queue_family_count; i++) { if(queue_family_properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { has_graphics_family_index = true; indices.graphics_family_index = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(application->vk_physical_device, i, application->vk_surface, &presentSupport); if(presentSupport) { indices.present_family_index = i; has_present_family_index = true; } } if(!has_graphics_family_index) { printf("No graphics queue family index found."); exit(1); } if(!has_present_family_index) { printf("No present queue family index found."); exit(1); } free(queue_family_properties); return indices; } //========================================================================================================================================== //Logical device #define TOTAL_QUEUE_INDICES 2 VkDevice get_logical_device(const application_t* application) { VkDevice vk_device; //setup a queue for each index we have uint32_t indices[TOTAL_QUEUE_INDICES]; VkDeviceQueueCreateInfo queue_create_infos[TOTAL_QUEUE_INDICES]; indices[0] = application->queue_family_indices.graphics_family_index; indices[1] = application->queue_family_indices.present_family_index; for(uint32_t i = 0; i < TOTAL_QUEUE_INDICES; i++) { VkDeviceQueueCreateInfo queue_create_info; queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queue_create_info.queueFamilyIndex = indices[i]; queue_create_info.queueCount = 1; queue_create_info.pNext = NULL; queue_create_info.flags = 0; float queuePriority = 1.0f; queue_create_info.pQueuePriorities = &queuePriority; queue_create_infos[i] = queue_create_info; } VkPhysicalDeviceFeatures device_features; device_features.robustBufferAccess = VK_FALSE; device_features.fullDrawIndexUint32 = VK_FALSE; device_features.imageCubeArray = VK_FALSE; device_features.independentBlend = VK_FALSE; device_features.geometryShader = VK_FALSE; device_features.sampleRateShading = VK_FALSE; device_features.logicOp = VK_FALSE; device_features.drawIndirectFirstInstance = VK_FALSE; device_features.depthBiasClamp = VK_FALSE; device_features.depthBounds = VK_FALSE; device_features.wideLines = VK_FALSE; device_features.largePoints = VK_FALSE; device_features.alphaToOne = VK_FALSE; device_features.multiViewport = VK_FALSE; device_features.samplerAnisotropy = VK_FALSE; device_features.textureCompressionETC2 = VK_FALSE; device_features.textureCompressionASTC_LDR = VK_FALSE; device_features.textureCompressionBC = VK_FALSE; device_features.occlusionQueryPrecise = VK_FALSE; device_features.pipelineStatisticsQuery = VK_FALSE; device_features.vertexPipelineStoresAndAtomics = VK_FALSE; device_features.fragmentStoresAndAtomics = VK_FALSE; device_features.shaderTessellationAndGeometryPointSize = VK_FALSE; device_features.shaderImageGatherExtended = VK_FALSE; device_features.shaderStorageImageExtendedFormats = VK_FALSE; device_features.shaderStorageImageMultisample = VK_FALSE; device_features.shaderStorageImageReadWithoutFormat = VK_FALSE; device_features.shaderStorageImageWriteWithoutFormat = VK_FALSE; device_features.shaderUniformBufferArrayDynamicIndexing = VK_FALSE; device_features.shaderStorageImageArrayDynamicIndexing = VK_FALSE; device_features.shaderClipDistance = VK_FALSE; device_features.shaderCullDistance = VK_FALSE; device_features.shaderFloat64 = VK_FALSE; device_features.shaderInt64 = VK_FALSE; device_features.shaderInt16 = VK_FALSE; device_features.shaderResourceResidency = VK_FALSE; device_features.shaderResourceMinLod = VK_FALSE; device_features.sparseBinding = VK_FALSE; device_features.sparseResidencyBuffer = VK_FALSE; device_features.sparseResidencyImage2D = VK_FALSE; device_features.inheritedQueries = VK_FALSE; device_features.dualSrcBlend = VK_FALSE; device_features.shaderSampledImageArrayDynamicIndexing = VK_FALSE; device_features.sparseResidency2Samples = VK_FALSE; device_features.sparseResidency8Samples = VK_FALSE; device_features.sparseResidencyAliased = VK_FALSE; device_features.shaderStorageBufferArrayDynamicIndexing = VK_FALSE; device_features.depthClamp = VK_FALSE; device_features.sparseResidency16Samples = VK_FALSE; VkDeviceCreateInfo create_info; create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; create_info.queueCreateInfoCount = TOTAL_QUEUE_INDICES; create_info.pQueueCreateInfos = queue_create_infos; create_info.pEnabledFeatures = &device_features; create_info.pNext = NULL; const char* device_extensions[] = { "VK_KHR_swapchain" }; create_info.ppEnabledExtensionNames = device_extensions; create_info.enabledExtensionCount = 1; create_info.enabledLayerCount = application->required_layer_names->current_index; create_info.ppEnabledLayerNames = (const char**)application->required_layer_names->data; create_info.flags = 0; if (vkCreateDevice(application->vk_physical_device, &create_info, NULL, &vk_device) != VK_SUCCESS) { printf("failed to create logical device\n"); exit(1); } else { printf("Successfully created logical device\n"); return vk_device; } } VkQueue get_graphics_queue(const application_t* application) { VkQueue vk_graphics_queue; vkGetDeviceQueue(application->vk_device, application->queue_family_indices.graphics_family_index, 0, &vk_graphics_queue); if(vk_graphics_queue == NULL) { printf("failed to create graphics queue\n"); exit(1); } printf("Setup graphics queue\n"); return vk_graphics_queue; } VkQueue get_present_queue(const application_t* application) { VkQueue vk_present_queue; vkGetDeviceQueue(application->vk_device, application->queue_family_indices.present_family_index, 0, &vk_present_queue); if(vk_present_queue == NULL) { printf("failed to create present queue\n"); exit(1); } printf("Setup present queue\n"); return vk_present_queue; } //========================================================================================================================================== //Debugging callbacks //The actual callback static VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback( VkDebugUtilsMessageSeverityFlagBitsEXT message_severity, VkDebugUtilsMessageTypeFlagsEXT message_type, const VkDebugUtilsMessengerCallbackDataEXT* p_callback_data, void* p_user_data ) { printf("validation layer: %s\n", p_callback_data->pMessage); exit(1); return VK_FALSE; } //creating an extension for the debug callback VkResult CreateDebugUtilsMessengerEXT(VkInstance vk_instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger) { PFN_vkCreateDebugUtilsMessengerEXT func = (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(vk_instance, "vkCreateDebugUtilsMessengerEXT"); if (func != NULL) { return func(vk_instance, pCreateInfo, pAllocator, pDebugMessenger); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } //deleting an extension for the debug callback void DestroyDebugUtilsMessengerEXT(VkInstance vk_instance, VkDebugUtilsMessengerEXT vk_debugMessenger, const VkAllocationCallbacks* pAllocator) { PFN_vkDestroyDebugUtilsMessengerEXT func = (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(vk_instance, "vkDestroyDebugUtilsMessengerEXT"); if (func != NULL) { func(vk_instance, vk_debugMessenger, pAllocator); } } void free_debug_utils_messenger_extension(const application_t* application) { DestroyDebugUtilsMessengerEXT(application->vk_instance, application->vk_debug_messenger, NULL); } //Setup the callback VkDebugUtilsMessengerEXT get_debug_callback(const application_t* application) { VkDebugUtilsMessengerEXT vk_debug_messenger; if(application->vulkan_debugging_mode == vulkan_debugging_enabled) { VkDebugUtilsMessengerCreateInfoEXT create_info; create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; create_info.pfnUserCallback = debug_callback; create_info.pUserData = NULL; // Optional create_info.flags = 0; if (CreateDebugUtilsMessengerEXT(application->vk_instance, &create_info, NULL, &vk_debug_messenger) != VK_SUCCESS) { printf("failed to set up debug messenger\n"); exit(1); } else { printf("Sucessfully set up debug messenger\n"); return vk_debug_messenger; } } return NULL; } //=========================================================================================================================================== //Initialization GLFWwindow* glfw_init_get_window(const application_t* application) { GLFWwindow* glfw_window; if(glfwInit() == GLFW_FALSE) { printf("Failed to initialize glfw.\n"); exit(1); } glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); glfw_window = glfwCreateWindow(application->window_width, application->window_height, application->title, NULL, NULL); if(glfw_window == NULL) { printf("Failed to create glfw window.\n"); exit(1); } return glfw_window; } string_list_t* get_required_extensions(const application_t* application) { //Create a stringlist to keep track of all the names of extensions we want to enable. string_list_t* list = (string_list_t*)malloc(sizeof(string_list_t)); string_list_init(list, 4); //fetch all the extensions that glfw needs and add all of the existing extensions uint32_t glfw_extension_count = 0; const char** glfw_extensions; glfw_extensions = glfwGetRequiredInstanceExtensions(&glfw_extension_count); for(size_t i = 0; i < glfw_extension_count; i++) { if(extension_exists(glfw_extensions[i])) { string_list_add(list, (char*)glfw_extensions[i]); } else { printf("glfw requests extension %s, which is not available on the current system. Proceeding without it...", glfw_extensions[i]); } } //Add debug utils if vulkan debugging is enabled if(application->vulkan_debugging_mode == vulkan_debugging_enabled) { string_list_add(list, "VK_EXT_debug_utils"); } return list; } string_list_t* get_required_layers(const application_t* application) { string_list_t* list = (string_list_t*)malloc(sizeof(string_list_t)); string_list_init(list, 1); if(application->vulkan_debugging_mode == vulkan_debugging_enabled) { string_list_add(list, "VK_LAYER_KHRONOS_validation"); } return list; } VkInstance get_instance(const application_t* application) { VkInstance vk_instance; VkApplicationInfo vk_app_info; vk_app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; vk_app_info.pApplicationName = "CVulkan"; vk_app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0); vk_app_info.pEngineName = "No Engine"; vk_app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0); vk_app_info.apiVersion = VK_API_VERSION_1_0; vk_app_info.pNext = NULL; VkInstanceCreateInfo vk_instance_create_info; vk_instance_create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; vk_instance_create_info.pApplicationInfo = &vk_app_info; vk_instance_create_info.pNext = NULL; vk_instance_create_info.flags = 0; vk_instance_create_info.enabledExtensionCount = application->required_extension_names->current_index; vk_instance_create_info.ppEnabledExtensionNames = (const char**) application->required_extension_names->data; vk_instance_create_info.enabledLayerCount = application->required_layer_names->current_index; vk_instance_create_info.ppEnabledLayerNames = (const char**)application->required_layer_names->data; if (vkCreateInstance(&vk_instance_create_info, NULL, &vk_instance) != VK_SUCCESS) { printf("failed to create instance\n"); exit(1); } printf("Successfully created instance\n"); return vk_instance; } VkPhysicalDevice get_physical_device(const application_t* application) { VkPhysicalDevice vk_physical_device; //Get the devices uint32_t device_count = 0; vkEnumeratePhysicalDevices(application->vk_instance, &device_count, NULL); //Someone could have more than 10 devices. This is a potential memory issue. VkPhysicalDevice devices[10]; if(device_count > 10) { printf("There are more physical devices than are allocated for."); exit(1); } vkEnumeratePhysicalDevices(application->vk_instance, &device_count, devices); if(device_count == 0 || devices[0] == VK_NULL_HANDLE) { printf("No devices with vulkan support found."); exit(1); } vk_physical_device = devices[0]; VkPhysicalDeviceProperties deviceProperties; vkGetPhysicalDeviceProperties(vk_physical_device, &deviceProperties); printf("Picked device %s\n", deviceProperties.deviceName); //printf("extensions:\n"); // //uint32_t extensions_count = 0; //vkEnumerateDeviceExtensionProperties(vk_physical_device, NULL, &extensions_count, NULL); //VkExtensionProperties* props = (VkExtensionProperties*)malloc(sizeof(VkExtensionProperties) * extensions_count); //vkEnumerateDeviceExtensionProperties(vk_physical_device, NULL, &extensions_count, props); // //for(uint32_t i = 0; i < extensions_count; i++) //{ // printf("%s\n", props[i].extensionName); //} return vk_physical_device; } //=========================================================================================================================================== //swapchain swapchain_details_t get_swapchain_details(const application_t* application) { swapchain_details_t swapchain_details; //get the capabilities vkGetPhysicalDeviceSurfaceCapabilitiesKHR(application->vk_physical_device, application->vk_surface, &swapchain_details.vk_surface_capabilities); //get the formats vkGetPhysicalDeviceSurfaceFormatsKHR(application->vk_physical_device, application->vk_surface, &swapchain_details.surface_formats_size, NULL); swapchain_details.vk_surface_formats = (VkSurfaceFormatKHR*)malloc(sizeof(VkSurfaceFormatKHR) * swapchain_details.surface_formats_size); vkGetPhysicalDeviceSurfaceFormatsKHR(application->vk_physical_device, application->vk_surface, &swapchain_details.surface_formats_size, swapchain_details.vk_surface_formats); vkGetPhysicalDeviceSurfacePresentModesKHR(application->vk_physical_device, application->vk_surface, &swapchain_details.present_modes_size, NULL); swapchain_details.vk_surface_present_modes = (VkPresentModeKHR*)malloc(sizeof(VkPresentModeKHR) * swapchain_details.present_modes_size); vkGetPhysicalDeviceSurfacePresentModesKHR(application->vk_physical_device, application->vk_surface, &swapchain_details.present_modes_size, swapchain_details.vk_surface_present_modes); return swapchain_details; } VkSurfaceFormatKHR get_surface_format(const application_t* application) { for(uint32_t i = 0; i < application->swapchain_details.surface_formats_size; i++) { VkSurfaceFormatKHR format = application->swapchain_details.vk_surface_formats[i]; if(format.format == VK_FORMAT_B8G8R8A8_SRGB && format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return format; } } //If we can't have nice things, try to get any at all (try to return the first value) if(application->swapchain_details.surface_formats_size > 0) { return application->swapchain_details.vk_surface_formats[0]; } printf("Couldn't get surface format.\n"); exit(1); } VkPresentModeKHR get_present_mode(const application_t* application) { for(uint32_t i = 0; i < application->swapchain_details.present_modes_size; i++) { VkPresentModeKHR present_mode = application->swapchain_details.vk_surface_present_modes[i]; if(present_mode == VK_PRESENT_MODE_MAILBOX_KHR) { return present_mode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D get_swap_extent(const application_t* application) { //VkSurfaceCapabilitiesKHR capabilities = application->swapchain_details.vk_surface_capabilities; //if(application->swapchain_details.vk_surface_capabilities.currentExtent.width != UINT32_MAX) //{ // return application->swapchain_details.vk_surface_capabilities.currentExtent; //} //Don't really know if this is any good/how to test it. VkExtent2D extent; extent.width = application->window_width; extent.height = application->window_height; //extent.width = max(capabilities.minImageExtent.width, min(capabilities.maxImageExtent.width, extent.width)); //extent.height = max(capabilities.minImageExtent.height, min(capabilities.maxImageExtent.height, extent.height)); return extent; } VkSwapchainKHR get_swapchain(const application_t* application) { VkSwapchainKHR vk_swapchain; //request one more than min without exceeding max uint32_t imageCount = application->swapchain_details.vk_surface_capabilities.minImageCount + 1; if (application->swapchain_details.vk_surface_capabilities.maxImageCount > 0 && imageCount > application->swapchain_details.vk_surface_capabilities.maxImageCount) { imageCount = application->swapchain_details.vk_surface_capabilities.maxImageCount; } VkSwapchainCreateInfoKHR create_info; create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; create_info.surface = application->vk_surface; create_info.minImageCount = imageCount; create_info.imageFormat = application->vk_surface_format.format; create_info.imageColorSpace = application->vk_surface_format.colorSpace; create_info.imageExtent = application->vk_extent; create_info.imageArrayLayers = 1; create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; create_info.flags = 0; create_info.pNext = NULL; uint32_t indices[2]; indices[0] = application->queue_family_indices.graphics_family_index; indices[1] = application->queue_family_indices.present_family_index; if (application->queue_family_indices.graphics_family_index != application->queue_family_indices.present_family_index) { create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT; create_info.queueFamilyIndexCount = 2; create_info.pQueueFamilyIndices = indices; } else { create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } create_info.preTransform = application->swapchain_details.vk_surface_capabilities.currentTransform; create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; create_info.presentMode = application->vk_present_mode; create_info.clipped = VK_TRUE; create_info.oldSwapchain = VK_NULL_HANDLE; if (vkCreateSwapchainKHR(application->vk_device, &create_info, NULL, &vk_swapchain) != VK_SUCCESS) { printf("failed to create swap chain.\n"); exit(1); } else { printf("Created swap chain.\n"); return vk_swapchain; } //vkGetSwapchainImagesKHR(application->vk_device, vk_swapchain, &imageCount, NULL); //swapChainImages.resize(imageCount); //vkGetSwapchainImagesKHR(application->vk_device, vk_swapchain, &imageCount, swapChainImages.data()); // //swapChainImageFormat = surfaceFormat.format; //swapChainExtent = extent; } VkImage* get_swapchain_images(const application_t* application, uint32_t* image_count) { vkGetSwapchainImagesKHR(application->vk_device, application->vk_swapchain, image_count, NULL); VkImage* vk_images = (VkImage*)malloc(sizeof(VkImage) * (*image_count)); vkGetSwapchainImagesKHR(application->vk_device, application->vk_swapchain, image_count, vk_images); return vk_images; } VkImageView* get_image_views(const application_t* application) { VkImageView* image_views = (VkImageView*)malloc(sizeof(VkImageView) * application->swapchain_images_size); for(uint32_t i = 0; i < application->swapchain_images_size; i++) { VkImageViewCreateInfo createInfo; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.flags = 0; createInfo.pNext = NULL; createInfo.image = application->vk_images[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = application->vk_surface_format.format; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; if (vkCreateImageView(application->vk_device, &createInfo, NULL, &image_views[i]) != VK_SUCCESS) { printf("failed to create image views\n"); exit(1); } } return image_views; } enum type { fragment, vertex, }; VkShaderModule get_shader_module(const application_t* application, const char* path, enum type stype) { //Read the shader file into a char buffer unsigned char* file_buffer; unsigned long file_size; read_file(path, &file_buffer, &file_size); //There are a couple caveats //We need the code and it's size //the size will be in bytes (which is already stored in file_size) //the code will be an uint32_t pointer instead of a char //That means we have to convert the data properly //Code size represents the amount of uint32_t's we need //char is guaranteed to be a byte by the spec size_t code_size = file_size/sizeof(uint32_t); uint32_t* shader_code = (uint32_t*)malloc(code_size * sizeof(uint32_t)); for(size_t i = 0; i < code_size; i++) { //Calculate the proper index into the char buffer size_t start_index = i * sizeof(uint32_t); //Reinterpret the data in the char buffer as a uint32_t shader_code[i] = (uint32_t) file_buffer[start_index+0] | (uint32_t) file_buffer[start_index+1] << 8u | (uint32_t) file_buffer[start_index+2] << 16u | (uint32_t) file_buffer[start_index+3] << 24u ; } free(file_buffer); //Create the shader module VkShaderModule vk_shader_module; VkShaderModuleCreateInfo create_info; create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; //apparently the codesize is in bytes. create_info.codeSize = file_size; create_info.pCode = shader_code; create_info.flags = 0; create_info.pNext = NULL; if (vkCreateShaderModule(application->vk_device, &create_info, NULL, &vk_shader_module) != VK_SUCCESS) { printf("failed to create shader module!\n"); exit(1); } //free the 2nd buffer, now that the shader module has been created free(shader_code); return vk_shader_module; } void get_pipeline_layout_and_pipeline(const application_t* application, VkPipelineLayout* vk_pipeline_layout, VkPipeline* vk_graphics_pipeline) { //Get the shader modules VkShaderModule vertex_shader_module = get_shader_module(application, "C:\\projects\\CVulkan\\shaders\\vert.spv", vertex); VkShaderModule fragment_shader_module = get_shader_module(application, "C:\\projects\\CVulkan\\shaders\\frag.spv", fragment); VkPipelineShaderStageCreateInfo vertShaderStageInfo; vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; vertShaderStageInfo.module = vertex_shader_module; vertShaderStageInfo.pName = "main"; vertShaderStageInfo.flags = 0; vertShaderStageInfo.pNext = VK_NULL_HANDLE; vertShaderStageInfo.pSpecializationInfo = VK_NULL_HANDLE; VkPipelineShaderStageCreateInfo fragShaderStageInfo; fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; fragShaderStageInfo.module = fragment_shader_module; fragShaderStageInfo.pName = "main"; fragShaderStageInfo.flags = 0; fragShaderStageInfo.pNext = VK_NULL_HANDLE; fragShaderStageInfo.pSpecializationInfo = VK_NULL_HANDLE; VkPipelineShaderStageCreateInfo shaderStages[2] = {vertShaderStageInfo, fragShaderStageInfo}; VkVertexInputBindingDescription vertex_input_description; vertex_input_description.binding = 0; vertex_input_description.stride = sizeof(vertex_t); vertex_input_description.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; VkVertexInputAttributeDescription vertex_attribute_descriptions[2]; vertex_attribute_descriptions[0].binding = 0; vertex_attribute_descriptions[0].location = 0; vertex_attribute_descriptions[0].format = VK_FORMAT_R32G32_SFLOAT; vertex_attribute_descriptions[0].offset = offsetof(vertex_t, pos); vertex_attribute_descriptions[1].binding = 0; vertex_attribute_descriptions[1].location = 1; vertex_attribute_descriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; vertex_attribute_descriptions[1].offset = offsetof(vertex_t, color); VkPipelineVertexInputStateCreateInfo vertexInputInfo; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.flags = 0; vertexInputInfo.pNext = 0; vertexInputInfo.vertexBindingDescriptionCount = 1; vertexInputInfo.pVertexBindingDescriptions = &vertex_input_description; vertexInputInfo.vertexAttributeDescriptionCount = 2; vertexInputInfo.pVertexAttributeDescriptions = vertex_attribute_descriptions; VkPipelineInputAssemblyStateCreateInfo inputAssembly; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; inputAssembly.flags = 0; inputAssembly.pNext = VK_NULL_HANDLE; VkViewport viewport; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = (float) application->vk_extent.width; viewport.height = (float) application->vk_extent.height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor; scissor.offset.x = 0; scissor.offset.y = 0; scissor.extent = application->vk_extent; VkPipelineViewportStateCreateInfo viewportState; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; viewportState.flags = 0; viewportState.pNext = VK_NULL_HANDLE; VkPipelineRasterizationStateCreateInfo rasterizer; rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizer.depthClampEnable = VK_FALSE; rasterizer.rasterizerDiscardEnable = VK_FALSE; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; rasterizer.lineWidth = 1.0f; //rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; //rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizer.depthBiasEnable = VK_FALSE; rasterizer.depthBiasConstantFactor = 0.0f; // Optional rasterizer.depthBiasClamp = 0.0f; // Optional rasterizer.depthBiasSlopeFactor = 0.0f; // Optional rasterizer.flags = 0; rasterizer.pNext = VK_NULL_HANDLE; VkPipelineMultisampleStateCreateInfo multisampling; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.sampleShadingEnable = VK_FALSE; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisampling.minSampleShading = 1.0f; // Optional multisampling.pSampleMask = VK_NULL_HANDLE; // Optional multisampling.alphaToCoverageEnable = VK_FALSE; // Optional multisampling.alphaToOneEnable = VK_FALSE; // Optional multisampling.flags = 0; multisampling.pNext = VK_NULL_HANDLE; VkPipelineColorBlendAttachmentState colorBlendAttachment; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // Optional colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // Optional VkPipelineColorBlendStateCreateInfo colorBlending; colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; // Optional colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; // Optional colorBlending.blendConstants[1] = 0.0f; // Optional colorBlending.blendConstants[2] = 0.0f; // Optional colorBlending.blendConstants[3] = 0.0f; // Optional colorBlending.flags = 0; colorBlending.pNext = VK_NULL_HANDLE; //VkDynamicState dynamicStates[] = { // VK_DYNAMIC_STATE_VIEWPORT, // VK_DYNAMIC_STATE_LINE_WIDTH //}; //VkPipelineDynamicStateCreateInfo dynamicState; //dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; //dynamicState.dynamicStateCount = 2; //dynamicState.pDynamicStates = dynamicStates; //dynamicState.flags = 0; //dynamicState.pNext = VK_NULL_HANDLE; VkPipelineLayoutCreateInfo pipelineLayoutInfo; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = 1; pipelineLayoutInfo.pSetLayouts = &application->vk_descriptor_set_layout; pipelineLayoutInfo.pushConstantRangeCount = 0; // Optional pipelineLayoutInfo.pPushConstantRanges = VK_NULL_HANDLE; // Optional pipelineLayoutInfo.flags = 0; pipelineLayoutInfo.pNext = VK_NULL_HANDLE; if (vkCreatePipelineLayout(application->vk_device, &pipelineLayoutInfo, VK_NULL_HANDLE, vk_pipeline_layout) != VK_SUCCESS) { printf("failed to create pipeline layout!\n"); exit(1); } printf("Created pipeline layout\n"); //Now setup the pipeline itself VkGraphicsPipelineCreateInfo pipelineInfo; pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineInfo.stageCount = 2; pipelineInfo.pStages = shaderStages; pipelineInfo.flags = 0; pipelineInfo.pNext = VK_NULL_HANDLE; pipelineInfo.pVertexInputState = &vertexInputInfo; pipelineInfo.pInputAssemblyState = &inputAssembly; pipelineInfo.pViewportState = &viewportState; pipelineInfo.pRasterizationState = &rasterizer; pipelineInfo.pMultisampleState = &multisampling; pipelineInfo.pDepthStencilState = VK_NULL_HANDLE; // Optional pipelineInfo.pColorBlendState = &colorBlending; pipelineInfo.pDynamicState = VK_NULL_HANDLE; // Optional pipelineInfo.layout = *vk_pipeline_layout; pipelineInfo.renderPass = application->vk_render_pass; pipelineInfo.subpass = 0; pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; // Optional pipelineInfo.basePipelineIndex = -1; // Optional if (vkCreateGraphicsPipelines( application->vk_device, //VkDevice device VK_NULL_HANDLE, //VkPipelineCache pipelineCache 1, //uint32_t createInfoCount &pipelineInfo, //const VkGraphicsPipelineCreateInfo *pCreateInfos VK_NULL_HANDLE, //const VkAllocationCallbacks *pAllocator vk_graphics_pipeline //VkPipeline *pPipelines ) != VK_SUCCESS) { printf("failed to create graphics pipeline.\n"); } printf("Created pipeline\n"); //Destroy the shader modules vkDestroyShaderModule(application->vk_device, fragment_shader_module, NULL); vkDestroyShaderModule(application->vk_device, vertex_shader_module, NULL); } VkRenderPass get_render_pass(const application_t* application) { VkAttachmentDescription color_attachment; color_attachment.format = application->vk_surface_format.format; color_attachment.samples = VK_SAMPLE_COUNT_1_BIT; color_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; color_attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; color_attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; color_attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; color_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; color_attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; color_attachment.flags = 0; VkAttachmentReference color_attachment_ref; color_attachment_ref.attachment = 0; color_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &color_attachment_ref; subpass.flags = 0; subpass.inputAttachmentCount = 0; subpass.preserveAttachmentCount = 0; subpass.pResolveAttachments = NULL; subpass.pDepthStencilAttachment = NULL; subpass.pPreserveAttachments = NULL; subpass.pInputAttachments = NULL; VkSubpassDependency dependency; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependency.dependencyFlags = 0; VkRenderPassCreateInfo render_pass_info; render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; render_pass_info.attachmentCount = 1; render_pass_info.pAttachments = &color_attachment; render_pass_info.subpassCount = 1; render_pass_info.pSubpasses = &subpass; render_pass_info.flags = 0; render_pass_info.pNext = NULL; render_pass_info.dependencyCount = 1; render_pass_info.pDependencies = &dependency; VkRenderPass vk_render_pass; if (vkCreateRenderPass(application->vk_device, &render_pass_info, NULL, &vk_render_pass) != VK_SUCCESS) { printf("failed to create render pass\n"); exit(1); } printf("created renderpass.\n"); return vk_render_pass; } VkFramebuffer* get_frame_buffers(const application_t* application) { VkFramebuffer* vk_frame_buffers = (VkFramebuffer*)malloc(sizeof(VkFramebuffer) * application->swapchain_images_size); for(size_t i = 0; i < application->swapchain_images_size; i++) { VkImageView attachments[] = {application->vk_image_views[i]}; VkFramebufferCreateInfo framebuffer_info; framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebuffer_info.renderPass = application->vk_render_pass; framebuffer_info.attachmentCount = 1; framebuffer_info.pAttachments = attachments; framebuffer_info.width = application->vk_extent.width; framebuffer_info.height = application->vk_extent.height; framebuffer_info.layers = 1; framebuffer_info.flags = 0; framebuffer_info.pNext = VK_NULL_HANDLE; if (vkCreateFramebuffer(application->vk_device, &framebuffer_info, VK_NULL_HANDLE, &vk_frame_buffers[i]) != VK_SUCCESS) { printf("failed to create framebuffer!\n"); } } printf("Created framebuffers\n"); return vk_frame_buffers; } VkCommandPool get_command_pool(const application_t* application) { VkCommandPool vk_command_pool; VkCommandPoolCreateInfo pool_info; pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; pool_info.queueFamilyIndex = application->queue_family_indices.graphics_family_index; pool_info.flags = 0; pool_info.pNext = VK_NULL_HANDLE; if (vkCreateCommandPool(application->vk_device, &pool_info, VK_NULL_HANDLE, &vk_command_pool) != VK_SUCCESS) { printf("failed to create command pool!\n"); } printf("Created command pool\n"); return vk_command_pool; } VkCommandBuffer* get_command_buffers(const application_t* application) { VkCommandBuffer* vk_command_buffer = (VkCommandBuffer*)malloc(sizeof(VkCommandBuffer) * application->swapchain_images_size); VkCommandBufferAllocateInfo allocInfo; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = application->vk_command_pool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = application->swapchain_images_size; allocInfo.pNext = VK_NULL_HANDLE; if (vkAllocateCommandBuffers(application->vk_device, &allocInfo, vk_command_buffer) != VK_SUCCESS) { printf("failed to allocate command buffers!"); } for (size_t i = 0; i < application->swapchain_images_size; i++) { VkCommandBufferBeginInfo beginInfo; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = 0; beginInfo.pNext = VK_NULL_HANDLE; beginInfo.pInheritanceInfo = VK_NULL_HANDLE; if (vkBeginCommandBuffer(vk_command_buffer[i], &beginInfo) != VK_SUCCESS) { printf("failed to begin recording command buffer!\n"); } VkRenderPassBeginInfo renderPassInfo; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = application->vk_render_pass; renderPassInfo.framebuffer = application->vk_frame_buffers[i]; renderPassInfo.renderArea.offset.x = 0; renderPassInfo.renderArea.offset.y = 0; renderPassInfo.renderArea.extent = application->vk_extent; renderPassInfo.pNext = VK_NULL_HANDLE; VkClearValue clearColor = {{{0.0f, 0.0f, 0.0f, 1.0f}}}; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; ///vkCmdBeginRenderPass(vk_command_buffer[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); /// ///////vkCmdBindPipeline(vk_command_buffer[i], VK_PIPELINE_BIND_POINT_GRAPHICS, application->vk_graphics_pipeline);//// ///////vkCmdDraw(vk_command_buffer[i], 3, 1, 0, 0);//// ///////vkCmdEndRenderPass(vk_command_buffer[i]); /// /// /// ///vkCmdBindPipeline(vk_command_buffer[i], VK_PIPELINE_BIND_POINT_GRAPHICS, application->vk_graphics_pipeline); ///VkBuffer vertexBuffers[] = {application->vk_vertex_buffer}; ///VkDeviceSize offsets[] = {0}; ///vkCmdBindVertexBuffers(vk_command_buffer[i], 0, 1, vertexBuffers, offsets); /// ///vkCmdDraw(vk_command_buffer[i], 15, 1, 0, 0); /// ///if (vkEndCommandBuffer(vk_command_buffer[i]) != VK_SUCCESS) ///{ /// printf("failed to record command buffer!\n"); ///} vkCmdBeginRenderPass(vk_command_buffer[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(vk_command_buffer[i], VK_PIPELINE_BIND_POINT_GRAPHICS, application->vk_graphics_pipeline); VkBuffer vertexBuffers[] = {application->vk_vertex_buffer}; VkDeviceSize offsets[] = {0}; vkCmdBindVertexBuffers(vk_command_buffer[i], 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(vk_command_buffer[i], application->vk_index_buffer, 0, VK_INDEX_TYPE_UINT16); vkCmdBindDescriptorSets(vk_command_buffer[i], VK_PIPELINE_BIND_POINT_GRAPHICS, application->vk_pipeline_layout, 0, 1, &application->vk_descriptor_sets[i], 0, VK_NULL_HANDLE); //vkCmdDraw(vk_command_buffer[i], 15, 1, 0, 0); vkCmdDrawIndexed(vk_command_buffer[i], 6, 1, 0, 0, 0); vkCmdEndRenderPass(vk_command_buffer[i]); if (vkEndCommandBuffer(vk_command_buffer[i]) != VK_SUCCESS) { printf("failed to record command buffer!\n"); } } return vk_command_buffer; } VkSemaphore get_semaphore(const application_t* application) { VkSemaphore semaphore; VkSemaphoreCreateInfo semaphore_info; semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; semaphore_info.flags = 0; semaphore_info.pNext = VK_NULL_HANDLE; if (vkCreateSemaphore(application->vk_device, &semaphore_info, VK_NULL_HANDLE, &semaphore) != VK_SUCCESS) { printf("failed to create semaphore!"); } return semaphore; } VkFence get_fence(const application_t* application) { VkFence vk_fence; VkFenceCreateInfo fence_info; fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;//Create them in signaled state, else calling wait on them will wait forever fence_info.pNext = VK_NULL_HANDLE; if(vkCreateFence(application->vk_device, &fence_info, NULL, &vk_fence) != VK_SUCCESS) { printf("Failed to create fence."); } return vk_fence; } void get_buffer(const application_t* application, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags memory_property_flags, VkBuffer* buffer, VkDeviceMemory* buffer_memory) { VkBufferCreateInfo buffer_info; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.size = size; buffer_info.usage = usage; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; buffer_info.flags = 0; buffer_info.pNext = VK_NULL_HANDLE; buffer_info.pQueueFamilyIndices = 0; buffer_info.queueFamilyIndexCount = 0; if (vkCreateBuffer(application->vk_device, &buffer_info, NULL, buffer) != VK_SUCCESS) { printf("failed to create buffer!\n"); } VkMemoryRequirements memory_requirements; vkGetBufferMemoryRequirements(application->vk_device, *buffer, &memory_requirements); VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(application->vk_physical_device, &memProperties); VkMemoryAllocateInfo alloc_info; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.allocationSize = memory_requirements.size; alloc_info.pNext = VK_NULL_HANDLE; alloc_info.memoryTypeIndex = find_memory_index(application, memory_requirements.memoryTypeBits, memory_property_flags); if (vkAllocateMemory(application->vk_device, &alloc_info, NULL, buffer_memory) != VK_SUCCESS) { printf("failed to allocate buffer memory!\n"); } vkBindBufferMemory(application->vk_device, *buffer, *buffer_memory, 0); } //private helper void copy_buffer(const application_t* application, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { VkCommandBufferAllocateInfo allocInfo; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = application->vk_command_pool; allocInfo.commandBufferCount = 1; allocInfo.pNext = VK_NULL_HANDLE; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(application->vk_device, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; beginInfo.pNext = VK_NULL_HANDLE; beginInfo.pInheritanceInfo = NULL; vkBeginCommandBuffer(commandBuffer, &beginInfo); VkBufferCopy copyRegion; copyRegion.srcOffset = 0; // Optional copyRegion.dstOffset = 0; // Optional copyRegion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion); vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; submitInfo.pNext = VK_NULL_HANDLE; submitInfo.pSignalSemaphores = NULL; submitInfo.signalSemaphoreCount = 0; submitInfo.pWaitSemaphores = NULL; submitInfo.waitSemaphoreCount = 0; submitInfo.pWaitDstStageMask = NULL; vkQueueSubmit(application->vk_graphics_queue, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(application->vk_graphics_queue); vkFreeCommandBuffers(application->vk_device, application->vk_command_pool, 1, &commandBuffer); } void get_vertex_buffer(const application_t* application, vertex_t* vertices, size_t vertices_size, VkBuffer* vertex_buffer, VkDeviceMemory* vertex_buffer_memory) { //Temporary buffers VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = sizeof(vertex_t) * vertices_size; get_buffer(application, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &stagingBuffer, &stagingBufferMemory); void* data; vkMapMemory(application->vk_device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices, vertices_size * sizeof(vertex_t)); vkUnmapMemory(application->vk_device, stagingBufferMemory); get_buffer(application, bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertex_buffer, vertex_buffer_memory); copy_buffer(application, stagingBuffer, *vertex_buffer, bufferSize); vkDestroyBuffer(application->vk_device, stagingBuffer, NULL); vkFreeMemory(application->vk_device, stagingBufferMemory, NULL); } void get_index_buffer(const application_t* application, uint16_t* indices, size_t indices_size, VkBuffer* index_buffer, VkDeviceMemory* index_buffer_memory) { VkDeviceSize bufferSize = sizeof(uint16_t) * indices_size; VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; get_buffer(application, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &stagingBuffer, &stagingBufferMemory); void* data; vkMapMemory(application->vk_device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices, (size_t) bufferSize); vkUnmapMemory(application->vk_device, stagingBufferMemory); get_buffer(application, bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, index_buffer, index_buffer_memory); copy_buffer(application, stagingBuffer, *index_buffer, bufferSize); vkDestroyBuffer(application->vk_device, stagingBuffer, VK_NULL_HANDLE); vkFreeMemory(application->vk_device, stagingBufferMemory, VK_NULL_HANDLE); } VkDescriptorSetLayout get_descriptor_set_layout(const application_t* application) { VkDescriptorSetLayout vk_descriptor_set_layout; VkDescriptorSetLayoutBinding vk_descriptor_set_layout_binding; vk_descriptor_set_layout_binding.binding = 0; vk_descriptor_set_layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; vk_descriptor_set_layout_binding.descriptorCount = 1; vk_descriptor_set_layout_binding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; vk_descriptor_set_layout_binding.pImmutableSamplers = VK_NULL_HANDLE; // Optional VkDescriptorSetLayoutCreateInfo layoutInfo; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 1; layoutInfo.pBindings = &vk_descriptor_set_layout_binding; layoutInfo.flags = 0; layoutInfo.pNext = VK_NULL_HANDLE; if (vkCreateDescriptorSetLayout(application->vk_device, &layoutInfo, VK_NULL_HANDLE, &vk_descriptor_set_layout) != VK_SUCCESS) { printf("failed to create descriptor set layout!\n"); } printf("Created descriptor set layout\n"); return vk_descriptor_set_layout; } void get_uniform_buffers(const application_t* application, VkBuffer** vk_uniform_buffers, VkDeviceMemory** vk_uniform_buffers_memory, size_t* vk_uniform_buffers_size) { VkDeviceSize bufferSize = sizeof(uniform_buffer_t); (*vk_uniform_buffers_size) = application->swapchain_images_size; VkBuffer* uniform_buffer = (VkBuffer* )malloc(sizeof(VkBuffer ) * application->swapchain_images_size); VkDeviceMemory* uniform_buffer_memory = (VkDeviceMemory*)malloc(sizeof(VkDeviceMemory ) * application->swapchain_images_size); for (size_t i = 0; i < application->swapchain_images_size; i++) { get_buffer(application, bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniform_buffer[i], &uniform_buffer_memory[i]); } *vk_uniform_buffers = uniform_buffer; *vk_uniform_buffers_memory = uniform_buffer_memory; } VkDescriptorPool get_descriptor_pool(const application_t* application) { VkDescriptorPoolSize poolSize; poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSize.descriptorCount = application->swapchain_images_size; VkDescriptorPoolCreateInfo poolInfo; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = 1; poolInfo.pPoolSizes = &poolSize; poolInfo.flags = 0; poolInfo.pNext = VK_NULL_HANDLE; poolInfo.maxSets = application->swapchain_images_size; VkDescriptorPool descriptorPool; if (vkCreateDescriptorPool(application->vk_device, &poolInfo, VK_NULL_HANDLE, &descriptorPool) != VK_SUCCESS) { printf("failed to create descriptor pool!\n"); } return descriptorPool; } VkDescriptorSet* get_descriptor_sets(const application_t* application) { VkDescriptorSetLayout layouts[application->swapchain_images_size]; for(size_t i = 0; i < application->swapchain_images_size; i++) { layouts[i]= application->vk_descriptor_set_layout; } VkDescriptorSetAllocateInfo allocInfo; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = application->vk_descriptor_pool; allocInfo.descriptorSetCount = application->swapchain_images_size; allocInfo.pSetLayouts = layouts; allocInfo.pNext = VK_NULL_HANDLE; VkDescriptorSet* descriptorSets = (VkDescriptorSet*)malloc(sizeof(VkDescriptorSet) * application->swapchain_images_size); if (vkAllocateDescriptorSets(application->vk_device, &allocInfo, descriptorSets) != VK_SUCCESS) { printf("failed to allocate descriptor sets!\n"); exit(1); } for (size_t i = 0; i < application->swapchain_images_size; i++) { VkDescriptorBufferInfo bufferInfo; bufferInfo.buffer = application->vk_uniform_buffers[i]; bufferInfo.offset = 0; bufferInfo.range = sizeof(uniform_buffer_t); VkWriteDescriptorSet descriptorWrite; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = descriptorSets[i]; descriptorWrite.dstBinding = 0; descriptorWrite.dstArrayElement = 0; descriptorWrite.pNext = VK_NULL_HANDLE; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorWrite.descriptorCount = 1; descriptorWrite.pBufferInfo = &bufferInfo; descriptorWrite.pImageInfo = VK_NULL_HANDLE; // Optional descriptorWrite.pTexelBufferView = VK_NULL_HANDLE; // Optional vkUpdateDescriptorSets(application->vk_device, 1, &descriptorWrite, 0, VK_NULL_HANDLE); } return descriptorSets; } void createTextureImage(const application_t* application) { int texWidth, texHeight, texChannels; stbi_uc* pixels = stbi_load("C:\\projects\\CVulkan\\textures\\texture.jpg", &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); uint32_t image_size = texWidth * texHeight * 4; VkDeviceSize vk_image_size = (uint64_t)image_size; if (!pixels) { printf("failed to load texture image!"); exit(1); } VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; get_buffer(application, vk_image_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &stagingBuffer, &stagingBufferMemory); void* data; vkMapMemory(application->vk_device, stagingBufferMemory, 0, vk_image_size, 0, &data); memcpy(data, pixels, image_size); vkUnmapMemory(application->vk_device, stagingBufferMemory); stbi_image_free(pixels); VkImage textureImage; VkDeviceMemory textureImageMemory; VkImageCreateInfo imageInfo; imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageInfo.imageType = VK_IMAGE_TYPE_2D; imageInfo.extent.width = texWidth; imageInfo.extent.height =texHeight; imageInfo.extent.depth = 1; imageInfo.mipLevels = 1; imageInfo.arrayLayers = 1; imageInfo.format = VK_FORMAT_R8G8B8A8_SRGB; imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageInfo.flags = 0; // Optional imageInfo.pNext = VK_NULL_HANDLE; if (vkCreateImage(application->vk_device, &imageInfo, VK_NULL_HANDLE, &textureImage) != VK_SUCCESS) { printf("failed to create image!"); exit(1); } VkMemoryRequirements memRequirements; vkGetImageMemoryRequirements(application->vk_device, textureImage, &memRequirements); VkMemoryAllocateInfo allocInfo; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = find_memory_index(application, memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); if (vkAllocateMemory(application->vk_device, &allocInfo, VK_NULL_HANDLE, &textureImageMemory) != VK_SUCCESS) { printf("failed to allocate image memory!"); exit(1); } vkBindImageMemory(application->vk_device, textureImage, textureImageMemory, 0); }
40.391608
203
0.743611
9e12bb88acf4daa8f1dc6ac7f6e7ed1a744530c7
19,364
c
C
arch/arm/mach/lpc11xx/lpc11xx.c
zhaohengyi/bitthunder
9c4a9ea8561817aa0c5c48b9256c192142548b8f
[ "BSD-2-Clause-FreeBSD" ]
1
2019-05-05T09:52:24.000Z
2019-05-05T09:52:24.000Z
arch/arm/mach/lpc11xx/lpc11xx.c
zhaohengyi/bitthunder
9c4a9ea8561817aa0c5c48b9256c192142548b8f
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
arch/arm/mach/lpc11xx/lpc11xx.c
zhaohengyi/bitthunder
9c4a9ea8561817aa0c5c48b9256c192142548b8f
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/** * LPC11xx Platform Machine Description. * * @author Robert Steinbauer * * @copyright (c)2013 Riegl Laser Measurement Systems GmBH * @copyright (c)2013 Robert Steinbauer <rsteinbauer@riegl.com> * **/ #include <bitthunder.h> #include "rcc.h" #include "ioconfig.h" static const BT_RESOURCE oLPC11xx_gpio_resources[] = { { .ulStart = BT_CONFIG_MACH_LPC11xx_GPIO_BASE, .ulEnd = BT_CONFIG_MACH_LPC11xx_GPIO_BASE + BT_SIZE_4K - 1, .ulFlags = BT_RESOURCE_MEM, }, { .ulStart = 0, .ulEnd = BT_CONFIG_MACH_LPC11xx_TOTAL_GPIOS-1, .ulFlags = BT_RESOURCE_IO, }, { .ulStart = 44, .ulEnd = 47, .ulFlags = BT_RESOURCE_IRQ, }, }; /** * By using the BT_INTEGRATED_DEVICE_DEF macro, we ensure that this structure is * placed into the device manager's integrated device table. * * This allows it to be automatically enumerated without "registering" a driver. **/ BT_INTEGRATED_DEVICE_DEF oLPC11xx_gpio_device = { .name = "LPC11xx,gpio", .ulTotalResources = BT_ARRAY_SIZE(oLPC11xx_gpio_resources), .pResources = oLPC11xx_gpio_resources, }; static const BT_RESOURCE oLPC11xx_nvic_resources[] = { { .ulStart = BT_CONFIG_ARCH_ARM_NVIC_BASE, .ulEnd = BT_CONFIG_ARCH_ARM_NVIC_BASE + BT_SIZE_4K, .ulFlags = BT_RESOURCE_MEM, }, { .ulStart = 0, .ulEnd = BT_CONFIG_ARCH_ARM_NVIC_TOTAL_IRQS - 1, .ulFlags = BT_RESOURCE_IRQ, }, }; static const BT_INTEGRATED_DEVICE oLPC11xx_nvic_device = { .name = "arm,common,nvic", .ulTotalResources = BT_ARRAY_SIZE(oLPC11xx_nvic_resources), .pResources = oLPC11xx_nvic_resources, }; static const BT_RESOURCE oLPC11xx_systick_resources[] = { { .ulStart = 0xE000E010, .ulEnd = 0xE000E01F, .ulFlags = BT_RESOURCE_MEM, }, { .ulStart = 32, .ulEnd = 32, .ulFlags = BT_RESOURCE_IRQ, }, }; static const BT_INTEGRATED_DEVICE oLPC11xx_systick_device = { .name = "arm,cortex-mx,systick", .ulTotalResources = BT_ARRAY_SIZE(oLPC11xx_systick_resources), .pResources = oLPC11xx_systick_resources, }; static void lpc11xx_gpio_init(void) { #ifdef BT_CONFIG_LPC11xx_PIO0_0_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_0, BT_CONFIG_LPC11xx_PIO0_0_FUNCTION, BT_CONFIG_LPC11xx_PIO0_0_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_0_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_1_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_1, BT_CONFIG_LPC11xx_PIO0_1_FUNCTION, BT_CONFIG_LPC11xx_PIO0_1_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_1_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_2_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_2, BT_CONFIG_LPC11xx_PIO0_2_FUNCTION, BT_CONFIG_LPC11xx_PIO0_2_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_2_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_3_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_3, BT_CONFIG_LPC11xx_PIO0_3_FUNCTION, BT_CONFIG_LPC11xx_PIO0_3_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_3_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_4_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_4, BT_CONFIG_LPC11xx_PIO0_4_FUNCTION, BT_CONFIG_LPC11xx_PIO0_4_MODE, BT_CONFIG_LPC11xx_PIO0_4_AD, BT_CONFIG_LPC11xx_PIO0_4_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_5_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_5, BT_CONFIG_LPC11xx_PIO0_5_FUNCTION, BT_CONFIG_LPC11xx_PIO0_5_MODE, BT_CONFIG_LPC11xx_PIO0_5_AD, BT_CONFIG_LPC11xx_PIO0_5_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_6_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_6, BT_CONFIG_LPC11xx_PIO0_6_FUNCTION, BT_CONFIG_LPC11xx_PIO0_6_MODE, BT_CONFIG_LPC11xx_PIO0_6_AD, BT_CONFIG_LPC11xx_PIO0_6_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_7_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_7, BT_CONFIG_LPC11xx_PIO0_7_FUNCTION, BT_CONFIG_LPC11xx_PIO0_7_MODE, BT_CONFIG_LPC11xx_PIO0_7_AD, BT_CONFIG_LPC11xx_PIO0_7_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_8_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_8, BT_CONFIG_LPC11xx_PIO0_8_FUNCTION, BT_CONFIG_LPC11xx_PIO0_8_MODE, BT_CONFIG_LPC11xx_PIO0_8_AD, BT_CONFIG_LPC11xx_PIO0_8_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_9_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_9, BT_CONFIG_LPC11xx_PIO0_9_FUNCTION, BT_CONFIG_LPC11xx_PIO0_9_MODE, BT_CONFIG_LPC11xx_PIO0_9_AD, BT_CONFIG_LPC11xx_PIO0_9_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_10_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_10, BT_CONFIG_LPC11xx_PIO0_10_FUNCTION, BT_CONFIG_LPC11xx_PIO0_10_MODE, BT_CONFIG_LPC11xx_PIO0_10_AD, BT_CONFIG_LPC11xx_PIO0_10_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_11_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_11, BT_CONFIG_LPC11xx_PIO0_11_FUNCTION, BT_CONFIG_LPC11xx_PIO0_11_MODE, BT_CONFIG_LPC11xx_PIO0_11_AD, BT_CONFIG_LPC11xx_PIO0_11_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_12_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_12, BT_CONFIG_LPC11xx_PIO0_12_FUNCTION, BT_CONFIG_LPC11xx_PIO0_12_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_12_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_13_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_13, BT_CONFIG_LPC11xx_PIO0_13_FUNCTION, BT_CONFIG_LPC11xx_PIO0_13_MODE, BT_CONFIG_LPC11xx_PIO0_13_AD, BT_CONFIG_LPC11xx_PIO0_13_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_14_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_14, BT_CONFIG_LPC11xx_PIO0_14_FUNCTION, BT_CONFIG_LPC11xx_PIO0_14_MODE, BT_CONFIG_LPC11xx_PIO0_14_AD, BT_CONFIG_LPC11xx_PIO0_14_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_15_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_15, BT_CONFIG_LPC11xx_PIO0_15_FUNCTION, BT_CONFIG_LPC11xx_PIO0_15_MODE, BT_CONFIG_LPC11xx_PIO0_15_AD, BT_CONFIG_LPC11xx_PIO0_15_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_16_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_16, BT_CONFIG_LPC11xx_PIO0_16_FUNCTION, BT_CONFIG_LPC11xx_PIO0_16_MODE, BT_CONFIG_LPC11xx_PIO0_16_AD, BT_CONFIG_LPC11xx_PIO0_16_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_17_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_17, BT_CONFIG_LPC11xx_PIO0_17_FUNCTION, BT_CONFIG_LPC11xx_PIO0_17_MODE, BT_CONFIG_LPC11xx_PIO0_17_AD, BT_CONFIG_LPC11xx_PIO0_17_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_18_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_18, BT_CONFIG_LPC11xx_PIO0_18_FUNCTION, BT_CONFIG_LPC11xx_PIO0_18_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_18_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_19_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_19, BT_CONFIG_LPC11xx_PIO0_19_FUNCTION, BT_CONFIG_LPC11xx_PIO0_19_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_19_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_20_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_20, BT_CONFIG_LPC11xx_PIO0_20_FUNCTION, BT_CONFIG_LPC11xx_PIO0_20_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_20_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_21_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_21, BT_CONFIG_LPC11xx_PIO0_21_FUNCTION, BT_CONFIG_LPC11xx_PIO0_21_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_21_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_22_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_22, BT_CONFIG_LPC11xx_PIO0_22_FUNCTION, BT_CONFIG_LPC11xx_PIO0_22_MODE, BT_CONFIG_LPC11xx_PIO0_22_AD, BT_CONFIG_LPC11xx_PIO0_22_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_23_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_23, BT_CONFIG_LPC11xx_PIO0_23_FUNCTION, BT_CONFIG_LPC11xx_PIO0_23_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_23_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_24_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_24, BT_CONFIG_LPC11xx_PIO0_24_FUNCTION, BT_CONFIG_LPC11xx_PIO0_24_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_24_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_25_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_25, BT_CONFIG_LPC11xx_PIO0_25_FUNCTION, BT_CONFIG_LPC11xx_PIO0_25_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_25_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_26_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_26, BT_CONFIG_LPC11xx_PIO0_26_FUNCTION, BT_CONFIG_LPC11xx_PIO0_26_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_26_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_27_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_27, BT_CONFIG_LPC11xx_PIO0_27_FUNCTION, BT_CONFIG_LPC11xx_PIO0_27_MODE, BT_CONFIG_LPC11xx_PIO0_27_AD, BT_CONFIG_LPC11xx_PIO0_27_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_28_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_28, BT_CONFIG_LPC11xx_PIO0_28_FUNCTION, BT_CONFIG_LPC11xx_PIO0_28_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_28_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_29_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_29, BT_CONFIG_LPC11xx_PIO0_29_FUNCTION, BT_CONFIG_LPC11xx_PIO0_29_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_29_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_30_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_30, BT_CONFIG_LPC11xx_PIO0_30_FUNCTION, BT_CONFIG_LPC11xx_PIO0_30_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_30_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO0_31_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO0_31, BT_CONFIG_LPC11xx_PIO0_31_FUNCTION, BT_CONFIG_LPC11xx_PIO0_31_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO0_31_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_0_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_0, BT_CONFIG_LPC11xx_PIO1_0_FUNCTION, BT_CONFIG_LPC11xx_PIO1_0_MODE, BT_CONFIG_LPC11xx_PIO1_0_AD, BT_CONFIG_LPC11xx_PIO1_0_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_1_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_1, BT_CONFIG_LPC11xx_PIO1_1_FUNCTION, BT_CONFIG_LPC11xx_PIO1_1_MODE, BT_CONFIG_LPC11xx_PIO1_1_AD, BT_CONFIG_LPC11xx_PIO1_1_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_2_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_2, BT_CONFIG_LPC11xx_PIO1_2_FUNCTION, BT_CONFIG_LPC11xx_PIO1_2_MODE, BT_CONFIG_LPC11xx_PIO1_2_AD, BT_CONFIG_LPC11xx_PIO1_2_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_3_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_3, BT_CONFIG_LPC11xx_PIO1_3_FUNCTION, BT_CONFIG_LPC11xx_PIO1_3_MODE, BT_CONFIG_LPC11xx_PIO1_3_AD, BT_CONFIG_LPC11xx_PIO1_3_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_4_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_4, BT_CONFIG_LPC11xx_PIO1_4_FUNCTION, BT_CONFIG_LPC11xx_PIO1_4_MODE, BT_CONFIG_LPC11xx_PIO1_4_AD, BT_CONFIG_LPC11xx_PIO1_4_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_5_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_5, BT_CONFIG_LPC11xx_PIO1_5_FUNCTION, BT_CONFIG_LPC11xx_PIO1_5_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO1_5_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_6_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_6, BT_CONFIG_LPC11xx_PIO1_6_FUNCTION, BT_CONFIG_LPC11xx_PIO1_6_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO1_6_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_7_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_7, BT_CONFIG_LPC11xx_PIO1_7_FUNCTION, BT_CONFIG_LPC11xx_PIO1_7_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO1_7_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_8_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_8, BT_CONFIG_LPC11xx_PIO1_8_FUNCTION, BT_CONFIG_LPC11xx_PIO1_8_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO1_8_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_9_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_9, BT_CONFIG_LPC11xx_PIO1_9_FUNCTION, BT_CONFIG_LPC11xx_PIO1_9_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO1_9_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_10_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_10, BT_CONFIG_LPC11xx_PIO1_10_FUNCTION, BT_CONFIG_LPC11xx_PIO1_10_MODE, BT_CONFIG_LPC11xx_PIO1_10_AD, BT_CONFIG_LPC11xx_PIO1_10_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO1_11_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO1_11, BT_CONFIG_LPC11xx_PIO1_11_FUNCTION, BT_CONFIG_LPC11xx_PIO1_11_MODE, BT_CONFIG_LPC11xx_PIO1_11_AD, BT_CONFIG_LPC11xx_PIO1_11_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_0_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_0, BT_CONFIG_LPC11xx_PIO2_0_FUNCTION, BT_CONFIG_LPC11xx_PIO2_0_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_0_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_1_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_1, BT_CONFIG_LPC11xx_PIO2_1_FUNCTION, BT_CONFIG_LPC11xx_PIO2_1_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_1_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_2_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_2, BT_CONFIG_LPC11xx_PIO2_2_FUNCTION, BT_CONFIG_LPC11xx_PIO2_2_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_2_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_3_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_3, BT_CONFIG_LPC11xx_PIO2_3_FUNCTION, BT_CONFIG_LPC11xx_PIO2_3_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_3_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_4_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_4, BT_CONFIG_LPC11xx_PIO2_4_FUNCTION, BT_CONFIG_LPC11xx_PIO2_4_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_4_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_5_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_5, BT_CONFIG_LPC11xx_PIO2_5_FUNCTION, BT_CONFIG_LPC11xx_PIO2_5_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_5_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_6_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_6, BT_CONFIG_LPC11xx_PIO2_6_FUNCTION, BT_CONFIG_LPC11xx_PIO2_6_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_6_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_7_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_7, BT_CONFIG_LPC11xx_PIO2_7_FUNCTION, BT_CONFIG_LPC11xx_PIO2_7_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_7_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_8_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_8, BT_CONFIG_LPC11xx_PIO2_8_FUNCTION, BT_CONFIG_LPC11xx_PIO2_8_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_8_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_9_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_9, BT_CONFIG_LPC11xx_PIO2_9_FUNCTION, BT_CONFIG_LPC11xx_PIO2_9_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_9_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_10_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_10, BT_CONFIG_LPC11xx_PIO2_10_FUNCTION, BT_CONFIG_LPC11xx_PIO2_10_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_10_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO2_11_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO2_11, BT_CONFIG_LPC11xx_PIO2_11_FUNCTION, BT_CONFIG_LPC11xx_PIO2_11_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO2_11_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_0_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_0, BT_CONFIG_LPC11xx_PIO3_0_FUNCTION, BT_CONFIG_LPC11xx_PIO3_0_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_0_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_1_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_1, BT_CONFIG_LPC11xx_PIO3_1_FUNCTION, BT_CONFIG_LPC11xx_PIO3_1_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_1_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_2_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_2, BT_CONFIG_LPC11xx_PIO3_2_FUNCTION, BT_CONFIG_LPC11xx_PIO3_2_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_2_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_3_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_3, BT_CONFIG_LPC11xx_PIO3_3_FUNCTION, BT_CONFIG_LPC11xx_PIO3_3_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_3_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_4_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_4, BT_CONFIG_LPC11xx_PIO3_4_FUNCTION, BT_CONFIG_LPC11xx_PIO3_4_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_4_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_5_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_5, BT_CONFIG_LPC11xx_PIO3_5_FUNCTION, BT_CONFIG_LPC11xx_PIO3_5_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_5_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_6_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_6, BT_CONFIG_LPC11xx_PIO3_6_FUNCTION, BT_CONFIG_LPC11xx_PIO3_6_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_6_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_7_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_7, BT_CONFIG_LPC11xx_PIO3_7_FUNCTION, BT_CONFIG_LPC11xx_PIO3_7_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_7_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_8_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_8, BT_CONFIG_LPC11xx_PIO3_8_FUNCTION, BT_CONFIG_LPC11xx_PIO3_8_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_8_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_9_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_9, BT_CONFIG_LPC11xx_PIO3_9_FUNCTION, BT_CONFIG_LPC11xx_PIO3_9_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_9_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_10_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_10, BT_CONFIG_LPC11xx_PIO3_10_FUNCTION, BT_CONFIG_LPC11xx_PIO3_10_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_10_OPENDRAIN); #endif #ifdef BT_CONFIG_LPC11xx_PIO3_11_FUNCTION BT_LPC11xx_SetIOConfig(LPC11xx_PIO3_11, BT_CONFIG_LPC11xx_PIO3_11_FUNCTION, BT_CONFIG_LPC11xx_PIO3_11_MODE, BT_FALSE, BT_CONFIG_LPC11xx_PIO3_11_OPENDRAIN); #endif #ifdef BT_CONFIG_MACH_LPC11Cxx if (*LPC11xx_PIO0_10 & LPC11xx_PIO0_10_SCK0) *LPC11xx_IOCON_SCK_LOC = 0; else if (*LPC11xx_PIO2_11 & LPC11xx_PIO2_11_SCK0) *LPC11xx_IOCON_SCK_LOC = 1; else if (*LPC11xx_PIO0_6 & LPC11xx_PIO0_6_SCK0) *LPC11xx_IOCON_SCK_LOC = 2; #endif } static BT_u32 lpc11xx_get_cpu_clock_frequency() { return BT_LPC11xx_GetSystemFrequency(); } static BT_u32 lpc11xx_machine_init() { BT_LPC11xx_SetSystemFrequency(BT_CONFIG_MAINCLK_SRC, BT_CONFIG_SYSCLK_CTRL, BT_CONFIG_PLLCLK_SRC, BT_CONFIG_PLLCLK_CTRL, BT_CONFIG_WDTCLK_CTRL, BT_CONFIG_SYSCLK_DIV); lpc11xx_gpio_init(); return BT_ERR_NONE; } #ifdef BT_CONFIG_MACH_LPC11xx_I2C_0 static const BT_RESOURCE oLPC11xx_i2c0_resources[] = { { .ulStart = BT_CONFIG_MACH_LPC11xx_I2C0_BASE, .ulEnd = BT_CONFIG_MACH_LPC11xx_I2C0_BASE + BT_SIZE_4K - 1, .ulFlags = BT_RESOURCE_MEM, }, { .ulStart = 31, .ulEnd = 31, .ulFlags = BT_RESOURCE_IRQ, }, { .ulStart = BT_CONFIG_MACH_LPC11xx_I2C_0_BUSID, .ulEnd = BT_CONFIG_MACH_LPC11xx_I2C_0_BUSID, .ulFlags = BT_RESOURCE_BUSID, }, { .ulStart = BT_CONFIG_MACH_LPC11xx_I2C_0_SPEED, .ulEnd = BT_CONFIG_MACH_LPC11xx_I2C_0_SPEED, .ulFlags = BT_RESOURCE_INTEGER, }, }; BT_INTEGRATED_DEVICE_DEF oLPC11xx_i2c0_device = { .name = "LPC11xx,i2c", .ulTotalResources = BT_ARRAY_SIZE(oLPC11xx_i2c0_resources), .pResources = oLPC11xx_i2c0_resources, }; const BT_DEVFS_INODE_DEF oLPC11xx_i2c0_inode = { .szpName = "i2c0", .pDevice = &oLPC11xx_i2c0_device, }; #endif #ifdef BT_CONFIG_MACH_LPC11xx_UART_0 static const BT_RESOURCE oLPC11xx_uart0_resources[] = { { .ulStart = BT_CONFIG_MACH_LPC11xx_UART0_BASE, .ulEnd = BT_CONFIG_MACH_LPC11xx_UART0_BASE + BT_SIZE_4K - 1, .ulFlags = BT_RESOURCE_MEM, }, { .ulStart = 37, .ulEnd = 37, .ulFlags = BT_RESOURCE_IRQ, }, }; static const BT_INTEGRATED_DEVICE oLPC11xx_uart0_device = { .name = "LPC11xx,usart", .ulTotalResources = BT_ARRAY_SIZE(oLPC11xx_uart0_resources), .pResources = oLPC11xx_uart0_resources, }; const BT_DEVFS_INODE_DEF oLPC11xx_uart0_inode = { .szpName = BT_CONFIG_MACH_LPC11xx_UART_0_INODE_NAME, .pDevice = &oLPC11xx_uart0_device, }; #endif BT_MACHINE_START(ARM, CORTEX_M0, "LPC Microcontroller Platform") .ulSystemClockHz = BT_CONFIG_MACH_LPC11xx_SYSCLOCK_FREQ, .pfnGetCpuClockFrequency = lpc11xx_get_cpu_clock_frequency, .pfnMachineInit = lpc11xx_machine_init, .pInterruptController = &oLPC11xx_nvic_device, .pSystemTimer = &oLPC11xx_systick_device, #ifdef BT_CONFIG_MACH_LPC11xx_BOOTLOG_UART_NULL .pBootLogger = NULL, #endif #ifdef BT_CONFIG_MACH_LPC11xx_BOOTLOG_UART_0 .pBootLogger = &oLPC11xx_uart0_device, #endif BT_MACHINE_END
47.577396
177
0.857571
9ee7df128f5935eeda7302e20f6d8de5f2b34278
2,422
h
C
test/core/configuration/mock/MockIHTTPClientConfiguration.h
Dynatrace/openkit-native
e072599196ea9086a2f9cfe67bae701d7d470fc0
[ "Apache-2.0" ]
8
2018-09-18T15:33:51.000Z
2022-02-20T12:19:03.000Z
test/core/configuration/mock/MockIHTTPClientConfiguration.h
Dynatrace/openkit-native
e072599196ea9086a2f9cfe67bae701d7d470fc0
[ "Apache-2.0" ]
2
2018-09-19T07:15:36.000Z
2019-03-14T17:16:19.000Z
test/core/configuration/mock/MockIHTTPClientConfiguration.h
Dynatrace/openkit-native
e072599196ea9086a2f9cfe67bae701d7d470fc0
[ "Apache-2.0" ]
15
2018-09-17T07:37:06.000Z
2020-10-02T11:47:47.000Z
/** * Copyright 2018-2021 Dynatrace LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _TEST_CORE_CONFIGURATION_MOCK_MOCKIHTTPCLIENTCONFIGURATION_H #define _TEST_CORE_CONFIGURATION_MOCK_MOCKIHTTPCLIENTCONFIGURATION_H #include "../../../DefaultValues.h" #include "OpenKit/ISSLTrustManager.h" #include "core/UTF8String.h" #include "core/configuration/IHTTPClientConfiguration.h" #include "gmock/gmock.h" #include <cstdint> #include <memory> namespace test { class MockIHTTPClientConfiguration : public core::configuration::IHTTPClientConfiguration { public: MockIHTTPClientConfiguration() { ON_CALL(*this, getBaseURL()) .WillByDefault(testing::ReturnRef(DefaultValues::UTF8_EMPTY_STRING)); ON_CALL(*this, getApplicationID()) .WillByDefault(testing::ReturnRef(DefaultValues::UTF8_EMPTY_STRING)); ON_CALL(*this, getSSLTrustManager()) .WillByDefault(testing::Return(nullptr)); } ~MockIHTTPClientConfiguration() override = default; static std::shared_ptr<testing::NiceMock<MockIHTTPClientConfiguration>> createNice() { return std::make_shared<testing::NiceMock<MockIHTTPClientConfiguration>>(); } static std::shared_ptr<testing::StrictMock<MockIHTTPClientConfiguration>> createStrict() { return std::make_shared<testing::StrictMock<MockIHTTPClientConfiguration>>(); } MOCK_METHOD(const core::UTF8String& , getBaseURL, (), (const, override)); MOCK_METHOD(int32_t, getServerID, (), (const, override)); MOCK_METHOD(const core::UTF8String& , getApplicationID, (), (const, override)); MOCK_METHOD(std::shared_ptr<openkit::ISSLTrustManager>, getSSLTrustManager, (), (const, override)); MOCK_METHOD(std::shared_ptr<openkit::IHttpRequestInterceptor>, getHttpRequestInterceptor, (), (const, override)); MOCK_METHOD(std::shared_ptr<openkit::IHttpResponseInterceptor>, getHttpResponseInterceptor, (), (const, override)); }; } #endif
32.293333
117
0.760528
7f3ea2c09603cb1507c10bc0653bee7fc66ca621
2,034
h
C
ble/SDK_585/sdk/platform/arch/main/arch_ram.h
moiify/llofo
71d81354c56b7e7c5b68ff667f18223d0e687df5
[ "MIT" ]
1
2022-02-28T16:11:39.000Z
2022-02-28T16:11:39.000Z
ble/SDK_585/sdk/platform/arch/main/arch_ram.h
moiify/llofo
71d81354c56b7e7c5b68ff667f18223d0e687df5
[ "MIT" ]
null
null
null
ble/SDK_585/sdk/platform/arch/main/arch_ram.h
moiify/llofo
71d81354c56b7e7c5b68ff667f18223d0e687df5
[ "MIT" ]
null
null
null
/** **************************************************************************************** * * @file arch_ram.h * * @brief System RAM definitions. * * Copyright (C) 2017 Dialog Semiconductor. * This computer program includes Confidential, Proprietary Information * of Dialog Semiconductor. All Rights Reserved. * * <bluetooth.support@diasemi.com> * **************************************************************************************** */ #ifndef _ARCH_RAM_H_ #define _ARCH_RAM_H_ /* * INCLUDE FILES **************************************************************************************** */ #include <stdint.h> /* * DEFINES **************************************************************************************** */ // The base addresses of the 4 RAM blocks #define RAM_1_BASE_ADDR (0x07FC0000) #define RAM_2_BASE_ADDR (0x07FC8000) #define RAM_3_BASE_ADDR (0x07FCC000) #define RAM_4_BASE_ADDR (0x07FD0000) #if defined (CFG_CUSTOM_SCATTER_FILE) #if defined (CFG_RETAIN_RAM_1_BLOCK) #define RETAIN_RAM_1_BLOCK (0x01) #else #define RETAIN_RAM_1_BLOCK (0) #endif #if defined (CFG_RETAIN_RAM_2_BLOCK) #define RETAIN_RAM_2_BLOCK (0x02) #else #define RETAIN_RAM_2_BLOCK (0) #endif #if defined (CFG_RETAIN_RAM_3_BLOCK) #define RETAIN_RAM_3_BLOCK (0x04) #else #define RETAIN_RAM_3_BLOCK (0) #endif #else #define RETAIN_RAM_1_BLOCK (0x01) #define RETAIN_RAM_2_BLOCK (0x02) #define RETAIN_RAM_3_BLOCK (0x04) // Keil ARM linker generated symbols extern uint32_t Image$$ER_IROM3$$Base; extern uint32_t Image$$ER_IROM3$$Length; extern uint32_t Image$$RET_DATA_UNINIT$$Base; #endif // CFG_CUSTOM_SCATTER_FILE extern uint32_t heap_mem_area_not_ret$$Base; extern uint32_t heap_mem_area_not_ret$$Length; #define RETAIN_RAM_4_BLOCK (0x08) #endif // _ARCH_RAM_H_
26.415584
89
0.542281
3d0644039f90635e2ee24efcac831e0954a3e590
5,411
h
C
libs/Qt5.7.0/5.7/gcc_64/include/QtQml/5.7.0/QtQml/private/qpointervaluepair_p.h
ankitakash2007/Slate
aad79cd0a353a94f2a049575a91ff961953f3af0
[ "MIT" ]
1
2021-08-30T07:17:40.000Z
2021-08-30T07:17:40.000Z
libs/Qt5.7.0/5.7/gcc_64/include/QtQml/5.7.0/QtQml/private/qpointervaluepair_p.h
ankitakash2007/Slate
aad79cd0a353a94f2a049575a91ff961953f3af0
[ "MIT" ]
null
null
null
libs/Qt5.7.0/5.7/gcc_64/include/QtQml/5.7.0/QtQml/private/qpointervaluepair_p.h
ankitakash2007/Slate
aad79cd0a353a94f2a049575a91ff961953f3af0
[ "MIT" ]
1
2021-07-13T18:24:54.000Z
2021-07-13T18:24:54.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QPOINTERVALUEPAIR_P_H #define QPOINTERVALUEPAIR_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <QtCore/qglobal.h> #include <private/qflagpointer_p.h> QT_BEGIN_NAMESPACE // QPointerValuePair is intended to help reduce the memory consumption of a class. // In the common case, QPointerValuePair behaves like a pointer. In this mode, it // consumes the same memory as a regular pointer. // Additionally, QPointerValuePair can store an arbitrary value type in *addition* // to the pointer. In this case, it uses slightly more memory than the pointer and // value type combined. // Consequently, this class is most useful in cases where a pointer is always stored // and a value type is rarely stored. template<typename P, typename V> class QPointerValuePair { public: inline QPointerValuePair(); inline QPointerValuePair(P *); inline ~QPointerValuePair(); inline bool isNull() const; inline bool flag() const; inline void setFlag(); inline void clearFlag(); inline void setFlagValue(bool); inline QPointerValuePair<P, V> &operator=(P *); inline P *operator->() const; inline P *operator*() const; inline bool hasValue() const; inline V &value(); inline const V *constValue() const; private: struct Value { P *pointer; V value; }; QBiPointer<P, Value> d; }; template<typename P, typename V> QPointerValuePair<P, V>::QPointerValuePair() { } template<typename P, typename V> QPointerValuePair<P, V>::QPointerValuePair(P *p) : d(p) { } template<typename P, typename V> QPointerValuePair<P, V>::~QPointerValuePair() { if (d.isT2()) delete d.asT2(); } template<typename P, typename V> bool QPointerValuePair<P, V>::isNull() const { if (d.isT1()) return 0 == d.asT1(); else return d.asT2()->pointer == 0; } template<typename P, typename V> bool QPointerValuePair<P, V>::flag() const { return d.flag(); } template<typename P, typename V> void QPointerValuePair<P, V>::setFlag() { d.setFlag(); } template<typename P, typename V> void QPointerValuePair<P, V>::clearFlag() { d.clearFlag(); } template<typename P, typename V> void QPointerValuePair<P, V>::setFlagValue(bool v) { d.setFlagValue(v); } template<typename P, typename V> QPointerValuePair<P, V> &QPointerValuePair<P, V>::operator=(P *o) { if (d.isT1()) d = o; else d.asT2()->pointer = o; return *this; } template<typename P, typename V> P *QPointerValuePair<P, V>::operator->() const { if (d.isT1()) return d.asT1(); else return d.asT2()->pointer; } template<typename P, typename V> P *QPointerValuePair<P, V>::operator*() const { if (d.isT1()) return d.asT1(); else return d.asT2()->pointer; } template<typename P, typename V> bool QPointerValuePair<P, V>::hasValue() const { return d.isT2(); } template<typename P, typename V> V &QPointerValuePair<P, V>::value() { if (d.isT1()) { P *p = d.asT1(); Value *value = new Value; value->pointer = p; d = value; } return d.asT2()->value; } // Will return null if hasValue() == false template<typename P, typename V> const V *QPointerValuePair<P, V>::constValue() const { if (d.isT2()) return &d.asT2()->value; else return 0; } QT_END_NAMESPACE #endif // QPOINTERVALUEPAIR_P_H
27.748718
84
0.682868
8296282345465824687d1b2ccc84a06722092dec
556
h
C
opal/mca/pmix/pmix4x/pmix/contrib/perf_tools/pmi2_pmap_parser.h
shengyushen/ompi
305beb263cc887a39efef455deb939cea6cebedf
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
opal/mca/pmix/pmix4x/pmix/contrib/perf_tools/pmi2_pmap_parser.h
shengyushen/ompi
305beb263cc887a39efef455deb939cea6cebedf
[ "BSD-3-Clause-Open-MPI" ]
1
2018-11-22T00:03:52.000Z
2018-11-22T02:48:48.000Z
opal/mca/pmix/pmix4x/pmix/contrib/perf_tools/pmi2_pmap_parser.h
shengyushen/ompi
305beb263cc887a39efef455deb939cea6cebedf
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
/* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * * Copyright (c) 2013 Mellanox Technologies, Inc. * All rights reserved. * Copyright (c) 2014-2018 Intel, Inc. All rights reserved. * $COPYRIGHT$ * Additional copyrights may follow * * $HEADER$ * */ /* This code was taken from Open MPI project, file opal/mca/pmix/s2/pmi2_pmap_parser.h */ #ifndef PMI2_PMAP_PARSER_H #define PMI2_PMAP_PARSER_H int *mca_common_pmi2_parse_pmap(char *pmap, int my_rank, int *node, int *nlrs); #endif
22.24
59
0.613309
c5c8ca410bd8d518360fe438f93d12cc0c89a031
15,462
c
C
src/pcap_file_io.c
1computerguy/mercury
193bf6432e4f53f1253965f5ca8634bd6ca69136
[ "BSD-2-Clause" ]
null
null
null
src/pcap_file_io.c
1computerguy/mercury
193bf6432e4f53f1253965f5ca8634bd6ca69136
[ "BSD-2-Clause" ]
null
null
null
src/pcap_file_io.c
1computerguy/mercury
193bf6432e4f53f1253965f5ca8634bd6ca69136
[ "BSD-2-Clause" ]
null
null
null
/* * pcap_file_io.c * * functions for reading and writing packets using the (old) libpcap * file format * * Copyright (c) 2019 Cisco Systems, Inc. All rights reserved. License at * https://github.com/cisco/mercury/blob/master/LICENSE */ #ifndef _GNU_SOURCE #define _GNU_SOURCE /* get fadvise() and fallocate() */ #endif #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <arpa/inet.h> #include <errno.h> #include "mercury.h" #include "pcap_file_io.h" #include "pkt_proc.h" #include "signal_handling.h" #include "utils.h" #include "llq.h" #include "buffer_stream.h" /* * constants used in file format */ static uint32_t magic = 0xa1b2c3d4; static uint32_t cagim = 0xd4c3b2a1; /* * global pcap header (one per file, at beginning) */ struct pcap_file_hdr { uint32_t magic_number; /* magic number */ uint16_t version_major; /* major version number */ uint16_t version_minor; /* minor version number */ int32_t thiszone; /* GMT to local correction */ uint32_t sigfigs; /* accuracy of timestamps */ uint32_t snaplen; /* max length of captured packets, in octets */ uint32_t network; /* data link type */ }; /* * packet header (one per packet, right before it) */ struct pcap_packet_hdr { uint32_t ts_sec; /* timestamp seconds */ uint32_t ts_usec; /* timestamp microseconds */ uint32_t incl_len; /* number of octets of packet saved in file */ uint32_t orig_len; /* actual length of packet */ }; // TBD: pack structure #define ONE_KB (1024) #define ONE_MB (1024 * ONE_KB) #ifndef FBUFSIZE #define STREAM_BUFFER_SIZE (ONE_MB) #else #define STREAM_BUFFER_SIZE FBUFSIZE #endif #define PRE_ALLOCATE_DISK_SPACE (100 * ONE_MB) static inline void set_file_io_buffer(struct pcap_file *f, const char *fname) { f->buffer = (unsigned char *) malloc(STREAM_BUFFER_SIZE); if (f->buffer != NULL) { if (setvbuf(f->file_ptr, (char *)f->buffer, _IOFBF, STREAM_BUFFER_SIZE) != 0) { printf("%s: error setting i/o buffer for file %s\n", strerror(errno), fname); free(f->buffer); f->buffer = NULL; } else { f->buf_len = STREAM_BUFFER_SIZE; } } else { printf("warning: could not malloc i/o buffer for %s\n", fname); } } enum status write_pcap_file_header(FILE *f) { struct pcap_file_hdr file_header; file_header.magic_number = magic; file_header.version_major = 2; file_header.version_minor = 4; file_header.thiszone = 0; /* no GMT correction for now */ file_header.sigfigs = 0; /* we don't claim sigfigs for now */ file_header.snaplen = 65535; file_header.network = 1; /* ethernet */ size_t items_written = fwrite(&file_header, sizeof(file_header), 1, f); if (items_written == 0) { perror("error writing pcap file header"); return status_err; } return status_ok; } enum status pcap_file_open(struct pcap_file *f, const char *fname, enum io_direction dir, int flags) { struct pcap_file_hdr file_header; ssize_t items_read; switch(dir) { case io_direction_reader: f->flags = O_RDONLY; break; case io_direction_writer: f->flags = O_WRONLY; break; default: printf("error: unsupported flag, other flags=0x%x\n", flags); return status_err; /* unsupported flags */ } if (f->flags == O_WRONLY) { /* create and open new file for writing */ f->file_ptr = fopen(fname, "w"); if (f->file_ptr == NULL) { printf("%s: error opening pcap file %s\n", strerror(errno), fname); return status_err; /* could not open file */ } f->fd = fileno(f->file_ptr); // save file descriptor if (f->fd < 0) { printf("%s: error getting file descriptor for pcap file %s\n", strerror(errno), fname); return status_err; /* system call failed */ } // set file i/o buffer set_file_io_buffer(f, fname); // set the file advisory for the read file #ifdef POSIX_FADV_SEQUENTIAL if (posix_fadvise(f->fd, 0, 0, POSIX_FADV_SEQUENTIAL) != 0) { printf("%s: Could not set file advisory for pcap file %s\n", strerror(errno), fname); } f->allocated_size = 0; // initialize if (fallocate(f->fd, FALLOC_FL_KEEP_SIZE, 0, PRE_ALLOCATE_DISK_SPACE) != 0) { printf("warning: %s: Could not pre-allocate %d MB disk space for pcap file %s\n", strerror(errno), PRE_ALLOCATE_DISK_SPACE, fname); } else { f->allocated_size = PRE_ALLOCATE_DISK_SPACE; // initial allocation } #endif enum status status = write_pcap_file_header(f->file_ptr); if (status) { perror("error writing pcap file header"); fclose(f->file_ptr); f->file_ptr = NULL; if (f->buffer != NULL) { free(f->buffer); f->buffer = NULL; } return status_err; } // initialize packets and bytes written f->bytes_written = sizeof(file_header); f->packets_written = 0; } else { /* O_RDONLY */ /* open existing file for reading */ f->file_ptr = fopen(fname, "r"); if (f->file_ptr == NULL) { printf("%s: error opening read file %s\n", strerror(errno), fname); return status_err; /* could not open file */ } f->fd = fileno(f->file_ptr); // save file descriptor if (f->fd < 0) { printf("%s: error getting file descriptor for read file %s\n", strerror(errno), fname); return status_err; /* system call failed */ } // set the file advisory for the read file #ifdef POSIX_FADV_SEQUENTIAL if (posix_fadvise(f->fd, 0, 0, POSIX_FADV_SEQUENTIAL) != 0) { printf("%s: Could not set file advisory for read file %s\n", strerror(errno), fname); } #endif // set file i/o buffer set_file_io_buffer(f, fname); f->bytes_written = 0L; // will never write any bytes to this file opened for reading // printf("info: file %s opened\n", fname); items_read = fread(&file_header, sizeof(file_header), 1, f->file_ptr); if (items_read == 0) { perror("could not read file header"); return status_err; /* could not read packet header from file */ } if (file_header.magic_number == magic) { f->byteswap = 0; // printf("file is in pcap format\nno byteswap needed\n"); } else if (file_header.magic_number == cagim) { f->byteswap = 1; // printf("file is in pcap format\nbyteswap is needed\n"); } else { printf("error: file %s not in pcap format (file header: %08x)\n", fname, file_header.magic_number); if (file_header.magic_number == 0x0a0d0d0a) { printf("error: pcap-ng format found; this format is currently unsupported\n"); } exit(255); } if (f->byteswap) { file_header.version_major = htons(file_header.version_major); file_header.version_minor = htons(file_header.version_minor); file_header.thiszone = htonl(file_header.thiszone); file_header.sigfigs = htonl(file_header.sigfigs); file_header.snaplen = htonl(file_header.snaplen); file_header.network = htonl(file_header.network); } } return status_ok; } enum status pcap_file_write_packet_direct(struct pcap_file *f, const void *packet, size_t length, unsigned int sec, unsigned int usec) { size_t items_written; struct pcap_packet_hdr packet_hdr; if (packet && !length) { printf("warning: attempt to write an empty packet\n"); return status_ok; } /* note: we never perform byteswap when writing */ packet_hdr.ts_sec = sec; packet_hdr.ts_usec = usec; packet_hdr.incl_len = length; packet_hdr.orig_len = length; // write the packet header items_written = fwrite(&packet_hdr, sizeof(struct pcap_packet_hdr), 1, f->file_ptr); if (items_written == 0) { perror("error: could not write packet header to output file\n"); return status_err; } // write the packet items_written = fwrite(packet, length, 1, f->file_ptr); if (items_written == 0) { perror("error: could not write packet data to output file\n"); return status_err; } f->bytes_written += length + sizeof(struct pcap_packet_hdr); f->packets_written++; #ifdef FALLOC_FL_KEEP_SIZE if ((f->allocated_size > 0) && (f->allocated_size - f->bytes_written) <= ONE_MB) { // need to allocate more if (fallocate(f->fd, FALLOC_FL_KEEP_SIZE, f->bytes_written, PRE_ALLOCATE_DISK_SPACE) != 0) { perror("warning: could not increase write file allocation by 100 MB"); } else { f->allocated_size = f->bytes_written + PRE_ALLOCATE_DISK_SPACE; // increase allocation } } #endif return status_ok; } #define BUFLEN 16384 enum status pcap_file_read_packet(struct pcap_file *f, struct pcap_pkthdr *pkthdr, /* output */ void *packet_data /* output */ ) { ssize_t items_read; struct pcap_packet_hdr packet_hdr; if (f->file_ptr == NULL) { printf("File not open\n"); return status_err; } items_read = fread(&packet_hdr, sizeof(packet_hdr), 1, f->file_ptr); if (items_read == 0) { return status_err_no_more_data; /* could not read packet header from file */ } if (f->byteswap) { pkthdr->ts.tv_sec = ntohl(packet_hdr.ts_sec); pkthdr->ts.tv_usec = ntohl(packet_hdr.ts_usec); pkthdr->caplen = ntohl(packet_hdr.incl_len); } else { pkthdr->ts.tv_sec = packet_hdr.ts_sec; pkthdr->ts.tv_usec = packet_hdr.ts_usec; pkthdr->caplen = packet_hdr.incl_len; } if (pkthdr->caplen <= BUFLEN) { items_read = fread(packet_data, pkthdr->caplen, 1, f->file_ptr); if (items_read == 0) { printf("could not read packet from file, caplen: %u\n", pkthdr->caplen); return status_err; /* could not read packet from file */ } } else { /* * The packet length is much bigger than BUFLEN. * Read BUFLEN bytes to process the packet and skip the remaining bytes. */ if (fread(packet_data, BUFLEN, 1, f->file_ptr) == 0) { printf("could not read %d bytes of the packet from file\n", (int)BUFLEN); return status_err; /* could not read packet from file */ } // advance the file pointer to skip the large packet if (fseek(f->file_ptr, pkthdr->caplen - BUFLEN, SEEK_CUR) != 0) { perror("error: could not advance file pointer\n"); return status_err; } // adjust the packet len and caplen pkthdr->len = pkthdr->caplen; pkthdr->caplen = BUFLEN; return status_ok; } return status_ok; } void packet_info_init_from_pkthdr(struct packet_info *pi, struct pcap_pkthdr *pkthdr) { pi->len = pkthdr->caplen; pi->caplen = pkthdr->caplen; pi->ts.tv_sec = pkthdr->ts.tv_sec; pi->ts.tv_nsec = pkthdr->ts.tv_usec * 1000; } enum status pcap_file_dispatch_pkt_processor(struct pcap_file *f, struct pkt_proc *pkt_processor, int loop_count) { enum status status = status_ok; struct pcap_pkthdr pkthdr; uint8_t packet_data[BUFLEN]; unsigned long total_length = sizeof(struct pcap_file_hdr); // file header is already written unsigned long num_packets = 0; struct packet_info pi; for (int i=0; i < loop_count && sig_close_flag == 0; i++) { do { status = pcap_file_read_packet(f, &pkthdr, packet_data); if (status == status_ok) { packet_info_init_from_pkthdr(&pi, &pkthdr); // process the packet that was read pkt_processor->apply(&pi, packet_data); num_packets++; total_length += pkthdr.caplen + sizeof(struct pcap_packet_hdr); } } while (status == status_ok && sig_close_flag == 0); if (i < loop_count - 1) { // Rewind the file to the first packet after skipping file header. if (fseek(f->file_ptr, sizeof(struct pcap_file_hdr), SEEK_SET) != 0) { perror("error: could not rewind file pointer\n"); status = status_err; } } } pkt_processor->bytes_written = total_length; pkt_processor->packets_written = num_packets; if (status == status_err_no_more_data) { return status_ok; } return status; } enum status pcap_file_close(struct pcap_file *f) { if (fclose(f->file_ptr) != 0) { perror("could not close input pcap file"); return status_err; } if (f->buffer) { free(f->buffer); } return status_ok; } /* * start of serialized output code - first cut */ void pcap_queue_write(struct ll_queue *llq, uint8_t *packet, size_t length, unsigned int sec, unsigned int nsec, bool blocking) { if (blocking) { while (llq->msgs[llq->widx].used != 0) { usleep(50); // sleep for fifty microseconds } } if (llq->msgs[llq->widx].used == 0) { //char obuf[LLQ_MSG_SIZE]; int olen = LLQ_MSG_SIZE; int ooff = 0; int trunc = 0; llq->msgs[llq->widx].ts.tv_sec = sec; llq->msgs[llq->widx].ts.tv_nsec = nsec; //obuf[sizeof(struct timespec)] = '\0'; llq->msgs[llq->widx].buf[0] = '\0'; if (packet && !length) { fprintf(stderr, "warning: attempt to write an empty packet\n"); } /* note: we never perform byteswap when writing */ struct pcap_packet_hdr packet_hdr; packet_hdr.ts_sec = sec; packet_hdr.ts_usec = nsec; packet_hdr.incl_len = length; packet_hdr.orig_len = length; // write the packet header int r = append_memcpy(llq->msgs[llq->widx].buf, &ooff, olen, &trunc, &packet_hdr, sizeof(packet_hdr)); // write the packet r += append_memcpy(llq->msgs[llq->widx].buf, &ooff, olen, &trunc, packet, length); // f->bytes_written += length + sizeof(struct pcap_packet_hdr); // f->packets_written++; if ((trunc == 0) && (r > 0)) { llq->msgs[llq->widx].len = r; //fprintf(stderr, "DEBUG: sent a message!\n"); __sync_synchronize(); /* A full memory barrier prevents the following flag set from happening too soon */ llq->msgs[llq->widx].used = 1; //llq->next_write(); llq->widx = (llq->widx + 1) % LLQ_DEPTH; } } else { //fprintf(stderr, "DEBUG: queue bucket used!\n"); // TODO: this is where we'd update an output drop counter // but currently this spot in the code doesn't have access to // any thread stats pointer or similar and I don't want // to update a global variable in this location. } }
32.34728
117
0.603221
d6781c1fa736af714fe12ab71017c6b51c46733a
2,513
h
C
src/baseClasses/vrp_assert.h
woodbri/vehicle-routing-problems
aae24d92f46a6b1d473ad8f4ec6db9c96742b708
[ "MIT" ]
16
2015-06-26T22:53:20.000Z
2021-03-09T22:54:33.000Z
src/baseClasses/vrp_assert.h
woodbri/vehicle-routing-problems
aae24d92f46a6b1d473ad8f4ec6db9c96742b708
[ "MIT" ]
21
2015-01-29T14:16:19.000Z
2016-03-27T00:09:50.000Z
src/baseClasses/vrp_assert.h
woodbri/vehicle-routing-problems
aae24d92f46a6b1d473ad8f4ec6db9c96742b708
[ "MIT" ]
10
2015-07-18T02:48:35.000Z
2019-12-25T11:04:17.000Z
/*VRP********************************************************************* * * vehicle routing problems * A collection of C++ classes for developing VRP solutions * and specific solutions developed using these classes. * * Copyright 2014 Stephen Woodbridge <woodbri@imaptools.com> * Copyright 2014 Vicky Vergara <vicky_vergara@hotmail.com> * * This is free software; you can redistribute and/or modify it under * the terms of the MIT License. Please file LICENSE for details. * ********************************************************************VRP*/ /*! \file vrp_assert.h * \brief An assert functionality that uses C++ throw(). * * This file provides an alternative to assert functionality that will * convert all assert() into C++ throw using an AssertFailedException class. * This allows us to catch these errors and do appropriate clean up and * re-throw if needed so we can catch errors in the postgresql environment * so we do not crash the backend server. */ #ifndef VRP_ASSERT_H #define VRP_ASSERT_H #if 1 #include <cassert> #else #include <exception> #ifdef assert #undef assert #endif #ifndef __STRING #define __STRING(x) #x #endif #define __TOSTRING(x) __STRING(x) /*! \def assert(expr) * \brief Uses the standard assert syntax. * * When an assertion fails it will throw \ref AssertFailedException and what() * will return a string like "AssertFailedException(2+2 == 5) at t.cpp:11" * * Here is an example of using it: * \code #include <iostream> #include "vrp_assert.h" int main() { try { assert(2+2 == 4); assert(2+2 == 5); } catch (AssertFailedException &e) { std::cout << e.what() << "\n"; } catch (std::exception& e) { std::cout << e.what() << "\n"; } catch(...) { std::cout << "Caught unknown exception!\n"; } return 0; } \endcode */ #define assert(expr) \ ((expr) \ ? static_cast<void>(0) \ : throw AssertFailedException( "AssertFailedException: " __STRING(expr) " at " __FILE__ ":" __TOSTRING(__LINE__) )) /*! \class AssertFailedException * \brief Extends std::exception and is the exception that we throw if an assert fails. */ class AssertFailedException : public std::exception { private: const char *str; ///< str Holds the what() string for the exception. public: virtual const char *what() const throw(); AssertFailedException( const char *_str ); }; #endif #endif
27.615385
120
0.621966
d05d61b18bcde22df67c66bfef694dededd4d628
3,259
c
C
sh/yorinone.c
terrillmoore/yori
0bfcf715d22e03cf494d8b683c012ab773c39055
[ "MIT" ]
null
null
null
sh/yorinone.c
terrillmoore/yori
0bfcf715d22e03cf494d8b683c012ab773c39055
[ "MIT" ]
null
null
null
sh/yorinone.c
terrillmoore/yori
0bfcf715d22e03cf494d8b683c012ab773c39055
[ "MIT" ]
null
null
null
/** * @file sh/yorinone.c * * Yori table of supported builtins for the modular build of Yori (ie., none.) * * Copyright (c) 2017-2019 Malcolm J. Smith * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "yori.h" /** The list of builtin commands supported by this build of Yori. */ CONST YORI_SH_BUILTIN_NAME_MAPPING YoriShBuiltins[] = { {NULL, NULL} }; /** A table of initial alias to value mappings to populate. */ CONST YORI_SH_DEFAULT_ALIAS_ENTRY YoriShDefaultAliasEntries[] = { {_T("cd"), _T("chdir $*$")}, {_T("cls"), _T("ycls $*$")}, {_T("copy"), _T("ycopy $*$")}, {_T("cut"), _T("ycut $*$")}, {_T("date"), _T("ydate $*$")}, {_T("del"), _T("yerase $*$")}, {_T("dir"), _T("ydir $*$")}, {_T("echo"), _T("yecho $*$")}, {_T("erase"), _T("yerase $*$")}, {_T("expr"), _T("yexpr $*$")}, {_T("head"), _T("ytype -h $*$")}, {_T("md"), _T("ymkdir $*$")}, {_T("mkdir"), _T("ymkdir $*$")}, {_T("mklink"), _T("ymklink $*$")}, {_T("move"), _T("ymove $*$")}, {_T("pause"), _T("ypause $*$")}, {_T("rd"), _T("yrmdir $*$")}, {_T("ren"), _T("ymove $*$")}, {_T("rename"), _T("ymove $*$")}, {_T("rmdir"), _T("yrmdir $*$")}, {_T("start"), _T("ystart $*$")}, {_T("time"), _T("ydate -t $*$")}, {_T("title"), _T("ytitle $*$")}, {_T("type"), _T("ytype $*$")}, {_T("vol"), _T("yvol $*$")}, {_T("?"), _T("yexpr $*$")} }; /** Register default aliases in a standard build. This includes core aliases only, and is done to ensure a consistent baseline when scripts start executing to extend these capabilities. @return TRUE to indicate success. */ BOOL YoriShRegisterDefaultAliases() { DWORD Count; for (Count = 0; Count < sizeof(YoriShDefaultAliasEntries)/sizeof(YoriShDefaultAliasEntries[0]); Count++) { YoriShAddAliasLiteral(YoriShDefaultAliasEntries[Count].Alias, YoriShDefaultAliasEntries[Count].Value, TRUE); } return TRUE; } // vim:sw=4:ts=4:et:
36.617978
117
0.585456
fdbc37cfd95d60fb8f12ac0a10544742253426f8
6,274
c
C
sdk-6.5.20/src/bcm/dnx/trunk/trunk_init.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/bcm/dnx/trunk/trunk_init.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/bcm/dnx/trunk/trunk_init.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
/** \file src/bcm/dnx/trunk/trunk_init.c * * * This file contains the implementation on init functions of * the trunk module. */ /* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ #ifdef BSL_LOG_MODULE #error "BSL_LOG_MODULE redefined" #endif #define BSL_LOG_MODULE BSL_LS_BCMDNX_TRUNK /* * Include files. * { */ #include <shared/shrextend/shrextend_debug.h> #include <bcm_int/dnx/trunk/trunk_init.h> #include <soc/dnx/dnx_data/auto_generated/dnx_data_trunk.h> #include <soc/dnx/dnx_data/auto_generated/dnx_data_device.h> #include <bcm_int/dnx/algo/trunk/algo_trunk.h> #include "trunk_utils.h" #include "trunk_dbal_access.h" #include "trunk_sw_db.h" #include "trunk_temp_structs_to_skip_papi.h" #include <bcm_int/dnx/algo/swstate/auto_generated/access/algo_trunk_access.h> /* * } */ /* * DEFINEs * { */ /* * } */ /* * MACROs * { */ /* * } */ /** * \brief - set smooth division profiles to the dbal * * \param [in] unit - unit number * \param [in] profile_array - array of smooth division profiles * \param [in] nof_profiles - number of profiles * \param [in] entries_per_profile - number of entries per * profile * * \return * shr_error_e * * \remark * * None * \see * * None */ static shr_error_e dnx_trunk_smd_profiles_to_dbal_set( int unit, int *profile_array, int nof_profiles, int entries_per_profile) { int profile; int entry; int value; SHR_FUNC_INIT_VARS(unit); for (profile = 0; profile < nof_profiles; ++profile) { for (entry = 0; entry < entries_per_profile; ++entry) { value = profile_array[profile * entries_per_profile + entry]; SHR_IF_ERR_EXIT(dnx_trunk_dbal_access_smooth_division_profile_configuration_set(unit, profile, entry, value)); } } exit: SHR_FUNC_EXIT; } /** * \brief - init of the SMD PSC * * \param [in] unit - unit number * * \return * shr_error_e * * \remark * * None * \see * * None */ static shr_error_e dnx_trunk_smd_init( int unit) { int *profile_array; int nof_profiles; int entries_per_profile; SHR_FUNC_INIT_VARS(unit); /** the max number of SMD members also defines the max amount of default profiles */ nof_profiles = dnx_data_trunk.psc.smooth_division_max_nof_member_get(unit); entries_per_profile = dnx_data_trunk.psc.smooth_division_entries_per_profile_get(unit); /** allocate 2D array in a single allocation as a flat 1D array and access it with pointer aritmetics */ profile_array = sal_alloc(nof_profiles * entries_per_profile * sizeof(int), "SMD init profile array"); if (profile_array == NULL) { SHR_ERR_EXIT(_SHR_E_MEMORY, "allocation failed"); } SHR_IF_ERR_EXIT(dnx_algo_trunk_smd_pre_defined_profiles_get(unit, profile_array, nof_profiles, entries_per_profile)); SHR_IF_ERR_EXIT(dnx_trunk_smd_profiles_to_dbal_set(unit, profile_array, nof_profiles, entries_per_profile)); exit: SHR_FREE(profile_array); SHR_FUNC_EXIT; } /** * \brief - init port selection criterias * * \param [in] unit - unit number * * \return * shr_error_e * * \remark * * None * \see * * None */ static shr_error_e dnx_trunk_psc_init( int unit) { SHR_FUNC_INIT_VARS(unit); if (dnx_data_trunk.psc.feature_get(unit, dnx_data_trunk_psc_multiply_and_divide)) { /** * init multiply_and_divide - currently a place holder, nothing * to init in this PSC */ } if (dnx_data_trunk.psc.feature_get(unit, dnx_data_trunk_psc_smooth_division)) { /** * init smooth_division. * set pre-defined profiles. */ SHR_IF_ERR_EXIT(dnx_trunk_smd_init(unit)); } if (dnx_data_trunk.psc.feature_get(unit, dnx_data_trunk_psc_consistant_hashing)) { /** * init consistant_hashing - currently a place holder. */ } exit: SHR_FUNC_EXIT; } /** * \brief - init trunk HW * * \param [in] unit - unit number * * \return * shr_error_e * * \remark * * None * \see * * None */ static shr_error_e dnx_trunk_hw_init( int unit) { int nof_pools; int pool_index; int pool_mode; SHR_FUNC_INIT_VARS(unit); /** init Trunk pool attributes */ nof_pools = dnx_data_trunk.parameters.nof_pools_get(unit); for (pool_index = 0; pool_index < nof_pools; ++pool_index) { /** get pool mode */ pool_mode = dnx_data_trunk.parameters.pool_info_get(unit, pool_index)->pool_hw_mode; /** write to DBAL */ SHR_IF_ERR_EXIT(dnx_trunk_dbal_access_trunk_pool_attributes_set(unit, pool_index, pool_mode)); } /** Init Egress trunk attributes */ if (dnx_data_trunk.egress_trunk.feature_get(unit, dnx_data_trunk_egress_trunk_multiple_egress_trunk_sizes)) { SHR_IF_ERR_EXIT(dnx_trunk_dbal_access_egress_trunk_attributes_set (unit, dnx_data_trunk.egress_trunk.size_mode_get(unit))); } exit: SHR_FUNC_EXIT; } /** * see header file */ shr_error_e dnx_trunk_init( int unit) { SHR_FUNC_INIT_VARS(unit); /** * initiate trunk sw db */ SHR_IF_ERR_EXIT(algo_trunk_db.init(unit)); SHR_IF_ERR_EXIT(dnx_trunk_sw_db_init(unit)); SHR_IF_ERR_EXIT(dnx_trunk_hw_init(unit)); /** * initiate trunk psc features, for each feature check if it is * supported and activate init function for it */ SHR_IF_ERR_EXIT(dnx_trunk_psc_init(unit)); /** trunk algo init */ SHR_IF_ERR_EXIT(dnx_algo_egress_trunk_init(unit)); exit: SHR_FUNC_EXIT; } /** * see header file */ shr_error_e dnx_trunk_deinit( int unit) { SHR_FUNC_INIT_VARS(unit); /** * deinit trunk sw db */ SHR_IF_ERR_EXIT(dnx_trunk_sw_db_deinit(unit)); /** trunk algo deinit */ SHR_IF_ERR_EXIT(dnx_algo_egress_trunk_deinit(unit)); exit: SHR_FUNC_EXIT; }
22.091549
134
0.655244
a6399b027365004bd2a20e2ab5bc5b2e5e02f3b2
375
c
C
src/ch3/1585.c
luowyang/UVaSolutions
09a89989d31c15ed66fdbcb5a0f8c3b32fef5ad9
[ "MIT" ]
null
null
null
src/ch3/1585.c
luowyang/UVaSolutions
09a89989d31c15ed66fdbcb5a0f8c3b32fef5ad9
[ "MIT" ]
null
null
null
src/ch3/1585.c
luowyang/UVaSolutions
09a89989d31c15ed66fdbcb5a0f8c3b32fef5ad9
[ "MIT" ]
null
null
null
/** * Score, UVa1585 **/ #include<stdio.h> #define maxn 85 int main() { int T; char s[maxn]; scanf("%d", &T); while (T--) { scanf("%s", s); int score = 0, count = 0; for (int i = 0; s[i]; i++) { if (s[i] == 'O') score += ++count; else count = 0; } printf("%d\n", score); } return 0; }
17.045455
46
0.394667
106aa2d9cb3c44384fe867897bcd055f629538fb
208
h
C
Source/Executable/Precomp.h
aiekick/VulkanRTSEngine
b02c0d0fa1530dc920fde2a9928bd540cfdd31e6
[ "Apache-2.0" ]
1
2021-05-11T07:52:05.000Z
2021-05-11T07:52:05.000Z
Source/Executable/Precomp.h
aiekick/VulkanRTSEngine
b02c0d0fa1530dc920fde2a9928bd540cfdd31e6
[ "Apache-2.0" ]
null
null
null
Source/Executable/Precomp.h
aiekick/VulkanRTSEngine
b02c0d0fa1530dc920fde2a9928bd540cfdd31e6
[ "Apache-2.0" ]
null
null
null
#include <chrono> #include <functional> #include <vector> #include <atomic> #include <array> #include <unordered_map> #include <fstream> #include <random> #include <tbb/tbb.h> #include <Core/Debug/Assert.h>
17.333333
30
0.730769
b768be29c785119aa71e2f5ecc056b13b0215f8e
2,436
h
C
BAIDU.h
liushouyun/interview
952b36d186e8f5fa29680eb195dc989678a3d001
[ "Apache-2.0" ]
null
null
null
BAIDU.h
liushouyun/interview
952b36d186e8f5fa29680eb195dc989678a3d001
[ "Apache-2.0" ]
null
null
null
BAIDU.h
liushouyun/interview
952b36d186e8f5fa29680eb195dc989678a3d001
[ "Apache-2.0" ]
null
null
null
// // Created by yanjun on 16-8-21. // #ifndef INTERVIEW_BAIDU_H #define INTERVIEW_BAIDU_H #include "My_Class.h" #include <iostream> using namespace std; class baidu{ private: void bracket_helper(int a){ if(a==1&&bracket_left+a<=bracket_N){ bracket_left+=a; bracket_right+=a; *(bracket_A+bracket_index)=a; bracket_index++; } else if(a==-1&&bracket_right+a>=0){ bracket_right+=a; *(bracket_A+bracket_index)=a; bracket_index++; } else { if(a==-1&&bracket_index==bracket_N*2){ bracket_print(); } return; } bracket_helper(1); bracket_helper(-1); if(a==1){ bracket_left-=a; bracket_right-=a; } else bracket_right-=a; bracket_index--; } void bracket_print(){ for(int i=0;i<bracket_N*2;i++){ if(*(bracket_A+i)==1)cout<<"("; else cout<<")"; } cout<<endl; } int *bracket_A; int bracket_index; int bracket_left; int bracket_right; int bracket_N; public: void print_binary_tree(binary_tree *root) { queue<int> print_queue; queue<binary_tree*> binary_queue; binary_tree* special; int special_int=(1<<31); binary_queue.push(root); binary_queue.push(special); while(!binary_queue.empty()){ binary_tree* top=binary_queue.front(); binary_queue.pop(); if(top==special){ if(binary_queue.back()!=special)binary_queue.push(special); print_queue.push(special_int); } else{ print_queue.push(top->val); if(top->left!=NULL)binary_queue.push(top->left); if(top->right!=NULL)binary_queue.push(top->right); } } while(!print_queue.empty()){ int top=print_queue.front(); if(top==special_int) cout<<endl; else cout<<top<<' '; print_queue.pop(); } } void bracket_main(int N){ bracket_A = new int[N*2]; bracket_index=0; bracket_left=0; bracket_right=0; bracket_N=N; bracket_helper(1); delete[] bracket_A; } }; #endif //INTERVIEW_BAIDU_H
25.642105
75
0.513957
c831d0ad321f2acab9d4cf6ff123059d58adf5f6
15,248
c
C
gdb-7.3/sim/common/dv-pal.c
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
1
2016-04-09T02:58:13.000Z
2016-04-09T02:58:13.000Z
gdb-7.3/sim/common/dv-pal.c
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
gdb-7.3/sim/common/dv-pal.c
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
/* The common simulator framework for GDB, the GNU Debugger. Copyright 2002, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. Contributed by Andrew Cagney and Red Hat. This file is part of GDB. 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 "hw-main.h" #include "sim-io.h" /* NOTE: pal is naughty and grubs around looking at things outside of its immediate domain */ #include "hw-tree.h" #ifdef HAVE_STRING_H #include <string.h> #else #ifdef HAVE_STRINGS_H #include <strings.h> #endif #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif /* DEVICE pal - glue logic device containing assorted junk DESCRIPTION Typical hardware dependant hack. This device allows the firmware to gain access to all the things the firmware needs (but the OS doesn't). The pal contains the following registers: |0 reset register (write, 8bit) |4 processor id register (read, 8bit) |8 interrupt register (8 - port, 9 - level) (write, 16bit) |12 processor count register (read, 8bit) |16 tty input fifo register (read, 8bit) |20 tty input status register (read, 8bit) |24 tty output fifo register (write, 8bit) |28 tty output status register (read, 8bit) |32 countdown register (read/write, 32bit, big-endian) |36 countdown value register (read, 32bit, big-endian) |40 timer register (read/write, 32bit, big-endian) |44 timer value register (read, 32bit, big-endian) RESET (write): halts the simulator. The value written to the register is used as an exit status. PROCESSOR ID (read): returns the processor identifier (0 .. N-1) of the processor performing the read. INTERRUPT (write): This register must be written using a two byte store. The low byte specifies a port and the upper byte specifies the a level. LEVEL is driven on the specified port. By convention, the pal's interrupt ports (int0, int1, ...) are wired up to the corresponding processor's level sensative external interrupt pin. Eg: A two byte write to address 8 of 0x0102 (big-endian) will result in processor 2's external interrupt pin being asserted. PROCESSOR COUNT (read): returns the total number of processors active in the current simulation. TTY INPUT FIFO (read): if the TTY input status register indicates a character is available by being nonzero, returns the next available character from the pal's tty input port. TTY OUTPUT FIFO (write): if the TTY output status register indicates the output fifo is not full by being nonzero, outputs the character written to the tty's output port. COUNDOWN (read/write): The countdown registers provide a non-repeating timed interrupt source. Writing a 32 bit big-endian zero value to this register clears the countdown timer. Writing a non-zero 32 bit big-endian value to this register sets the countdown timer to expire in VALUE ticks (ticks is target dependant). Reading the countdown register returns the last value writen. COUNTDOWN VALUE (read): Reading this 32 bit big-endian register returns the number of ticks remaining until the countdown timer expires. TIMER (read/write): The timer registers provide a periodic timed interrupt source. Writing a 32 bit big-endian zero value to this register clears the periodic timer. Writing a 32 bit non-zero value to this register sets the periodic timer to triger every VALUE ticks (ticks is target dependant). Reading the timer register returns the last value written. TIMER VALUE (read): Reading this 32 bit big-endian register returns the number of ticks until the next periodic interrupt. PROPERTIES reg = <address> <size> (required) Specify the address (within the parent bus) that this device is to be located. poll? = <boolean> If present and true, indicates that the device should poll its input. PORTS int[0..NR_PROCESSORS] (output) Driven as a result of a write to the interrupt-port / interrupt-level register pair. countdown Driven whenever the countdown counter reaches zero. timer Driven whenever the timer counter reaches zero. BUGS At present the common simulator framework does not support input polling. */ enum { hw_pal_reset_register = 0x0, hw_pal_cpu_nr_register = 0x4, hw_pal_int_register = 0x8, hw_pal_nr_cpu_register = 0xa, hw_pal_read_fifo = 0x10, hw_pal_read_status = 0x14, hw_pal_write_fifo = 0x18, hw_pal_write_status = 0x1a, hw_pal_countdown = 0x20, hw_pal_countdown_value = 0x24, hw_pal_timer = 0x28, hw_pal_timer_value = 0x2c, hw_pal_address_mask = 0x3f, }; typedef struct _hw_pal_console_buffer { char buffer; int status; } hw_pal_console_buffer; typedef struct _hw_pal_counter { struct hw_event *handler; signed64 start; unsigned32 delta; int periodic_p; } hw_pal_counter; typedef struct _hw_pal_device { hw_pal_console_buffer input; hw_pal_console_buffer output; hw_pal_counter countdown; hw_pal_counter timer; struct hw *disk; do_hw_poll_read_method *reader; } hw_pal_device; enum { COUNTDOWN_PORT, TIMER_PORT, INT_PORT, }; static const struct hw_port_descriptor hw_pal_ports[] = { { "countdown", COUNTDOWN_PORT, 0, output_port, }, { "timer", TIMER_PORT, 0, output_port, }, { "int", INT_PORT, MAX_NR_PROCESSORS, output_port, }, { NULL, 0, 0, 0 } }; /* countdown and simple timer */ static void do_counter_event (struct hw *me, void *data) { hw_pal_counter *counter = (hw_pal_counter *) data; if (counter->periodic_p) { HW_TRACE ((me, "timer expired")); counter->start = hw_event_queue_time (me); hw_port_event (me, TIMER_PORT, 1); hw_event_queue_schedule (me, counter->delta, do_counter_event, counter); } else { HW_TRACE ((me, "countdown expired")); counter->delta = 0; hw_port_event (me, COUNTDOWN_PORT, 1); } } static void do_counter_read (struct hw *me, hw_pal_device *pal, const char *reg, hw_pal_counter *counter, unsigned32 *word, unsigned nr_bytes) { unsigned32 val; if (nr_bytes != 4) hw_abort (me, "%s - bad read size must be 4 bytes", reg); val = counter->delta; HW_TRACE ((me, "read - %s %ld", reg, (long) val)); *word = H2BE_4 (val); } static void do_counter_value (struct hw *me, hw_pal_device *pal, const char *reg, hw_pal_counter *counter, unsigned32 *word, unsigned nr_bytes) { unsigned32 val; if (nr_bytes != 4) hw_abort (me, "%s - bad read size must be 4 bytes", reg); if (counter->delta != 0) val = (counter->start + counter->delta - hw_event_queue_time (me)); else val = 0; HW_TRACE ((me, "read - %s %ld", reg, (long) val)); *word = H2BE_4 (val); } static void do_counter_write (struct hw *me, hw_pal_device *pal, const char *reg, hw_pal_counter *counter, const unsigned32 *word, unsigned nr_bytes) { if (nr_bytes != 4) hw_abort (me, "%s - bad write size must be 4 bytes", reg); if (counter->handler != NULL) { hw_event_queue_deschedule (me, counter->handler); counter->handler = NULL; } counter->delta = BE2H_4 (*word); counter->start = hw_event_queue_time (me); HW_TRACE ((me, "write - %s %ld", reg, (long) counter->delta)); if (counter->delta > 0) hw_event_queue_schedule (me, counter->delta, do_counter_event, counter); } /* check the console for an available character */ static void scan_hw_pal (struct hw *me) { hw_pal_device *hw_pal = (hw_pal_device *)hw_data (me); char c; int count; count = do_hw_poll_read (me, hw_pal->reader, 0/*STDIN*/, &c, sizeof(c)); switch (count) { case HW_IO_NOT_READY: case HW_IO_EOF: hw_pal->input.buffer = 0; hw_pal->input.status = 0; break; default: hw_pal->input.buffer = c; hw_pal->input.status = 1; } } /* write the character to the hw_pal */ static void write_hw_pal (struct hw *me, char val) { hw_pal_device *hw_pal = (hw_pal_device *) hw_data (me); sim_io_write_stdout (hw_system (me), &val, 1); hw_pal->output.buffer = val; hw_pal->output.status = 1; } /* Reads/writes */ static unsigned hw_pal_io_read_buffer (struct hw *me, void *dest, int space, unsigned_word addr, unsigned nr_bytes) { hw_pal_device *hw_pal = (hw_pal_device *) hw_data (me); unsigned_1 *byte = (unsigned_1 *) dest; memset (dest, 0, nr_bytes); switch (addr & hw_pal_address_mask) { case hw_pal_cpu_nr_register: #ifdef CPU_INDEX *byte = CPU_INDEX (hw_system_cpu (me)); #else *byte = 0; #endif HW_TRACE ((me, "read - cpu-nr %d\n", *byte)); break; case hw_pal_nr_cpu_register: if (hw_tree_find_property (me, "/openprom/options/smp") == NULL) { *byte = 1; HW_TRACE ((me, "read - nr-cpu %d (not defined)\n", *byte)); } else { *byte = hw_tree_find_integer_property (me, "/openprom/options/smp"); HW_TRACE ((me, "read - nr-cpu %d\n", *byte)); } break; case hw_pal_read_fifo: *byte = hw_pal->input.buffer; HW_TRACE ((me, "read - input-fifo %d\n", *byte)); break; case hw_pal_read_status: scan_hw_pal (me); *byte = hw_pal->input.status; HW_TRACE ((me, "read - input-status %d\n", *byte)); break; case hw_pal_write_fifo: *byte = hw_pal->output.buffer; HW_TRACE ((me, "read - output-fifo %d\n", *byte)); break; case hw_pal_write_status: *byte = hw_pal->output.status; HW_TRACE ((me, "read - output-status %d\n", *byte)); break; case hw_pal_countdown: do_counter_read (me, hw_pal, "countdown", &hw_pal->countdown, dest, nr_bytes); break; case hw_pal_countdown_value: do_counter_value (me, hw_pal, "countdown-value", &hw_pal->countdown, dest, nr_bytes); break; case hw_pal_timer: do_counter_read (me, hw_pal, "timer", &hw_pal->timer, dest, nr_bytes); break; case hw_pal_timer_value: do_counter_value (me, hw_pal, "timer-value", &hw_pal->timer, dest, nr_bytes); break; default: HW_TRACE ((me, "read - ???\n")); break; } return nr_bytes; } static unsigned hw_pal_io_write_buffer (struct hw *me, const void *source, int space, unsigned_word addr, unsigned nr_bytes) { hw_pal_device *hw_pal = (hw_pal_device*) hw_data (me); unsigned_1 *byte = (unsigned_1 *) source; switch (addr & hw_pal_address_mask) { case hw_pal_reset_register: hw_halt (me, sim_exited, byte[0]); break; case hw_pal_int_register: hw_port_event (me, INT_PORT + byte[0], /*port*/ (nr_bytes > 1 ? byte[1] : 0)); /* val */ break; case hw_pal_read_fifo: hw_pal->input.buffer = byte[0]; HW_TRACE ((me, "write - input-fifo %d\n", byte[0])); break; case hw_pal_read_status: hw_pal->input.status = byte[0]; HW_TRACE ((me, "write - input-status %d\n", byte[0])); break; case hw_pal_write_fifo: write_hw_pal (me, byte[0]); HW_TRACE ((me, "write - output-fifo %d\n", byte[0])); break; case hw_pal_write_status: hw_pal->output.status = byte[0]; HW_TRACE ((me, "write - output-status %d\n", byte[0])); break; case hw_pal_countdown: do_counter_write (me, hw_pal, "countdown", &hw_pal->countdown, source, nr_bytes); break; case hw_pal_timer: do_counter_write (me, hw_pal, "timer", &hw_pal->timer, source, nr_bytes); break; } return nr_bytes; } /* instances of the hw_pal struct hw */ #if NOT_YET static void hw_pal_instance_delete_callback(hw_instance *instance) { /* nothing to delete, the hw_pal is attached to the struct hw */ return; } #endif #if NOT_YET static int hw_pal_instance_read_callback (hw_instance *instance, void *buf, unsigned_word len) { DITRACE (pal, ("read - %s (%ld)", (const char*) buf, (long int) len)); return sim_io_read_stdin (buf, len); } #endif #if NOT_YET static int hw_pal_instance_write_callback (hw_instance *instance, const void *buf, unsigned_word len) { int i; const char *chp = buf; hw_pal_device *hw_pal = hw_instance_data (instance); DITRACE (pal, ("write - %s (%ld)", (const char*) buf, (long int) len)); for (i = 0; i < len; i++) write_hw_pal (hw_pal, chp[i]); sim_io_flush_stdoutput (); return i; } #endif #if NOT_YET static const hw_instance_callbacks hw_pal_instance_callbacks = { hw_pal_instance_delete_callback, hw_pal_instance_read_callback, hw_pal_instance_write_callback, }; #endif #if 0 static hw_instance * hw_pal_create_instance (struct hw *me, const char *path, const char *args) { return hw_create_instance_from (me, NULL, hw_data (me), path, args, &hw_pal_instance_callbacks); } #endif static void hw_pal_attach_address (struct hw *me, int level, int space, address_word addr, address_word nr_bytes, struct hw *client) { hw_pal_device *pal = (hw_pal_device*) hw_data (me); pal->disk = client; } #if 0 static hw_callbacks const hw_pal_callbacks = { { generic_hw_init_address, }, { hw_pal_attach_address, }, /* address */ { hw_pal_io_read_buffer_callback, hw_pal_io_write_buffer_callback, }, { NULL, }, /* DMA */ { NULL, NULL, hw_pal_interrupt_ports }, /* interrupt */ { generic_hw_unit_decode, generic_hw_unit_encode, generic_hw_address_to_attach_address, generic_hw_size_to_attach_size }, hw_pal_create_instance, }; #endif static void hw_pal_finish (struct hw *hw) { /* create the descriptor */ hw_pal_device *hw_pal = HW_ZALLOC (hw, hw_pal_device); hw_pal->output.status = 1; hw_pal->output.buffer = '\0'; hw_pal->input.status = 0; hw_pal->input.buffer = '\0'; set_hw_data (hw, hw_pal); set_hw_attach_address (hw, hw_pal_attach_address); set_hw_io_read_buffer (hw, hw_pal_io_read_buffer); set_hw_io_write_buffer (hw, hw_pal_io_write_buffer); set_hw_ports (hw, hw_pal_ports); /* attach ourselves */ do_hw_attach_regs (hw); /* If so configured, enable polled input */ if (hw_find_property (hw, "poll?") != NULL && hw_find_boolean_property (hw, "poll?")) { hw_pal->reader = sim_io_poll_read; } else { hw_pal->reader = sim_io_read; } /* tag the periodic timer */ hw_pal->timer.periodic_p = 1; } const struct hw_descriptor dv_pal_descriptor[] = { { "pal", hw_pal_finish, }, { NULL, NULL }, };
25.120264
78
0.675695
bd4292fc95a866f8cffe45e03a4848e2a296ad2c
621
h
C
bot/includes.h
gitYayo/HoHo
df0bca0cbcfb1bac0fda50e8aa697d64855c53ec
[ "MIT" ]
null
null
null
bot/includes.h
gitYayo/HoHo
df0bca0cbcfb1bac0fda50e8aa697d64855c53ec
[ "MIT" ]
null
null
null
bot/includes.h
gitYayo/HoHo
df0bca0cbcfb1bac0fda50e8aa697d64855c53ec
[ "MIT" ]
null
null
null
#pragma once #include <unistd.h> #include <stdint.h> #include <stdarg.h> #define STDIN 0 #define STDOUT 1 #define STDERR 2 #define FALSE 0 #define TRUE 1 typedef char BOOL; typedef uint32_t ipv4_t; typedef uint16_t port_t; #define INET_ADDR(o1,o2,o3,o4) (htonl((o1 << 24) | (o2 << 16) | (o3 << 8) | (o4 << 0))) #define FAKE_CNC_ADDR (int)inet_addr((const char*)"Botnet Made By greek.Helios"); #define FAKE_CNC_PORT 701 #define SCANIP (int)inet_addr((const char*)"1.1.1.1"); #define SERVIP (int)inet_addr((const char*)"1.1.1.1"); ipv4_t LOCAL_ADDR;
20.7
87
0.623188
bd458dde181ce9fe6d3f2bb62a0d57c694a44432
21,099
h
C
packages/cplint/approx/simplecuddLPADs/simplecudd.h
miar/yap-il
68cafb779a8f954a689f2f0d7bdcc9f030be8f0e
[ "Artistic-1.0-Perl", "ClArtistic" ]
2
2015-11-01T07:38:31.000Z
2016-03-30T18:05:28.000Z
packages/cplint/approx/simplecuddLPADs/simplecudd.h
miar/yap-il
68cafb779a8f954a689f2f0d7bdcc9f030be8f0e
[ "Artistic-1.0-Perl", "ClArtistic" ]
null
null
null
packages/cplint/approx/simplecuddLPADs/simplecudd.h
miar/yap-il
68cafb779a8f954a689f2f0d7bdcc9f030be8f0e
[ "Artistic-1.0-Perl", "ClArtistic" ]
null
null
null
/******************************************************************************\ * * * SimpleCUDD library (www.cs.kuleuven.be/~theo/tools/simplecudd.html) * * SimpleCUDD was developed at Katholieke Universiteit Leuven(www.kuleuven.be) * * * * Copyright Katholieke Universiteit Leuven 2008 * * * * Author: Theofrastos Mantadelis * * File: simplecudd.h * * * ******************************************************************************** * * * Artistic License 2.0 * * * * Copyright (c) 2000-2006, The Perl Foundation. * * * * Everyone is permitted to copy and distribute verbatim copies of this license * * document, but changing it is not allowed. * * * * Preamble * * * * This license establishes the terms under which a given free software Package * * may be copied, modified, distributed, and/or redistributed. The intent is * * that the Copyright Holder maintains some artistic control over the * * development of that Package while still keeping the Package available as * * open source and free software. * * * * You are always permitted to make arrangements wholly outside of this license * * directly with the Copyright Holder of a given Package. If the terms of this * * license do not permit the full use that you propose to make of the Package, * * you should contact the Copyright Holder and seek a different licensing * * arrangement. * * Definitions * * * * "Copyright Holder" means the individual(s) or organization(s) named in the * * copyright notice for the entire Package. * * * * "Contributor" means any party that has contributed code or other material to * * the Package, in accordance with the Copyright Holder's procedures. * * * * "You" and "your" means any person who would like to copy, distribute, or * * modify the Package. * * * * "Package" means the collection of files distributed by the Copyright Holder, * * and derivatives of that collection and/or of those files. A given Package * * may consist of either the Standard Version, or a Modified Version. * * * * "Distribute" means providing a copy of the Package or making it accessible * * to anyone else, or in the case of a company or organization, to others * * outside of your company or organization. * * * * "Distributor Fee" means any fee that you charge for Distributing this * * Package or providing support for this Package to another party. It does not * * mean licensing fees. * * * * "Standard Version" refers to the Package if it has not been modified, or has * * been modified only in ways explicitly requested by the Copyright Holder. * * * * "Modified Version" means the Package, if it has been changed, and such * * changes were not explicitly requested by the Copyright Holder. * * * * "Original License" means this Artistic License as Distributed with the * * Standard Version of the Package, in its current version or as it may be * * modified by The Perl Foundation in the future. * * * * "Source" form means the source code, documentation source, and configuration * * files for the Package. * * * * "Compiled" form means the compiled bytecode, object code, binary, or any * * other form resulting from mechanical transformation or translation of the * * Source form. * * Permission for Use and Modification Without Distribution * * * * (1) You are permitted to use the Standard Version and create and use * * Modified Versions for any purpose without restriction, provided that you do * * not Distribute the Modified Version. * * Permissions for Redistribution of the Standard Version * * * * (2) You may Distribute verbatim copies of the Source form of the Standard * * Version of this Package in any medium without restriction, either gratis or * * for a Distributor Fee, provided that you duplicate all of the original * * copyright notices and associated disclaimers. At your discretion, such * * verbatim copies may or may not include a Compiled form of the Package. * * * * (3) You may apply any bug fixes, portability changes, and other * * modifications made available from the Copyright Holder. The resulting * * Package will still be considered the Standard Version, and as such will be * * subject to the Original License. * * Distribution of Modified Versions of the Package as Source * * * * (4) You may Distribute your Modified Version as Source (either gratis or for * * a Distributor Fee, and with or without a Compiled form of the Modified * * Version) provided that you clearly document how it differs from the Standard * * Version, including, but not limited to, documenting any non-standard * * features, executables, or modules, and provided that you do at least ONE of * * the following: * * * * (a) make the Modified Version available to the Copyright Holder of the * * Standard Version, under the Original License, so that the Copyright Holder * * may include your modifications in the Standard Version. * * (b) ensure that installation of your Modified Version does not prevent the * * user installing or running the Standard Version. In addition, the Modified * * Version must bear a name that is different from the name of the Standard * * Version. * * (c) allow anyone who receives a copy of the Modified Version to make the * * Source form of the Modified Version available to others under * * (i) the Original License or * * (ii) a license that permits the licensee to freely copy, modify and * * redistribute the Modified Version using the same licensing terms that apply * * to the copy that the licensee received, and requires that the Source form of * * the Modified Version, and of any works derived from it, be made freely * * available in that license fees are prohibited but Distributor Fees are * * allowed. * * Distribution of Compiled Forms of the Standard Version or Modified Versions * * without the Source * * * * (5) You may Distribute Compiled forms of the Standard Version without the * * Source, provided that you include complete instructions on how to get the * * Source of the Standard Version. Such instructions must be valid at the time * * of your distribution. If these instructions, at any time while you are * * carrying out such distribution, become invalid, you must provide new * * instructions on demand or cease further distribution. If you provide valid * * instructions or cease distribution within thirty days after you become aware * * that the instructions are invalid, then you do not forfeit any of your * * rights under this license. * * * * (6) You may Distribute a Modified Version in Compiled form without the * * Source, provided that you comply with Section 4 with respect to the Source * * of the Modified Version. * * Aggregating or Linking the Package * * * * (7) You may aggregate the Package (either the Standard Version or Modified * * Version) with other packages and Distribute the resulting aggregation * * provided that you do not charge a licensing fee for the Package. Distributor * * Fees are permitted, and licensing fees for other components in the * * aggregation are permitted. The terms of this license apply to the use and * * Distribution of the Standard or Modified Versions as included in the * * aggregation. * * * * (8) You are permitted to link Modified and Standard Versions with other * * works, to embed the Package in a larger work of your own, or to build * * stand-alone binary or bytecode versions of applications that include the * * Package, and Distribute the result without restriction, provided the result * * does not expose a direct interface to the Package. * * Items That are Not Considered Part of a Modified Version * * * * (9) Works (including, but not limited to, modules and scripts) that merely * * extend or make use of the Package, do not, by themselves, cause the Package * * to be a Modified Version. In addition, such works are not considered parts * * of the Package itself, and are not subject to the terms of this license. * * General Provisions * * * * (10) Any use, modification, and distribution of the Standard or Modified * * Versions is governed by this Artistic License. By using, modifying or * * distributing the Package, you accept this license. Do not use, modify, or * * distribute the Package, if you do not accept this license. * * * * (11) If your Modified Version has been derived from a Modified Version made * * by someone other than you, you are nevertheless required to ensure that your * * Modified Version complies with the requirements of this license. * * * * (12) This license does not grant you the right to use any trademark, service * * mark, tradename, or logo of the Copyright Holder. * * * * (13) This license includes the non-exclusive, worldwide, free-of-charge * * patent license to make, have made, use, offer to sell, sell, import and * * otherwise transfer the Package with respect to any patent claims licensable * * by the Copyright Holder that are necessarily infringed by the Package. If * * you institute patent litigation (including a cross-claim or counterclaim) * * against any party alleging that the Package constitutes direct or * * contributory patent infringement, then this Artistic License to you shall * * terminate on the date that such litigation is filed. * * * * (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER * * AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE * * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR * * NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. * * UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE * * FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN * * ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF * * SUCH DAMAGE. * * * * The End * * * \******************************************************************************/ /* modified by Fabrizio Riguzzi in 2009 for dealing with multivalued variables instead of variables or their negation, the script can contain equations of the form variable=value */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include "util.h" #include "cudd.h" #include "cuddInt.h" #include "general.h" #define IsHigh(manager, node) HIGH(manager) == node #define IsLow(manager, node) LOW(manager) == node #define HIGH(manager) Cudd_ReadOne(manager) #define LOW(manager) Cudd_Not(Cudd_ReadOne(manager)) #define NOT(node) Cudd_Not(node) #define GetIndex(node) Cudd_NodeReadIndex(node) #define GetMVar(manager, index, value, varmap) equality(manager,index,value,varmap)//Cudd_bddIthVar(manager, index) #define GetVar(manager, index) Cudd_bddIthVar(manager, index) #define NewVar(manager) Cudd_bddNewVar(manager) #define KillBDD(manager) Cudd_Quit(manager) #define GetVarCount(manager) Cudd_ReadSize(manager) #define DEBUGON _debug = 1 #define DEBUGOFF _debug = 0 #define RAPIDLOADON _RapidLoad = 1 #define RAPIDLOADOFF _RapidLoad = 0 #define SETMAXBUFSIZE(size) _maxbufsize = size #define BDDFILE_ERROR -1 #define BDDFILE_OTHER 0 #define BDDFILE_SCRIPT 1 #define BDDFILE_NODEDUMP 2 extern int _RapidLoad; extern int _debug; extern int _maxbufsize; typedef struct _bddfileheader { FILE *inputfile; int version; int varcnt; int bvarcnt; int varstart; int intercnt; int filetype; } bddfileheader; typedef struct { int nVal,nBit,init; double * probabilities; int * booleanVars; } variable; typedef struct _namedvars { int varcnt; int varstart; char **vars; int *loaded; double *dvalue; int *ivalue; void **dynvalue; variable * mvars; int * bVar2mVar; } namedvars; typedef struct _hisnode { DdNode *key; double dvalue; int ivalue; void *dynvalue; } hisnode; typedef struct _hisqueue { int cnt; hisnode *thenode; } hisqueue; typedef struct _nodeline { char *varname; char *truevar; char *falsevar; int nodenum; int truenode; int falsenode; } nodeline; /* Initialization */ DdManager* simpleBDDinit(int varcnt); /* BDD Generation */ DdNode* D_BDDAnd(DdManager *manager, DdNode *bdd1, DdNode *bdd2); DdNode* D_BDDNand(DdManager *manager, DdNode *bdd1, DdNode *bdd2); DdNode* D_BDDOr(DdManager *manager, DdNode *bdd1, DdNode *bdd2); DdNode* D_BDDNor(DdManager *manager, DdNode *bdd1, DdNode *bdd2); DdNode* D_BDDXor(DdManager *manager, DdNode *bdd1, DdNode *bdd2); DdNode* D_BDDXnor(DdManager *manager, DdNode *bdd1, DdNode *bdd2); DdNode* FileGenerateBDD(DdManager *manager, namedvars varmap, bddfileheader fileheader); DdNode* OnlineGenerateBDD(DdManager *manager, namedvars *varmap); DdNode* LineParser(DdManager *manager, namedvars varmap, DdNode **inter, int maxinter, char *function, int iline); DdNode* OnlineLineParser(DdManager *manager, namedvars *varmap, DdNode **inter, int maxinter, char *function, int iline); DdNode* BDD_Operator(DdManager *manager, DdNode *bdd1, DdNode *bdd2, char Operator, int inegoper); int getInterBDD(char *function); char* getFileName(const char *function); int GetParam(char *inputline, int iParam); int LoadVariableData(namedvars varmap, char *filename); int LoadMultiVariableData(DdManager * mgr,namedvars varmap, char *filename); /* Named variables */ namedvars InitNamedVars(int varcnt, int varstart); namedvars InitNamedMultiVars(int varcnt, int varstart, int bvarcnt); void EnlargeNamedVars(namedvars *varmap, int newvarcnt); int AddNamedVarAt(namedvars varmap, const char *varname, int index); int AddNamedVar(namedvars varmap, const char *varname); int AddNamedMultiVar(DdManager *mgr,namedvars varmap, const char *varnamei, int *value); void SetNamedVarValuesAt(namedvars varmap, int index, double dvalue, int ivalue, void *dynvalue); int SetNamedVarValues(namedvars varmap, const char *varname, double dvalue, int ivalue, void *dynvalue); int GetNamedVarIndex(const namedvars varmap, const char *varname); int RepairVarcnt(namedvars *varmap); char* GetNodeVarName(DdManager *manager, namedvars varmap, DdNode *node); char* GetNodeVarNameDisp(DdManager *manager, namedvars varmap, DdNode *node); int all_loaded(namedvars varmap, int disp); /* Traversal */ DdNode* HighNodeOf(DdManager *manager, DdNode *node); DdNode* LowNodeOf(DdManager *manager, DdNode *node); /* Traversal - History */ hisqueue* InitHistory(int varcnt); void ReInitHistory(hisqueue *HisQueue, int varcnt); void AddNode(hisqueue *HisQueue, int varstart, DdNode *node, double dvalue, int ivalue, void *dynvalue); hisnode* GetNode(hisqueue *HisQueue, int varstart, DdNode *node); int GetNodeIndex(hisqueue *HisQueue, int varstart, DdNode *node); void onlinetraverse(DdManager *manager, namedvars varmap, hisqueue *HisQueue, DdNode *bdd); /* Save-load */ bddfileheader ReadFileHeader(char *filename); int CheckFileVersion(const char *version); DdNode * LoadNodeDump(DdManager *manager, namedvars varmap, FILE *inputfile); DdNode * LoadNodeRec(DdManager *manager, namedvars varmap, hisqueue *Nodes, FILE *inputfile, nodeline current); DdNode * GetIfExists(DdManager *manager, namedvars varmap, hisqueue *Nodes, char *varname, int nodenum); int SaveNodeDump(DdManager *manager, namedvars varmap, DdNode *bdd, char *filename); void SaveExpand(DdManager *manager, namedvars varmap, hisqueue *Nodes, DdNode *Current, FILE *outputfile); void ExpandNodes(hisqueue *Nodes, int index, int nodenum); /* Export */ int simpleBDDtoDot(DdManager *manager, DdNode *bdd, char *filename); int simpleNamedBDDtoDot(DdManager *manager, namedvars varmap, DdNode *bdd, char *filename); DdNode * equality(DdManager *mgr,int varIndex,int value,namedvars varmap); hisnode* GetNodei1(int *bVar2mVar,hisqueue *HisQueue, int varstart, DdNode *node); void AddNode1(int *bVar2mVar, hisqueue *HisQueue, int varstart, DdNode *node, double dvalue, int ivalue, void *dynvalue); hisnode* GetNode1(int *bVar2mVar,hisqueue *HisQueue, int varstart, DdNode *node);
59.266854
121
0.560595
bd55875fef590197b644d0107e763b25f2cf263a
952
h
C
System/Library/Frameworks/Vision.framework/VNPersonsModelFaceModelDataProvider.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
5
2021-04-29T04:31:43.000Z
2021-08-19T18:59:58.000Z
System/Library/Frameworks/Vision.framework/VNPersonsModelFaceModelDataProvider.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
null
null
null
System/Library/Frameworks/Vision.framework/VNPersonsModelFaceModelDataProvider.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
1
2022-03-19T11:16:23.000Z
2022-03-19T11:16:23.000Z
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 28, 2021 at 9:05:09 PM Mountain Standard Time * Operating System: Version 14.5 (Build 18L204) * Image Source: /System/Library/Frameworks/Vision.framework/Vision * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ @protocol VNPersonsModelFaceModelDataProvider <NSObject> @required -(unsigned long long)faceModelPersonsCount; -(id)faceModelUniqueIdentifierOfPersonAtIndex:(unsigned long long)arg1; -(unsigned long long)faceModelIndexOfPersonWithUniqueIdentifier:(id)arg1; -(unsigned long long)faceModelNumberOfFaceObservationsForPersonAtIndex:(unsigned long long)arg1; -(id)faceModelFaceObservationAtIndex:(unsigned long long)arg1 forPersonAtIndex:(unsigned long long)arg2; @end
47.6
130
0.697479
aefce236a146f8e710be07b0eb1aaf09ae121f5e
1,425
h
C
libsel4vmm/include/vmm/processor/decode.h
aisamanra/seL4_libs
4840caf887bb7dc851e6c231007f25029d3a6dc7
[ "BSD-2-Clause" ]
null
null
null
libsel4vmm/include/vmm/processor/decode.h
aisamanra/seL4_libs
4840caf887bb7dc851e6c231007f25029d3a6dc7
[ "BSD-2-Clause" ]
null
null
null
libsel4vmm/include/vmm/processor/decode.h
aisamanra/seL4_libs
4840caf887bb7dc851e6c231007f25029d3a6dc7
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2017, Data61 * Commonwealth Scientific and Industrial Research Organisation (CSIRO) * ABN 41 687 119 230. * * This software may be distributed and modified according to the terms of * the GNU General Public License version 2. Note that NO WARRANTY is provided. * See "LICENSE_GPLv2.txt" for details. * * @TAG(DATA61_GPL) */ #ifndef _VMM_DECODE_H #define _VMM_DECODE_H #include "vmm/vmm.h" #include "vmm/guest_state.h" int vmm_fetch_instruction(vmm_vcpu_t *vcpu, uint32_t eip, uintptr_t cr3, int len, uint8_t *buf); int vmm_decode_instruction(uint8_t *instr, int instr_len, int *reg, uint32_t *imm, int *op_len); /* Interpret just enough virtual 8086 instructions to run trampoline code. Returns the final jump address */ uintptr_t vmm_emulate_realmode(guest_memory_t *gm, uint8_t *instr_buf, uint16_t *segment, uintptr_t eip, uint32_t len, guest_state_t *gs); // TODO don't have these in a header, make them inline functions const static int vmm_decoder_reg_mapw[] = { USER_CONTEXT_EAX, USER_CONTEXT_ECX, USER_CONTEXT_EDX, USER_CONTEXT_EBX, /*USER_CONTEXT_ESP*/-1, USER_CONTEXT_EBP, USER_CONTEXT_ESI, USER_CONTEXT_EDI }; const static int vmm_decoder_reg_mapb[] = { USER_CONTEXT_EAX, USER_CONTEXT_ECX, USER_CONTEXT_EDX, USER_CONTEXT_EBX, USER_CONTEXT_EAX, USER_CONTEXT_ECX, USER_CONTEXT_EDX, USER_CONTEXT_EBX }; #endif
27.941176
96
0.745965
b7e7685562bf20a3186e5b641d298c9e009bda00
27,980
c
C
vendors/marvell/WMSDK/mw320/sdk/src/drivers/mw300/lowlevel/mw300_qspi.c
ictk-solution-dev/amazon-freertos
cc76512292ddfb70bba3030dbcb740ef3c6ead8b
[ "MIT" ]
2
2020-06-23T08:05:58.000Z
2020-06-24T01:25:51.000Z
vendors/marvell/WMSDK/mw320/sdk/src/drivers/mw300/lowlevel/mw300_qspi.c
ictk-solution-dev/amazon-freertos
cc76512292ddfb70bba3030dbcb740ef3c6ead8b
[ "MIT" ]
2
2022-03-29T05:16:50.000Z
2022-03-29T05:16:50.000Z
vendors/marvell/WMSDK/mw320/sdk/src/drivers/mw300/lowlevel/mw300_qspi.c
ictk-solution-dev/amazon-freertos
cc76512292ddfb70bba3030dbcb740ef3c6ead8b
[ "MIT" ]
null
null
null
/** @file mw300_qspi.h * * @brief This file provides QSPI driver module header file. * * (C) Copyright 2012-2019 Marvell International Ltd. All Rights Reserved. * * MARVELL CONFIDENTIAL * The source code contained or described herein and all documents related to * the source code ("Material") are owned by Marvell International Ltd or its * suppliers or licensors. Title to the Material remains with Marvell * International Ltd or its suppliers and licensors. The Material contains * trade secrets and proprietary and confidential information of Marvell or its * suppliers and licensors. The Material is protected by worldwide copyright * and trade secret laws and treaty provisions. No part of the Material may be * used, copied, reproduced, modified, published, uploaded, posted, * transmitted, distributed, or disclosed in any way without Marvell's prior * express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or delivery * of the Materials, either expressly, by implication, inducement, estoppel or * otherwise. Any license under such intellectual property rights must be * express and approved by Marvell in writing. * */ #include "mw300.h" #include "mw300_driver.h" #include "mw300_qspi.h" /** @addtogroup MW300_Periph_Driver * @{ */ /** @defgroup QSPI QSPI * @brief QSPI driver modules * @{ */ /** @defgroup QSPI_Private_Type * @{ */ /*@} end of group QSPI_Private_Type*/ /** @defgroup QSPI_Private_Defines * @{ */ /*@} end of group QSPI_Private_Defines */ /** @defgroup QSPI_Private_Variables * @{ */ /*@} end of group QSPI_Private_Variables */ /** @defgroup QSPI_Global_Variables * @{ */ /*@} end of group QSPI_Global_Variables */ /** @defgroup QSPI_Private_FunctionDeclaration * @{ */ /*@} end of group QSPI_Private_FunctionDeclaration */ /** @defgroup QSPI_Private_Functions * @{ */ /****************************************************************************//** * @brief QSPI interrupt function * * @param none * * @return none * *******************************************************************************/ void QSPI_IRQHandler(void) { uint32_t temp; /* Store interrupt flags for later use */ temp = QSPI->ISR.WORDVAL; /* Clear all interrupt flags */ QSPI->ISC.WORDVAL = 0x1; /* QSPI transfer done inerrupt */ if( temp & (1 << QSPI_XFER_DONE) ) { if(intCbfArra[INT_QSPI][QSPI_XFER_DONE] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_XFER_DONE](); } else { /* Mask this interrupt */ QSPI->IMR.BF.XFER_DONE_IM = 1; } } /* QSPI transfer ready interrupt */ if( temp & (1 << QSPI_XFER_RDY) ) { if(intCbfArra[INT_QSPI][QSPI_XFER_RDY] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_XFER_RDY](); } else { /* Mask this interrupt */ QSPI->IMR.BF.XFER_RDY_IM = 1; } } /* QSPI read fifo dma burst interrupt */ if( temp & (1 << QSPI_RFIFO_DMA_BURST) ) { if(intCbfArra[INT_QSPI][QSPI_RFIFO_DMA_BURST] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_RFIFO_DMA_BURST](); } else { /* Mask this interrupt */ QSPI->IMR.BF.RFIFO_DMA_BURST_IM = 1; } } /* QSPI write fifo dma burst interrupt */ if( temp & (1 << QSPI_WFIFO_DMA_BURST) ) { if(intCbfArra[INT_QSPI][QSPI_WFIFO_DMA_BURST] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_WFIFO_DMA_BURST](); } else { /* Mask this interrupt */ QSPI->IMR.BF.WFIFO_DMA_BURST_IM = 1; } } /* QSPI read fifo empty interrupt */ if( temp & (1 << QSPI_RFIFO_EMPTY) ) { if(intCbfArra[INT_QSPI][QSPI_RFIFO_EMPTY] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_RFIFO_EMPTY](); } else { /* Mask this interrupt */ QSPI->IMR.BF.RFIFO_EMPTY_IM = 1; } } /* QSPI read fifo full inerrupt */ if( temp & (1 << QSPI_RFIFO_FULL) ) { if(intCbfArra[INT_QSPI][QSPI_RFIFO_FULL] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_RFIFO_FULL](); } else { /* Mask this interrupt */ QSPI->IMR.BF.RFIFO_FULL_IM = 1; } } /* QSPI write fifo empty interrupt */ if( temp & (1 << QSPI_WFIFO_EMPTY) ) { if(intCbfArra[INT_QSPI][QSPI_WFIFO_EMPTY] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_WFIFO_EMPTY](); } else { /* Mask this interrupt */ QSPI->IMR.BF.WFIFO_EMPTY_IM = 1; } } /* QSPI write fifo full interrupt */ if( temp & (1 << QSPI_WFIFO_FULL) ) { if(intCbfArra[INT_QSPI][QSPI_WFIFO_FULL] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_WFIFO_FULL](); } else { /* Mask this interrupt */ QSPI->IMR.BF.WFIFO_FULL_IM = 1; } } /* QSPI read fifo underflow interrupt */ if( temp & (1 << QSPI_RFIFO_UNDRFLW) ) { if(intCbfArra[INT_QSPI][QSPI_RFIFO_UNDRFLW] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_RFIFO_UNDRFLW](); } else { /* Mask this interrupt */ QSPI->IMR.BF.RFIFO_UNDRFLW_IM = 1; } } /* QSPI read fifo overflow interrupt */ if( temp & (1 << QSPI_RFIFO_OVRFLW) ) { if(intCbfArra[INT_QSPI][QSPI_RFIFO_OVRFLW] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_RFIFO_OVRFLW](); } else { /* Mask this interrupt */ QSPI->IMR.BF.RFIFO_OVRFLW_IM = 1; } } /* QSPI read fifo underflow interrupt */ if( temp & (1 << QSPI_RFIFO_UNDRFLW) ) { if(intCbfArra[INT_QSPI][QSPI_RFIFO_UNDRFLW] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_RFIFO_UNDRFLW](); } else { /* Mask this interrupt */ QSPI->IMR.BF.WFIFO_UNDRFLW_IM = 1; } } /* QSPI write fifo overflow interrupt */ if( temp & (1 << QSPI_WFIFO_OVRFLW) ) { if(intCbfArra[INT_QSPI][QSPI_WFIFO_OVRFLW] != NULL) { /* Call the callback function */ intCbfArra[INT_QSPI][QSPI_WFIFO_OVRFLW](); } else { /* Mask this interrupt */ QSPI->IMR.BF.WFIFO_OVRFLW_IM = 1; } } } /*@} end of group QSPI_Private_Functions */ /** @defgroup QSPI_Public_Functions * @{ */ /****************************************************************************//** * @brief Reset QSPI * * @param none * * @return none * * Reset QSPI *******************************************************************************/ void QSPI_Reset(void) { uint32_t i; QSPI->CONF2.BF.SRST = 1; /* Delay */ for(i=0; i<10; i++); QSPI->CONF2.BF.SRST = 0; } /****************************************************************************//** * @brief Initializes the QSPI * * @param[in] qspiConfigSet: Pointer to a QSPI configuration structure * * @return none * * Initializes the QSPI *******************************************************************************/ void QSPI_Init(QSPI_CFG_Type* qspiConfigSet) { /* Set data pin number */ QSPI->CONF.BF.DATA_PIN = qspiConfigSet->dataPinMode; /* Set address pin number */ QSPI->CONF.BF.ADDR_PIN = qspiConfigSet->addrPinMode; /* Set QSPI clock mode */ QSPI->CONF.BF.CLK_PHA = (qspiConfigSet->clkMode) & 1; QSPI->CONF.BF.CLK_POL = ((qspiConfigSet->clkMode)>>1) & 1; /* Set QSPI capture clock edge */ QSPI->TIMING.BF.CLK_CAPT_EDGE = qspiConfigSet->captEdge; /* Set data length mode */ QSPI->CONF.BF.BYTE_LEN = qspiConfigSet->byteLen; /* Set QSPI clock prescaler */ QSPI->CONF.BF.CLK_PRESCALE = qspiConfigSet->preScale; } /****************************************************************************//** * @brief Mask/Unmask specified interrupt type * * @param[in] intType: Specified interrupt type * - QSPI_XFER_DONE - QSPI_XFER_RDY * - QSPI_RFIFO_DMA_BURST - QSPI_WFIFO_DMA_BURST * - QSPI_RFIFO_EMPTY - QSPI_RFIFO_FULL * - QSPI_WFIFO_EMPTY - QSPI_WFIFO_FULL * - QSPI_RFIFO_UNDRFLW - QSPI_RFIFO_OVRFLW * - QSPI_WFIFO_UNDRFLW - QSPI_WFIFO_OVRFLW * - QSPI_INT_ALL * @param[in] intMask: Interrupt mask/unmask type * - UNMASK * - MASK * * @return none * *******************************************************************************/ void QSPI_IntMask( QSPI_INT_Type intType, IntMask_Type intMask) { /* Check the parameters */ CHECK_PARAM(IS_QSPI_INT_TYPE(intType)); CHECK_PARAM(IS_INTMASK(intMask)); switch(intType) { case QSPI_XFER_DONE: QSPI->IMR.BF.XFER_DONE_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_XFER_RDY: QSPI->IMR.BF.XFER_RDY_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_RFIFO_DMA_BURST: QSPI->IMR.BF.RFIFO_DMA_BURST_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_WFIFO_DMA_BURST: QSPI->IMR.BF.WFIFO_DMA_BURST_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_RFIFO_EMPTY: QSPI->IMR.BF.RFIFO_EMPTY_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_RFIFO_FULL: QSPI->IMR.BF.RFIFO_FULL_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_WFIFO_EMPTY: QSPI->IMR.BF.WFIFO_EMPTY_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_WFIFO_FULL: QSPI->IMR.BF.WFIFO_FULL_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_RFIFO_UNDRFLW: QSPI->IMR.BF.RFIFO_UNDRFLW_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_RFIFO_OVRFLW: QSPI->IMR.BF.RFIFO_OVRFLW_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_WFIFO_UNDRFLW: QSPI->IMR.BF.WFIFO_UNDRFLW_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_WFIFO_OVRFLW: QSPI->IMR.BF.WFIFO_OVRFLW_IM = ((intMask == MASK)? 1 : 0); break; case QSPI_INT_ALL: QSPI->IMR.WORDVAL = ((intMask == MASK)? 0xFFF : 0); break; default: break; } } /****************************************************************************//** * @brief Clear transfer done interrupt * * @param none * * @return none * * Clear transfer done interrupt *******************************************************************************/ void QSPI_IntClr(void) { QSPI->ISC.WORDVAL = 1; } /****************************************************************************//** * @brief Flush Write and Read FIFOs * * @param none * * @return none * * Flush Write and Read FIFOs *******************************************************************************/ Status QSPI_FlushFIFO(void) { volatile uint32_t localCnt = 0; QSPI->CONF.BF.FIFO_FLUSH = 1; /* Wait until Write and Read FIFOs are flushed. */ while(localCnt++ < 0xFFFFFFF) { if( (QSPI->CONF.BF.FIFO_FLUSH) == RESET ) { return DSUCCESS; } } return ERROR; } /****************************************************************************//** * @brief Set QSPI serial interface header count * * @param[in] instrcnt: number of bytes in INSTR register to shift out * QSPI_INSTR_CNT_0BYTE/QSPI_INSTR_CNT_1BYTE/QSPI_INSTR_CNT_2BYTE * * addrcnt: number of bytes in ADDR register to shift out * QSPI_ADDR_CNT_0BYTE/QSPI_ADDR_CNT_1BYTE/QSPI_ADDR_CNT_2BYTE/QSPI_ADDR_CNT_3BYTE/QSPI_ADDR_CNT_4BYTE * * rmcnt: number of bytes in RMODE register to shift out * QSPI_RM_CNT_0BYTE/QSPI_RM_CNT_1BYTE/QSPI_RM_CNT_2BYTE * * dummycnt: number of bytes as dummy to shift out * QSPI_DUMMY_CNT_0BYTE/QSPI_DUMMY_CNT_1BYTE/QSPI_DUMMY_CNT_2BYTE/QSPI_DUMMY_CNT_3BYTE * * @return none * * Set QSPI serial interface header count *******************************************************************************/ void QSPI_SetHdrcnt(QSPI_INSTR_CNT_TYPE instrcnt, QSPI_ADDR_CNT_TYPE addrcnt, QSPI_RM_CNT_TYPE rmcnt, QSPI_DUMMY_CNT_TYPE dummycnt) { /* Check the parameters */ CHECK_PARAM(IS_QSPI_INSTR_CNT_TYPE(instrcnt)); CHECK_PARAM(IS_QSPI_ADDR_CNT_TYPE(addrcnt)); CHECK_PARAM(IS_QSPI_RM_CNT_TYPE(rmcnt)); CHECK_PARAM(IS_QSPI_DUMMY_CNT_TYPE(dummycnt)); QSPI->HDRCNT.BF.INSTR_CNT = instrcnt; QSPI->HDRCNT.BF.ADDR_CNT = addrcnt; QSPI->HDRCNT.BF.RM_CNT = rmcnt; QSPI->HDRCNT.BF.DUMMY_CNT = dummycnt; } /****************************************************************************//** * @brief Set number of bytes in INSTR register to shift out to the serial interface * * @param[in] instrcnt: number of bytes in INSTR register to shift out * * @return none * * Set number of bytes in INSTR register to shift out to the serial interface *******************************************************************************/ void QSPI_SetInstrCnt(QSPI_INSTR_CNT_TYPE instrcnt) { /* Check the parameter */ CHECK_PARAM(IS_QSPI_INSTR_CNT_TYPE(instrcnt)); QSPI->HDRCNT.BF.INSTR_CNT = instrcnt; } /****************************************************************************//** * @brief Set number of bytes in ADDR register to shift out to the serial interface * * @param[in] addrcnt: number of bytes in ADDR register to shift out * * @return none * * Set number of bytes in ADDR register to shift out to the serial interface *******************************************************************************/ void QSPI_SetAddrCnt(QSPI_ADDR_CNT_TYPE addrcnt) { /* Check the parameter */ CHECK_PARAM(IS_QSPI_ADDR_CNT_TYPE(addrcnt)); QSPI->HDRCNT.BF.ADDR_CNT = addrcnt; } /****************************************************************************//** * @brief Set number of bytes in RMODE register to shift out to the serial interface * * @param[in] rmcnt: number of bytes in RMODE register to shift out * * @return none * * Set number of bytes in RMODE register to shift out to the serial interface *******************************************************************************/ void QSPI_SetRModeCnt(QSPI_RM_CNT_TYPE rmcnt) { /* Check the parameter */ CHECK_PARAM(IS_QSPI_RM_CNT_TYPE(rmcnt)); QSPI->HDRCNT.BF.RM_CNT = rmcnt; } /****************************************************************************//** * @brief Set number of bytes as dummy to shift out to the serial interface * * @param[in] dummycnt: number of bytes as dummy to shift out * * @return none * * Set number of bytes as dummy to shift out to the serial interface *******************************************************************************/ void QSPI_SetDummyCnt(QSPI_DUMMY_CNT_TYPE dummycnt) { /* Check the parameter */ CHECK_PARAM(IS_QSPI_DUMMY_CNT_TYPE(dummycnt)); QSPI->HDRCNT.BF.DUMMY_CNT = dummycnt; } /****************************************************************************//** * @brief Set QSPI serial interface instruction * * @param[in] instruct: QSPI serial interface instruction * * @return none * * Set QSPI serial interface instruction *******************************************************************************/ void QSPI_SetInstr(uint32_t instruct) { QSPI->INSTR.BF.INSTR = instruct; } /****************************************************************************//** * @brief Set QSPI serial interface address * * @param[in] address: QSPI serial interface address * * @return none * * Set QSPI serial interface address *******************************************************************************/ void QSPI_SetAddr(uint32_t address) { QSPI->ADDR.WORDVAL = address; } /****************************************************************************//** * @brief Set QSPI serial interface read mode * * @param[in] readMode: QSPI serial interface read mode * * @return none * * Set QSPI serial interface read mode *******************************************************************************/ void QSPI_SetRMode(uint32_t readMode) { QSPI->RDMODE.BF.RMODE = readMode; } /****************************************************************************//** * @brief Set number of bytes of data to shift in from the serial interface * * @param[in] count: number of bytes of data to shift in * * @return none * * Set number of bytes of data to shift in from the serial interface *******************************************************************************/ void QSPI_SetDInCnt(uint32_t count) { QSPI->DINCNT.BF.DATA_IN_CNT = count; } /****************************************************************************//** * @brief Activate or de-activate serial select output * * @param[in] newCmd: Activate or de-activate * * @return none * * Activate or de-activate serial select output *******************************************************************************/ void QSPI_SetSSEnable(FunctionalState newCmd) { QSPI->CNTL.BF.SS_EN = newCmd; while(0==QSPI->CNTL.BF.XFER_RDY); } /****************************************************************************//** * @brief Start the specified QSPI transfer * * @param[in] rw: read/write transfer * * @return none * * Start the QSPI transfer *******************************************************************************/ void QSPI_StartTransfer(QSPI_RW_Type rw) { /* Assert QSPI SS */ QSPI_SetSSEnable(ENABLE); /* Set read/write mode */ QSPI->CONF.BF.RW_EN = rw; /* Start QSPI */ QSPI->CONF.BF.XFER_START = 1; } /****************************************************************************//** * @brief Stop QSPI transfer * * @param none * * @return none * * Stop QSPI transfer *******************************************************************************/ void QSPI_StopTransfer(void) { /* Wait until QSPI ready */ while(QSPI->CNTL.BF.XFER_RDY == 0); /* Wait until wfifo empty */ while(QSPI->CNTL.BF.WFIFO_EMPTY == 0); /* Stop QSPI */ QSPI->CONF.BF.XFER_STOP = 1; /* Wait until QSPI release start signal */ while(QSPI->CONF.BF.XFER_START == 1); /* De-assert QSPI SS */ QSPI_SetSSEnable(DISABLE); } /****************************************************************************//** * @brief Write a byte to QSPI serial interface * * @param[in] byte: data to be written * * @return none * * Write a byte to QSPI serial interface *******************************************************************************/ void QSPI_WriteByte(uint8_t byte) { /* Wait unitl WFIFO is not full*/ while(QSPI->CNTL.BF.WFIFO_FULL == 1); QSPI->DOUT.WORDVAL = (byte & 0xFF); } /****************************************************************************//** * @brief Read a byte from QSPI serial interface * * @param none * * @return byte from QSPI serial interface * * Read a byte from QSPI serial interface *******************************************************************************/ uint8_t QSPI_ReadByte(void) { uint8_t data; /* Wait if RFIFO is empty*/ while(QSPI->CNTL.BF.RFIFO_EMPTY == 1); data = (QSPI->DIN.BF.DATA_IN & 0xFF); return data; } /****************************************************************************//** * @brief Write a word to QSPI serial interface * * @param[in] word: data to be written * * @return none * * Write a word to QSPI serial interface *******************************************************************************/ void QSPI_WriteWord(uint32_t word) { /* Wait unitl WFIFO is not full*/ while(QSPI->CNTL.BF.WFIFO_FULL == 1); QSPI->DOUT.WORDVAL = word; } /****************************************************************************//** * @brief Read a word from QSPI serial interface * * @param none * * @return word from QSPI serial interface * * Read a word from QSPI serial interface *******************************************************************************/ uint32_t QSPI_ReadWord(void) { /* Wait if RFIFO is empty*/ while(QSPI->CNTL.BF.RFIFO_EMPTY == 1); return QSPI->DIN.WORDVAL; } /****************************************************************************//** * @brief Check whether status flag is set or not for given status type * * @param[in] qspiStatus: Specified status type * - QSPI_STATUS_XFER_RDY * - QSPI_STATUS_RFIFO_EMPTY * - QSPI_STATUS_RFIFO_FULL * - QSPI_STATUS_WFIFO_EMPTY * - QSPI_STATUS_WFIFO_FULL * - QSPI_STATUS_RFIFO_UNDRFLW * - QSPI_STATUS_RFIFO_OVRFLW * - QSPI_STATUS_WFIFO_UNDRFLW * - QSPI_STATUS_WFIFO_OVRFLW * * @return The state value of QSPI serial interface control register. * - SET * - RESET * *******************************************************************************/ FlagStatus QSPI_GetStatus(QSPI_Status_Type qspiStatus) { FlagStatus intBitStatus = RESET; /* Check the parameters */ CHECK_PARAM(IS_QSPI_STATUS_BIT(qspiStatus)); switch(qspiStatus) { case QSPI_STATUS_XFER_RDY: intBitStatus = (QSPI->CNTL.BF.XFER_RDY? SET : RESET); break; case QSPI_STATUS_RFIFO_EMPTY: intBitStatus = (QSPI->CNTL.BF.RFIFO_EMPTY? SET : RESET); break; case QSPI_STATUS_RFIFO_FULL: intBitStatus = (QSPI->CNTL.BF.RFIFO_FULL? SET : RESET); break; case QSPI_STATUS_WFIFO_EMPTY: intBitStatus = (QSPI->CNTL.BF.WFIFO_EMPTY? SET : RESET); break; case QSPI_STATUS_WFIFO_FULL: intBitStatus = (QSPI->CNTL.BF.WFIFO_FULL? SET : RESET); break; case QSPI_STATUS_RFIFO_UNDRFLW: intBitStatus = (QSPI->CNTL.BF.RFIFO_UNDRFLW? SET : RESET); break; case QSPI_STATUS_RFIFO_OVRFLW: intBitStatus = (QSPI->CNTL.BF.RFIFO_OVRFLW? SET : RESET); break; case QSPI_STATUS_WFIFO_UNDRFLW: intBitStatus = (QSPI->CNTL.BF.WFIFO_UNDRFLW? SET : RESET); break; case QSPI_STATUS_WFIFO_OVRFLW: intBitStatus = (QSPI->CNTL.BF.WFIFO_OVRFLW? SET : RESET); break; default: break; } return intBitStatus; } /****************************************************************************//** * @brief Check whether int status flag is set or not for given status type * * @param[in] qspiIntStatus: Specified int status type * - QSPI_XFER_DONE - QSPI_XFER_RDY * - QSPI_RFIFO_DMA_BURST - QSPI_WFIFO_DMA_BURST * - QSPI_RFIFO_EMPTY - QSPI_RFIFO_FULL * - QSPI_WFIFO_EMPTY - QSPI_WFIFO_FULL * - QSPI_RFIFO_UNDRFLW - QSPI_RFIFO_OVRFLW * - QSPI_WFIFO_UNDRFLW - QSPI_WFIFO_OVRFLW * - QSPI_INT_ALL * * @return The state value of QSPI serial interface control register. * - SET * - RESET * *******************************************************************************/ FlagStatus QSPI_GetIntStatus(QSPI_INT_Type qspiIntStatus) { FlagStatus intBitStatus = RESET; /* Check the parameters */ CHECK_PARAM(IS_QSPI_INT_TYPE(qspiIntStatus)); switch(qspiIntStatus) { case QSPI_XFER_DONE: intBitStatus = (QSPI->ISR.BF.XFER_DONE_IS? SET : RESET); break; case QSPI_XFER_RDY: intBitStatus = (QSPI->ISR.BF.XFER_RDY_IS? SET : RESET); break; case QSPI_RFIFO_DMA_BURST: intBitStatus = (QSPI->ISR.BF.RFIFO_DMA_BURST_IS? SET : RESET); break; case QSPI_WFIFO_DMA_BURST: intBitStatus = (QSPI->ISR.BF.WFIFO_DMA_BURST_IS? SET : RESET); break; case QSPI_RFIFO_EMPTY: intBitStatus = (QSPI->ISR.BF.RFIFO_EMPTY_IS? SET : RESET); break; case QSPI_RFIFO_FULL: intBitStatus = (QSPI->ISR.BF.RFIFO_FULL_IS? SET : RESET); break; case QSPI_WFIFO_EMPTY: intBitStatus = (QSPI->ISR.BF.WFIFO_EMPTY_IS? SET : RESET); break; case QSPI_WFIFO_FULL: intBitStatus = (QSPI->ISR.BF.WFIFO_FULL_IS? SET : RESET); break; case QSPI_RFIFO_UNDRFLW: intBitStatus = (QSPI->ISR.BF.RFIFO_UNDRFLW_IS? SET : RESET); break; case QSPI_RFIFO_OVRFLW: intBitStatus = (QSPI->ISR.BF.RFIFO_OVRFLW_IS? SET : RESET); break; case QSPI_WFIFO_UNDRFLW: intBitStatus = (QSPI->ISR.BF.WFIFO_UNDRFLW_IS? SET : RESET); break; case QSPI_WFIFO_OVRFLW: intBitStatus = (QSPI->ISR.BF.WFIFO_OVRFLW_IS? SET : RESET); break; case QSPI_INT_ALL: intBitStatus = ((QSPI->ISR.WORDVAL & 0xFFF)? SET : RESET); break; default: break; } return intBitStatus; } /****************************************************************************//** * @brief Get serial interface transfer state * * @param none * * @return serial interface transfer state * - SET * - RESET * Get serial interface transfer state *******************************************************************************/ FlagStatus QSPI_IsTransferCompleted(void) { return (QSPI->CONF.BF.XFER_START == 0? SET : RESET); } /****************************************************************************//** * @brief Enable or disable the QSPI DMA function and set the burst size * * @param[in] dmaCtrl: DMA read or write, QSPI_DMA_READ or QSPI_DMA_WRITE * @param[in] dmaDataCtrl: DMA Diable/Enable and set the data burst size * - QSPI_DMA_DISABLE * - QSPI_DMA_1DATA * - QSPI_DMA_4DATA * - QSPI_DMA_8DATA * * @return none * *******************************************************************************/ void QSPI_DmaCmd(QSPI_DMA_Type dmaCtrl, QSPI_DMA_Data_Type dmaDataCtrl) { CHECK_PARAM(IS_QSPI_DMA_TYPE(dmaCtrl)); CHECK_PARAM(IS_QSPI_DMA_DATA_TYPE(dmaDataCtrl)); if(dmaCtrl == QSPI_DMA_READ) { if(dmaDataCtrl == QSPI_DMA_DISABLE) { QSPI->CONF2.BF.DMA_RD_EN = 0; } else { QSPI->CONF2.BF.DMA_RD_EN = 1; QSPI->CONF2.BF.DMA_RD_BURST = dmaDataCtrl; } } else { if(dmaDataCtrl == QSPI_DMA_DISABLE) { QSPI->CONF2.BF.DMA_WR_EN = 0; } else { QSPI->CONF2.BF.DMA_WR_EN = 1; QSPI->CONF2.BF.DMA_WR_BURST = dmaDataCtrl; } } } /*@} end of group QSPI_Public_Functions */ /*@} end of group QSPI_definitions */ /*@} end of group MW300_Periph_Driver */
28.93485
132
0.513545
646a8872c346a4475fd146f3b817c6ecb719ccd7
757
h
C
BTJSBridge/Classes/BTJSBridge+Common.h
BrooksWon/BTJSBridge
72b4ac55aad89d0be566ebada8b611a608dda470
[ "MIT" ]
null
null
null
BTJSBridge/Classes/BTJSBridge+Common.h
BrooksWon/BTJSBridge
72b4ac55aad89d0be566ebada8b611a608dda470
[ "MIT" ]
null
null
null
BTJSBridge/Classes/BTJSBridge+Common.h
BrooksWon/BTJSBridge
72b4ac55aad89d0be566ebada8b611a608dda470
[ "MIT" ]
null
null
null
// // BTJSBridge+Common.h // BTJSBridge // // Created by Brooks on 2019/4/26. // #import "BTJSBridge.h" /** this.webviewAppearEvent = 'webviewAppear'; this.webviewDisappearEvent = 'webviewDisappear'; this.applicationEnterBackgroundEvent = 'applicationEnterBackground'; this.applicationEnterForegroundEvent = 'applicationEnterForeground'; */ FOUNDATION_EXTERN NSString * const BTJSBridgeAppEnterBackgroundEvent; FOUNDATION_EXTERN NSString * const BTJSBridgeAppEnterForegroundEvent; NS_ASSUME_NONNULL_BEGIN @interface BTJSBridge (Common) -(void)registCommonHandler; -(void)applicationEnterForeground; -(void)applicationEnterBackground; -(void)addLifeCycleListenerCommon; -(void)removeLifeCycleListenerCommon; @end NS_ASSUME_NONNULL_END
19.410256
69
0.805812
230437cca216cdc7bce701f795ae458704337c3c
599
h
C
TempAlarmControl/DisplayOffState.h
Zer0-Vector/arduino-temperature-alarm
b1cd5992ecc2f64f75cfec254504858f78ed87eb
[ "MIT" ]
null
null
null
TempAlarmControl/DisplayOffState.h
Zer0-Vector/arduino-temperature-alarm
b1cd5992ecc2f64f75cfec254504858f78ed87eb
[ "MIT" ]
5
2019-05-08T08:21:25.000Z
2020-12-07T20:47:33.000Z
TempAlarmControl/DisplayOffState.h
Zer0-Vector/arduino-temperature-alarm
b1cd5992ecc2f64f75cfec254504858f78ed87eb
[ "MIT" ]
null
null
null
#pragma once #include "ProgramState.h" class DisplayOffState : public ProgramState { public: static DisplayOffState* const INSTANCE; void setMin(TempAlarmControl* control); void setMax(TempAlarmControl* control); void changeUnits(TempAlarmControl* control); void toggleDisplay(TempAlarmControl* control); void tick(TempAlarmControl* control); void entered(TempAlarmControl* control); void exiting(TempAlarmControl* control); void render(SSD1306Ascii* oled); protected: DisplayOffState(); };
31.526316
55
0.669449
d95698fe1ca0ff0292f73f6a383bac64b38a8ae5
600
h
C
src/include/commands/conversioncmds.h
wanghongxiang2018/postgres-x2
2a845c3e796a8ab830053b6a1268e0a9d9118216
[ "PostgreSQL" ]
326
2015-05-11T14:53:36.000Z
2022-03-26T13:50:30.000Z
src/include/commands/conversioncmds.h
wanghongxiang2018/postgres-x2
2a845c3e796a8ab830053b6a1268e0a9d9118216
[ "PostgreSQL" ]
323
2015-05-07T10:39:33.000Z
2021-07-23T09:43:39.000Z
src/include/commands/conversioncmds.h
wanghongxiang2018/postgres-x2
2a845c3e796a8ab830053b6a1268e0a9d9118216
[ "PostgreSQL" ]
117
2015-05-11T14:15:02.000Z
2021-09-12T13:22:59.000Z
/*------------------------------------------------------------------------- * * conversioncmds.h * prototypes for conversioncmds.c. * * * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/commands/conversioncmds.h * *------------------------------------------------------------------------- */ #ifndef CONVERSIONCMDS_H #define CONVERSIONCMDS_H #include "nodes/parsenodes.h" extern Oid CreateConversionCommand(CreateConversionStmt *parsetree); #endif /* CONVERSIONCMDS_H */
26.086957
75
0.565
033327a2d3fdac609232b581e432a41ab9a21927
529
h
C
ext/stub/arrayiteratortest.zep.h
nawawi/zephir
cc7ecd35745594710913edab1afe5c6d82f52932
[ "MIT" ]
2,508
2015-01-02T09:48:45.000Z
2021-02-13T14:58:39.000Z
ext/stub/arrayiteratortest.zep.h
nawawi/zephir
cc7ecd35745594710913edab1afe5c6d82f52932
[ "MIT" ]
1,321
2015-01-03T09:31:20.000Z
2021-02-16T06:39:07.000Z
ext/stub/arrayiteratortest.zep.h
nawawi/zephir
cc7ecd35745594710913edab1afe5c6d82f52932
[ "MIT" ]
507
2015-01-02T09:51:11.000Z
2021-02-15T08:13:53.000Z
extern zend_class_entry *stub_arrayiteratortest_ce; ZEPHIR_INIT_CLASS(Stub_ArrayIteratorTest); PHP_METHOD(Stub_ArrayIteratorTest, test); ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_arrayiteratortest_test, 0, 0, 0) ZEND_END_ARG_INFO() ZEPHIR_INIT_FUNCS(stub_arrayiteratortest_method_entry) { #if PHP_VERSION_ID >= 80000 PHP_ME(Stub_ArrayIteratorTest, test, arginfo_stub_arrayiteratortest_test, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) #else PHP_ME(Stub_ArrayIteratorTest, test, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) #endif PHP_FE_END };
27.842105
107
0.858223
b3390d605b97e1784624ee009377f9cb0e0fd547
2,896
c
C
tools/fpga_rw/devmem.c
derek-yi/xdaemon
38f6e26c03215f221dfffdade7bb92651c6122f4
[ "MIT" ]
null
null
null
tools/fpga_rw/devmem.c
derek-yi/xdaemon
38f6e26c03215f221dfffdade7bb92651c6122f4
[ "MIT" ]
null
null
null
tools/fpga_rw/devmem.c
derek-yi/xdaemon
38f6e26c03215f221dfffdade7bb92651c6122f4
[ "MIT" ]
null
null
null
//from https://github.com/VCTLabs/devmem2/blob/master/devmem2.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <signal.h> #include <fcntl.h> #include <ctype.h> #include <termios.h> #include <sys/types.h> #include <sys/mman.h> #define FATAL do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \ __LINE__, __FILE__, errno, strerror(errno)); exit(1); } while(0) #define MAP_SIZE 4096UL #define MAP_MASK (MAP_SIZE - 1) int main(int argc, char **argv) { int fd; void *map_base, *virt_addr; unsigned long read_result, writeval; off_t target; int access_type = 'w'; if(argc < 2) { fprintf(stderr, "\nUsage:\t%s { address } [ type [ data ] ]\n" "\taddress : memory address to act upon\n" "\ttype : access operation type : [b]yte, [h]alfword, [w]ord\n" "\tdata : data to be written\n\n", argv[0]); exit(1); } target = strtoul(argv[1], 0, 0); if(argc > 2) access_type = tolower(argv[2][0]); if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) FATAL; printf("/dev/mem opened.\n"); fflush(stdout); /* Map one page */ map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, target & ~MAP_MASK); if(map_base == (void *) -1) FATAL; printf("Memory mapped at address %p.\n", map_base); fflush(stdout); virt_addr = map_base + (target & MAP_MASK); switch(access_type) { case 'b': read_result = *((unsigned char *) virt_addr); break; case 'h': read_result = *((unsigned short *) virt_addr); break; case 'w': read_result = *((unsigned long *) virt_addr); break; default: fprintf(stderr, "Illegal data type '%c'.\n", access_type); exit(2); } printf("Value at address 0x%lld (%p): 0x%lu\n", (long long)target, virt_addr, read_result); fflush(stdout); if(argc > 3) { writeval = strtoul(argv[3], 0, 0); switch(access_type) { case 'b': *((unsigned char *) virt_addr) = writeval; read_result = *((unsigned char *) virt_addr); break; case 'h': *((unsigned short *) virt_addr) = writeval; read_result = *((unsigned short *) virt_addr); break; case 'w': *((unsigned long *) virt_addr) = writeval; read_result = *((unsigned long *) virt_addr); break; } printf("Written 0x%lu; readback 0x%lu\n", writeval, read_result); fflush(stdout); } if(munmap(map_base, MAP_SIZE) == -1) FATAL; close(fd); return 0; }
30.808511
96
0.525207
6c4c4473a9563ad9b5ddbac75dc7693f1c5be492
382
h
C
src/platformargswrapper.h
getraid-gg/MIDIRenderer
b94b64a9a001f9b4fe8a9eb1c21dc7d39685921b
[ "BSD-3-Clause" ]
null
null
null
src/platformargswrapper.h
getraid-gg/MIDIRenderer
b94b64a9a001f9b4fe8a9eb1c21dc7d39685921b
[ "BSD-3-Clause" ]
8
2021-01-31T08:31:37.000Z
2021-11-04T02:33:20.000Z
src/platformargswrapper.h
getraid-gg/MIDIRenderer
b94b64a9a001f9b4fe8a9eb1c21dc7d39685921b
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "platformchar.h" #include <vector> #include <memory> class PlatformArgsWrapper { public: PlatformArgsWrapper(int argc, argv_t** argv); int getArgc() const { return m_argc; } char** getArgv() { return m_argv.data(); } private: void consumeArg(argv_t* arg); int m_argc; std::vector<char*> m_argv; std::vector<std::unique_ptr<char[]>> m_managedArgs; };
19.1
52
0.71466
8c0362d49e4517bd3fd876ab64d944c4698b3d8b
885
h
C
third_party/LspCpp/include/LibLsp/lsp/JavaExtentions/executeCommand.h
RcSepp/minc
8add46095ba7990ca636a6e6c266dda4148052fd
[ "MIT" ]
null
null
null
third_party/LspCpp/include/LibLsp/lsp/JavaExtentions/executeCommand.h
RcSepp/minc
8add46095ba7990ca636a6e6c266dda4148052fd
[ "MIT" ]
null
null
null
third_party/LspCpp/include/LibLsp/lsp/JavaExtentions/executeCommand.h
RcSepp/minc
8add46095ba7990ca636a6e6c266dda4148052fd
[ "MIT" ]
null
null
null
#pragma once #include "LibLsp/JsonRpc/RequestInMessage.h" #include "LibLsp/JsonRpc/lsResponseMessage.h" #include <string> #include "LibLsp/lsp/lsWorkspaceEdit.h" #include "LibLsp/lsp/ExecuteCommandParams.h" namespace buildpath { static const char* EDIT_ORGNIZEIMPORTS = "java.edit.organizeImports"; static const char* RESOLVE_SOURCE_ATTACHMENT = "java.project.resolveSourceAttachment"; static const char* UPDATE_SOURCE_ATTACHMENT = "java.project.updateSourceAttachment"; static const char* ADD_TO_SOURCEPATH = "java.project.addToSourcePath"; static const char* REMOVE_FROM_SOURCEPATH = "java.project.removeFromSourcePath"; static const char* LIST_SOURCEPATHS = "java.project.listSourcePaths"; struct Result { bool status; std::string message; }; } DEFINE_REQUEST_RESPONSE_TYPE(java_executeCommand, ExecuteCommandParams, lsWorkspaceEdit);
27.65625
89
0.780791
1eaff5e2bcc2431c105106516e59eb7b738cb977
1,528
h
C
feeds/ipq807x/qca-nss-drv/src/nss_ipv6_stats.h
ArthurSu0211/wlan-ap
5bf882b0e0225d49860b88d25c9b9ff9bc354516
[ "BSD-3-Clause" ]
2
2021-05-17T02:47:24.000Z
2021-05-17T02:48:01.000Z
feeds/ipq807x/qca-nss-drv/src/nss_ipv6_stats.h
ArthurSu0211/wlan-ap
5bf882b0e0225d49860b88d25c9b9ff9bc354516
[ "BSD-3-Clause" ]
1
2021-01-14T18:40:50.000Z
2021-01-14T18:40:50.000Z
feeds/ipq807x/qca-nss-drv/src/nss_ipv6_stats.h
ArthurSu0211/wlan-ap
5bf882b0e0225d49860b88d25c9b9ff9bc354516
[ "BSD-3-Clause" ]
3
2021-02-22T04:54:20.000Z
2021-04-13T01:54:40.000Z
/* ************************************************************************** * Copyright (c) 2017,2019-2020, The Linux Foundation. All rights reserved. * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all copies. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ************************************************************************** */ #ifndef __NSS_IPV6_STATS_H #define __NSS_IPV6_STATS_H /* * IPV6 statistics APIs */ extern void nss_ipv6_stats_notify(struct nss_ctx_instance *nss_ctx); extern void nss_ipv6_stats_node_sync(struct nss_ctx_instance *nss_ctx, struct nss_ipv6_node_sync *nins); extern void nss_ipv6_stats_conn_sync(struct nss_ctx_instance *nss_ctx, struct nss_ipv6_conn_sync *nics); extern void nss_ipv6_stats_conn_sync_many(struct nss_ctx_instance *nss_ctx, struct nss_ipv6_conn_sync_many_msg *nicsm); extern void nss_ipv6_stats_dentry_create(void); #endif /* __NSS_IPV6_STATS_H */
50.933333
119
0.722513
6cc827fe783eec9047284572a898f1616ef21323
1,388
h
C
HKYunLib/Frameworks/KKBLibrary.framework/Headers/KKBTextView.h
kaikeba-github/HKYunLib
4d27d1bd6081477eb862ad9b26bbbc1fcbad499d
[ "MIT" ]
null
null
null
HKYunLib/Frameworks/KKBLibrary.framework/Headers/KKBTextView.h
kaikeba-github/HKYunLib
4d27d1bd6081477eb862ad9b26bbbc1fcbad499d
[ "MIT" ]
null
null
null
HKYunLib/Frameworks/KKBLibrary.framework/Headers/KKBTextView.h
kaikeba-github/HKYunLib
4d27d1bd6081477eb862ad9b26bbbc1fcbad499d
[ "MIT" ]
null
null
null
// // KKBTextView.h // KKBLibrary // // Created by Duane on 2019/6/4. // Copyright © 2019 KaiKeBa. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** 文字最多字符数量显示类型 **/ typedef enum { KKBTextViewMaxNumStateNone = 0, // 不显示 KKBTextViewMaxNumStateNormal = 1, // 默认模式(0/200) KKBTextViewMaxNumStateDiminishing = 2, // 递减模式(200) } KKBTextViewMaxNumState; typedef void(^KKBTextViewHeightBlock)(CGFloat fitHeight); typedef void(^KKBTextViewListeningBlock)(NSString *text); @interface KKBTextView : UIView @property (nonatomic, strong, readonly) UILabel *numLabel; @property (nonatomic, strong, readonly) UITextView *textView; /** textView的内容 */ @property (nonatomic, copy) NSString *text; /** 是否禁止输入换行(默认为NO) */ @property (nonatomic, assign) BOOL disableInputLineBreak; /** 满足当前内容需要的高度 */ @property (nonatomic, assign, readonly) CGFloat fitHeight; @property (nonatomic, assign) UIEdgeInsets edges; /** 中间距 (默认8) */ @property (nonatomic, assign) CGFloat space; /** 文字最多数量 (默认200个字符) */ @property (nonatomic, assign) NSInteger textMaxNum; /** Num 样式 (默认 0/200 */ @property (nonatomic, assign) KKBTextViewMaxNumState maxNumState; /** 返回输入监听内容 */ @property (nonatomic, copy) KKBTextViewListeningBlock textViewListening; /** 满足当前内容的高度发生变化 */ @property (nonatomic,copy) KKBTextViewHeightBlock fitHeightChangeBlock; @end NS_ASSUME_NONNULL_END
23.931034
72
0.742075
1b358f47e2cffdd0064eaa04fa14cf673dad37d0
1,649
h
C
src/databases/PLY/avtPLYFileFormat.h
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
226
2018-12-29T01:13:49.000Z
2022-03-30T19:16:31.000Z
src/databases/PLY/avtPLYFileFormat.h
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
5,100
2019-01-14T18:19:25.000Z
2022-03-31T23:08:36.000Z
src/databases/PLY/avtPLYFileFormat.h
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
84
2019-01-24T17:41:50.000Z
2022-03-10T10:01:46.000Z
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. // ************************************************************************* // // avtPLYFileFormat.h // // ************************************************************************* // #ifndef AVT_PLY_FILE_FORMAT_H #define AVT_PLY_FILE_FORMAT_H #include <avtSTSDFileFormat.h> class DBOptionsAttributes; // **************************************************************************** // Class: avtPLYFileFormat // // Purpose: // Reads in PLY files as a plugin to VisIt. // // Programmer: pugmire -- generated by xml2avt // Creation: Tue Apr 16 08:57:58 PDT 2013 // // **************************************************************************** class avtPLYFileFormat : public avtSTSDFileFormat { public: avtPLYFileFormat(const char *filename, const DBOptionsAttributes*); virtual ~avtPLYFileFormat(); virtual const char *GetType(void) { return "PLY"; }; virtual void FreeUpResources(void); virtual vtkDataSet *GetMesh(const char *); virtual vtkDataArray *GetVar(const char *); virtual vtkDataArray *GetVectorVar(const char *); protected: vtkDataSet *dataset; bool readInDataset; bool checkedFile; void ReadInDataset(void); virtual void PopulateDatabaseMetaData(avtDatabaseMetaData *); }; #endif
31.711538
79
0.520315
9b13c37a5b3df41016fd279e728cf019ad656fe8
8,218
h
C
packages/PIPS/pips/src/Libs/phrase/phrase_distribution.h
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
51
2015-01-31T01:51:39.000Z
2022-02-18T02:01:50.000Z
packages/PIPS/pips/src/Libs/phrase/phrase_distribution.h
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
7
2017-05-29T09:29:00.000Z
2019-03-11T16:01:39.000Z
packages/PIPS/pips/src/Libs/phrase/phrase_distribution.h
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
12
2015-03-26T08:05:38.000Z
2022-02-18T02:01:51.000Z
/* $Id$ Copyright 1989-2014 MINES ParisTech This file is part of PIPS. PIPS 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 any later version. PIPS 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 PIPS. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PHRASE_DISTRIBUTOR_DEFS #define PHRASE_DISTRIBUTOR_DEFS #define EXTERNALIZED_CODE_PRAGMA_BEGIN "BEGIN_FPGA_%s" #define EXTERNALIZED_CODE_PRAGMA_END "END_FPGA_%s" #define EXTERNALIZED_CODE_PRAGMA_ANALYZED "ANALYZED_FPGA_%s (%d statements)" #define EXTERNALIZED_CODE_PRAGMA_CALL "CALL_FPGA_%s" /* Stuff for distribution controlization */ #define EXTERNALIZED_FUNCTION_PARAM_NAME "%s_PARAM_%d" #define EXTERNALIZED_FUNCTION_PRIVATE_PARAM_NAME "%s_PRIV" #define CONTROL_DATA_COMMON_NAME "CONTROL_DATA" #define FUNCTION_COMMON_NAME "%s_COMMON" #define COMMON_PARAM_NAME "%s_%s" #define DYN_VAR_PARAM_NAME "%s_DV_PARAM" #define REF_VAR_PARAM_NAME "%s_REF_PARAM" #define UNITS_NB_NAME "UNITS_NB" #define UNIT_ID_NAME "UNIT%d" #define FUNCTIONS_NB_NAME "FUNCTIONS_NB" #define FUNCTION_ID_NAME "%s_FUNCTION" #define IN_PARAM_ID_NAME "%s_%s_IN_PARAM" #define OUT_PARAM_ID_NAME "%s_%s_OUT_PARAM" #define CONTROLIZED_STATEMENT_COMMENT "! CONTROLIZED CALL TO %s\n" /* Stuff for START_RU(...) subroutine generation */ #define START_RU_MODULE_NAME "START_RU" #define START_RU_PARAM1_NAME "FUNC_ID" #define START_RU_PARAM2_NAME "UNIT_ID" /* Stuff for WAIT_RU(...) subroutine generation */ #define WAIT_RU_MODULE_NAME "WAIT_RU" #define WAIT_RU_PARAM1_NAME "FUNC_ID" #define WAIT_RU_PARAM2_NAME "UNIT_ID" /* Stuff for SEND_PARAM....(...) and RECEIVE_PARAM....(...) * subroutines generation */ #define VARIABLE_NAME_FORMAT "_%"PRIdPTR"_%"PRIdPTR #define SEND_PARAMETER_MODULE_NAME "SEND_%s_PARAMETER" #define RECEIVE_PARAMETER_MODULE_NAME "RECEIVE_%s_PARAMETER" #define SEND_ARRAY_PARAM_MODULE_NAME "SEND_%s_%s_PARAMETER" #define RECEIVE_ARRAY_PARAM_MODULE_NAME "RECEIVE_%s_%s_PARAMETER" #define COM_MODULE_PARAM1_NAME "FUNC_ID" #define COM_MODULE_PARAM2_NAME "UNIT_ID" #define COM_MODULE_PARAM3_NAME "PARAM_ID" #define COM_MODULE_PARAM4_NAME "PARAM" #define RU_SEND_FLOAT_PARAM_MODULE_NAME "RU_SEND_FLOAT_PARAM" #define RU_RECEIVE_FLOAT_PARAM_MODULE_NAME "RU_RECEIVE_FLOAT_PARAM" /** * Return the identified function name of the externalized portion of code * by searching comment matching tag */ string get_function_name_by_searching_tag (statement stat,const char* tag); /** * Return the identified function name of the externalized portion of code * by searching comment matching tag EXTERNALIZED_CODE_PRAGMA_BEGIN */ string get_externalizable_function_name(statement stat); /** * Return the identified function name of the externalized portion of code * by searching comment matching tag EXTERNALIZED_CODE_PRAGMA_CALL */ string get_externalized_function_name(statement stat); /** * Return the identified function name of the externalized portion of code * by searching comment matching tags EXTERNALIZED_CODE_PRAGMA_ANALYZED * Sets the number of statements of this externalizable statement */ string get_externalized_and_analyzed_function_name(statement stat, int* stats_nb); bool compute_distribution_context (list l_stats, statement module_stat, entity module, hash_table* ht_stats, hash_table* ht_params, hash_table* ht_private, hash_table* ht_out_regions, hash_table* ht_in_regions); bool compute_distribution_controlization_context (list l_calls, statement module_stat, entity module, hash_table* ht_calls, hash_table* ht_params, hash_table* ht_private, hash_table* ht_out_regions, hash_table* ht_in_regions); void register_scalar_communications (hash_table* ht_communications, entity function, list l_regions); string variable_to_string (variable var); /** * Build and store new module START_RU. * Create statement module_statement */ entity make_start_ru_module (hash_table ht_params, statement* module_statement, int number_of_deployment_units, entity global_common, list l_commons); /** * Build and store new module WAIT_RU. * Create statement module_statement */ entity make_wait_ru_module (statement* module_statement, int number_of_deployment_units, entity global_common, list l_commons); /** * Return SEND_PARAM module name for function and region */ string get_send_param_module_name(entity function, region reg); /** * Return RECEIVE_PARAM module name for function and region */ string get_receive_param_module_name(entity function, region reg); /** * Build and return list of modules used for INPUT communications * (SEND_PARAMETERS...) */ list make_send_scalar_params_modules (hash_table ht_in_communications, int number_of_deployment_units, entity global_common, list l_commons); /** * Build and return list of modules used for OUTPUT communications * (RECEIVE_PARAMETERS...) */ list make_receive_scalar_params_modules (hash_table ht_out_communications, int number_of_deployment_units, entity global_common, list l_commons); /** * Make all SEND_PARAM communication modules for non-scalar regions for a * given function */ list make_send_array_params_modules (entity function, list l_regions, entity global_common, entity externalized_fonction_common, int number_of_deployment_units); /** * Make all RECEIVE_PARAM communication modules for non-scalar regions for a * given function */ list make_receive_array_params_modules (entity function, list l_regions, entity global_common, entity externalized_fonction_common, int number_of_deployment_units); /** * Creates a private variable in specified module */ entity create_private_variable_for_new_module (entity a_variable, const char* new_name, const char* new_module_name, entity module); /** * Create new variable parameter for a newly created module */ entity create_parameter_for_new_module (variable var, const char* parameter_name, const char* module_name, entity module, int param_nb); /** * Create new integer variable parameter for a newly created module */ entity create_integer_parameter_for_new_module (const char* parameter_name, const char* module_name, entity module, int param_nb); /** * Store (PIPDBM) newly created module module with module_statement * as USER_FILE by saving pretty printing */ void store_new_module (const char* module_name, entity module, statement module_statement); /* * Return COMMON_PARAM_NAME */ string get_common_param_name (entity variable, entity function); /* * Return FUNCTION_ID_NAME */ string get_function_id_name (entity function); /* * Return SEND_PARAMETER_MODULE_NAME */ string get_send_parameter_module_name (variable var); /* * Return RECEIVE_PARAMETER_MODULE_NAME */ string get_receive_parameter_module_name (variable var); /* * Return IN_PARAM_ID_NAME */ string get_in_param_id_name (entity variable, entity function); /* * Return OUT_PARAM_ID_NAME */ string get_out_param_id_name (entity variable, entity function); /** * Build and return parameters (PHI1,PHI2) and dynamic variables for * region reg. * NOT IMPLEMENTED: suppress unused dynamic variables !!!! */ void compute_region_variables (region reg, list* l_reg_params, list* l_reg_variables); /** * Creates all the things that need to be created in order to declare common * in module (all the variable are created) */ void declare_common_variables_in_module (entity common, entity module); #endif
30.213235
76
0.758457
f0420b9f63dc28c39d008e6a5898da9efd639777
1,143
h
C
src/developer/feedback/feedback_agent/annotations.h
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
src/developer/feedback/feedback_agent/annotations.h
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
src/developer/feedback/feedback_agent/annotations.h
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_DEVELOPER_FEEDBACK_FEEDBACK_AGENT_ANNOTATIONS_H_ #define SRC_DEVELOPER_FEEDBACK_FEEDBACK_AGENT_ANNOTATIONS_H_ #include <fuchsia/feedback/cpp/fidl.h> #include <lib/async/dispatcher.h> #include <lib/fit/promise.h> #include <lib/sys/cpp/service_directory.h> #include <lib/zx/time.h> #include <memory> #include <set> #include <string> #include <vector> #include "src/developer/feedback/utils/cobalt.h" namespace feedback { // Returns annotations useful to attach in feedback reports (crash or user feedback). // // * only annotations which keys are in the |allowlist| will be returned. // * |timeout| is per annotation. std::vector<fit::promise<std::vector<fuchsia::feedback::Annotation>>> GetAnnotations( async_dispatcher_t* dispatcher, std::shared_ptr<sys::ServiceDirectory> services, const std::set<std::string>& allowlist, zx::duration timeout, Cobalt* cobalt); } // namespace feedback #endif // SRC_DEVELOPER_FEEDBACK_FEEDBACK_AGENT_ANNOTATIONS_H_
33.617647
85
0.774278
534e91e3a924c6b3b036078fedf7c4b7b0b7e9f3
1,238
h
C
include/cnl/_impl/cstdint/macros.h
data-man/cnl
160e72661fdcb803787a42196f28841e4a929370
[ "BSL-1.0" ]
523
2017-07-27T02:43:25.000Z
2022-03-24T21:27:22.000Z
include/cnl/_impl/cstdint/macros.h
data-man/cnl
160e72661fdcb803787a42196f28841e4a929370
[ "BSL-1.0" ]
377
2017-07-28T04:09:46.000Z
2022-03-19T12:20:11.000Z
include/cnl/_impl/cstdint/macros.h
data-man/cnl
160e72661fdcb803787a42196f28841e4a929370
[ "BSL-1.0" ]
63
2017-08-16T14:43:40.000Z
2022-03-21T16:07:02.000Z
// Copyright John McFarlane 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file ../LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) /// \file /// \brief integer creation macros equivalent to those in \verbatim<cstdint>\endverbatim #if !defined(CNL_IMPL_CSTDINT_MACROS_H) #define CNL_IMPL_CSTDINT_MACROS_H #include "../config.h" #include "../parse.h" #include "types.h" #include <cstdint> //////////////////////////////////////////////////////////////////////////////// // CNL_INTMAX_C and CNL_UINTMAX_C #if defined(CNL_INT128_ENABLED) #define CNL_STR_HELPER(x) #x // NOLINT(cppcoreguidelines-macro-usage) #define CNL_STR(x) CNL_STR_HELPER(x) // NOLINT(cppcoreguidelines-macro-usage) // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define CNL_INTMAX_C(N) (::cnl::_impl::parse<::cnl::intmax>(CNL_STR(N))) // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define CNL_UINTMAX_C(N) (::cnl::_impl::parse<::cnl::uintmax>(CNL_STR(N))) #else // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define CNL_INTMAX_C INTMAX_C // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define CNL_UINTMAX_C UINTMAX_C #endif #endif // CNL_IMPL_CSTDINT_MACROS_H
28.136364
88
0.700323
537053d25ac0a70199258e25bb951447692d8668
1,490
c
C
kernel/platform.c
RossComputerPerson/skift
e42e349011206c0d140a856e835f5682fc96f4ef
[ "MIT" ]
null
null
null
kernel/platform.c
RossComputerPerson/skift
e42e349011206c0d140a856e835f5682fc96f4ef
[ "MIT" ]
null
null
null
kernel/platform.c
RossComputerPerson/skift
e42e349011206c0d140a856e835f5682fc96f4ef
[ "MIT" ]
null
null
null
/* Copyright © 2018-2019 N. Van Bossuyt. */ /* This code is licensed under the MIT License. */ /* See: LICENSE.md */ #include "platform.h" /* --- FPU ------------------------------------------------------------------ */ void platform_fpu_enable(void) { asm volatile("clts"); size_t t; asm volatile("mov %%cr0, %0" : "=r"(t)); t &= ~(1 << 2); t |= (1 << 1); asm volatile("mov %0, %%cr0" ::"r"(t)); asm volatile("mov %%cr4, %0" : "=r"(t)); t |= 3 << 9; asm volatile("mov %0, %%cr4" ::"r"(t)); // Initialize the FPU asm volatile("fninit"); } char fpu_registers[512] __attribute__((aligned(16))); void platform_fpu_save_context(task_t *t) { asm volatile("fxsave (%0)" ::"r"(fpu_registers)); memcpy(&t->fpu_registers, &fpu_registers, 512); } void platform_fpu_load_context(task_t *t) { memcpy(&fpu_registers, &t->fpu_registers, 512); asm volatile("fxrstor (%0)" ::"r"(fpu_registers)); } /* --- Public functions ----------------------------------------------------- */ void platform_setup(void) { // setup the gdt and idt // Setup the fpu logger_info("Enabling fpu..."); platform_fpu_enable(); } void platform_save_context(task_t *t) { platform_fpu_save_context(t); } void platform_load_context(task_t *t) { platform_fpu_load_context(t); }
24.42623
80
0.495973
e9ec495abe140bd03d2eb25e1f7595a67823a3fa
6,253
h
C
Servers/ServerManager/vtkSMDoubleRangeDomain.h
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
1
2021-07-31T19:38:03.000Z
2021-07-31T19:38:03.000Z
Servers/ServerManager/vtkSMDoubleRangeDomain.h
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
null
null
null
Servers/ServerManager/vtkSMDoubleRangeDomain.h
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
2
2019-01-22T19:51:40.000Z
2021-07-31T19:38:05.000Z
/*========================================================================= Program: ParaView Module: $RCSfile$ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkSMDoubleRangeDomain - double interval specified by min and max // .SECTION Description // vtkSMDoubleRangeDomain represents an interval in real space (using // double precision) specified using a min and a max value. // Valid XML attributes are: // @verbatim // * min // * max // @endverbatim // Both min and max attributes can have one or more space space // separated (double) arguments. // Optionally, a Required Property may be specified (which typically is a // information property) which can be used to obtain the range for the values as // follows: // @verbatim // <DoubleRangeDomain ...> // <RequiredProperties> // <Property name="<InfoPropName>" function="RangeInfo" /> // </RequiredProperties> // </DoubleRangeDomain> // @endverbatim // .SECTION See Also // vtkSMDomain #ifndef __vtkSMDoubleRangeDomain_h #define __vtkSMDoubleRangeDomain_h #include "vtkSMDomain.h" //BTX struct vtkSMDoubleRangeDomainInternals; //ETX class VTK_EXPORT vtkSMDoubleRangeDomain : public vtkSMDomain { public: static vtkSMDoubleRangeDomain* New(); vtkTypeRevisionMacro(vtkSMDoubleRangeDomain, vtkSMDomain); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Returns true if the value of the propery is in the domain. // The propery has to be a vtkSMIntVectorProperty. If all // vector values are in the domain, it returns 1. It returns // 0 otherwise. A value is in the domain if it is between (min, max) virtual int IsInDomain(vtkSMProperty* property); // Description: // Returns true if the double (val) is in the domain. If value is // in domain, it's index is return in idx. // A value is in the domain if it is between (min, max) int IsInDomain(unsigned int idx, double val); // Description: // Return a min. value if it exists. If the min. exists // exists is set to 1. Otherwise, it is set to 0. // An unspecified min. is equivalent to -inf double GetMinimum(unsigned int idx, int& exists); // Description: // Return a max. value if it exists. If the max. exists // exists is set to 1. Otherwise, it is set to 0. // An unspecified max. is equivalent to +inf double GetMaximum(unsigned int idx, int& exists); // Description: // Returns if minimum/maximum bound is set for the domain. int GetMinimumExists(unsigned int idx); int GetMaximumExists(unsigned int idx); // Description: // Returns the minimum/maximum value, is exists, otherwise // 0 is returned. Use GetMaximumExists() GetMaximumExists() to make sure that // the bound is set. double GetMinimum(unsigned int idx); double GetMaximum(unsigned int idx); // Description: // Return a resolution. value if it exists. If the resolution. exists // exists is set to 1. Otherwise, it is set to 0. // An unspecified max. is equivalent to 1 double GetResolution(unsigned int idx, int& exists); // Description: // Returns is the relution value is set for the given index. int GetResolutionExists(unsigned int idx); // Description: // Return a resolution. value if it exists, otherwise 0. // Use GetResolutionExists() to make sure that the value exists. double GetResolution(unsigned int idx); // Description: // Set a min. of a given index. void AddMinimum(unsigned int idx, double value); // Description: // Remove a min. of a given index. // An unspecified min. is equivalent to -inf void RemoveMinimum(unsigned int idx); // Description: // Clear all minimum values. void RemoveAllMinima(); // Description: // Set a max. of a given index. void AddMaximum(unsigned int idx, double value); // Description: // Remove a max. of a given index. // An unspecified min. is equivalent to inf void RemoveMaximum(unsigned int idx); // Description: // Clear all maximum values. void RemoveAllMaxima(); // Description: // Set a resolution. of a given index. void AddResolution(unsigned int idx, double value); // Description: // Remove a resolution. of a given index. // An unspecified resolution. is equivalent to 1 void RemoveResolution(unsigned int idx); // Description: // Clear all resolution values. void RemoveAllResolutions(); // Description: // Update self checking the "unchecked" values of all required // properties. Overwritten by sub-classes. virtual void Update(vtkSMProperty*); // Description: // Set the value of an element of a property from the animation editor. virtual void SetAnimationValue(vtkSMProperty *property, int idx, double value); // Description: // Returns the number of entries in the internal // maxima/minima list. No maxima/minima exists beyond // this index. Maxima/minima below this number may or // may not exist. unsigned int GetNumberOfEntries(); protected: vtkSMDoubleRangeDomain(); ~vtkSMDoubleRangeDomain(); // Description: // Set the appropriate ivars from the xml element. Should // be overwritten by subclass if adding ivars. virtual int ReadXMLAttributes(vtkSMProperty* prop, vtkPVXMLElement* element); virtual void ChildSaveState(vtkPVXMLElement* propertyElement); // Description: // General purpose method called by both AddMinimum() and AddMaximum() void SetEntry(unsigned int idx, int minOrMax, int set, double value); // Internal use only. // Set the number of min/max entries. void SetNumberOfEntries(unsigned int size); vtkSMDoubleRangeDomainInternals* DRInternals; //BTX enum { MIN = 0, MAX = 1, RESOLUTION = 2 }; //ETX private: vtkSMDoubleRangeDomain(const vtkSMDoubleRangeDomain&); // Not implemented void operator=(const vtkSMDoubleRangeDomain&); // Not implemented }; #endif
31.422111
80
0.700304
18c17e70e2c865570dfa676a6a3910268fb107b8
5,231
c
C
src/emu/audio/generic.c
Zoltan45/Mame-mkp119
d219a3549eafb4215727c974e09e43b28d058328
[ "CC0-1.0" ]
null
null
null
src/emu/audio/generic.c
Zoltan45/Mame-mkp119
d219a3549eafb4215727c974e09e43b28d058328
[ "CC0-1.0" ]
null
null
null
src/emu/audio/generic.c
Zoltan45/Mame-mkp119
d219a3549eafb4215727c974e09e43b28d058328
[ "CC0-1.0" ]
null
null
null
/*************************************************************************** generic.c Generic simple sound functions. Copyright (c) 1996-2007, Nicola Salmoria and the MAME Team. Visit http://mamedev.org for licensing and usage restrictions. ***************************************************************************/ #include "driver.h" #include "generic.h" /*************************************************************************** GLOBAL VARIABLES ***************************************************************************/ static UINT16 latch_clear_value = 0x00; static UINT16 latched_value[4]; static UINT8 latch_read[4]; /*************************************************************************** INITIALIZATION ***************************************************************************/ /*------------------------------------------------- generic_sound_init - initialize globals and register for save states -------------------------------------------------*/ int generic_sound_init(void) { /* reset latches */ latch_clear_value = 0; memset(latched_value, 0, sizeof(latched_value)); memset(latch_read, 0, sizeof(latch_read)); /* register globals with the save state system */ state_save_register_global_array(latched_value); state_save_register_global_array(latch_read); return 0; } /*************************************************************************** Many games use a master-slave CPU setup. Typically, the main CPU writes a command to some register, and then writes to another register to trigger an interrupt on the slave CPU (the interrupt might also be triggered by the first write). The slave CPU, notified by the interrupt, goes and reads the command. ***************************************************************************/ /*------------------------------------------------- latch_callback - time-delayed callback to set a latch value -------------------------------------------------*/ static TIMER_CALLBACK( latch_callback ) { UINT16 value = param >> 8; int which = param & 0xff; /* if the latch hasn't been read and the value is changed, log a warning */ if (!latch_read[which] && latched_value[which] != value) logerror("Warning: sound latch %d written before being read. Previous: %02x, new: %02x\n", which, latched_value[which], value); /* store the new value and mark it not read */ latched_value[which] = value; latch_read[which] = 0; } /*------------------------------------------------- latch_w - handle a write to a given latch -------------------------------------------------*/ INLINE void latch_w(int which, UINT16 value) { timer_call_after_resynch(which | (value << 8), latch_callback); } /*------------------------------------------------- latch_r - handle a read from a given latch -------------------------------------------------*/ INLINE UINT16 latch_r(int which) { latch_read[which] = 1; return latched_value[which]; } /*------------------------------------------------- latch_clear - clear a given latch -------------------------------------------------*/ INLINE void latch_clear(int which) { latched_value[which] = latch_clear_value; } /*------------------------------------------------- soundlatch_w - global write handlers for writing to sound latches -------------------------------------------------*/ WRITE8_HANDLER( soundlatch_w ) { latch_w(0, data); } WRITE16_HANDLER( soundlatch_word_w ) { latch_w(0, data); } WRITE8_HANDLER( soundlatch2_w ) { latch_w(1, data); } WRITE16_HANDLER( soundlatch2_word_w ) { latch_w(1, data); } WRITE8_HANDLER( soundlatch3_w ) { latch_w(2, data); } WRITE16_HANDLER( soundlatch3_word_w ) { latch_w(2, data); } WRITE8_HANDLER( soundlatch4_w ) { latch_w(3, data); } WRITE16_HANDLER( soundlatch4_word_w ) { latch_w(3, data); } /*------------------------------------------------- soundlatch_r - global read handlers for reading from sound latches -------------------------------------------------*/ READ8_HANDLER( soundlatch_r ) { return latch_r(0); } READ16_HANDLER( soundlatch_word_r ) { return latch_r(0); } READ8_HANDLER( soundlatch2_r ) { return latch_r(1); } READ16_HANDLER( soundlatch2_word_r ) { return latch_r(1); } READ8_HANDLER( soundlatch3_r ) { return latch_r(2); } READ16_HANDLER( soundlatch3_word_r ) { return latch_r(2); } READ8_HANDLER( soundlatch4_r ) { return latch_r(3); } READ16_HANDLER( soundlatch4_word_r ) { return latch_r(3); } /*------------------------------------------------- soundlatch_clear_w - global write handlers for clearing sound latches -------------------------------------------------*/ WRITE8_HANDLER( soundlatch_clear_w ) { latch_clear(0); } WRITE8_HANDLER( soundlatch2_clear_w ) { latch_clear(1); } WRITE8_HANDLER( soundlatch3_clear_w ) { latch_clear(2); } WRITE8_HANDLER( soundlatch4_clear_w ) { latch_clear(3); } /*------------------------------------------------- soundlatch_setclearedvalue - set the "clear" value for all sound latches -------------------------------------------------*/ void soundlatch_setclearedvalue(int value) { latch_clear_value = value; }
32.092025
129
0.508889
c0db6c9b7ebd047d2b61b06bec828a95d0f3ea77
6,187
h
C
src/Shared/Core/Maths/FCMatrix.h
mslinklater/FC
d00e2e56a982cd7c85c7de18ac0449bf43d8025e
[ "MIT" ]
null
null
null
src/Shared/Core/Maths/FCMatrix.h
mslinklater/FC
d00e2e56a982cd7c85c7de18ac0449bf43d8025e
[ "MIT" ]
null
null
null
src/Shared/Core/Maths/FCMatrix.h
mslinklater/FC
d00e2e56a982cd7c85c7de18ac0449bf43d8025e
[ "MIT" ]
2
2015-04-13T10:07:14.000Z
2019-05-16T11:14:18.000Z
/* Copyright (C) 2011-2012 by Martin Linklater 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. */ //#import <Foundation/Foundation.h> #ifndef FCMatrix_h #define FCMatrix_h #include <math.h> #include "FCVector.h" class FCMatrix4f { public: FCMatrix4f(){} FCMatrix4f( const FCMatrix4f& mat ) { e[0] = mat.e[0]; e[1] = mat.e[1]; e[2] = mat.e[2]; e[3] = mat.e[3]; e[4] = mat.e[4]; e[5] = mat.e[5]; e[6] = mat.e[6]; e[7] = mat.e[7]; e[8] = mat.e[8]; e[9] = mat.e[9]; e[10] = mat.e[10]; e[11] = mat.e[11]; e[12] = mat.e[12]; e[13] = mat.e[13]; e[14] = mat.e[14]; e[15] = mat.e[15]; } static FCMatrix4f Identity( void ) { FCMatrix4f mat; mat.e[0] = mat.e[5] = mat.e[10] = mat.e[15] = 1.0f; mat.e[1] = mat.e[2] = mat.e[3] = mat.e[4] = mat.e[6] = mat.e[7] = mat.e[8] = mat.e[9] = mat.e[11] = mat.e[12] = mat.e[13] = mat.e[14] = 0.0f; return mat; } FCMatrix4f Transpose( void ) { FCMatrix4f ret; ret.e[0] = e[0]; ret.e[1] = e[4]; ret.e[2] = e[8]; ret.e[3] = e[12]; ret.e[4] = e[1]; ret.e[5] = e[5]; ret.e[6] = e[9]; ret.e[7] = e[13]; ret.e[8] = e[2]; ret.e[9] = e[6]; ret.e[10] = e[10]; ret.e[11] = e[14]; ret.e[12] = e[3]; ret.e[13] = e[7]; ret.e[14] = e[11]; ret.e[15] = e[15]; return ret; } static FCMatrix4f Frustum( float left, float right, float bottom, float top, float near, float far ) { FCMatrix4f mat; float a = 2 * near / ( right - left ); float b = 2 * near / ( top - bottom ); float c = ( right + left ) / ( right - left ); float d = ( top + bottom ) / ( top - bottom ); float E = -( far + near ) / ( far - near ); float f = -2 * far * near / ( far - near ); mat.e[0] = a; mat.e[1] = mat.e[2] = mat.e[3] = 0.0f; mat.e[4] = 0; mat.e[5] = b; mat.e[6] = mat.e[7] = 0; mat.e[8] = c; mat.e[9] = d; mat.e[10] = E; mat.e[11] = -1; mat.e[12] = 0; mat.e[13] = 0; mat.e[14] = f; mat.e[15] = 1; return mat; } static FCMatrix4f Orthographic( float width, float height, float near, float far ) { FCMatrix4f mat; mat.e[0] = 2.0f / width; mat.e[5] = 2.0f / height; mat.e[10] = 2.0f / (far - near); mat.e[15] = 1.0f; mat.e[1] = mat.e[2] = mat.e[3] = mat.e[4] = mat.e[6] = mat.e[7] = mat.e[8] = mat.e[9] = mat.e[11] = mat.e[12] = mat.e[13] = mat.e[14] = 0.0f; return mat; } static FCMatrix4f Translate( float x, float y, float z ) { FCMatrix4f mat; mat.e[0] = mat.e[5] = mat.e[10] = mat.e[15] = 1.0f; mat.e[1] = mat.e[2] = mat.e[3] = mat.e[4] = mat.e[6] = mat.e[7] = mat.e[8] = mat.e[9] = mat.e[11] = 0.0f; mat.e[12] = x; mat.e[13] = y; mat.e[14] = z; return mat; } FCMatrix4f operator*( FCMatrix4f &mat ) const { FCMatrix4f out; out.e[0] = (e[0] * mat.e[0]) + (e[1] * mat.e[4]) + (e[2] * mat.e[8]) + (e[3] * mat.e[12]); out.e[1] = (e[0] * mat.e[1]) + (e[1] * mat.e[5]) + (e[2] * mat.e[9]) + (e[3] * mat.e[13]); out.e[2] = (e[0] * mat.e[2]) + (e[1] * mat.e[6]) + (e[2] * mat.e[10]) + (e[3] * mat.e[14]); out.e[3] = (e[0] * mat.e[3]) + (e[1] * mat.e[7]) + (e[2] * mat.e[11]) + (e[3] * mat.e[15]); out.e[4] = (e[4] * mat.e[0]) + (e[5] * mat.e[4]) + (e[6] * mat.e[8]) + (e[7] * mat.e[12]); out.e[5] = (e[4] * mat.e[1]) + (e[5] * mat.e[5]) + (e[6] * mat.e[9]) + (e[7] * mat.e[13]); out.e[6] = (e[4] * mat.e[2]) + (e[5] * mat.e[6]) + (e[6] * mat.e[10]) + (e[7] * mat.e[14]); out.e[7] = (e[4] * mat.e[3]) + (e[5] * mat.e[7]) + (e[6] * mat.e[11]) + (e[7] * mat.e[15]); out.e[8] = (e[8] * mat.e[0]) + (e[9] * mat.e[4]) + (e[10] * mat.e[8]) + (e[11] * mat.e[12]); out.e[9] = (e[8] * mat.e[1]) + (e[9] * mat.e[5]) + (e[10] * mat.e[9]) + (e[11] * mat.e[13]); out.e[10] = (e[8] * mat.e[2]) + (e[9] * mat.e[6]) + (e[10] * mat.e[10]) + (e[11] * mat.e[14]); out.e[11] = (e[8] * mat.e[3]) + (e[9] * mat.e[7]) + (e[10] * mat.e[11]) + (e[11] * mat.e[15]); out.e[12] = (e[12] * mat.e[0]) + (e[13] * mat.e[4]) + (e[14] * mat.e[8]) + (e[15] * mat.e[12]); out.e[13] = (e[12] * mat.e[1]) + (e[13] * mat.e[5]) + (e[14] * mat.e[9]) + (e[15] * mat.e[13]); out.e[14] = (e[12] * mat.e[2]) + (e[13] * mat.e[6]) + (e[14] * mat.e[10]) + (e[15] * mat.e[14]); out.e[15] = (e[12] * mat.e[3]) + (e[13] * mat.e[7]) + (e[14] * mat.e[11]) + (e[15] * mat.e[15]); return out; } static FCMatrix4f Rotate( float angle, FCVector3f axis ) { float s = (float)sin(angle); float c = (float)cos(angle); FCMatrix4f mat = FCMatrix4f::Identity(); mat.e[0] = c + (1 - c) * axis.x * axis.x; mat.e[1] = (1 - c) * axis.x * axis.y - axis.z * s; mat.e[2] = (1 - c) * axis.x * axis.z + axis.y * s; mat.e[4] = (1 - c) * axis.x * axis.y + axis.z * s; mat.e[5] = c + (1 - c) * axis.y * axis.y; mat.e[6] = (1 - c) * axis.y * axis.z - axis.x * s; mat.e[8] = (1 - c) * axis.x * axis.z - axis.y * s; mat.e[9] = (1 - c) * axis.y * axis.z + axis.x * s; mat.e[10] = c + (1 - c) * axis.z * axis.z; return mat; } float e[16]; }; static FCVector3f operator *( const FCVector3f& vec, const FCMatrix4f& mat ) { FCVector3f ret; ret.x = vec.x * mat.e[0] + vec.y * mat.e[1] + vec.z * mat.e[2]; ret.y = vec.x * mat.e[4] + vec.y * mat.e[5] + vec.z * mat.e[6]; ret.z = vec.x * mat.e[8] + vec.y * mat.e[9] + vec.z * mat.e[10]; return ret; } #endif // FCMatrix_h
39.660256
143
0.532568
8d7ec6c13cedf1c791704967a86c8b4e0363b50d
1,253
c
C
Chapter 14/14.6-EncodeString.c
Ruesigoren/Solution
882471de39cb4bf471e958769f9f1c1a967da9c2
[ "MIT" ]
1
2020-05-18T02:16:55.000Z
2020-05-18T02:16:55.000Z
Chapter 14/14.6-EncodeString.c
Ruesigoren/Solution
882471de39cb4bf471e958769f9f1c1a967da9c2
[ "MIT" ]
null
null
null
Chapter 14/14.6-EncodeString.c
Ruesigoren/Solution
882471de39cb4bf471e958769f9f1c1a967da9c2
[ "MIT" ]
1
2019-07-03T21:34:58.000Z
2019-07-03T21:34:58.000Z
/* * File: 14.6-EncodeString.c * ------------------------- * This program implements the cipher program described in exercise 8 of Chapter 9, * but it uses the ANSI string library rather than strlib.h. */ #include <stdio.h> #include <ctype.h> #include <string.h> #include "simpio.h" /* * Constant * -------- * MaxLength -- Maximum length of a string */ #define MaxLength 40 /* function prototypes */ void EncodeString(char *string, char *enstring, int key); /* main program */ main() { char Enstr[MaxLength + 1];; char *Str; int key; printf("This program encodes a message using a cyclic cipher.\n"); printf("Enter the numberic key:"); key = GetInteger(); printf("Enter a message: "); Str = GetLine(); EncodeString(Str, Enstr, key); printf("Encoded message: %s\n", Enstr); } void EncodeString(char *string, char *enstring, int key) { int len; len = strlen(string); key %= 26; strncpy_s(enstring, MaxLength + 1, string, len); for (; *enstring != '\0'; ++enstring) { if (islower(*enstring)) { if (*enstring + key > 'z') { *enstring += key - 26; } else { *enstring += key; } } else { if (*enstring + key > 'Z') { *enstring += key - 26; } else { *enstring += key; } } } }
18.15942
84
0.599362
a5bbc57caea2a717e385cf01de81b65e348747b1
1,310
h
C
Sources/Core/Manager/UIManager.h
vgabi94/Lava-Engine
ab5b89d7379b2d0f7398fb2f4dae5b14baa7fd19
[ "MIT" ]
null
null
null
Sources/Core/Manager/UIManager.h
vgabi94/Lava-Engine
ab5b89d7379b2d0f7398fb2f4dae5b14baa7fd19
[ "MIT" ]
null
null
null
Sources/Core/Manager/UIManager.h
vgabi94/Lava-Engine
ab5b89d7379b2d0f7398fb2f4dae5b14baa7fd19
[ "MIT" ]
null
null
null
#pragma once #define NK_INCLUDE_FIXED_TYPES #define NK_INCLUDE_STANDARD_IO #define NK_INCLUDE_STANDARD_VARARGS #define NK_INCLUDE_DEFAULT_ALLOCATOR #define NK_INCLUDE_VERTEX_BUFFER_OUTPUT #define NK_INCLUDE_FONT_BAKING #define NK_INCLUDE_DEFAULT_FONT #include <nuklear.h> #include <vulkan\vulkan.hpp> #include "BufferManager.h" #include <Engine\Material.h> namespace Engine { class UIManager { public: void Init(); void Destroy(); void MirrorInput(); void SetupDrawBuffers(); void Draw(vk::CommandBuffer cmdBuf); void FreeDrawBuffers(); void Update(); private: void CreateUIBuffer(); static constexpr const char* DEF_FONT = "Roboto-Regular.ttf"; static constexpr size_t MAX_VERTEX_BUFFER = 512 * 1024; static constexpr size_t MAX_INDEX_BUFFER = 128 * 1024; nk_context mUIContext; nk_font* mFont; nk_font_atlas mAtlas; uint32_t mAtlasTex; nk_draw_null_texture mNullTexture; nk_buffer mCmds, mVerts, mIdx; nk_convert_config mCfg; std::array<nk_draw_vertex_layout_element, 4> mVertexLayout; uint32_t mIdxCount; Material* mMaterial; vk::Buffer mBuffer; vk::Buffer mIndBuffer; VmaAllocation mBufferAlloc; VmaAllocation mIndBufferAlloc; VmaAllocationInfo mBufferAllocInfo; VmaAllocationInfo mIndBufferAllocInfo; }; extern UIManager g_UIManager; }
22.586207
63
0.783969
9d6e6ce3999e2f4346cc79d39679f0158d5da3f7
177
h
C
framework/bass/bass_util.h
alchzh/danser-jf
638bbd50d3ff5a0a9d83d72e7fe19807fbee8151
[ "MIT" ]
1
2021-09-08T06:46:51.000Z
2021-09-08T06:46:51.000Z
framework/bass/bass_util.h
alchzh/danser-jf
638bbd50d3ff5a0a9d83d72e7fe19807fbee8151
[ "MIT" ]
null
null
null
framework/bass/bass_util.h
alchzh/danser-jf
638bbd50d3ff5a0a9d83d72e7fe19807fbee8151
[ "MIT" ]
null
null
null
#ifndef BASS_UTIL_H #define BASS_UTIL_H #include "bass.h" HSTREAM CreateBassStream(char* file, DWORD flags); HSAMPLE LoadBassSample(char* file, DWORD max, DWORD flags); #endif
22.125
59
0.785311
77e6cd7c9528fe383b4b979acf8da7af8ef60ae3
1,213
h
C
component/oai-smf/src/api-server/model/NotificationMethod.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-smf/src/api-server/model/NotificationMethod.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-smf/src/api-server/model/NotificationMethod.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/** * Nsmf_EventExposure * Session Management Event Exposure Service. © 2019, 3GPP Organizational * Partners (ARIB, ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * The version of the OpenAPI document: 1.1.0.alpha-1 * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ /* * NotificationMethod.h * * Possible values are - PERIODIC - ONE_TIME - ON_EVENT_DETECTION */ #ifndef NotificationMethod_H_ #define NotificationMethod_H_ #include <nlohmann/json.hpp> namespace oai { namespace smf_server { namespace model { /// <summary> /// Possible values are - PERIODIC - ONE_TIME - ON_EVENT_DETECTION /// </summary> class NotificationMethod { public: NotificationMethod(); virtual ~NotificationMethod(); void validate(); ///////////////////////////////////////////// /// NotificationMethod members friend void to_json(nlohmann::json& j, const NotificationMethod& o); friend void from_json(const nlohmann::json& j, NotificationMethod& o); protected: }; } // namespace model } // namespace smf_server } // namespace oai #endif /* NotificationMethod_H_ */
23.326923
79
0.695796
e28ef4f4637b0862e2182ae17b96243b219f20bf
14,083
h
C
setbench/setbench/common/tree_stats.h
cmuparlay/flock
afdcfe55cdd7507c2a19a6e0b30f3115e183cd58
[ "MIT" ]
19
2022-01-29T02:44:30.000Z
2022-03-29T15:52:51.000Z
setbench/setbench/common/tree_stats.h
cmuparlay/flock
afdcfe55cdd7507c2a19a6e0b30f3115e183cd58
[ "MIT" ]
null
null
null
setbench/setbench/common/tree_stats.h
cmuparlay/flock
afdcfe55cdd7507c2a19a6e0b30f3115e183cd58
[ "MIT" ]
1
2022-02-22T05:58:11.000Z
2022-02-22T05:58:11.000Z
/** * This class lets us write methods to gather tree structure statistics once, * and apply them to many data structures. */ #ifndef TREE_STATS_H #define TREE_STATS_H #ifdef USE_TREE_STATS #include <cassert> #include <sstream> #include <string> #include <vector> #include <limits> #include "plaf.h" #define MAX_HEIGHT (1<<10) /** * TODO: extend tree_stats.h to start tracking memory layout issues * (avg cache line crossings, * avg cache set occupancy (need to demarcate search data), * neighbouring object types, * page crossings, * avg page density, * alignment histogram, * page occupancy visualizations, * unique pages needed, * unique cache lines needed) */ template <typename NodeHandlerT> class TreeStats { private: typedef typename NodeHandlerT::NodePtrType nodeptr; PAD; size_t internalsAtDepth[MAX_HEIGHT]; size_t leavesAtDepth[MAX_HEIGHT]; size_t keysAtDepth[MAX_HEIGHT]; size_t keysInLeavesAtDepth[MAX_HEIGHT]; size_t keysInInternalsAtDepth[MAX_HEIGHT]; size_t sumOfKeys; #ifdef TREE_STATS_BYTES_AT_DEPTH size_t bytesAtDepth[MAX_HEIGHT]; #endif PAD; void computeStats(NodeHandlerT * handler, nodeptr node, size_t depth, size_t maxDepth = std::numeric_limits<size_t>::max()) { if (!handler) return; //std::cout<<"nodeAddr="<<(size_t)node<<" depth="<<depth<<" degree="<<node->size<<" internal?="<<NodeHandlerT::isInternal(node)<<std::endl; if (!node || depth > maxDepth) return; size_t numKeys = handler->getNumKeys(node); keysAtDepth[depth] += numKeys; sumOfKeys += handler->getSumOfKeys(node); #ifdef TREE_STATS_BYTES_AT_DEPTH bytesAtDepth[depth] += handler->getSizeInBytes(node); #endif if (handler->isLeaf(node)) { ++leavesAtDepth[depth]; keysInLeavesAtDepth[depth] += numKeys; } else { ++internalsAtDepth[depth]; keysInInternalsAtDepth[depth] += numKeys; auto it = handler->getChildIterator(node); while (it.hasNext()) { auto child = it.next(); computeStats(handler, child, 1+depth, maxDepth); } } } public: TreeStats(NodeHandlerT * handler, nodeptr root, bool parallelConstruction, bool freeHandler = true) { for (size_t d=0;d<MAX_HEIGHT;++d) { internalsAtDepth[d] = 0; leavesAtDepth[d] = 0; keysAtDepth[d] = 0; keysInLeavesAtDepth[d] = 0; keysInInternalsAtDepth[d] = 0; #ifdef TREE_STATS_BYTES_AT_DEPTH bytesAtDepth[d] = 0; #endif } sumOfKeys = 0; #ifdef _OPENMP if (!handler) return; if (!parallelConstruction) { computeStats(handler, root, 0); } else { /** * PARALLEL constructor */ std::cout<<"computing tree_stats in PARALLEL..."<<std::endl; #ifdef _OPENMP const size_t minNodes = 4*omp_get_max_threads(); #else const size_t minNodes = 1; #endif std::vector<nodeptr> qn; // queue of node pointers std::vector<size_t> qd; // queue of depths qn.reserve(minNodes*2); qd.reserve(minNodes*2); qn.push_back(root); qd.push_back(0); size_t ix = 0; // index of top in qn and qd size_t currDepth = 0; size_t ixStartOfDepth = 0; size_t nodesSeenAtDepth = 0; #ifdef _OPENMP const size_t ompThreads = omp_get_max_threads(); #else const size_t ompThreads = 1; #endif std::cout<<"bounded depth BFS to partition into subtrees for parallel computation ("<<ompThreads<<" threads)..."<<std::endl; while (ix < qn.size()) { auto node = qn[ix]; auto depth = qd[ix]; TRACE COUTATOMIC("tree_stats: queue visiting node "<<(uintptr_t) node<<" at depth "<<depth<<std::endl); ++ix; TRACE COUTATOMIC("tree_stats: new ix="<<ix<<std::endl); if (depth != currDepth) { if (nodesSeenAtDepth >= minNodes) { TRACE COUTATOMIC("tree_stats: we have seen enough nodes ("<<nodesSeenAtDepth<<") at depth "<<currDepth<<" so we cut off the bfs"<<std::endl); --ix; TRACE COUTATOMIC("tree_stats: new new ix="<<ix<<std::endl); break; } currDepth = depth; nodesSeenAtDepth = 0; ixStartOfDepth = ix-1; TRACE COUTATOMIC("tree_stats: new depth "<<depth<<" ixStartOfDepth="<<ixStartOfDepth<<std::endl); } ++nodesSeenAtDepth; TRACE COUTATOMIC("tree_stats: nodesSeenAtDepth "<<currDepth<<" changed to "<<nodesSeenAtDepth<<std::endl); // add any children to the queue if (node && !handler->isLeaf(node)) { auto it = handler->getChildIterator(node); while (it.hasNext()) { auto child = it.next(); TRACE COUTATOMIC("tree_stats: add child "<<(uintptr_t) child<<" of node "<<(uintptr_t) node<<" to queue at depth "<<(1+depth)<<std::endl); qn.push_back(child); qd.push_back(1+depth); } } } if (nodesSeenAtDepth < minNodes) { currDepth = 0; ix = 1; ixStartOfDepth = 0; TRACE COUTATOMIC("tree_stats: not enough nodes seen ("<<nodesSeenAtDepth<<") at any depth just partition into ONE tree"<<std::endl); } // we now have at least minNodes subtrees to process (in qn[ixStartOfDepth ... ix]), // so we can use openmp parallel for to construct TreeStats for these subtrees in parallel. std::cout<<"partitioned into "<<(ix-ixStartOfDepth)<<" subtrees; running parallel for..."<<std::endl; #pragma omp parallel for schedule(dynamic, 1) for (size_t i=ixStartOfDepth;i<ix;++i) { TreeStats<NodeHandlerT> * ts = new TreeStats(handler, qn[i], false, false); TRACE COUTATOMIC("tree_stats: sequential compute at depth "<<currDepth<<std::endl); for (size_t d=0;d<MAX_HEIGHT-currDepth;++d) { FAA(&internalsAtDepth[d+currDepth], ts->internalsAtDepth[d]); FAA(&leavesAtDepth[d+currDepth], ts->leavesAtDepth[d]); FAA(&keysAtDepth[d+currDepth], ts->keysAtDepth[d]); FAA(&keysInLeavesAtDepth[d+currDepth], ts->keysInLeavesAtDepth[d]); FAA(&keysInInternalsAtDepth[d+currDepth], ts->keysInInternalsAtDepth[d]); #ifdef TREE_STATS_BYTES_AT_DEPTH FAA(&bytesAtDepth[d+currDepth], ts->bytesAtDepth[d]); #endif } FAA(&sumOfKeys, ts->sumOfKeys); delete ts; } // std::cout<<"currDepth="<<currDepth<<std::endl; // std::cout<<(ix-ixStartOfDepth+1)<<" subtrees computed in parallel... addresses:"<<std::endl; // for (int i=ixStartOfDepth;i<ix;++i) { // std::cout<<" "<<qn[i]<<"[depth "<<qd[i]<<"]"; // } // std::cout<<std::endl; // compute stats for the top of the tree, ABOVE the parallel constructed subtrees. std::cout<<"computing stats for the top of the tree (above the partitions)..."<<std::endl; if (currDepth > 0) computeStats(handler, root, 0, currDepth - 1); } #else computeStats(handler, root, 0); #endif if (freeHandler) delete handler; } size_t getInternalsAtDepth(size_t d) { assert(d < MAX_HEIGHT); return internalsAtDepth[d]; } size_t getLeavesAtDepth(size_t d) { assert(d < MAX_HEIGHT); return leavesAtDepth[d]; } size_t getNodesAtDepth(size_t d) { assert(d < MAX_HEIGHT); return getInternalsAtDepth(d) + getLeavesAtDepth(d); } size_t getHeight() { size_t d=0; while (d < MAX_HEIGHT && getNodesAtDepth(d) > 0) { ++d; } return d; } size_t getInternals() { size_t maxDepth = getHeight(); size_t result = 0; for (size_t d=0;d<maxDepth;++d) { result += getInternalsAtDepth(d); } return result; } size_t getLeaves() { size_t maxDepth = getHeight(); size_t result = 0; for (size_t d=0;d<maxDepth;++d) { result += getLeavesAtDepth(d); } return result; } size_t getNodes() { return getInternals() + getLeaves(); } size_t getPointersAtDepth(size_t d) { assert(d+1 < MAX_HEIGHT); return getNodesAtDepth(d+1); } size_t getKeysAtDepth(size_t d) { assert(d < MAX_HEIGHT); return keysAtDepth[d]; } size_t getKeys() { size_t maxDepth = getHeight(); size_t result = 0; for (size_t d=0;d<maxDepth;++d) { result += getKeysAtDepth(d); } return result; } size_t getKeysInLeaves() { size_t maxDepth = getHeight(); size_t result = 0; for (size_t d=0;d<maxDepth;++d) { result += keysInLeavesAtDepth[d]; } return result; } size_t getKeysInInternals() { size_t maxDepth = getHeight(); size_t result = 0; for (size_t d=0;d<maxDepth;++d) { result += keysInInternalsAtDepth[d]; } return result; } double getAverageDegreeLeavesAtDepth(size_t d) { double denom = getLeavesAtDepth(d); return (denom == 0) ? 0 : getKeysAtDepth(d) / denom; } double getAverageDegreeLeaves() { double denom = getLeaves(); return (denom == 0) ? 0 : getKeysInLeaves() / denom; } double getAverageDegreeInternalsAtDepth(size_t d) { double denom = getInternalsAtDepth(d); return (denom == 0) ? 0 : getPointersAtDepth(d) / denom; } double getAverageDegreeInternals() { double denom = getInternals(); return (denom == 0) ? 0 : getNodes() / denom; } double getAverageDegreeAtDepth(size_t d) { // double denom = getNodesAtDepth(d); // return (getPointersAtDepth(d) + getKeysAtDepth(d)) / denom; return (getPointersAtDepth(d) + keysInLeavesAtDepth[d]) / (double) getNodesAtDepth(d); } double getAverageDegree() { double denom = getNodes(); return (denom == 0) ? 0 : (denom + getKeysInLeaves()) / denom; } double getAverageKeyDepth() { size_t height = getHeight(); size_t sumDepths = 0; for (size_t d=0;d<height;++d) { sumDepths += keysAtDepth[d] * d; } double denom = getKeys(); return (denom == 0) ? 0 : sumDepths / denom; } #ifdef TREE_STATS_BYTES_AT_DEPTH size_t getBytesAtDepth(size_t d) { return bytesAtDepth[d]; } size_t getSizeInBytes() { size_t height = getHeight(); size_t bytes = 0; for (size_t d=0;d<height;++d) { bytes += bytesAtDepth[d]; } return bytes; } #endif size_t getSumOfKeys() { return sumOfKeys; } std::string toString() { std::stringstream ss; size_t height = getHeight(); ss<<"tree_stats_numInternalsAtDepth="; for (size_t d=0;d<height;++d) { ss<<(d?" ":"")<<getInternalsAtDepth(d); } ss<<std::endl; ss<<"tree_stats_numLeavesAtDepth="; for (size_t d=0;d<height;++d) { ss<<(d?" ":"")<<getLeavesAtDepth(d); } ss<<std::endl; ss<<"tree_stats_numNodesAtDepth="; for (size_t d=0;d<height;++d) { ss<<(d?" ":"")<<getNodesAtDepth(d); } ss<<std::endl; // ss<<"tree_stats_numPointersAtDepth="; // for (size_t d=0;d<height;++d) { // ss<<(d?" ":"")<<getPointersAtDepth(d); // } // ss<<std::endl; ss<<"tree_stats_numKeysAtDepth="; for (size_t d=0;d<height;++d) { ss<<(d?" ":"")<<getKeysAtDepth(d); } ss<<std::endl; // ss<<"tree_stats_avgDegreeLeavesAtDepth="; // for (size_t d=0;d<height;++d) { // ss<<(d?" ":"")<<getAverageDegreeLeavesAtDepth(d); // } // ss<<std::endl; // // ss<<"tree_stats_avgDegreeInternalsAtDepth="; // for (size_t d=0;d<height;++d) { // ss<<(d?" ":"")<<getAverageDegreeInternalsAtDepth(d); // } // ss<<std::endl; ss<<"tree_stats_avgDegreeAtDepth="; for (size_t d=0;d<height;++d) { ss<<(d?" ":"")<<getAverageDegreeAtDepth(d); } ss<<std::endl; ss<<std::endl; ss<<"tree_stats_height="<<height<<std::endl; ss<<"tree_stats_numInternals="<<getInternals()<<std::endl; ss<<"tree_stats_numLeaves="<<getLeaves()<<std::endl; ss<<"tree_stats_numNodes="<<getNodes()<<std::endl; ss<<"tree_stats_numKeys="<<getKeys()<<std::endl; ss<<std::endl; ss<<"tree_stats_avgDegreeInternal="<<getAverageDegreeInternals()<<std::endl; ss<<"tree_stats_avgDegreeLeaves="<<getAverageDegreeLeaves()<<std::endl; ss<<"tree_stats_avgDegree="<<getAverageDegree()<<std::endl; ss<<"tree_stats_avgKeyDepth="<<getAverageKeyDepth()<<std::endl; #ifdef TREE_STATS_BYTES_AT_DEPTH ss<<std::endl; ss<<"tree_stats_bytesAtDepth="; for (size_t d=0;d<height;++d) { ss<<(d?" ":"")<<getBytesAtDepth(d); } ss<<std::endl; ss<<"tree_stats_sizeInBytes="<<getSizeInBytes()<<std::endl; #endif return ss.str(); } }; #endif #endif /* TREE_STATS_H */
34.858911
165
0.553717
e2d0732c161aa1643063377e90f853c4f0d44504
293
h
C
ios-sealtalk/RCloudMessage/Sections/Me/PersonalDetail/RCDSetSealTalkNumViewController.h
pangang107/sealtalk-ios
0b96cba61e64f7a14a0700bfbf6b2bb034cad4ee
[ "MIT" ]
414
2016-06-23T21:07:09.000Z
2021-11-09T10:53:41.000Z
ios-sealtalk/RCloudMessage/Sections/Me/PersonalDetail/RCDSetSealTalkNumViewController.h
pangang107/sealtalk-ios
0b96cba61e64f7a14a0700bfbf6b2bb034cad4ee
[ "MIT" ]
61
2016-07-02T12:53:21.000Z
2021-08-17T01:32:15.000Z
ios-sealtalk/RCloudMessage/Sections/Me/PersonalDetail/RCDSetSealTalkNumViewController.h
pangang107/sealtalk-ios
0b96cba61e64f7a14a0700bfbf6b2bb034cad4ee
[ "MIT" ]
190
2016-06-21T00:37:47.000Z
2021-11-04T08:35:03.000Z
// // RCDSetSealTalkNumViewController.h // SealTalk // // Created by 孙浩 on 2019/7/8. // Copyright © 2019 RongCloud. All rights reserved. // #import "RCDViewController.h" NS_ASSUME_NONNULL_BEGIN @interface RCDSetSealTalkNumViewController : RCDViewController @end NS_ASSUME_NONNULL_END
16.277778
62
0.771331
3fbc4bf839d27998382ff5a53258c7305daaba26
743
h
C
cpp/p3/source/p3/widgets/Button.h
0lru/p3ui
162c6c68f4a55ec109a593c8ced66a62520b5602
[ "MIT" ]
21
2021-07-22T21:33:01.000Z
2022-02-12T15:17:46.000Z
cpp/p3/source/p3/widgets/Button.h
0lru/p3ui
162c6c68f4a55ec109a593c8ced66a62520b5602
[ "MIT" ]
3
2021-07-26T19:00:39.000Z
2021-12-12T09:29:09.000Z
cpp/p3/source/p3/widgets/Button.h
0lru/p3ui
162c6c68f4a55ec109a593c8ced66a62520b5602
[ "MIT" ]
2
2021-07-23T04:57:21.000Z
2021-12-15T22:51:45.000Z
#pragma once #include <string> #include <functional> #include <p3/Node.h> namespace p3 { class Button : public Node { public: using OnClick = std::function<void()>; Button(std::optional<std::string> label = std::nullopt); StyleStrategy& style_strategy() const override; void render_impl(Context&, float width, float height) override; void set_on_click(OnClick); OnClick on_click() const; void update_content() override; // this is used by the loader to apply xml attributes virtual void set_attribute(std::string const&, std::string const&) override; protected: void dispose() override; private: OnClick _on_click; }; }
20.638889
84
0.635262
8f6db0bd3ae34e2dfeb38ebdfa55b396a95ffba1
8,925
h
C
usr/src/uts/common/sys/fibre-channel/ulp/fcp.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/uts/common/sys/fibre-channel/ulp/fcp.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/uts/common/sys/fibre-channel/ulp/fcp.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
1
2020-12-30T00:04:16.000Z
2020-12-30T00:04:16.000Z
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FCP_H #define _FCP_H /* * Frame format and protocol definitions for transferring * commands and data between a SCSI initiator and target * using an FC4 serial link interface. * * this file originally taken from fc4/fcp.h */ #ifdef __cplusplus extern "C" { #endif #include <sys/types.h> /* * FCP Device Data Frame Information Categories */ #define FCP_SCSI_DATA 0x01 /* frame contains SCSI data */ #define FCP_SCSI_CMD 0x02 /* frame contains SCSI command */ #define FCP_SCSI_RSP 0x03 /* frame contains SCSI response */ #define FCP_SCSI_XFER_RDY 0x05 /* frame contains xfer rdy block */ /* * fcp SCSI control structure */ typedef struct fcp_cntl { uchar_t cntl_reserved_0; /* reserved */ #if defined(_BIT_FIELDS_HTOL) uchar_t cntl_reserved_1 : 5, /* reserved */ cntl_qtype : 3; /* tagged queueing type */ uchar_t cntl_kill_tsk : 1, /* terminate task */ cntl_clr_aca : 1, /* clear aca */ cntl_reset_tgt : 1, /* reset target */ cntl_reset_lun : 1, /* reset lun */ cntl_reserved_2 : 1, /* reserved */ cntl_clr_tsk : 1, /* clear task set */ cntl_abort_tsk : 1, /* abort task set */ cntl_reserved_3 : 1; /* reserved */ uchar_t cntl_reserved_4 : 6, /* reserved */ cntl_read_data : 1, /* initiator read */ cntl_write_data : 1; /* initiator write */ #elif defined(_BIT_FIELDS_LTOH) uchar_t cntl_qtype : 3, /* tagged queueing type */ cntl_reserved_1 : 5; /* reserved */ uchar_t cntl_reserved_3 : 1, /* reserved */ cntl_abort_tsk : 1, /* abort task set */ cntl_clr_tsk : 1, /* clear task set */ cntl_reserved_2 : 1, /* reserved */ cntl_reset_lun : 1, /* reset lun */ cntl_reset_tgt : 1, /* reset target */ cntl_clr_aca : 1, /* clear aca */ cntl_kill_tsk : 1; /* terminate task */ uchar_t cntl_write_data : 1, /* initiator write */ cntl_read_data : 1, /* initiator read */ cntl_reserved_4 : 6; /* reserved */ #else #error one of _BIT_FIELDS_HTOL or _BIT_FIELDS_LTOH must be defined #endif } fcp_cntl_t; /* * fcp SCSI control tagged queueing types - cntl_qtype */ #define FCP_QTYPE_SIMPLE 0 /* simple queueing */ #define FCP_QTYPE_HEAD_OF_Q 1 /* head of queue */ #define FCP_QTYPE_ORDERED 2 /* ordered queueing */ #define FCP_QTYPE_ACA_Q_TAG 4 /* ACA queueing */ #define FCP_QTYPE_UNTAGGED 5 /* Untagged */ /* * fcp SCSI entity address * * ent_addr_0 is always the first and highest layer of * the hierarchy. The depth of the hierarchy of addressing, * up to a maximum of four layers, is arbitrary and * device-dependent. */ typedef struct fcp_ent_addr { ushort_t ent_addr_0; /* entity address 0 */ ushort_t ent_addr_1; /* entity address 1 */ ushort_t ent_addr_2; /* entity address 2 */ ushort_t ent_addr_3; /* entity address 3 */ } fcp_ent_addr_t; /* * maximum size of SCSI cdb in fcp SCSI command */ #define FCP_CDB_SIZE 16 #define FCP_LUN_SIZE 8 #define FCP_LUN_HEADER 8 /* * FCP SCSI command payload */ typedef struct fcp_cmd { fcp_ent_addr_t fcp_ent_addr; /* entity address */ fcp_cntl_t fcp_cntl; /* SCSI options */ uchar_t fcp_cdb[FCP_CDB_SIZE]; /* SCSI cdb */ int fcp_data_len; /* data length */ } fcp_cmd_t; /* * fcp SCSI status */ typedef struct fcp_status { ushort_t reserved_0; /* reserved */ #if defined(_BIT_FIELDS_HTOL) uchar_t reserved_1 : 4, /* reserved */ resid_under : 1, /* resid non-zero */ resid_over : 1, /* resid non-zero */ sense_len_set : 1, /* sense_len non-zero */ rsp_len_set : 1; /* response_len non-zero */ #elif defined(_BIT_FIELDS_LTOH) uchar_t rsp_len_set : 1, /* response_len non-zero */ sense_len_set : 1, /* sense_len non-zero */ resid_over : 1, /* resid non-zero */ resid_under : 1, /* resid non-zero */ reserved_1 : 4; /* reserved */ #endif uchar_t scsi_status; /* status of cmd */ } fcp_status_t; /* * fcp SCSI response payload */ typedef struct fcp_rsp { uint32_t reserved_0; /* reserved */ uint32_t reserved_1; /* reserved */ union { fcp_status_t fcp_status; /* command status */ uint32_t i_fcp_status; } fcp_u; uint32_t fcp_resid; /* resid of operation */ uint32_t fcp_sense_len; /* sense data length */ uint32_t fcp_response_len; /* response data length */ /* * 'm' bytes of scsi response info follow * 'n' bytes of scsi sense info follow */ } fcp_rsp_t; /* MAde 256 for sonoma as it wants to give tons of sense info */ #define FCP_MAX_RSP_IU_SIZE 256 /* * fcp rsp_info field format */ struct fcp_rsp_info { uchar_t resvd1; uchar_t resvd2; uchar_t resvd3; uchar_t rsp_code; uchar_t resvd4; uchar_t resvd5; uchar_t resvd6; uchar_t resvd7; }; /* * rsp_code definitions */ #define FCP_NO_FAILURE 0x0 #define FCP_DL_LEN_MISMATCH 0x1 #define FCP_CMND_INVALID 0x2 #define FCP_DATA_RO_MISMATCH 0x3 #define FCP_TASK_MGMT_NOT_SUPPTD 0x4 #define FCP_TASK_MGMT_FAILED 0x5 #ifdef THIS_NEEDED_YET /* * fcp scsi_xfer_rdy payload */ typedef struct fcp_xfer_rdy { ulong64_t fcp_seq_offset; /* relative offset */ ulong64_t fcp_burst_len; /* buffer space */ ulong64_t reserved; /* reserved */ } fcp_xfer_rdy_t; #endif /* THIS_NEEDED_YET */ /* * fcp PRLI payload */ struct fcp_prli { uchar_t type; uchar_t resvd1; /* rsvd by std */ #if defined(_BIT_FIELDS_HTOL) uint16_t orig_process_assoc_valid : 1, resp_process_assoc_valid : 1, establish_image_pair : 1, resvd2 : 13; /* rsvd by std */ #elif defined(_BIT_FIELDS_LTOH) uint16_t resvd2 : 13, /* rsvd by std */ establish_image_pair : 1, resp_process_assoc_valid : 1, orig_process_assoc_valid : 1; #endif uint32_t orig_process_associator; uint32_t resp_process_associator; #if defined(_BIT_FIELDS_HTOL) uint32_t resvd3 : 23, /* rsvd by std */ retry : 1, confirmed_compl_allowed : 1, data_overlay_allowed : 1, initiator_fn : 1, target_fn : 1, obsolete_2 : 1, obsolete_1 : 1, read_xfer_rdy_disabled : 1, write_xfer_rdy_disabled : 1; #elif defined(_BIT_FIELDS_LTOH) uint32_t write_xfer_rdy_disabled : 1, read_xfer_rdy_disabled : 1, obsolete_1 : 1, obsolete_2 : 1, target_fn : 1, initiator_fn : 1, data_overlay_allowed : 1, confirmed_compl_allowed : 1, retry : 1, resvd3 : 23; /* rsvd by std */ #endif }; /* * fcp PRLI ACC payload */ struct fcp_prli_acc { uchar_t type; uchar_t resvd1; /* type code extension */ #if defined(_BIT_FIELDS_HTOL) uint16_t orig_process_assoc_valid : 1, resp_process_assoc_valid : 1, image_pair_established : 1, resvd2 : 1, accept_response_code : 4, resvd3 : 8; #elif defined(_BIT_FIELDS_LTOH) uint16_t resvd3 : 8, accept_response_code : 4, resvd2 : 1, image_pair_established : 1, resp_process_assoc_valid : 1, orig_process_assoc_valid : 1; #endif uint32_t orig_process_associator; uint32_t resp_process_associator; #if defined(_BIT_FIELDS_HTOL) uint32_t resvd4 : 26, initiator_fn : 1, target_fn : 1, cmd_data_mixed : 1, data_resp_mixed : 1, read_xfer_rdy_disabled : 1, write_xfer_rdy_disabled : 1; #elif defined(_BIT_FIELDS_LTOH) uint32_t write_xfer_rdy_disabled : 1, read_xfer_rdy_disabled : 1, data_resp_mixed : 1, cmd_data_mixed : 1, target_fn : 1, initiator_fn : 1, resvd4 : 26; #endif }; #define FC_UB_FCP_CDB_FLAG 0x0001 /* UB has valid cdb */ #define FC_UB_FCP_PORT_LOGOUT 0x0002 /* Port logout UB */ #define FC_UB_FCP_ABORT_TASK 0x0004 /* Abort task UB */ #define FC_UB_FCP_BUS_RESET 0x0008 /* Bus reset UB */ #define FC_UB_FCP_CMD_DONE 0x8000 /* Work on this UB is done */ #define FC_UB_FCP_OOB_CMD (FC_UB_FCP_PORT_LOGOUT | FC_UB_FCP_ABORT_TASK \ | FC_UB_FCP_BUS_RESET) /* Out-of-band traget cmds */ #if !defined(__lint) _NOTE(SCHEME_PROTECTS_DATA("Unshared Data", fcp_cmd fcp_rsp fcp_prli)) #endif /* __lint */ /* * FC4 type setttings for Name Server registration. */ #define FC4_TYPE_WORD_POS(x) ((uchar_t)(x) >> 5) #define FC4_TYPE_BIT_POS(x) ((uchar_t)(x) & 0x1F) #ifdef __cplusplus } #endif #endif /* _FCP_H */
25.070225
73
0.702969
e933092d863012564f51c25058c8fbf9f5e46b97
1,631
h
C
cppEngineConcept/engine/World.h
ProkopHapala/SimpleSimulationEngine
240f9b7e85b3a6eda7a27dc15fe3f7b8c08774c5
[ "MIT" ]
26
2016-12-04T04:45:12.000Z
2022-03-24T09:39:28.000Z
cppEngineConcept/engine/World.h
Aki78/FlightAI
9c5480f2392c9c89b9fee4902db0c4cde5323a6c
[ "MIT" ]
null
null
null
cppEngineConcept/engine/World.h
Aki78/FlightAI
9c5480f2392c9c89b9fee4902db0c4cde5323a6c
[ "MIT" ]
2
2019-02-09T12:31:06.000Z
2019-04-28T02:24:50.000Z
#ifndef Shooter_h #define Shooter_h #include <vector> //#include <unordered_set> //#include <algorithm> #include "fastmath.h" #include "Vec3.h" #include "Mat3.h" #include "quaternion.h" #include "Body.h" //#include "NBodyWorld2D.h" // TODO: We would like to add this later #include "Object3D.h" #include "Terrain25D.h" #include "Warrior3D.h" #include "Warrior25D.h" #include "Projectile3D.h" // class NonInertWorld : public NBodyWorld2D { // TODO: We would like to add this later class Shooter { public: int debug_shit=19; int perFrame = 10; double dt = 0.005d; double restitution = -0.8d; double airDrag = -0.05d; double landDrag = -0.5d; double gravity = -9.81; double objR = 10.0d; double ground_height = 0.0; Vec3d wind_speed,watter_speed; double projLifetime = 10.0; int shotsCount=0,warriorCount=0; std::vector<Warrior3D*> warriors; std::vector<Warrior25D*> warriors25D; std::vector<Projectile3D*> projectiles; // see http://stackoverflow.com/questions/11457571/how-to-set-initial-size-of-stl-vector std::vector<Object3D*> objects; Terrain25D * terrain = NULL; // ==== function declarations virtual void update_warriors3D(); virtual void update_warriors25D(); virtual void update_projectiles3D(); virtual void update_world( ); virtual void init_world ( ); //virtual void drawEnvironment(); Projectile3D* fireProjectile( Warrior3D * w, double speed, int kind ); Warrior3D* makeWarrior ( const Vec3d& pos, const Vec3d& dir, const Vec3d& up, int kind ); }; #endif
23.3
131
0.67198
978d89ddc713517b4c0a69af5b7c34fcfaa2cc1f
88,335
c
C
src/dc4wZip.c
geoffmcl/dc4w
40e24d9367d16266d6646f7feff7ff8ecb520d2b
[ "Unlicense" ]
null
null
null
src/dc4wZip.c
geoffmcl/dc4w
40e24d9367d16266d6646f7feff7ff8ecb520d2b
[ "Unlicense" ]
1
2020-07-01T17:51:19.000Z
2020-07-01T17:51:19.000Z
src/dc4wZip.c
geoffmcl/dc4w
40e24d9367d16266d6646f7feff7ff8ecb520d2b
[ "Unlicense" ]
null
null
null
// dc4wZip.c // this is public domain software - praise me, if ok, just don't blame me! // Handles BOTH the reading/unzipping of a ZIP file, and // the creation of a ZIP of the LIST about to be overwritten by an update // This 2nd function, not yet COMPLETED, would allow a BACKUP or UNDO if // done CAREFULLY. #include "dc4w.h" //#include "dc4wZip.h" #ifdef ADD_ZIP_SUPPORT // ZIP file support /////////////////////////////////////////////////////////////////// #define UNZIP_INTERNAL #include "izuz\iz_unzip.h" /* includes, typedefs, macros, prototypes, etc. */ #define INSPERPATH // add 'files' from zip per folder sort extern int getNTfiletime(struct Globals * pg, FILETIME * pModFT, FILETIME * pAccFT, FILETIME * pCreFT ); extern int gmuzToMemory(__GPRO__ char * zip, char * file, UzpBuffer *retstr ); extern BOOL GetListMember( LPTSTR lpb, DWORD dwNum ); extern BOOL g_bZipAll; // -NA to override the exclusions extern VOID prt( LPTSTR lps ); extern INT_PTR Do_IDM_EDITZIPUP( VOID ); #undef SHOWTIMES #define SHOWFL2 // write a LIST file - from the ZIP list #define SHWCMP2 // diagnostic compare of ZIP file times #define MXCFNDS 16 // max. concurrent finds #define dwf_Done1 1 // flag is shifed left by dwFndLev #define W_PATH '\\' #define U_PATH '/' // NOTE: Have done g_dwTZID = GetTimeZoneInformation( &g_sTZ ); // time zone // which gives - //typedef struct _TIME_ZONE_INFORMATION { // LONG Bias; // WCHAR StandardName[ 32 ]; // SYSTEMTIME StandardDate; // LONG StandardBias; // WCHAR DaylightName[ 32 ]; // SYSTEMTIME DaylightDate; // LONG DaylightBias; //} TIME_ZONE_INFORMATION, *PTIME_ZONE_INFORMATION; // if g_dwTZID is NOT = TIME_ZONE_ID_INVALID // where // Members // Bias // Specifies the current bias, in minutes, for local time translation on this computer. // The bias is the difference, in minutes, between Coordinated Universal Time (UTC) // and local time. All translations between UTC and local time are based on the // following formula: // UTC = local time + bias // This member is required. // ***STRUGGLING WITH TIME*** // Now ShowTime() outputs // DIR listing show // Directory of D:\DTEMP\temp2\FlightGear //ACLOCAL M4 4,699 17/02/00 21:34 aclocal.m4 // Directory of D:\FG2\FlightGear //ACLOCAL M4 4,699 17/02/00 21:34 aclocal.m4 //CHECK: [FlightGear/aclocal.m4] <F> (1) //Unix=[Thu Feb 17 21:34:30 2000] GMT=[Thu Feb 17 20:34:30 2000] // FT=[17/02/00 22:34] ST =[17/02/2000 20:34] // List file originally showed // .\FlightGear\aclocal.m4 <Newer but=size>17/02/00 20:34 17/02/00 19:34 4699 // BUT changed LIST file to show //.\FlightGear\aclocal.m4 <Newer but=size> 17/02/00 22:34 17/02/00 21:34 4699 // ***A ONE HOUR DIFFERENCE*** typedef struct tagZIPFILE { LIST_ENTRY pList; // MUST be first entry DWORD dwOrder; // zip order of file DWORD dwRank; // rank, in alphabetic list DWORD dwLevel; // zero if ROOT DWORD dwFlag; // flag of bits DWORD dwCompSize; // compressed size DWORD dwRatio; // ration time_t uxTime; TCHAR szDC4WName[264]; // *** FULL ZIP NAME *** BOOL bSys2FT; // convertion of SYSTEMTIME to FILETIME SYSTEMTIME sST; // local time WIN32_FIND_DATA sFD; // maybe better TCHAR szZipPath[264]; // path, (if there is one) TCHAR szModZName[264]; // may be shortened by root TCHAR szRes1[264]; // reserved memory }ZIPFILE, * PZIPFILE; BOOL bUseUTime = TRUE; USERFUNCTIONS sUsrFun; //# define CONSTRUCTGLOBALS() Uz_Globs *pG = globalsCtor() Uz_Globs * g_pG = 0; BOOL bAddIDsp = FALSE; //TCHAR g_szCurZip[264] = { "\0" }; TCHAR gzszTmpBuf[1024]; DWORD g_iActZip = 0; // active ZIP length BOOL g_bInZipWait = FALSE; int UZ_EXP MyInfo(pG, buf, size, flag) zvoid *pG; /* globals struct: always passed */ uch *buf; /* preformatted string to be printed */ ulg size; /* length of string (may include nulls) */ int flag; /* flag bits */ { ulg i, k; INT c, d, acrlf, iRet; LPTSTR po = &gzszTmpBuf[0]; uch * endbuf = buf + (unsigned)size; k = 0; c = d = 0; acrlf = 0; iRet = 0; if(MSG_TNEWLN(flag)) { /* request for END OF LINE characters to be added */ if(( !size && !((Uz_Globs *)pG)->sol) || ( size && (endbuf[-1] != '\n') ) ) { acrlf = 1; // signal MEOR appended } } for( i = 0; i < size; i++ ) { c = buf[i]; if( c < ' ' ) { if( c == '\r' ) { if( (i+1) < size ) { if( buf[i+1] != '\n' ) { po[k++] = (TCHAR)c; c = '\n'; } } else { po[k++] = (TCHAR)c; c = '\n'; } } else if( c == '\n' ) { if( d != '\r' ) po[k++] = '\r'; } else if( c == '\t' ) { c = ' '; } else { c = 0; } } if(c) { po[k++] = (TCHAR)c; d = c; if( k >= MXTMPBUF ) { po[k] = 0; if(iRet) { if( bAddIDsp ) { sprtf(po); } } else { if( bAddIDsp ) { TrimIB(po); sprtf("I:[%s]"MEOR, po); // WriteFile(hOut, po, k, &dwm, NULL ); } } iRet += k; k = 0; } } } if(k || acrlf) { // ( ( c != '\n' ) && // ( bEnsEOL ) ) ) if( acrlf ) { po[k++] = '\r'; po[k++] = '\n'; } if(iRet) { if( bAddIDsp ) { sprtf(po); } } else { if( bAddIDsp ) { TrimIB(po); sprtf("I:[%s]"MEOR, po); } } //WriteFile(hOut, po, k, &dwm, NULL ); iRet += k; } ((Uz_Globs *)pG)->sol = (endbuf[-1] == '\n'); return 0; } BOOL IsValidZip( LPTSTR lpf ) // #ifdef ADD_ZIP_SUPPORT { BOOL bRet = FALSE; char * fnames[2]; int retcode; CONSTRUCTGLOBALS(); g_pG = &G; G.message = (MsgFn *)MyInfo; uO.jflag = 1; uO.tflag = 1; uO.overwrite_none = 0; G.extract_flag = FALSE; //uO.zipinfo_mode && //!uO.cflag && //!uO.tflag && uO.vflag = 0; //!uO.zflag //!uO.T_flag uO.qflag = 2; /* turn off all messages */ G.fValidate = TRUE; fnames[0] = lpf; fnames[1] = 0; //G.pfnames = (char **)&fnames[0]; /* assign default filename vector */ G.pfnames = &fnames[0]; /* assign default filename vector */ //#ifdef WINDLL // Wiz_NoPrinting(TRUE); //#endif // if (archive == NULL) { /* something is screwed up: no filename */ // DESTROYGLOBALS(); // return PK_NOZIP; // } //G.wildzipfn = (char *)malloc(FILNAMSIZ + 1); //strcpy(G.wildzipfn, archive); G.wildzipfn = lpf; //#if (defined(WINDLL) && !defined(CRTL_CP_IS_ISO)) // _ISO_INTERN(G.wildzipfn); //#endif G.process_all_files = TRUE; /* for speed */ retcode = process_zipfiles(__G); DESTROYGLOBALS(); if( retcode == PK_OK ) bRet = TRUE; return bRet; } typedef struct tagFNDSTR { LIST_ENTRY sList; // always at top HANDLE hFind; // find handle DWORD dwFndLev; // up to MXFNDS TCHAR szZipFile[264]; // ZIP we are finding in TCHAR szFndPath[264]; // and PATH for THIS find, and its DWORD dwDep; // depth of paths PLE pList; // pointer to ZIP file list PLE pDirs; // and a corresponding FOLDER list }FNDSTR, * PFNDSTR; LIST_ENTRY sFindList = { &sFindList, &sFindList }; LIST_ENTRY sDirList = { &sDirList, &sDirList }; PLE gpCurrList = 0; DWORD gdwMaxDep, gdwMinDep; DWORD gdwOrder = 0; // ctime() // Convert a time value to a string and adjust for local time zone settings. // char *ctime( const time_t *timer ); // where timer = the number of seconds elapsed since midnight (00:00:00), // January 1, 1970, coordinated universal time (UTC). #define YR_BASE 1900 // mktime() // Converts the local time to a calendar value. // time_t mktime( struct tm *timeptr ); time_t sys_to_ux_time(SYSTEMTIME * pst) { time_t m_time; struct tm *tm; time_t now = time(NULL); tm = localtime(&now); tm->tm_isdst = -1; /* let mktime determine if DST is in effect */ /* dissect date */ // tm_year = Year (current year minus 1900) // wYear Specifies the current year. tm->tm_year = (int)(pst->wYear - YR_BASE); // tm_mon Month (0 to 11; January = 0) // wMonth Specifies the current month; January = 1, February = 2, and so on. tm->tm_mon = (int)(pst->wMonth - 1); tm->tm_mday = (int)(pst->wDay); /* dissect time */ tm->tm_hour = (int)pst->wHour; tm->tm_min = (int)pst->wMinute; tm->tm_sec = (int)pst->wSecond; m_time = mktime(tm); return m_time; } VOID ShowTime( LPTSTR pName, DWORD dwAttr, DWORD dwLevel, time_t ltime, FILETIME * pft, SYSTEMTIME * pst ) { struct tm * gmt; LPTSTR lpb = &gszTmpBuf[0]; LPTSTR lpb2 = &lpb[64]; LPTSTR lpb3 = &lpb2[64]; LPTSTR lpb4 = GetFDTStg( pft ); // Convert a time value to a string and adjust for local time zone settings. strcpy(lpb, ctime( &ltime )); TrimIB(lpb); // gmtime returns a pointer to a structure of type tm. // The fields of the returned structure hold the evaluated value // of the timer argument in UTC rather than in local time. // Each of the structure fields is of type int, ... gmt = gmtime( &ltime ); strcpy(lpb2, asctime(gmt)); TrimIB(lpb2); *lpb3 = 0; AppendDateTime2( lpb3, pst ); // include 4 digit year sprtf( "CHECK: [%s] <%s> (%d)"MEOR "Unix=[%s] GMT=[%s]"MEOR " FT=[%s] ST =[%s]"MEOR, pName, ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) ? "D" : "F"), dwLevel, lpb, lpb2, lpb4, lpb3 ); // if( g_pG ) // { // FILETIME ModFT; /* File time type defined in NT, `last modified' time */ // FILETIME AccFT; /* NT file time type, `last access' time */ // FILETIME CreFT; /* NT file time type, `file creation' time */ // INT gotTime = getNTfiletime( g_pG, &ModFT, &AccFT, &CreFT ); // if(gotTime) // { // sprtf( "NTtime: Mod=%s Acc=%s Crt=%s"MEOR, // ((gotTime & EB_UT_FL_MTIME) ? GetFDTStg( &ModFT ) : "<none>"), // ((gotTime & EB_UT_FL_ATIME) ? GetFDTStg( &AccFT ) : "<none>"), // ((gotTime & EB_UT_FL_CTIME) ? GetFDTStg( &CreFT ) : "<none>") ); // } // } } DWORD GetDepth( LPTSTR lpf ) { DWORD dwi = 0; LPTSTR lpb = &g_szBuf1[0]; LPTSTR p; strcpy(lpb,lpf); // make copy (to modify) p = strrchr(lpb, W_PATH); while(p) { dwi++; *p = 0; p = strrchr(lpb,W_PATH); } return dwi; } VOID Forward2Back( LPTSTR lpf ) // and CHANGE back to 'Windows' paths { INT i = strlen(lpf); INT j; for( j = 0; j < i; j++ ) { if( lpf[j] == U_PATH ) lpf[j] = W_PATH; } } VOID Back2Forward( LPTSTR lpf ) // and CHANGE back to 'Windows' paths { INT i = strlen(lpf); INT j; for( j = 0; j < i; j++ ) { if( lpf[j] == W_PATH ) lpf[j] = U_PATH; } } PZIPFILE CopyZipFileStr( PZIPFILE pzf ) { PZIPFILE pzf2 = (PZIPFILE)MALLOC(sizeof(ZIPFILE)); if( !pzf2 ) { chkme( "C:ERROR: CopyZipFileStr: No alloc. memory!"MEOR ); return 0; } memcpy( pzf2, pzf, sizeof(ZIPFILE) ); return pzf2; } //VOID AddDirLev( LPTSTR lpd, DWORD dwlev, PFD pfd ) /////////////////////////////////////////////////////////////////////////////// // FUNCTION : AddDirLev // Return type: VOID // Arguments : LPTSTR lpf // : LPTSTR lpd // : DWORD dwlev // : PFD pfd // Description: Add a DIRECTORY, taken from a FILE in the ZIP, // thus is a sort of artificial entry, more // so that FidnFirstZip/FindNextZip function very 'correctly' // returning FOLDERS, and only if -reiterate into subs- // then successive calls will be using the FOLDER, thus // the DEPTH of the call ... /////////////////////////////////////////////////////////////////////////////// VOID AddDirLev( LPTSTR lpf, LPTSTR lpd, DWORD dwlev, PFD pfd ) { PLE phdirs = &sDirList; PLE pnd; PZIPFILE pzf2; LPTSTR lpd2; INT ii; PFD pfd2; ii = 1; Traverse_List( phdirs, pnd ) { pzf2 = (PZIPFILE)pnd; if( pzf2->dwLevel == dwlev ) { lpd2 = &pzf2->sFD.cFileName[0]; ii = strcmp( lpd, lpd2 ); if( ii == 0 ) return; // already exists, at this level // break; } } if( ii != 0 ) { pzf2 = (PZIPFILE)MALLOC(sizeof(ZIPFILE)); if( !pzf2 ) { chkme( "C:ERROR: AddDirLev: No alloc. memory!"MEOR ); return; } ZeroMemory( pzf2, sizeof(ZIPFILE)); // set a DIRECTORY/PATH/FOLDER, at a level lpd2 = &pzf2->szZipPath[0]; strcpy( lpd2, lpd ); pzf2->dwLevel = dwlev; // use the DATE/TIME info of the FILE NAME from the ZIP // tha first 'exposed' this FOLDER ... maybe not the // 'best' date/time for a FOLDER, but will do for now // ============================= pfd2 = &pzf2->sFD; memcpy( pfd2, pfd, sizeof(FD) ); pfd2->nFileSizeLow = 0; pfd2->nFileSizeHigh = 0; pfd2->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY; strcpy( &pzf2->sFD.cFileName[0], lpd ); // **************************************************************** strcpy( &pzf2->szModZName[0], lpf ); // keep FULL ZIP NAME always strcpy( &pzf2->szDC4WName[0], lpf ); // version used - maybe modified // **************************************************************** InsertTailList(phdirs, &pzf2->pList); } } #ifdef GMUZ // WIN32_FIND_DATA // GetLocalTime() // /* Display UTC. */ // time_t ltime; // struct tm *gmt // time( &ltime ); // printf( "UNIX time and date:\t\t\t%s", ctime( &ltime ) ); // gmt = gmtime( &ltime ); // printf( "Coordinated universal time:\t\t%s", asctime( gmt ) ); // // dwsize compsiz ratio, // month, day, year hour, minute second // path unix-time // NOTES ON pName // It appears FILES are given as // "CMPFG.BAT", "MSVC6/MSG-01.TXT" or "MSVC6/FGFS32/FlightGear.dsw" // It appears DIRECTORIES are given as // <none> "MSVC6/" or "MSVC6/FGFS32/". // I want both the FILE CMPFG.BAT and the FOLDER "MSVC6/" // to be at the SAME level, ie ZERO // and both "MSVC6/MSG-01.TXT" and "MSVC6/FGFS32" to be level 1 // then level 2, 3 etc ... void WINAPI SendAppMsg(ulg dwSize, ulg dwCompSz, unsigned ratio, unsigned month, unsigned day, unsigned year, unsigned hour, unsigned minute, unsigned second, LPSTR pName, time_t uTime, unsigned dwAttr ) { PZIPFILE pzf = (PZIPFILE)MALLOC(sizeof(ZIPFILE)); if(pzf) { PLE ph = gpCurrList; // PLE phdirs = &sDirList; LPTSTR ptmp = &gszTmpBuf[0]; LPTSTR p, lpd, lpf; PZIPFILE pzf2; LPTSTR lpd2, lpf2; PFD pfd; // PFD pfd2; //DWORD dep; ZeroMemory(pzf,sizeof(ZIPFILE)); // ensure it is ALL blank pzf->dwCompSize = dwCompSz; pzf->dwRatio = ratio; // number of seconds elapsed since midnight (00:00:00), January 1, 1970, UTC pzf->uxTime = uTime; lpf = &pzf->szModZName[0]; // copy the COMPLETE ZIP entry pfd = &pzf->sFD; // and a 'simulated' WIN32 pad if( bUseUTime ) { struct tm * gmt; // FILETIME ft; // gmtime returns a pointer to a structure of type tm. // The fields of the returned structure hold the evaluated value // of the timer argument in UTC rather than in local time. gmt = gmtime( &uTime ); pzf->sST.wHour = gmt->tm_hour; pzf->sST.wMinute = gmt->tm_min; pzf->sST.wSecond = gmt->tm_sec; // tm_mday Day of month (1 to 31) // wDay Specifies the current day of the month. pzf->sST.wDay = gmt->tm_mday; // tm_mon Month (0 to 11; January = 0) // wMonth Specifies the current month; January = 1, February = 2, and so on. pzf->sST.wMonth = gmt->tm_mon + 1; // tm_year = Year (current year minus 1900) // wYear Specifies the current year. pzf->sST.wYear = gmt->tm_year + 1900; // The SystemTimeToFileTime function converts a system time to a file time. pzf->bSys2FT = SystemTimeToFileTime( &pzf->sST, // system time &pzf->sFD.ftLastWriteTime ); // &ft // file time // AWK - The following is WORSE //if( pzf->bSys2FT ) //{ // // The FileTimeToLocalFileTime function converts a file time // // to a local file time. // pzf->bSys2FT = FileTimeToLocalFileTime( // &ft, // UTC file time to convert // &pzf->sFD.ftLastWriteTime ); // converted file time //} } else { // establish the SYSTEMTIME stuff pzf->sST.wHour = hour; pzf->sST.wMinute = minute; pzf->sST.wSecond = second; pzf->sST.wDay = day; pzf->sST.wMonth = month; pzf->sST.wYear = year; //pzf->sST.wDayOfWeek = 0; //pzf->sST.wMilliseconds = 0; // The FILETIME structure is a 64-bit value representing // the number of 100-nanosecond intervals since January 1, 1601 (UTC). pzf->bSys2FT = SystemTimeToFileTime( &pzf->sST, // system time &pzf->sFD.ftLastWriteTime ); // file time } //pzf->dwLevel = 0; //pzf->dwFlag = 0; // no bits yet pzf->sFD.nFileSizeLow = dwSize; //pzf->sFD.nFileSizeHigh = 0; strcpy(ptmp, pName); // copy the NAME Forward2Back(ptmp); // and CHANGE back to 'Windows' paths //dep = GetDepth(ptmp); //strcpy( &pzf->szModZName[0], ptmp ); // copy the COMPLETE ZIP entry strcpy( lpf, ptmp ); // copy the COMPLETE ZIP entry strcpy( &pzf->szDC4WName[0], lpf ); // used ... modified lpd = &pzf->szZipPath[0]; // and KEEP the separated PATH // Now we can check for a PATH p = strrchr(ptmp, W_PATH); if(p) { p++; if( *p ) // if FOLDER(S) *PLUS* FILENAME { pzf->dwLevel++; // it has DEPTH // simulate the 'title' portion of a file name strcpy( &pzf->sFD.cFileName[0], p ); // ENSURE IT IS A FILE ONLY if( dwAttr & FILE_ATTRIBUTE_DIRECTORY ) { chkme( "WARNING: What appears to be a FILE has FOLDER attribute!"MEOR "[%s]"MEOR, pName ); dwAttr = FILE_ATTRIBUTE_NORMAL; } p--; *p = 0; // kill trailing slash //strcpy( &pzf->szPath[0], ptmp ); // and KEEP the separated PATH strcpy( lpd, ptmp ); // and KEEP the separated PATH // now we have a PATH as well p = strrchr(ptmp,W_PATH); // and search for MORE while(p) { pzf->dwLevel++; // it has MORE DEPTH *p = 0; // kill it p = strrchr(ptmp,W_PATH); // and find next } } else // NOTHING following the PATH == A FOLDER NAME ONLY { p--; *p = 0; // kill this trailing '/' p = strrchr(ptmp,W_PATH); if(p) { pzf->dwLevel++; // it has DEPTH, like "this\that\" p++; strcpy( &pzf->sFD.cFileName[0], p ); p--; // back up *p = 0; // remove trailing slash strcpy( &pzf->szZipPath[0], ptmp ); // and KEEP the separated PATH "this\that" p = strrchr(ptmp,W_PATH); // and search for MORE while(p) { pzf->dwLevel++; // it has MORE DEPTH *p = 0; // kill it p = strrchr(ptmp,W_PATH); // and find next } } else { // else a level ZERO directory strcpy( &pzf->szZipPath[0], ptmp ); // and KEEP the separated PATH strcpy( &pzf->sFD.cFileName[0], ptmp ); } // ENSURE IT IS A DIRECTORY if( !( dwAttr & FILE_ATTRIBUTE_DIRECTORY ) ) { chkme( "WARNING: What appears to be a FOLDER does NOT have the attribute!"MEOR "[%s]"MEOR, pName ); dwAttr = FILE_ATTRIBUTE_DIRECTORY; } } } else { // a level ZERO file name strcpy( &pzf->sFD.cFileName[0], pName ); // ENSURE IT IS *NOT* A DIRECTORY if( dwAttr & FILE_ATTRIBUTE_DIRECTORY ) { chkme( "WARNING: What appears to be a FILE has FOLDER attribute!"MEOR "[%s]"MEOR, pName ); dwAttr = FILE_ATTRIBUTE_NORMAL; } } pzf->sFD.dwFileAttributes = dwAttr; // store the ATTRIBUTE gdwOrder++; // bump the ZIP order of output pzf->dwOrder = gdwOrder; // keep that, if needed #ifdef INSPERPATH //lpf = &pzf->szModZName[0]; // copy the COMPLETE ZIP entry //lpd = &pzf->szZipPath[0]; // and KEEP the separated PATH (if any) { PLE pn2; // PZIPFILE pzf2; // LPTSTR lpd2, lpf2; INT i = 0; Traverse_List(ph,pn2) { pzf2 = (PZIPFILE)pn2; lpd2 = &pzf2->szZipPath[0]; i = strcmp( lpd, lpd2 ); if( i == 0 ) { lpf2 = &pzf2->szModZName[0]; i = strcmp( lpf, lpf2 ); if( i < 0 ) { break; } } else if( i < 0 ) { break; } } if( i < 0 ) { InsertBefore(pn2, &pzf->pList ); } else { InsertTailList(ph, &pzf->pList); } } #else // !INSPERPATH InsertTailList(ph, &pzf->pList); #endif // INSPERPATH #ifdef SHOWTIMES ShowTime( pName, dwAttr, pzf->dwLevel, uTime, &pzf->sFD.ftLastWriteTime, &pzf->sST ); //sprtf( "Lev=%d for [%s]"MEOR, pzf->dwLevel, pName ); #endif // SHOWTIMES if( pzf->dwLevel < gdwMinDep ) // it has MORE DEPTH gdwMinDep = pzf->dwLevel; if( pzf->dwLevel > gdwMaxDep ) gdwMaxDep = pzf->dwLevel; if( *lpd ) { // PLE phdirs = &sDirList; // PLE pnd; // INT ii = 1; // DWORD dep = pzf->dwLevel; // it has MORE DEPTH DWORD dwo = 0; // LPTSTR ptmp = &gszTmpBuf[0]; LPTSTR lpb = GetStgBuf(); strcpy(lpb, lpd); // get copy of DIRECTORY/FOLDER(S) p = strchr(lpb,W_PATH); // find first while(p) { *p = 0; // kill it // keep where this came from // ie, the directory tree it first appeared in ... //AddDirLev( lpd, lpb, dwo, pfd ); AddDirLev( lpf, lpb, dwo, pfd ); p++; lpb = p; p = strchr(lpb,W_PATH); // find first dwo++; // bump level } if( *lpb ) AddDirLev( lpf, lpb, dwo, pfd ); // AddDirLev( lpd, lpb, dwo, pfd ); } } // allocated memory else { chkme( "C:ERROR: SendAppMsg: No alloc. memory!"MEOR ); } } #else // !GMUZ // NOT USED void WINAPI SendAppMsg(ulg dwSize, ulg dwCompressedSize, unsigned ratio, unsigned month, unsigned day, unsigned year, unsigned hour, unsigned minute, char uppercase, LPSTR szPath, LPSTR szMethod, ulg dwCRC, char chCrypt) { } #endif // GMUZ #if 0 // out of use static TCHAR _s_szCommDir[264]; static DWORD _s_dwOffset; VOID SetShortest( PLE ph ) { PLE pn; DWORD dwmin = (DWORD)-1; DWORD dwo, dwi; LPTSTR lpd; PZIPFILE pzf; dwo = 0; _s_dwOffset = 0; _s_szCommDir[0] = 0; Traverse_List( ph, pn ) { dwo++; pzf = (PZIPFILE)pn; lpd = &pzf->szZipPath[0]; dwi = strlen(lpd); //if( strlen(lpd) < dwmin ) if( dwi && ( dwi < dwmin ) ) { //dwmin = strlen(lpd); dwmin = dwi; _s_dwOffset = dwo; strcpy(_s_szCommDir, lpd); // keep shortest } } } #endif // #if 0 // out of use TCHAR g_szZipRoot2[264]; /////////////////////////////////////////////////////////////////////////////// // FUNCTION : CheckZipLists // Return type: INT // Arguments : PLE phz // : PLE phdirs // Description: Add any missing DIRECTORIES/FOLDER, // like fg79\FlightGear\misc is 3 folders at appropriate levels // called from } // near end - GetFileList() /////////////////////////////////////////////////////////////////////////////// INT CheckZipLists( PLE phz, PLE phdirs ) { DWORD dep; INT i, icnt, iadd; PZIPFILE pzf, pzf2; LPTSTR lpd, lpd2; PLE pn, pnz, pnd; g_szZipRoot2[0] = 0; ListCount2(phdirs, &icnt); if( !icnt ) return 0; Do_Again: i = 0; pn = 0; Traverse_List( phdirs, pnd ) { pzf2 = (PZIPFILE)pnd; //lpd2 = &pzf2->szPath[0]; //lpd2 = &pzf2->sFD.cFileName[0]; dep = pzf2->dwLevel; if( dep == 0 ) { i++; pn = pnd; } } if( i == 1 ) { i = 0; pzf2 = (PZIPFILE)pn; lpd2 = &pzf2->szZipPath[0]; Traverse_List( phz, pnz ) { pzf = (PZIPFILE)pnz; lpd = &pzf->szZipPath[0]; if( pzf->dwLevel == 0 ) i++; else if( InStr( lpd, lpd2 ) != 1 ) i++; } if( i == 0 ) { LPTSTR lpb; DWORD i2; // We CAN remove this, and reduce the DEPTH of the files // as they came from the ZIP // ie reduce each depth of each by one // accumulate the ROOT being removed if( g_szZipRoot2[0] ) strcat(g_szZipRoot2,"\\"); strcat(g_szZipRoot2, lpd2); // build up the ROOT being 'deleted' i = strlen(lpd2); // get LENGTH of this FOLDER name Traverse_List( phz, pnz ) { pzf = (PZIPFILE)pnz; lpd = &pzf->szZipPath[0]; i2 = strlen(lpd); //lpb = Right( lpd, (strlen(lpd) - i) ); lpb = Right( lpd, (i2 - i) ); //strcpy(lpd, &pzf->szPath[i+1]); if( *lpb == '\\' ) lpb++; strcpy(lpd, lpb); pzf->dwLevel--; } RemoveEntryList(pn); MFREE(pn); i = 0; Traverse_List( phdirs, pnd ) { pzf2 = (PZIPFILE)pnd; pzf2->dwLevel--; if( pzf2->dwLevel == 0 ) i++; } if( i == 1 ) goto Do_Again; } } if( g_szZipRoot2[0] ) { sprtf( "Removed BASE [%s] from ZIP list."MEOR, g_szZipRoot2 ); } iadd = 0; // for EACH in the DIRECTORY/FOLDER list Traverse_List( phdirs, pnd ) { pzf2 = (PZIPFILE)pnd; //lpd2 = &pzf2->szPath[0]; lpd2 = &pzf2->sFD.cFileName[0]; dep = pzf2->dwLevel; // search the MAIN zip list Traverse_List( phz, pnz ) { pzf = (PZIPFILE)pnz; lpd = &pzf->sFD.cFileName[0]; if(( pzf->dwLevel == dep ) && ( pzf->sFD.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) { if( strcmp( lpd, lpd2 ) == 0 ) { lpd2 = 0; break; // do next in DIRECTORY/FOLDER list } } } if( lpd2 ) // if we still have it, then it must be added { PFD pfd; pzf2 = CopyZipFileStr( pzf2 ); if(pzf2) { // and position it within the MAIN list, alphabetically Traverse_List(phz, pnz) { pzf = (PZIPFILE)pnz; pfd = &pzf->sFD; lpd = &pfd->cFileName[0]; if( pzf->sFD.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { i = strcmp( &pzf2->sFD.cFileName[0], lpd ); if( i < 0 ) { InsertBefore(pnz, &pzf2->pList); pzf2 = 0; break; } } } if(pzf2) { InsertHeadList(phz, &pzf2->pList); } iadd++; } } } return iadd; } #if 0 // out of use INT CheckZipLists_NOT_USED( PLE phz, PLE phdirs ) { INT iret = 0; PLE pnz, pnd; LPTSTR p, lpb, lpc, lpd, lpd2; PZIPFILE pzf, pzf2; INT i, icnt; DWORD iPos, dwl, dwl2; // DWORD dep; i = 0; ListCount2(phdirs, &icnt); //if( !icnt ) if( icnt < 2 ) return 0; // naught to do //#if 0 // this no longer works, but do I want it anyway SetShortest( phdirs ); // get SHORTEST of the DIR'S lpc = &_s_szCommDir[0]; Traverse_List( phdirs, pnd ) { pzf2 = (PZIPFILE)pnd; lpd2 = &pzf2->szPath[0]; iPos = InStr( lpd2, lpc ); if( iPos != 1 ) break; i++; } if( i == icnt ) { // we have a 'common' ancester folder/directory set dwl = strlen(lpc); } else { *lpc = 0; // no common 'lower' portion lpc = 0; // and no common pointer dwl = 0; } //ClearAllDone( phdirs ); Traverse_List( phdirs, pnd ) { pzf2 = (PZIPFILE)pnd; lpd2 = &pzf2->szPath[0]; dwl2 = strlen(lpd2); i = 1; lpb = GetStgBuf(); if(lpc && dwl && (dwl <= dwl2)) { if(( dwl == dwl2 ) && ( strcmp( lpc, lpd2 ) == 0 ) ) { // this is the BASE folder, for this ZIP set continue; // skip it for now } //strcpy(lpb, &lpd2[dwl]); p = &lpd2[dwl]; if( *p == '\\' ) p++; // move to FOLDER name strcpy(lpb, p); // set SHORTEST folder name } else { strcpy(lpb,lpd2); } Traverse_List( phz, pnz ) { pzf = (PZIPFILE)pnz; lpd = &pzf->szPath[0]; if( pzf->sFD.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { //i = strcmp( lpd, lpd2 ); i = strcmp( lpd, lpb ); if( i == 0 ) { break; } } } if(i) { // Add this directory to the MASTER list iret++; } } //#endif // #if 0 // this no longer works, but do I want it anyway return iret; } #endif // #if 0 // out of use /////////////////////////////////////////////////////////////////////////////// // FUNCTION : GetFileList // Return type: BOOL // Arguments : LPTSTR lpf // : PLE ph // Description: Extract a file list from a ZIP file, // and store them in a }ZIPFILE, * PZIPFILE; // structure. /////////////////////////////////////////////////////////////////////////////// BOOL GetFileList( LPTSTR lpf, PLE ph ) { INT i; CONSTRUCTGLOBALS(); g_pG = &G; G.message = (MsgFn *)MyInfo; gpCurrList = ph; gdwMaxDep = 0; gdwMinDep = (DWORD)-1; gdwOrder = 0; // zip extraction order G.incnt_leftover = 0; ZeroMemory( &sUsrFun, sizeof(USERFUNCTIONS)); sUsrFun.SendApplicationMessage = SendAppMsg; G.lpUserFunctions = &sUsrFun; uO.zipinfo_mode = FALSE; G.extract_flag = FALSE; G.wildzipfn = lpf; G.process_all_files = TRUE; /* for speed */ G.filespecs = 0; G.xfilespecs = 0; uO.qflag = 2; /* turn off all messages */ uO.vflag = 1; // set ONLY list. ie -l i = process_zipfiles(__G); if( i == PK_OK ) // add in any MISSING DIRECTORIES/FOLDERS CheckZipLists( ph, &sDirList ); DESTROYGLOBALS(); if( i == PK_OK ) return TRUE; else return FALSE; } // end - GetFileList() DWORD ClearDoneFlag( PLE pf, DWORD dwfl ) { DWORD dwi = 0; PLE pn; PZIPFILE pzf; DWORD dwdf = ~(dwf_Done1 << dwfl); Traverse_List(pf,pn) { pzf = (PZIPFILE)pn; pzf->dwFlag &= dwdf; // FindFisrt CLEARS ALL flags at this level dwi++; } return dwi; } DWORD ClearAllDone( PLE pf ) { DWORD dwi = 0; PLE pn; PZIPFILE pzf; Traverse_List(pf,pn) { pzf = (PZIPFILE)pn; pzf->dwFlag = 0; } return dwi; } // We have done the FIRST big listing // now should be RECURSIVE into the FOLDERS // form scandir.c // NOT the ROOT, so ADD the relative folder name AFTER the ZIP // For example, if 'comparing' say "E:\FG\FG-06.ZIP" // then this will produce // "E:\FG\FG-06.ZIP\FlightGear\ to pass to FindFirstZip // (a) it is thus highly unlikely to pass the dir_isvalidfile() // test, and (b) most certainly will NOT pass the IsValidZip() // test, so we will KNOW it is a folder path within the ZIP #if 0 // discontinue this find first //HANDLE FindFirstZip2( LPTSTR lpf, PWIN32_FIND_DATA pfd ) HANDLE FindFirstZip2( LPTSTR lpf, PFDX pfdx ) { PFD pfd = &pfdx->sFD; HANDLE hFind = 0; LPTSTR ppath = &pfdx->szPath[0]; if( InStr( lpf, &g_szActZip[0] ) == 1 ) // like strbgn { LPTSTR ptmp = &gszTmpBuf[0]; INT ilen = strlen(&g_szActZip[0]); PLE ph = &sFindList; //PLE pn = MALLOC(sizeof(FNDSTR)); PLE pn = 0; PLE pf; PZIPFILE pzf; DWORD dwfl; // find level (up to MXFNDS) (was 16) ListCount2(ph, &dwfl); if( dwfl >= MXCFNDS ) { chkme( "ERROR: Maximum concurrent finds %d EXCEEDED!"MEOR, MXCFNDS ); return 0; } pn = MALLOC(sizeof(FNDSTR)); if(pn) { PFNDSTR pfs = (PFNDSTR)pn; BOOL bFound = FALSE; LPTSTR lpf2; DWORD dep; DWORD dwdf = (dwf_Done1 << dwfl); pfs->dwFndLev = dwfl; // set FIND level (concurrent to MXFNDS) pf = &g_sZipFiles; strcpy(ptmp, &lpf[ilen+1]); // get the FOLDER dep = GetDepth(ptmp); if(*ptmp && dep) ptmp[ (strlen(ptmp)-1) ] = 0; // kill the TRAILING if(( *ptmp ) && ( !IsListEmpty( pf ) ) ) // ( ClearDoneFlag( pf, dep ) ) ) { PLE pn2; strcpy( &pfs->szFile[0], &g_szActZip[0] ); // KEEP the ZIP file name strcpy( &pfs->szPath[0], ptmp ); // path MINUS trailing slash hFind = (HANDLE)pn; pfs->hFind = hFind; pfs->dwDep = dep; // set the DEPTH into the folder structure Traverse_List(pf,pn2) { pzf = (PZIPFILE)pn2; if(!( pzf->dwFlag & dwdf ) && ( pzf->dwLevel == dep ) ) { //lpf2 = &pzf->szModZName[0]; lpf2 = &pzf->szPath[0]; //if( InStr( lpf2, ptmp ) == 1 ) if( strcmpi( lpf2, ptmp ) == 0 ) { // first to return memcpy( pfd, &pzf->sFD, sizeof(WIN32_FIND_DATA) ); pzf->dwFlag |= dwdf; bFound = TRUE; strcpy( ppath, &pzf->szModZName[0] ); // = &pfdx->szPath[0]; break; } } } if(bFound) InsertTailList(ph,pn); // add to LIST of FINDINGS } if( !hFind || !bFound ) { MFREE(pn); hFind = 0; } } } return hFind; } #endif // #if 0 // discontinue this find first // pf = &g_sZipFiles; #ifdef SHOWFL2 TCHAR szTmpFL[] = "TEMPLIST.TXT"; TCHAR szTmpMI[] = "TEMPMISS.TXT"; TCHAR gszActDir[264]; // active directory #define wi(a) WriteFile(h, a, strlen(a), &dww, NULL) #endif // SHOWFL2 #define addsp(a,b) while(strlen(a) < b) strcat(a," ") VOID WRiteFileList( LPTSTR lpzf, PLE pf, BOOL bflg, DWORD dwfl ) { #ifdef SHOWFL2 PLE pn; DWORD dwc, dww, dwo; PZIPFILE pzf; LPTSTR lpf, lpft; LPTSTR lpb = &gszTmpBuf[0]; LPTSTR lpb1 = &g_szBuf1[0]; LPTSTR lpb2 = &g_szBuf2[0]; HANDLE h; DWORD dwtot = 0; DWORD dwdf = (dwf_Done1 << dwfl); LPTSTR p, lpd; ListCount2(pf, &dwc); if( !dwc ) return; if( bflg ) lpf = &szTmpFL[0]; // TEMPLIST.TXT else lpf = &szTmpMI[0]; h = CreateFile( lpf, // file name GENERIC_READ | GENERIC_WRITE, // access mode 0, // share mode 0, // SD CREATE_ALWAYS, // how to create FILE_ATTRIBUTE_NORMAL, // file attributes 0 ); // handle to template file if( !VFH(h) ) return; //ListCount2(pf, &dwc); // sprintf(lpb, "List of %d files in [%s]..."MEOR, dwc, lpzf ); sprintf(lpb, "List of %d items in [%s]..."MEOR, dwc, lpzf ); wi(lpb); if( bflg ) ClearDoneFlag(pf, dwfl); // ClearAllDone(pf); dwo = dwtot = 0; Traverse_List( pf, pn ) { pzf = (PZIPFILE)pn; if( !(pzf->dwFlag & dwdf) && ( pzf->sFD.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) { lpf = &pzf->szModZName[0]; // FULL zip name lpd = &pzf->szZipPath[0]; // PATH, and lpft = &pzf->sFD.cFileName[0]; // FILE TITLE dwtot++; sprintf(lpb2, "%4d <DIR> ", dwtot ); sprintf(lpb, "%s %s %s", lpb2, GetFDTStg( &pzf->sFD.ftLastWriteTime ), lpft ); //if(*lpd) // sprintf(EndBuf(lpb)," in %s ", lpd ); strcpy(lpb2,lpf); p = strrchr(lpb2, '\\'); // get LAST if(*lpf) sprintf(EndBuf(lpb)," [%s]", lpf); addsp(lpb,75); sprintf(EndBuf(lpb), " (%d)", pzf->dwLevel); strcat(lpb,MEOR); wi(lpb); pzf->dwFlag |= dwdf; dwo++; } } if( dwtot == dwc ) goto End_List; Traverse_List( pf, pn ) { pzf = (PZIPFILE)pn; if( !( pzf->sFD.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) && !( pzf->dwFlag & dwdf ) ) { lpf = &pzf->szModZName[0]; // FULL zip name lpd = &pzf->szZipPath[0]; // PATH, and lpft = &pzf->sFD.cFileName[0]; // FILE TITLE p = strrchr(lpf, '\\'); //if( strrchr(lpf, '\\') == 0 ) if(p) { // file name contains a DIRECTORY //lpd = &pzf->szPath[0]; if( strcmp( lpd, gszActDir ) ) { strcpy(gszActDir, lpd); //sprintf(lpb, " Directory of %s"MEOR, lpd ); //wi(lpb); } } else { // just a FILE TITLE if(dwo == 0) { sprintf(lpb, " Directory of BASE"MEOR ); wi(lpb); } } dwtot++; sprintf(lpb2, "%4d %12d", dwtot, pzf->sFD.nFileSizeLow ); if( *lpd ) { // show file and path separately sprintf(lpb, "%s %s %s in %s", lpb2, GetFDTStg( &pzf->sFD.ftLastWriteTime ), lpft, lpd ); } else { sprintf(lpb, "%s %s %s", lpb2, GetFDTStg( &pzf->sFD.ftLastWriteTime ), lpf ); } addsp(lpb,75); sprintf(EndBuf(lpb), " (%d)", pzf->dwLevel); strcat(lpb,MEOR); wi(lpb); pzf->dwFlag |= dwdf; dwo++; } } if( dwtot == dwc ) goto End_List; Traverse_List( pf, pn ) { pzf = (PZIPFILE)pn; if( !(pzf->dwFlag & dwdf) && ( pzf->sFD.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) { PLE pn2; PZIPFILE pzf2; BOOL bdnh; LPTSTR lpf2; DWORD dwl; bdnh = FALSE; dwo = 0; lpf = &pzf->szModZName[0]; dwl = strlen(lpf); Traverse_List( pf, pn2 ) { pzf2 = (PZIPFILE)pn2; lpf2 = &pzf2->szModZName[0]; if(( pn != pn2 ) && !( pzf2->dwFlag & dwdf ) && !( pzf2->sFD.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) { if(( InStr( lpf2, lpf ) == 1 ) && ( strrchr( &lpf2[dwl], '\\' ) == 0 ) ) { if(dwo == 0) { dwtot++; sprintf(lpb, "%4d Directory of %s", dwtot, lpf ); sprintf(EndBuf(lpb), " (%d)", pzf->dwLevel); strcat(lpb,MEOR); wi(lpb); } dwtot++; sprintf(lpb2, "%4d %12d", dwtot, pzf2->sFD.nFileSizeLow ); sprintf(lpb, "%s %s %s", lpb2, GetFDTStg( &pzf2->sFD.ftLastWriteTime ), &lpf2[dwl] ); sprintf(EndBuf(lpb), " (%d)", pzf2->dwLevel); strcat(lpb,MEOR); wi(lpb); dwo++; pzf2->dwFlag |= dwdf; // done this FILE in a DIRECTORY } } } pzf->dwFlag |= dwdf; // done this DIRECTORY } } if( dwtot == dwc ) goto End_List; dwo = 0; Traverse_List( pf, pn ) { pzf = (PZIPFILE)pn; if( !(pzf->dwFlag & dwdf) ) { if(dwo == 0) { sprintf(lpb, " Directory of MISSED"MEOR ); wi(lpb); } dwtot++; if( pzf->sFD.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) sprintf(lpb2, "%4d <DIR> ", dwtot ); else sprintf(lpb2, "%4d %10d ", dwtot, pzf->sFD.nFileSizeLow ); sprintf(lpb, "%s %s %s", lpb2, GetFDTStg( &pzf->sFD.ftLastWriteTime ), &pzf->szModZName[0] ); sprintf(EndBuf(lpb), " (%d)", pzf->dwLevel); strcat(lpb,MEOR); wi(lpb); dwo++; } } End_List: sprintf(lpb, "Written List of %d files."MEOR, dwtot ); wi(lpb); CloseHandle(h); if( bflg ) ClearDoneFlag(pf, dwfl); // ClearAllDone(pf); #endif // SHOWFL2 } VOID ChkMissedList( VOID ) // #ifdef ADD_ZIP_SUPPORT { #ifdef SHOWFL2 WRiteFileList( &g_szActZip[0], &g_sZipFiles, FALSE, 31 ); #endif // SHOWFL2 } /////////////////////////////////////////////////////////////////////////////// // FUNCTION : FindFirstZip // Return type: HANDLE // Arguments : LPTSTR lpf // : PWIN32_FIND_DATA pfd // Description: Passed the ZIP name, EXTRACT all the files // in the ZIP (if any) /////////////////////////////////////////////////////////////////////////////// //HANDLE FindFirstZip( LPTSTR lpf, PWIN32_FIND_DATA pfd ) // #ifdef ADD_ZIP_SUPPORT HANDLE FindFirstZip( LPTSTR lpfstr, PFDX pfdx ) // #ifdef ADD_ZIP_SUPPORT { HANDLE hFind = 0; BOOL bFound = FALSE; DWORD dwfl; LPTSTR lpf = lpfstr; LPTSTR lpa = g_szActZip; DWORD iPos = InStr(lpf,lpa); LPTSTR lpb, lpd; lpd = 0; if( iPos == 1 ) { lpb = GetStgBuf(); lpd = &lpfstr[ strlen(lpa) + 1 ]; // point to directory/file added strcpy(lpb,lpf); lpb[ strlen(lpa) ] = 0; lpf = lpb; } if(( iPos == 1 ) || (( dir_isvalidfile(lpf) ) && ( IsValidZip( lpf ) )) ) // #ifdef ADD_ZIP_SUPPORT { PLE ph = &sFindList; PLE pn; PLE pf; PZIPFILE pzf; PFD pfd = &pfdx->sFD; LPTSTR ppath = &pfdx->szPath[0]; ListCount2(ph, &dwfl); if( dwfl >= MXCFNDS ) { chkme( "ERROR: Maximum concurrent finds %d EXCEEDED!"MEOR, MXCFNDS ); return 0; } pn = MALLOC(sizeof(FNDSTR)); if(pn) { PFNDSTR pfs = (PFNDSTR)pn; DWORD dep = 0; DWORD dwdf = (dwf_Done1 << dwfl); LPTSTR lpfnd = &pfs->szFndPath[0]; ZeroMemory(pfs, sizeof(FNDSTR)); // ensure ALL zero pfs->dwFndLev = dwfl; pf = &g_sZipFiles; strcpy( &pfs->szZipFile[0], lpf ); //InitLList( &pfs->sFiles ); if(( iPos != 1 ) && ( strcmp( &g_szActZip[0], lpf ) ) ) { strcpy( &g_szActZip[0], lpf ); // update to NEW file g_iActZip = strlen(lpf); // set LENGTH KillLList( pf ); // remove any OLD list KillLList( &sDirList ); if( !GetFileList( lpf, pf ) ) { // if ERROR, remove LIST KillLList( pf ); g_szActZip[0] = 0; // update to NEW file g_iActZip = 0; // set LENGTH } else { WRiteFileList( lpf, pf, TRUE, dwfl ); } } //if( GetFileList( lpf, pf ) ) // if(( !IsListEmpty( pf ) ) && // ( ClearDoneFlag( pf, dwfl ) ) ) if( !IsListEmpty( pf ) ) { if( iPos != 1 ) ClearDoneFlag( pf, dwfl ); hFind = (HANDLE)pn; pfs->hFind = hFind; // if(dep < gdwMinDep) // dep = gdwMinDep; // begin the min. DEPTH if(lpd) { DWORD dwi; dep = GetDepth(lpd); // set the DEPTH of the search strcpy(lpfnd,lpd); // keep the FIND path string dwi = strlen(lpfnd); if( dwi && ( lpfnd[ (dwi-1) ] == '\\' ) ) lpfnd[ (dwi-1) ] = 0; } pfs->dwDep = dep; InsertTailList(ph,pn); // add this to ACTIVE FINDS Traverse_List(pf,pn) { pzf = (PZIPFILE)pn; //if( pzf->dwLevel == (dep + gdwMinDep) ) if( pzf->dwLevel == dep ) { // first to return memcpy( pfd, &pzf->sFD, sizeof(WIN32_FIND_DATA) ); pzf->dwFlag |= dwdf; strcpy( ppath, &pzf->szModZName[0] ); bFound = TRUE; break; } } } if( !hFind || !bFound ) { KillLList(pf); MFREE(pn); hFind = 0; g_szActZip[0] = 0; // update to NEW file g_iActZip = 0; // set LENGTH } } } #if 0 // discontinue this find first else { //hFind = FindFirstZip2( lpf, pfd ); hFind = FindFirstZip2( lpf, pfdx ); } #endif // #if 0 // discontinue this find first if( !VFH(hFind) ) { bFound = FALSE; } return hFind; } //BOOL FindNextZip( HANDLE hFind, PWIN32_FIND_DATA pfd ) BOOL FindNextZip( HANDLE hFind, PFDX pfdx ) { BOOL bFound = FALSE; PLE ph = &sFindList; PLE pn = 0; PFNDSTR pfs = 0; PFD pfd = &pfdx->sFD; LPTSTR ppath = &pfdx->szPath[0]; Traverse_List(ph,pn) { pfs = (PFNDSTR)pn; if( pfs->hFind == hFind ) break; } if( pn && pfs && ( pfs->hFind == hFind ) ) { //PLE pf = &pfs->sFiles; PLE pf = &g_sZipFiles; PZIPFILE pzf; // search the ZIP list for the NEXT DWORD dep = pfs->dwDep; LPTSTR lpfnd, lpf2; DWORD dwfl = pfs->dwFndLev; DWORD dwdf = (dwf_Done1 << dwfl); lpfnd = &pfs->szFndPath[0]; Traverse_List(pf,pn) { pzf = (PZIPFILE)pn; // cast it to my pointer if( ( pzf->dwLevel == dep ) && !( pzf->dwFlag & dwdf ) ) { if(*lpfnd) { lpf2 = &pzf->szZipPath[0]; if( strcmpi( lpfnd, lpf2 ) == 0 ) { // next to return memcpy( pfd, &pzf->sFD, sizeof(WIN32_FIND_DATA) ); pzf->dwFlag |= dwdf; bFound = TRUE; if(dep == 0) { chkme( "HOW COME we have a PATH but DEPTH is ZERO!"MEOR ); } break; } } else // NO PATH == BASE level=0 case { // next to return memcpy( pfd, &pzf->sFD, sizeof(WIN32_FIND_DATA) ); pzf->dwFlag |= dwdf; bFound = TRUE; strcpy( ppath, &pzf->szModZName[0] ); if(dep != 0) { chkme( "HOW COME we have NO PATH but DEPTH is NOT ZERO!"MEOR ); } break; } } } } return bFound; } VOID FindCloseZip( HANDLE hFind ) { PLE ph = &sFindList; PLE pn = 0; PFNDSTR pfs = 0; Traverse_List(ph,pn) { pfs = (PFNDSTR)pn; if( pfs->hFind == hFind ) break; } if( pn && pfs && ( pfs->hFind == hFind ) ) { RemoveEntryList(pn); MFREE(pn); } } #define TRYCOMP2 LONG CompFTZip( LONG lg, FILETIME * pft1, FILETIME * pft2 ) { SYSTEMTIME st1, st2; LPTSTR lpb = &gszTmpBuf[0]; LONG lg2 = lg; if(( FT2LST( pft1, &st1 ) ) && ( FT2LST( pft2, &st2 ) ) ) { //FILETIME ft; // UTC file time to convert // converted file time #ifdef SHWCMP2 sprintf( lpb, "Comparing %s with %s ... ", GetFDTSStg( pft1 ), GetFDTSStg( pft2 ) ); sprtf( lpb ); #endif // #ifdef SHWCMP2 #ifdef TRYCOMP2 if( g_dwTZID != TIME_ZONE_ID_INVALID ) { // VALID TIME ZONE // FIX20070328 - forget seconds ( st1.wSecond == st2.wSecond ) ) // add year, month, day check if(( st1.wMinute == st2.wMinute ) && ( st1.wYear == st2.wYear ) && ( st1.wMonth == st2.wMonth ) && ( st1.wDay == st2.wDay ) ) { time_t t1, t2; //if( abs( st1.wHour - st2.wHour ) == 1 ) // return 0; // FIX20070328 - make second and ms EQUAL st1.wSecond = st2.wSecond; st1.wMilliseconds = st2.wMilliseconds; t1 = sys_to_ux_time( &st1 ); t2 = sys_to_ux_time( &st2 ); if(( t1 != (time_t)-1 ) && ( t2 != (time_t)-1 ) ) { if(abs( g_sTZ.Bias ) == abs( (int)(t1 / 60) - (int)(t2 / 60) ) ) { #ifdef SHWCMP2 sprtf( "found EQUAL with bias %d ..."MEOR, g_sTZ.Bias ); #endif // #ifdef SHWCMP2 return 0; } else { #ifdef SHWCMP2 sprtf( "still NO %d vs %d ..."MEOR, abs( g_sTZ.Bias ), abs( (int)(t1 / 60) - (int)(t2 / 60) ) ); #endif // #ifdef SHWCMP2 } } else { #ifdef SHWCMP2 sprtf( "Unix conversion FAILED ..."MEOR ); #endif // #ifdef SHWCMP2 } } else { // still not the SAME??? #ifdef SHWCMP2 sprtf( "Year, Month, Day, or MInutes NOT SAME ..."MEOR ); #endif // #ifdef SHWCMP2 } } else { #ifdef SHWCMP2 sprtf( "EEK: Timezone NOT VALID ..."MEOR ); #endif // #ifdef SHWCMP2 } #else // !TRYCOMP2 if( FileTimeToLocalFileTime( pft1, &ft ) ) { sprintf( lpb, "Comparing %s with %s ..."MEOR, GetFDTStg( &ft ), GetFDTStg( pft2 ) ); if( CompareFileTime( &ft, pft2 ) == 0 ) return 0; } if( FileTimeToLocalFileTime( pft2, &ft ) ) { sprintf( lpb, "Comparing %s with %s ..."MEOR, GetFDTStg( pft1 ), GetFDTStg( &ft ) ); if( CompareFileTime( &ft, pft1 ) == 0 ) return 0; } if( LocalFileTimeToFileTime( pft1, &ft ) ) { sprintf( lpb, "Comparing %s with %s ..."MEOR, GetFDTStg( &ft ), GetFDTStg( pft2 ) ); if( CompareFileTime( &ft, pft2 ) == 0 ) return 0; } if( LocalFileTimeToFileTime( pft2, &ft ) ) { sprintf( lpb, "Comparing %s with %s ..."MEOR, GetFDTStg( pft1 ), GetFDTStg( &ft ) ); if( CompareFileTime( &ft, pft1 ) == 0 ) return 0; } #endif // #ifdef TRYCOMP2 } else { sprintf( lpb, "Compare of %s with %s FAILED!"MEOR, GetFDTStg( pft1 ), GetFDTStg( pft2 ) ); chkme( lpb ); } return lg2; } INT UnzFile( POZF pozf ) { INT i = 0; LPTSTR lpb = 0; UzpBuffer g_sUzb; CONSTRUCTGLOBALS(); G.message = (MsgFn *)MyInfo; uO.qflag = 2; /* turn off all messages */ g_sUzb.strptr = 0; g_sUzb.strlength = 0; i = gmuzToMemory(__G__ pozf->pZName, pozf->pFName, &g_sUzb ); if(( i == PK_OK ) && ( g_sUzb.strptr ) && ( g_sUzb.strlength ) ) { pozf->pData = g_sUzb.strptr; pozf->dwLen = g_sUzb.strlength; i = TRUE; // user to FREE } else { if( g_sUzb.strptr ) free( g_sUzb.strptr ); } DESTROYGLOBALS(); return i; } INT OpenZIPFile( POZF pozf ) // return a BUFFER of file data { INT i = 0; LPTSTR zname = pozf->pZName; LPTSTR fname = pozf->pFName; if(( dir_isvalidfile(zname) ) && ( IsValidZip( zname ) ) ) // #ifdef ADD_ZIP_SUPPORT { LPTSTR lpf = &g_szActZip[0]; PLE pf = &g_sZipFiles; PLE pn; PZIPFILE pzf; BOOL bFnd = FALSE; if( strcmpi( zname, lpf ) ) { strcpy( lpf, zname ); KillLList( pf ); // remove any OLD list if( !GetFileList( lpf, pf ) ) { // if ERROR, remove LIST KillLList( pf ); } // else // { // WRiteFileList( lpf, pf, TRUE, 31 ); // } } Traverse_List( pf, pn ) { pzf = (PZIPFILE)pn; lpf = &pzf->szModZName[0]; if( strcmpi( lpf, fname ) == 0 ) { bFnd = TRUE; break; } } if( bFnd ) { Back2Forward(fname); // switch to UNIX form i = UnzFile( pozf ); Forward2Back(fname); // switch to UNIX form } } return i; } // ******* ZIPUP A LIST ********* //TCHAR szZpCmd[] = "ZipCommand"; //extern TCHAR szZipUp[]; // [264] = {"Zip8 -a TEMPZ001.zip @tempz001.lst"}; extern TCHAR szZipCmd[]; // [264] = {"Zip8 -a TEMPZ001.zip @tempz001.lst"}; //BOOL bChgZp = FALSE; extern INT giSelection; // = -1 if NONE, or is selected row in table //extern TCHAR szZpCmd2[]; // = "ZipCommand2"; extern TCHAR szZipCmd2[]; // [264] = { DEF_ZIP_CMD2 }; extern BOOL bChgZp2; // = FALSE; extern int complist_writelist( COMPLIST cl, LPTSTR poutfile, DWORD dwo, BOOL bSetGlob, BOOL bDoMB ); //#ifndef ADDZIPUP VOID getnxtlist( LPTSTR lpIn ) { static TCHAR _s_szOrg[264]; static TCHAR _s_szDir[264]; static TCHAR _s_szFile[264]; static TCHAR _s_szBase[264]; static TCHAR _s_szExt[264]; LPTSTR lpd, lpf, lpb, lpe; DWORD ilen; INT c, icnt; if( dir_isvalidfile( lpIn ) ) { strcpy(_s_szOrg,lpIn); // get copy of original lpd = _s_szDir; lpf = _s_szFile; lpb = _s_szBase; lpe = _s_szExt; icnt = 0; do { SplitFN( lpd, lpf, lpIn ); // remove any directory SplitExt2( lpb, lpe, lpf ); // split into base name and extent // work on the BASE name ilen = strlen(lpb); if( ilen == 0 ) return; // nothing to change here while(ilen) { if( icnt > 3 ) break; // only backup a max. of 999 + 1 times ilen--; // back up one char c = lpb[ilen]; // get LAST char if( ISNUM(c) ) { if( c < '9' ) { c++; lpb[ilen] = (TCHAR)c; break; } else if(ilen) { lpb[ilen] = '0'; // and cycle in while for some more while icnt++; // count the '9' backup } else { strcpy(lpIn,_s_szOrg); // FAILED - put back original return; } } else { lpb[ilen] = '0'; // change to a ZERO icnt++; // count the '9' backup - well maybe count '0's added break; } } // assemble it back strcpy(lpIn,lpd); strcat(lpIn,lpb); if(*lpe) strcat(lpIn,"."); strcat(lpIn,lpe); } while( dir_isvalidfile( lpIn ) ); } } VOID Set_Zip_Info( PTSTR pb ) { DWORD len = strlen(pb); if( len == 0 ) return; if( g_dwZipMax ) { if((len + 1) < g_dwZipMax) { strcpy(g_pZipInfo,pb); } else { DWORD nl = (g_dwZipMax + len + 256); PTSTR pn = MALLOC(nl); if(pn) { if(g_pZipInfo)MFREE(g_pZipInfo); g_pZipInfo = pn; strcpy(g_pZipInfo,pb); g_dwZipMax = nl; } } } else { g_dwZipMax = strlen(pb) + 1; if(g_dwZipMax < 1024) g_dwZipMax = 1024; g_pZipInfo = MALLOC(g_dwZipMax); if(g_pZipInfo) { strcpy(g_pZipInfo,pb); } else { g_dwZipMax = 0; } } } VOID Add_Zip_Info( PTSTR pb ) { DWORD len = strlen(pb); if( len == 0 ) return; if( g_dwZipMax && g_pZipInfo ) { DWORD len2 = strlen(g_pZipInfo); if((len2 + len + 1) < g_dwZipMax) { strcat(g_pZipInfo,pb); } else { DWORD nl = (len2 + len + 256); PTSTR pn = MALLOC(nl); if(pn) { strcpy(pn,g_pZipInfo); strcat(pn,pb); MFREE(g_pZipInfo); g_pZipInfo = pn; g_dwZipMax = nl; } } } else { Set_Zip_Info(pb); } } /////////////////////////////////////////////////////////////////////////////// // FUNCTION : do_ziplist // Return type: LONG // Argument : PEDITARGS pe // Description: Input in pe->pCmd should have an @file-name in it. // This will be extracted, and used as the LIST name // for the OUTPUT of *** ALL FILES LIKELY TO BE EFFECTED BY AN UPDATE *** // This is a list output, using a FIXED set of 'compare' criteria // At present this INCLUDES everything ONLY in right side, since the // introduction of the DELETE function means these can be DELETED. // FIX20021115 - Unless -NA = zip all is used, then EXCLUDE RIGHT ONLY // files of the group: *.obj;*.sbr;*.idb;*.pdb;*.ncb;*.opt /////////////////////////////////////////////////////////////////////////////// LONG do_ziplist( PEDITARGS pe ) { PVIEW view = pe->view; DWORD dwo = pe->option; int selection = pe->selection; LPTSTR pcmd = &pe->cCmdLine[0]; LPTSTR lpb = &gszTmpBuf[0]; // COMPITEM item; // LPSTR fname; // static char cmdline[256]; // int currentline; // char * pOut = cmdline; char * pOut = pcmd; char * pIn = pe->pCmd; // like "Zip8 -a tempz001.zip @tempz001.lst" // DWORD dwi = gdwFileOpts; // get the WRITE FILE LIST options //STARTUPINFO si; // STARTUPINFO sSI; // STARTUPINFO * psi = &sSI; // PROCESS_INFORMATION pi; //COMPLIST cl = view_getcomplist(current_view); COMPLIST cl = pe->cl; char * p; LONG cnt = 0; // p = strchr(pIn,'@'); p = strrchr(pIn,'@'); if(p) { p++; getnxtlist(p); // role the FILENAME numerically to it is UNIQUE strcpy(pcmd,p); // and MAKE that the *** ZIP INPUT LIST FILE *** } else { strcpy(pcmd,"tempz001.lst"); // then we will CREATE a name to use } //dwi = gdwFileOpts; // use to when writing OUTLINE list of files //if( ( dwi & (INCLUDE_SAME | INCLUDE_NEWER | INCLUDE_OLDER | INCLUDE_LEFTONLY | // INCLUDE_RIGHTONLY ) ) == 0 ) //dwo = ( dwi & (INCLUDE_SAME | INCLUDE_NEWER | INCLUDE_OLDER | INCLUDE_LEFTONLY | // INCLUDE_RIGHTONLY ) ); //if( dwo == 0 ) if(( dwo & (INCLUDE_SAME | INCLUDE_ALLDIFF | INCLUDE_LEFTONLY | INCLUDE_RIGHTONLY) ) == 0 ) { // then there can be NO LIST! // * caller should have checked this BEFORE now ... return 0xfDead000; // note NEGATIVE error value } // dwo |= FULL_NAMES; // dwo |= FRIGHT_NAME; // dwo &= ~(FLEFT_NAME | COMBINED_NAME); cnt = complist_writelist( cl, pcmd, dwo, FALSE, FALSE ); if( cnt == 0 ) { // nothing found matching the 'compare' criteria // * caller should have checked this BEFORE now ... return 0xf0Dead00; // note negative } else { //LPTSTR lpb = &gszTmpBuf[0]; // success in writing a LIST file LPTSTR lpinp = &pe->sCmdLn.szInp[0]; sprintf(lpb, "Written list file [%s] ..."MEOR, lpinp); sprtf(lpb); Add_Zip_Info(lpb); // LPTSTR pinp = g_sZipCmd.szInp; // if( strcmp( pinp, pcmd ) ) // { // strcpy(pinp, pcmd); // 3 = input file name // if( strcmp(lpinp,pinp) ) // { // gbChgZp2[3] = TRUE; // k++; // } // } } return cnt; } //typedef struct tagCMDLN { // TCHAR szCmd[264]; // TCHAR szSws[264]; // TCHAR szZip[264]; // TCHAR szInp[264]; //}CMDLN, * PCMDLN; static EDITARGS _s_sActCmd; static TCHAR _s_szActCmd[264]; static TCHAR _s_szNewCmd[264]; extern TCHAR szZipCmd[]; // [264] = {"c:\\mdos\\Zip8.bat -a -P -o TEMPZ001.zip @tempz001.lst"}; extern BOOL bChgZp; // = FALSE; /////////////////////////////////////////////////////////////////////////////// // FUNCTION : ReSetCmdLnStruc // Return type: BOOL // Argument : PEDITARGS pe // Description: Transfer the ZIPUP components, in an allocated edit arguments // to the FIXED WORK structure, to be later written to the INI file // NOTE: It set the CHANGE flag for each of up to 8 items // Presently only 4 components are used for this ZIP command. // 1=Runtime.exe, like "C:\\mdos\\Zip8.bat" // 2=Switches, like -a minimum - maybe add if none // 3=Output ZIP file name, like TEMPZ001.zip // 4=Input list file, preceeded by an '@' character, like @tempz001.lst /////////////////////////////////////////////////////////////////////////////// BOOL ReSetCmdLnStruc( PEDITARGS pe ) { // PCMDLN pcmdln = &g_sZipCmd; // g_sZipArgs.sCmdLn // sFW.fw_sZipCmd PEDITARGS pe2 = &g_sZipArgs; // sFW.fw_sZipArgs // g_- Arguments for ZIP of a LIST LPTSTR plst = &pe->cCmdLine[0]; // NEW command line components - for this zipped list LPTSTR lpcmd = &pe->sCmdLn.szCmd[0]; LPTSTR lpswi = &pe->sCmdLn.szSws[0]; LPTSTR lpzip = &pe->sCmdLn.szZip[0]; LPTSTR lpinp = &pe->sCmdLn.szInp[0]; LPTSTR lpcmp = &pe->sCmdLn.szCmp[0]; LPTSTR lpenv = &pe->sCmdLn.szEnv[0]; // INI command line components - output as LastZip LPTSTR pcmd = &pe2->sCmdLn.szCmd[0]; LPTSTR pswi = &pe2->sCmdLn.szSws[0]; LPTSTR pzip = &pe2->sCmdLn.szZip[0]; LPTSTR pinp = &pe2->sCmdLn.szInp[0]; LPTSTR penv = &pe2->sCmdLn.szEnv[0]; LPTSTR pcmp = &pe2->sCmdLn.szCmp[0]; //LPTSTR pccmd = _s_szNewCmd; LPTSTR pccmd = _s_szActCmd; LPTSTR picmd = szZipCmd; LPTSTR p; INT i, k; i = k = 0; if( g_bZipAll ) picmd = szZipCmd; else picmd = szZipCmd2; // 0 = command/exe to run if( strcmp(lpcmd,pcmd) ) { strcpy(pcmd, lpcmd); gbChgZp2[i] = TRUE; k++; } i++; // 1 = switches to apply if( strcmp(lpswi,pswi) ) { strcpy(pswi, lpswi); gbChgZp2[i] = TRUE; k++; } i++; // 2 = zip file name to write if( strcmp(lpzip,pzip) ) { strcpy(pzip, lpzip); gbChgZp2[i] = TRUE; k++; } i++; // 3 = input file name p = lpinp; if( *p == '@' ) { p++; if( strcmp( p, plst ) ) { strcpy( p, plst ); } } if( strcmp(lpinp,pinp) ) { strcpy(pinp, lpinp); gbChgZp2[i] = TRUE; k++; } i++; // 4 = env not used if( strcmp(lpenv,penv) ) { gbChgZp2[i] = TRUE; k++; } if( GetListMember( lpcmp, 0 ) ) { if( strcmp( lpcmp, pcmp ) ) { strcpy(pcmp, lpcmp); gbChgZp2[ZP_DIRCMP] = TRUE; } } // up to 7 = total 8 reserved // Then the CHANGE @Input file name //if( strcmp( _s_szNewCmd, szZipUp ) ) // [264] = {"c:\\mdos\\Zip8.bat -a -P -o TEMPZ001.zip @tempz001.lst"}; if( strcmp( pccmd, picmd ) ) // [264] = {"c:\\mdos\\Zip8.bat -a -P -o TEMPZ001.zip @tempz001.lst"}; { //strcpy( szZipUp, _s_szNewCmd ); //strcpy( picmd, pccmd ); p = GetStgBuf(); strcpy(p, pcmd); if( *pswi ) { strcat(p," "); strcat(p,pswi); } strcat(p," "); strcat(p, pzip); strcat(p, " "); strcat(p, pinp); if( strcmpi( picmd, p ) ) { chkme( "WARNING: This update was in-buffer!"MEOR ); strcpy(picmd, p); } bChgZp = TRUE; k++; } return k; } /////////////////////////////////////////////////////////////////////////////// // FUNCTION : SetCmdLnStruc // Return type: BOOL // Argument : PEDITARGS pe // Description: Process of splitting a single command line into ZIPUP sCmdLn // components. It is NOT really complete, but it // works on a 'simple' zip commands ... /////////////////////////////////////////////////////////////////////////////// BOOL SetCmdLnStruc( PEDITARGS pe ) { LPTSTR lpcmd = &pe->sCmdLn.szCmd[0]; LPTSTR lpswi = &pe->sCmdLn.szSws[0]; LPTSTR lpzip = &pe->sCmdLn.szZip[0]; LPTSTR lpinp = &pe->sCmdLn.szInp[0]; LPTSTR lpenv = &pe->sCmdLn.szEnv[0]; // PCMDLN pcmdln = &g_sZipCmd; // g_sZipArgs.sCmdLn // sFW.fw_sZipCmd LPTSTR pcmd = pe->pCmd; // get single command line // to be broken into components - Cmd, Sws, Zip, Inp, etc ... INT c, i, ilen, k, sk; // *** ZERO ALL COMPONENTS *** *lpcmd = 0; *lpswi = 0; *lpzip = 0; *lpinp = 0; *lpenv = 0; ilen = strlen(pcmd); strcpy( _s_szActCmd, pcmd ); // COPY current single line into ACTIVE command sk = 0; for( i = 0; i < ilen; i++ ) { c = pcmd[i]; if( c > ' ' ) { if(( c == '-') || ( c == '/' ) || ( c == '@' ) ) { // switch or INPUT file if( c == '@' ) { if( *lpinp ) return FALSE; k = 0; lpinp[k++] = (TCHAR)c; i++; for( ; i < ilen; i++ ) { c = pcmd[i]; if( c > ' ' ) lpinp[k++] = (TCHAR)c; else break; } lpinp[k] = 0; } else // command line SWITCH { // switch if(sk) // if previous lpswi[sk++] = ' '; // add a space lpswi[sk++] = (TCHAR)c; // then begin switch i++; // accumulation while > ' ' for( ; i < ilen; i++ ) { c = pcmd[i]; if( c > ' ' ) lpswi[sk++] = (TCHAR)c; else break; } lpswi[sk] = 0; // zero terminate SWITCH accumulation } } #ifdef ADDENVEXP2 else if( ( c == ':' ) && strchr( &pcmd[i+1], ':' ) ) { // we have :something: // assume an environment variable i++; k = 0; for( ; i < ilen; i++ ) { c = pcmd[i]; if( ( c > ' ' ) && ( c != ':' ) ) lpenv[k++] = (TCHAR)c; // accumulate chars else break; } lpenv[k] = 0; // close item if( c == ':' ) { } } #endif // #ifdef ADDENVEXP2 else { // not switch or input if( *lpcmd == 0 ) { // FIRST non-switched command is the runtime k = 0; // start counter lpcmd[k++] = (TCHAR)c; // insert first command i++; // TO NEXT CHAR, untill <= ' ' for( ; i < ilen; i++ ) { c = pcmd[i]; if( c > ' ' ) lpcmd[k++] = (TCHAR)c; else break; } lpcmd[k] = 0; // now have a COMMAND } else if( *lpzip == 0 ) { // SECOND non-switched command is OUTPUT zipup file name k = 0; // start counter lpzip[k++] = (TCHAR)c; // inser first command i++; // until <= ' ' for( ; i < ilen; i++ ) { c = pcmd[i]; if( c > ' ' ) lpzip[k++] = (TCHAR)c; else break; } lpzip[k] = 0; // zero-terminate ZIP file name } else { // have filled command and zip inputs return FALSE; } } } } if(( *lpzip ) && ( *lpcmd ) ) { getnxtlist(lpzip); strcpy(pcmd, lpcmd); strcat(pcmd, " "); if( *lpswi ) { strcat(pcmd,lpswi); strcat(pcmd," "); } strcat(pcmd, lpzip); strcat(pcmd, " " ); strcat(pcmd, lpinp); strcpy( _s_szNewCmd, pcmd ); memcpy( &_s_sActCmd, pe, sizeof(EDITARGS) ); // get ZIP output file name, if none from previous // ************************ strcpy( g_szCurZip, lpzip ); // { // PEDITARGS pe2 = &g_sZipArgs; // LPTSTR pzip = &pe2->sCmdLn.szZip[0]; // if( *pzip == 0 ) // { // strcpy(pzip,lpzip); // } // } return TRUE; } return FALSE; } #define ZIP_OK 0x0Abceed #define LIST_OK 0x0Abc000 DWORD LaunchZipCmd( PEDITARGS pe ) { LPTSTR pcmd = pe->pCmd; static STARTUPINFO _s_sSI; STARTUPINFO * psi = &_s_sSI; PROCESS_INFORMATION pi; PTHREADARGS pta = (PTHREADARGS)pe->pThreadArgs; // extract thread arguments LPTSTR lpb = &pta->ta_szTmpBuf[0]; pe->dwError = 0; // no error /* Launch the process and waits for it to complete */ ZeroMemory(psi, sizeof(STARTUPINFO)); psi->cb = sizeof(STARTUPINFO); //psi->lpReserved = NULL; //psi->lpReserved2 = NULL; //psi->cbReserved2 = 0; //si.lpTitle = (LPSTR)cmdline; psi->lpTitle = pcmd; //psi->lpDesktop = (LPTSTR)NULL; psi->dwFlags = STARTF_FORCEONFEEDBACK; // sprtf("CMD=[%s]"MEOR, pcmd); // output the COMMAND LINE passed strcpy(lpb,"CMD=["); strcat(lpb,pcmd); strcat(lpb,"]"MEOR); prt(lpb); Add_Zip_Info(lpb); // si.cb = sizeof(STARTUPINFO); // si.lpReserved = NULL; // si.lpReserved2 = NULL; // si.cbReserved2 = 0; // //si.lpTitle = (LPSTR)cmdline; // si.lpTitle = pcmd; // si.lpDesktop = (LPTSTR)NULL; // si.dwFlags = STARTF_FORCEONFEEDBACK; if( !CreateProcess(NULL, pcmd, // cmdline, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, (LPTSTR)NULL, psi, &pi) ) { LPTSTR lpe = &pe->cErrMsg[0]; pe->dwError = GetLastError(); // get error indications sprintf(lpb, "ERROR: YEEK! Failed to launch zip8 batch!" ); SBSetTimedTxt(lpb, 45, FALSE ); sprintf(lpe, "ERROR: YEEK! Failed to launch zip8 batch!"MEOR "with CMD[%s]" MEOR "Error id = %d (%#x)", pcmd, pe->dwError, pe->dwError ); Add_Zip_Info(lpe); Add_Zip_Info(MEOR); sprtf( MEOR"%s"MEOR, lpe ); if( pe->bDoMB ) { //MB(hwndClient, "YEEK! Failed to launch zip8 batch!!!", MB(hwndClient, lpe, APPNAME, MB_ICONSTOP|MB_OK); } //goto error; if( pe->dwError ) return pe->dwError; else return 0x000Dead; } else { strcpy(lpb,"Thread entering WaitForSingleObject - INFINITE wait"); SBSetTimedTxt(lpb, -1, FALSE); Add_Zip_Info(lpb); Add_Zip_Info(MEOR); g_bInZipWait = TRUE; // **************************************************************** /* wait for completion. (hopefully) thread will be blocked */ pe->dwWait = WaitForSingleObject(pi.hProcess, INFINITE); g_bInZipWait = FALSE; // **************************************************************** /* close process and thread handles */ CloseHandle(pi.hThread); CloseHandle(pi.hProcess); pe->dwError = 0; // no error switch(pe->dwWait) { case WAIT_ABANDONED: pe->dwError = 0x0Abad0ed; break; case WAIT_OBJECT_0: pe->bZipOk = TRUE; pe->dwError = ZIP_OK; break; case WAIT_TIMEOUT: pe->dwError = 0x0ffff; break; case WAIT_FAILED: pe->dwError = GetLastError(); break; default: pe->dwError = 0x0fffff; break; } ReSetCmdLnStruc( pe ); // get the ZIP COMMAND line components sprintf(lpb,"Thread exit WaitForSingleObject %s = %#X ", ( pe->bZipOk ? "ok" : "ERROR" ), pe->dwError ); SBSetTimedTxt(lpb, -1, FALSE); Add_Zip_Info(lpb); Add_Zip_Info(MEOR); sprtf("%s"MEOR,lpb); } // error: // gmem_free(hHeap, (LPSTR) pe, sizeof(EDITARGS), "do_zipthread" ); return pe->dwError; // return the actions } LPTSTR GetPEWaitStg( PEDITARGS pe ) { LPTSTR lpe = GetStgBuf(); *lpe = 0; switch(pe->dwWait) { case WAIT_ABANDONED: strcpy(lpe,"Wait Abandoned ... mutex not signaled"); break; case WAIT_OBJECT_0: //pe->bZipOk = TRUE; strcpy(lpe, "mutext of object signaled - bZipOk"); break; case WAIT_TIMEOUT: strcpy(lpe,"Wait Timeout ... mutex not signaled"); break; case WAIT_FAILED: pe->dwError = GetLastError(); sprintf(lpe,"Wait Error: %d ... mutex not signaled", pe->dwError ); break; default: sprintf(lpe,"Wait not listed! %d (%#x)", pe->dwWait,pe->dwWait); break; } return lpe; } PEDITARGS GetZipMem( PTHREADARGS pta ) { COMPLIST cl; PEDITARGS pe; cl = view_getcomplist(current_view); if( cl == 0 ) return 0; pe = (PEDITARGS) gmem_get(hHeap, sizeof(EDITARGS), "do_ziplist" ); if( !pe ) return 0; ZeroMemory(pe, sizeof(EDITARGS)); pe->view = current_view; //pe->option = (INCLUDE_SAME | INCLUDE_NEWER | INCLUDE_OLDER ); pe->option = INCLUDE_ALLDIFF; // forget SAME, only NEW or OLDER pe->option |= INCLUDE_RIGHTONLY; // and items that may be DELETED!!! 14Mch2002 pe->option |= FULL_NAMES | FRIGHT_NAME | INCLUDE_HEADER; //dwo &= ~(FLEFT_NAME | COMBINED_NAME); pe->selection = giSelection; // copy the GLOBAL selection row (-1 if NOT) if( g_bZipAll ) pe->pCmd = szZipCmd; // get the INI command else { pe->pCmd = szZipCmd2; // get the INI command2, with EXCLUSION input file } //pe->cl = view_getcomplist(current_view); pe->cl = cl; // view_getcomplist(current_view); pe->pThreadArgs = pta; // pass on the THREAD ARGUMENT pointer // =============================================================== // Desc: Process of splitting a single command line into ZIPUP sCmdLn SetCmdLnStruc( pe ); // split the ZIP COMMAND line into components // =============================================================== return pe; } INT WriteZIPList(PTHREADARGS pta, DWORD dwt_NOT_USED ) // #ifdef ADD_ZIP_SUPPORT { LONG lg; BOOL bRet = 1; PEDITARGS pe; // = GetZipMem(); LPTSTR lpb = &pta->ta_szTmpBuf[0]; // setup a work buffer // allocated if called from a THREAD, or GLOBAL if from a command. pe = GetZipMem(pta); if( !pe ) return 0; pe->pThreadArgs = pta; Set_Zip_Info("Current Work Directory: "); Add_Zip_Info(GetCWDStg()); Add_Zip_Info(MEOR); lg = do_ziplist( pe ); if( lg > 0 ) { LPTSTR lps = GetPEWaitStg( pe ); sprintf(lpb, "Zip list done - %ld files. *Mutex* = [%s]", lg, lps ); SBSetTimedTxt(lpb, 20, FALSE ); sprtf( "Zip list done - %ld files."MEOR " *Mutex* = [%s]"MEOR, lg, lps ); } else { // if(( lg == 0 ) || ( lg < 0 ) ) if( lg == 0xf0Dead00 ) { sprintf(lpb, "No ZIP made, since NO overwrites or deletes available!" ); SBSetTimedTxt(lpb, 20, FALSE ); sprtf("%s"MEOR,lpb); } //gmem_free(hHeap, (LPSTR) pe, sizeof(EDITARGS), "do_ziplist" ); //return 0; bRet = 0; } Add_Zip_Info( lpb ); Add_Zip_Info( MEOR ); if( bRet ) { if( LaunchZipCmd( pe ) != ZIP_OK ) bRet = 0; } if( bRet ) { // success should mean a valid LIST file, and a valid ZIP // could TEST for existance of ZIP components memcpy( &g_sZAwd_init, pe, sizeof(EDITARGS) ); // keep the RUNTIME arguments } gmem_free(hHeap, (LPSTR) pe, sizeof(EDITARGS), "do_ziplist" ); if(g_pZipInfo) { MB(hwndClient, g_pZipInfo, APPNAME, MB_ICONINFORMATION|MB_OK); MFREE(g_pZipInfo); g_dwZipMax = 0; g_pZipInfo = 0; } return bRet; } // do_zipup LONG do_zipup_NOT_USED( PEDITARGS pe ) { PVIEW view = pe->view; int option = pe->option; int selection = pe->selection; LPTSTR pcmd = &pe->cCmdLine[0]; COMPITEM item; // LPSTR fname; // static char cmdline[256]; int currentline; // char * pOut = cmdline; char * pOut = pcmd; // char * pIn = szZipUp; char * pIn = pe->pCmd; // like "Zip8 -a tempz001.zip @tempz001.lst" DWORD dwi = gdwFileOpts; // get the WRITE FILE LIST options DWORD dwo; //STARTUPINFO si; STARTUPINFO sSI; STARTUPINFO * psi = &sSI; PROCESS_INFORMATION pi; //COMPLIST cl = view_getcomplist(current_view); COMPLIST cl = pe->cl; char * p; p = strchr(pIn,'@'); if(p) { p++; strcpy(pcmd,p); } else { strcpy(pcmd,"tempz001.lst"); } //dwi = gdwFileOpts; // use to when writing OUTLINE list of files //if( ( dwi & (INCLUDE_SAME | INCLUDE_NEWER | INCLUDE_OLDER | INCLUDE_LEFTONLY | // INCLUDE_RIGHTONLY ) ) == 0 ) dwo = ( dwi & (INCLUDE_SAME | INCLUDE_NEWER | INCLUDE_OLDER | INCLUDE_LEFTONLY | INCLUDE_RIGHTONLY ) ); if( dwo == 0 ) { return 0x0Dead000; } dwo |= FULL_NAMES; dwo |= FRIGHT_NAME; dwo &= ~(FLEFT_NAME | COMBINED_NAME); option = complist_writelist( cl, pcmd, dwo, FALSE, FALSE ); if( option == 0 ) { return 0x0Dead00; } *pcmd = 0; // NOTE: Returns EXPANDED item if expanded, else // only if the 'selection' row is VALID item = view_getitem(view, selection); if( item == NULL ) { // return -1; } // fname = compitem_getfilename(item, option); // if( 0 == fname ) { // MB(hwndClient, LoadRcString(IDS_FILE_DOESNT_EXIST), // APPNAME, MB_ICONSTOP|MB_OK); // goto error; } // switch ( option ) // { currentline = 1; // break; // } while( *pIn ) { switch( *pIn ) { case '%': pIn++; switch ( *pIn ) { // case 'p': // strcpy( (LPTSTR)pOut, fname ); // while ( *pOut ) // pOut++; // break; case 'l': _ltoa( currentline, pOut, 10 ); while ( *pOut ) pOut++; break; default: if (IsDBCSLeadByte(*pIn) && *(pIn+1)) { *pOut++ = *pIn++; } *pOut++ = *pIn; break; } pIn++; break; default: if (IsDBCSLeadByte(*pIn) && *(pIn+1)) { *pOut++ = *pIn++; } *pOut++ = *pIn++; break; } } /* Launch the process and waits for it to complete */ ZeroMemory(psi, sizeof(STARTUPINFO)); psi->cb = sizeof(STARTUPINFO); //psi->lpReserved = NULL; //psi->lpReserved2 = NULL; //psi->cbReserved2 = 0; //si.lpTitle = (LPSTR)cmdline; psi->lpTitle = pcmd; //psi->lpDesktop = (LPTSTR)NULL; psi->dwFlags = STARTF_FORCEONFEEDBACK; // si.cb = sizeof(STARTUPINFO); // si.lpReserved = NULL; // si.lpReserved2 = NULL; // si.cbReserved2 = 0; // //si.lpTitle = (LPSTR)cmdline; // si.lpTitle = pcmd; // si.lpDesktop = (LPTSTR)NULL; // si.dwFlags = STARTF_FORCEONFEEDBACK; if( !CreateProcess(NULL, pcmd, // cmdline, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, (LPTSTR)NULL, psi, &pi)) { LPTSTR lpe = &pe->cErrMsg[0]; pe->dwError = GetLastError(); // get error indications sprintf(lpe, "ERROR: YEEK! Failed to launch zip8 batch!"MEOR "with CMD[%s]" MEOR "Error id = %d (%#x)", pcmd, pe->dwError, pe->dwError ); sprtf( MEOR"%s"MEOR, lpe ); if( pe->bDoMB ) { //MB(hwndClient, "YEEK! Failed to launch zip8 batch!!!", MB(hwndClient, lpe, APPNAME, MB_ICONSTOP|MB_OK); } goto error; } /* wait for completion. */ WaitForSingleObject(pi.hProcess, INFINITE); /* close process and thread handles */ CloseHandle(pi.hThread); CloseHandle(pi.hProcess); /* finished with the filename. deletes it if it was a temp. */ //compitem_freefilename(item, option, fname); /* * refresh cached view always . A common trick is to edit the * composite file and then save it as a new left or right file. * Equally the user can edit the left and save as a new right. */ /* We want to force both files to be re-read, but it's not a terribly * good idea to throw the lines away on this thread. Someone might * be reading them on another thread! */ /* file_discardlines(compitem_getleftfile(item)) */ /* file_discardlines(compitem_getrightfile(item)) */ /* force the compare to be re-done */ //PostMessage(hwndClient, WM_COMMAND, IDM_UPDATE, (LONG)item); error: gmem_free(hHeap, (LPSTR) pe, sizeof(EDITARGS), "do_zipthread" ); return 0x0Face000; } #if 0 void do_zipthread(PVIEW view, int option) { PEDITARGS pe; HANDLE thread; CC sCC; PCC pcc = &sCC; // DWORD dwi = gdwFileOpts; // get the WRITE FILE LIST options DWORD dwi = (DWORD)option; // combined with outline_include COMPLIST cl = view_getcomplist(view); if( !cl ) return; //if(dwi) { // just want to write out a list of names // options = gdwFileOpts ZeroMemory(pcc,sizeof(CC)); // zero the memory block pcc->bUseOpt = TRUE; pcc->dwopts = dwi; complist_countlistable( pcc ); if( pcc->cnt2 == 0 ) { return; // nothing to do } } sprtf( "Starting ZIPUP of %d items ..."MEOR, pcc->cnt2 ); pe = (PEDITARGS) gmem_get(hHeap, sizeof(EDITARGS), "do_zipthread" ); ZeroMemory(pe, sizeof(EDITARGS)); pe->view = view; pe->option = option; pe->selection = giSelection; // copy the GLOBAL selection row (-1 if NOT) pe->pCmd = szZipCmd; pe->cl = cl; //pe->bDoMB = FALSE; thread = NULL; #ifdef USETHDTD2 thread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)do_zipup, (LPVOID) pe, 0, &threadid ); #endif // USETHDTD2 if (thread == NULL) { /* The createthread failed, do without the extra thread - just * call the function synchronously */ do_zipup(pe); } else { CloseHandle(thread); // get thread rolling Sleep(10); // and some CPU } } /* do_zipthread */ #endif // 0 INT_PTR Do_ID_FILE_CREATEZIPFILE( VOID ) // #ifdef ADD_ZIP_SUPPORT { INT_PTR iret = Do_IDM_EDITZIPUP(); return iret; } /////////////////////////////////////////////////////////////////// #endif // #ifdef ADD_ZIP_SUPPORT // ZIP file support // ****************************** // eof - dc4wZip.c
27.989544
112
0.476414
1c5557b4bcbc858a95e025bee529c027d0c9502b
7,591
c
C
IntelEdison/1.0.2/src/Application.c
sorphin/traffic-light-system
c4422e860a8498ae8f64f11bb4fab4294e6be8d7
[ "MIT" ]
null
null
null
IntelEdison/1.0.2/src/Application.c
sorphin/traffic-light-system
c4422e860a8498ae8f64f11bb4fab4294e6be8d7
[ "MIT" ]
null
null
null
IntelEdison/1.0.2/src/Application.c
sorphin/traffic-light-system
c4422e860a8498ae8f64f11bb4fab4294e6be8d7
[ "MIT" ]
1
2020-11-27T00:58:42.000Z
2020-11-27T00:58:42.000Z
/* * Application.c * * Created on: Jan 24, 2016 * Author: user */ #include <stdio.h> #include <stdlib.h> #include "mraa.h" #include "Application.h" #include "Serial.h" #include "Utility.h" #include "MCP23017.h" #include "MAX6958.h" void Variable_Assign(mraa_i2c_context structure, uint16_t input) { junction temp_cross; temp_cross.northeast = 0; temp_cross.southwest = 0; temp_cross.northeast |= ((input & 0x0FC0) >> 6); temp_cross.southwest |= (input & 0x003F); IO_Expander_Write(structure, MCP23017_GPIOA_ADDR, temp_cross.northeast); // Write cross.northeast to GPIOA register delay_microseconds(10); IO_Expander_Write(structure, MCP23017_GPIOB_ADDR, temp_cross.southwest); // Write cross.southwest to GPIOB register } void Light_Change(mraa_i2c_context structure, uint16_t input, uint8_t junc, uint8_t phase) { uint8_t i; uint16_t temp, final; switch(junc) { case 1: temp = 0x0800; for(i = 0; i < phase; i++) { temp >>= 1; } final = (input & 0xF1FF) | temp; // Case 1 0000XXX000000000 (Bit 9-11) break; case 2: temp = 0x0100; for(i = 0; i < phase; i++) { temp >>= 1; } final = (input & 0xFE3F) | temp; // Case 2 0000000XXX000000 (Bit 6-8) break; case 3: temp = 0x0020; for(i = 0; i < phase; i++) { temp >>= 1; } final = (input & 0xFFC7) | temp; // Case 3 0000000000XXX000 (Bit 3-5) break; case 4: temp = 0x0004; for(i = 0; i < phase; i++) { temp >>= 1; } final = (input & 0xFFF8) | temp; // Case 4 0000000000000XXX (Bit 0-2) break; } Variable_Assign(structure, final); } void Traffic_Initial(mraa_i2c_context structure, uint16_t temp_input) { Light_Change(structure, temp_input, NORTH, RED); Light_Change(structure, temp_input, EAST, RED); Light_Change(structure, temp_input, SOUTH, RED); Light_Change(structure, temp_input, WEST, RED); } void Traffic_Run(mraa_i2c_context structure, uint16_t temp_input, uint8_t temp_junc, uint8_t temp_time) { Light_Change(structure, temp_input, temp_junc, GREEN); delay_seconds(temp_time); Light_Change(structure, temp_input, temp_junc, YELLOW); delay_seconds(2); Light_Change(structure, temp_input, temp_junc, RED); delay_microseconds(100); } void Traffic_Mode(mraa_i2c_context structure, uint16_t input, uint8_t mode, direction time) { switch(mode) { case NORTH: Traffic_Run(structure, input, NORTH, time.north); break; case EAST: Traffic_Run(structure, input, EAST, time.east); break; case SOUTH: Traffic_Run(structure, input, SOUTH, time.south); break; case WEST: Traffic_Run(structure, input, WEST, time.west); break; } } uint8_t Priority_Sort(direction priority) { uint8_t i, temp_priority, temp_direction; uint8_t priority_array[4]; uint8_t direction_array[4]; priority_array[0] = priority.north; priority_array[1] = priority.east; priority_array[2] = priority.south; priority_array[3] = priority.west; direction_array[0] = NORTH; direction_array[1] = EAST; direction_array[2] = SOUTH; direction_array[3] = WEST; for(i = 0; i < 4; i++) { if (priority_array[i] < priority_array[i+1]) { temp_priority = priority_array[i]; priority_array[i] = priority_array[i+1]; priority_array[i+1] = temp_priority; temp_direction = direction_array[i]; direction_array[i] = direction_array[i+1]; direction_array[i+1] = temp_direction; } } return *direction_array; } void System_Run(void) { uint8_t i, mode, final_direction[4]; static uint8_t first = 1; uint16_t initial_state = 0x0249; direction time; mraa_init(); mraa_i2c_context i2c; if(first == 1) { mode = 1; } switch(mode) { case 1: i2c = I2C_Pin(6); // Arduino breakout board only have bus 6 I2C I2C_Frequency(i2c, 1); IO_Expander_Init(i2c); // Seven_Segment_Driver_Init(i2c); IO_Expander_Write(i2c, MCP23017_GPIOA_ADDR, 0x09); // Set all to red light IO_Expander_Write(i2c, MCP23017_GPIOB_ADDR, 0x09); // Set all to red light first = 0; mode = 2; case 2: time.north = 2; time.east = 2; time.south = 2; time.west = 2; ///////////////////////// direction time, direction priority // final_direction[] = priority_arrange(priority); final_direction[0] = NORTH; final_direction[1] = EAST; final_direction[2] = SOUTH; final_direction[3] = WEST; // Traffic_Initial(structure, initial_state); for(i = 0;i < 4; i++) { Traffic_Mode(i2c, initial_state, final_direction[i], time); // delay_microseconds(1); // Seven_Segment_Driver_Show(i2c, i, 1); // delay_microseconds(1); // Seven_Segment_Driver_Show(i2c, i, 2); // delay_microseconds(1); // Seven_Segment_Driver_Show(i2c, i, 3); // delay_microseconds(1); // Seven_Segment_Driver_Show(i2c, i, 4); } ////////////////////////// break; } } void Seven_Segment_Driver_Test(mraa_i2c_context structure, uint8_t value) { Seven_Segment_Driver_Show(structure, value, 1); Seven_Segment_Driver_Show(structure, value, 2); Seven_Segment_Driver_Show(structure, value, 3); Seven_Segment_Driver_Show(structure, value, 4); // Seven_Segment_Driver_ShowTest(structure, value, value, value, value); } void Seven_Segment_Driver_Show(mraa_i2c_context structure, uint8_t value, uint8_t sequence) { if(sequence == 1) { Seven_Segment_Driver_Write(structure, MAX6958_DIGIT0_ADDR, value); } else if(sequence == 2) { Seven_Segment_Driver_Write(structure, MAX6958_DIGIT1_ADDR, value); } else if(sequence == 3) { Seven_Segment_Driver_Write(structure, MAX6958_DIGIT2_ADDR, value); } else if(sequence == 4) { Seven_Segment_Driver_Write(structure, MAX6958_DIGIT3_ADDR, value); } } void Seven_Segment_Driver_ShowTest(mraa_i2c_context structure, uint8_t content1, uint8_t content2, uint8_t content3, uint8_t content4) { uint8_t rx_tx_buf[5]; rx_tx_buf[0] = MAX6958_DIGIT0_ADDR; // Access to register rx_tx_buf[1] = content1; // Write digit0 rx_tx_buf[2] = content2; // Write digit1 rx_tx_buf[3] = content3; // Write digit2 rx_tx_buf[4] = content4; // Write digit3 MAX6958_Access_Address(structure, MAX6958_I2C_ADDR); mraa_i2c_write(structure, rx_tx_buf, 5); } void Seven_Segment_Driver_Write(mraa_i2c_context structure, uint8_t register_address, uint8_t content) { MAX6958_Access_Address(structure, MAX6958_I2C_ADDR); MAX6958_Register_Write(structure, register_address, content); } void Seven_Segment_Driver_Init(mraa_i2c_context structure) { MAX6958_Access_Address(structure, MAX6958_I2C_ADDR); // Access MAX6958 MAX6958_Register_Write(structure, MAX6958_DECODE_ADDR, 0x0F); // Set digit0-3 in decode mode MAX6958_Register_Write(structure, MAX6958_INTENSITY_ADDR, 0x04); // Set intensity 4/64 brightness MAX6958_Register_Write(structure, MAX6958_SCANLIMIT_ADDR, 0x03); // Set scan limit for 4 digits MAX6958_Register_Write(structure, MAX6958_CONFIG_ADDR, 0x01); // Set normal operation } void IO_Expander_Write(mraa_i2c_context structure, uint8_t register_address, uint8_t content) { MCP23017_Access_Address(structure, MCP23017_I2C_ADDR); MCP23017_Register_Write(structure, register_address, content); } void IO_Expander_Init(mraa_i2c_context structure) { IO_Expander_Write(structure, MCP23017_IOCON_ADDR, 0x28); // Write 0x28 to IOCON register IO_Expander_Write(structure, MCP23017_IODIRA_ADDR, 0xC0); // Set all GPIOA as output pins in IODIRA register except GPIO6, 7 IO_Expander_Write(structure, MCP23017_IODIRB_ADDR, 0xC0); // Set all GPIOB as output pins in IODIRB register except GPIO6, 7 }
25.819728
134
0.71295
2da7c3bf8dc57c799a0e32a97d5208b91bb3344b
9,887
c
C
freebsd5/sys/alpha/pci/apecs.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
1
2019-10-15T06:29:32.000Z
2019-10-15T06:29:32.000Z
freebsd5/sys/alpha/pci/apecs.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
null
null
null
freebsd5/sys/alpha/pci/apecs.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
3
2017-01-09T02:15:36.000Z
2019-10-15T06:30:25.000Z
/*- * Copyright (c) 1998 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* * Copyright (c) 1995, 1996 Carnegie-Mellon University. * All rights reserved. * * Author: Chris G. Demetriou * * Permission to use, copy, modify and distribute this software and * its documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie the * rights to redistribute these changes. */ /* * Additional Copyright (c) 1998 by Andrew Gallatin for Duke University */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: src/sys/alpha/pci/apecs.c,v 1.24 2003/11/17 06:10:14 peter Exp $"); #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/lock.h> #include <sys/malloc.h> #include <sys/module.h> #include <sys/mutex.h> #include <sys/bus.h> #include <machine/bus.h> #include <sys/proc.h> #include <sys/rman.h> #include <sys/interrupt.h> #include <alpha/pci/apecsreg.h> #include <alpha/pci/apecsvar.h> #include <alpha/isa/isavar.h> #include <machine/cpuconf.h> #include <machine/intr.h> #include <machine/intrcnt.h> #include <machine/md_var.h> #include <machine/resource.h> #include <machine/rpb.h> #include <machine/sgmap.h> #include <machine/swiz.h> #include <vm/vm.h> #include <vm/vm_page.h> #define KV(pa) ALPHA_PHYS_TO_K0SEG(pa) static devclass_t apecs_devclass; static device_t apecs0; /* XXX only one for now */ struct apecs_softc { vm_offset_t dmem_base; /* dense memory */ vm_offset_t smem_base; /* sparse memory */ vm_offset_t io_base; /* dense i/o */ vm_offset_t cfg0_base; /* dense pci0 config */ vm_offset_t cfg1_base; /* dense pci1 config */ }; #define APECS_SOFTC(dev) (struct apecs_softc*) device_get_softc(dev) static alpha_chipset_read_hae_t apecs_read_hae; static alpha_chipset_write_hae_t apecs_write_hae; static alpha_chipset_t apecs_swiz_chipset = { apecs_read_hae, apecs_write_hae, }; /* * Memory functions. * * XXX linux does 32-bit reads/writes via dense space. This doesn't * appear to work for devices behind a ppb. I'm using sparse * accesses & they appear to work just fine everywhere. */ static u_int32_t apecs_hae_mem; #define REG1 (1UL << 24) static u_int32_t apecs_set_hae_mem(void *arg, u_int32_t pa) { int s; u_int32_t msb; if (pa >= REG1){ msb = pa & 0xf8000000; pa -= msb; s = splhigh(); if (msb != apecs_hae_mem) { apecs_hae_mem = msb; REGVAL(EPIC_HAXR1) = apecs_hae_mem; alpha_mb(); apecs_hae_mem = REGVAL(EPIC_HAXR1); } splx(s); } return pa; } static u_int64_t apecs_read_hae(void) { return apecs_hae_mem & 0xf8000000; } static void apecs_write_hae(u_int64_t hae) { u_int32_t pa = hae; apecs_set_hae_mem(0, pa); } static int apecs_probe(device_t dev); static int apecs_attach(device_t dev); static int apecs_setup_intr(device_t dev, device_t child, struct resource *irq, int flags, driver_intr_t *intr, void *arg, void **cookiep); static int apecs_teardown_intr(device_t dev, device_t child, struct resource *irq, void *cookie); static device_method_t apecs_methods[] = { /* Device interface */ DEVMETHOD(device_probe, apecs_probe), DEVMETHOD(device_attach, apecs_attach), /* Bus interface */ DEVMETHOD(bus_setup_intr, apecs_setup_intr), DEVMETHOD(bus_teardown_intr, apecs_teardown_intr), { 0, 0 } }; static driver_t apecs_driver = { "apecs", apecs_methods, sizeof(struct apecs_softc), }; #define APECS_SGMAP_BASE (8*1024*1024) #define APECS_SGMAP_SIZE (8*1024*1024) static void apecs_sgmap_invalidate(void) { alpha_mb(); REGVAL(EPIC_TBIA) = 0; alpha_mb(); } static void apecs_sgmap_map(void *arg, bus_addr_t ba, vm_offset_t pa) { u_int64_t *sgtable = arg; int index = alpha_btop(ba - APECS_SGMAP_BASE); if (pa) { if (pa > (1L<<32)) panic("apecs_sgmap_map: can't map address 0x%lx", pa); sgtable[index] = ((pa >> 13) << 1) | 1; } else { sgtable[index] = 0; } alpha_mb(); apecs_sgmap_invalidate(); } static void apecs_init_sgmap(void) { void *sgtable; /* * First setup Window 0 to map 8Mb to 16Mb with an * sgmap. Allocate the map aligned to a 32 boundary. */ REGVAL(EPIC_PCI_BASE_1) = APECS_SGMAP_BASE | EPIC_PCI_BASE_SGEN | EPIC_PCI_BASE_WENB; alpha_mb(); REGVAL(EPIC_PCI_MASK_1) = EPIC_PCI_MASK_8M; alpha_mb(); sgtable = contigmalloc(8192, M_DEVBUF, M_NOWAIT, 0, (1L<<34), 32*1024, (1L<<34)); if (!sgtable) panic("apecs_init_sgmap: can't allocate page table"); REGVAL(EPIC_TBASE_1) = (pmap_kextract((vm_offset_t) sgtable) >> EPIC_TBASE_SHIFT); chipset.sgmap = sgmap_map_create(APECS_SGMAP_BASE, APECS_SGMAP_BASE + APECS_SGMAP_SIZE, apecs_sgmap_map, sgtable); } void apecs_init() { static int initted = 0; static struct swiz_space io_space, mem_space; if (initted) return; initted = 1; swiz_init_space(&io_space, KV(APECS_PCI_SIO)); swiz_init_space_hae(&mem_space, KV(APECS_PCI_SPARSE), apecs_set_hae_mem, 0); busspace_isa_io = (struct alpha_busspace *) &io_space; busspace_isa_mem = (struct alpha_busspace *) &mem_space; chipset = apecs_swiz_chipset; if (platform.pci_intr_init) platform.pci_intr_init(); } static int apecs_probe(device_t dev) { int memwidth; if (apecs0) return ENXIO; apecs0 = dev; memwidth = (REGVAL(COMANCHE_GCR) & COMANCHE_GCR_WIDEMEM) != 0 ? 128 : 64; if(memwidth == 64){ device_set_desc(dev, "DECchip 21071 Core Logic chipset"); } else { device_set_desc(dev, "DECchip 21072 Core Logic chipset"); } apecs_hae_mem = REGVAL(EPIC_HAXR1); isa_init_intr(); apecs_init_sgmap(); device_add_child(dev, "pcib", 0); return 0; } static int apecs_attach(device_t dev) { struct apecs_softc* sc = APECS_SOFTC(dev); apecs_init(); sc->dmem_base = APECS_PCI_DENSE; sc->smem_base = APECS_PCI_SPARSE; sc->io_base = APECS_PCI_SIO; sc->cfg0_base = KV(APECS_PCI_CONF); sc->cfg1_base = NULL; set_iointr(alpha_dispatch_intr); snprintf(chipset_type, sizeof(chipset_type), "apecs"); chipset_bwx = 0; chipset_ports = APECS_PCI_SIO; chipset_memory = APECS_PCI_SPARSE; chipset_dense = APECS_PCI_DENSE; chipset_hae_mask = EPIC_HAXR1_EADDR; bus_generic_attach(dev); return 0; } static void apecs_disable_intr(uintptr_t vector) { int irq; irq = (vector - 0x900) >> 4; mtx_lock_spin(&icu_lock); platform.pci_intr_disable(irq); mtx_unlock_spin(&icu_lock); } static void apecs_enable_intr(uintptr_t vector) { int irq; irq = (vector - 0x900) >> 4; mtx_lock_spin(&icu_lock); platform.pci_intr_enable(irq); mtx_unlock_spin(&icu_lock); } static int apecs_setup_intr(device_t dev, device_t child, struct resource *irq, int flags, driver_intr_t *intr, void *arg, void **cookiep) { int error; /* * the avanti routes interrupts through the isa interrupt * controller, so we need to special case it */ if(hwrpb->rpb_type == ST_DEC_2100_A50) return isa_setup_intr(dev, child, irq, flags, intr, arg, cookiep); error = rman_activate_resource(irq); if (error) return error; error = alpha_setup_intr(device_get_nameunit(child ? child : dev), 0x900 + (irq->r_start << 4), intr, arg, flags, cookiep, &intrcnt[INTRCNT_EB64PLUS_IRQ + irq->r_start], apecs_disable_intr, apecs_enable_intr); if (error) return error; /* Enable PCI interrupt */ mtx_lock_spin(&icu_lock); platform.pci_intr_enable(irq->r_start); mtx_unlock_spin(&icu_lock); device_printf(child, "interrupting at APECS irq %d\n", (int) irq->r_start); return 0; } static int apecs_teardown_intr(device_t dev, device_t child, struct resource *irq, void *cookie) { /* * the avanti routes interrupts through the isa interrupt * controller, so we need to special case it */ if(hwrpb->rpb_type == ST_DEC_2100_A50) return isa_teardown_intr(dev, child, irq, cookie); alpha_teardown_intr(cookie); return rman_deactivate_resource(irq); } DRIVER_MODULE(apecs, root, apecs_driver, apecs_devclass, 0, 0);
25.547804
87
0.727926