file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/184518275.c | #include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
volatile int sigusr1_flag, sigalarm_flag;
static void sigusr1_action(int arg) {
sigusr1_flag = 1;
}
static void sigalarm_action(int arg) {
sigalarm_flag = 1;
}
int main(int argc, char ** argv) {
if (argc != 2) {
fprintf(stderr, "Uso: %s <secs>\n", argv[0]);
return -1;
}
sigset_t sig_set;
struct sigaction sigalarm_struct, sigusr1_struct;
sigusr1_flag = 0;
sigalarm_flag = 0;
sigfillset(&sig_set);
sigdelset(&sig_set, SIGALRM);
sigdelset(&sig_set, SIGUSR1);
sigalarm_struct.sa_handler = sigalarm_action;
sigalarm_struct.sa_mask = sig_set;
sigalarm_struct.sa_flags = 0;
sigusr1_struct.sa_handler = sigusr1_action;
sigusr1_struct.sa_mask = sig_set;
sigusr1_struct.sa_flags = 0;
sigaction(SIGALRM, &sigalarm_struct, NULL);
sigaction(SIGUSR1, &sigusr1_struct, NULL);
alarm(atoi(argv[1]));
printf("El ejecutable se borrará en %d segundos. Si quiere abortar, envíe SIGUSR1 al proceso\n", atoi(argv[1]));
sigsuspend(&sig_set);
if (sigalarm_flag) {
unlink(argv[0]);
printf("Ejecutable borrado\n");
}
else if (sigusr1_flag) {
printf("Se ha cancelado el borrado del archivo\n");
}
else { // Si se ha despertado el proceso y no está activado ningún flag, es por algún error
printf("Se ha producido un error\n");
return -1;
}
return 0;
}
|
the_stack_data/449456.c | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
#include <linux/fiemap.h>
static void syntax(char **argv)
{
fprintf(stderr, "%s filename blkdev\n", argv[0]);
}
static struct fiemap *read_fiemap(int fd)
{
struct fiemap *fiemap;
int extents_size;
if ((fiemap = (struct fiemap *)malloc(sizeof(struct fiemap))) == NULL) {
fprintf(stderr, "Out of memory allocating fiemap\n");
return NULL;
}
memset(fiemap, 0, sizeof(struct fiemap));
fiemap->fm_start = 0;
fiemap->fm_length = ~0; /* Lazy */
fiemap->fm_flags = 0;
fiemap->fm_extent_count = 0;
fiemap->fm_mapped_extents = 0;
/* Find out how many extents there are */
if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0) {
fprintf(stderr, "fiemap ioctl() failed\n");
return NULL;
}
/* Read in the extents */
extents_size = sizeof(struct fiemap_extent) * (fiemap->fm_mapped_extents);
/* Resize fiemap to allow us to read in the extents */
if ((fiemap = (struct fiemap *)realloc(fiemap, sizeof(struct fiemap) + extents_size)) == NULL) {
fprintf(stderr, "Out of memory allocating fiemap\n");
return NULL;
}
memset(fiemap->fm_extents, 0, extents_size);
fiemap->fm_extent_count = fiemap->fm_mapped_extents;
fiemap->fm_mapped_extents = 0;
if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0) {
fprintf(stderr, "fiemap ioctl() failed\n");
return NULL;
}
return fiemap;
}
static off_t compare_extent(int fd1, int fd2, off_t start_offs, size_t len)
{
char buf1[32768], buf2[32768];
off_t offs;
ssize_t res1, res2;
size_t segpos = 0;
offs = lseek(fd1, start_offs, SEEK_SET);
if (offs < 0)
return offs;
offs = lseek(fd2, start_offs, SEEK_SET);
if (offs < 0)
return offs;
while (len > 0) {
const size_t rdsiz = (len > sizeof(buf1)) ? (sizeof buf1) : (len);
res1 = read(fd1, buf1, rdsiz);
res2 = read(fd2, buf2, rdsiz);
if (res1 == res2 && res1 > 0) {
if (memcmp(buf1, buf2, res1) == 0) {
len -= res1;
segpos += res1;
}
else {
return start_offs + segpos + 1;
}
}
else {
return start_offs + segpos + 1;
}
}
return 0;
}
static ssize_t write_all(int fd, const char *buf, ssize_t size)
{
ssize_t res;
while (size > 0 && (res = write(fd, buf, size)) != size) {
if (res < 0 && errno == EINTR)
continue;
else if (res < 0) {
return res;
}
size -= res;
buf += res;
}
return 0;
}
static off_t copy_extent(int fd_dest, int fd_src, off_t start_offs, size_t len)
{
char copy_buf[32768];
off_t offs = lseek(fd_dest, start_offs, SEEK_SET);
if (offs < 0)
return offs;
offs = lseek(fd_src, start_offs, SEEK_SET);
if (offs < 0)
return offs;
while (len > 0) {
const size_t nread = len > sizeof(copy_buf) ? sizeof(copy_buf) : len;
ssize_t rlen = read(fd_src, copy_buf, nread);
if (rlen < 0 && errno == EINTR)
continue;
else if (rlen > 0) {
ssize_t res = write_all(fd_dest, copy_buf, rlen);
if (res == 0) {
len -= rlen;
}
else {
return -1;
}
}
else {
return -1;
}
}
return 0;
}
static int verify_image(const char *image_file, const char *block_device)
{
int fd_sparse, fd_block;
if ((fd_sparse = open(image_file, O_RDONLY)) < 0) {
fprintf(stderr, "Cannot open sparse file %s\n", image_file);
return EXIT_FAILURE;
}
if ((fd_block = open(block_device, O_RDONLY)) < 0) {
fprintf(stderr, "Cannot open block device %s\n", block_device);
close(fd_sparse);
return EXIT_FAILURE;
}
struct fiemap *fiemap;
if (!(fiemap = read_fiemap(fd_sparse))) {
fprintf(stderr, "Unable to read fiemap %s\n", image_file);
close(fd_sparse);
close(fd_block);
return EXIT_FAILURE;
}
printf("File %s verify %d extents:\n", image_file, fiemap->fm_mapped_extents);
printf("#\tOffset Length Verify\n");
off_t result = -1;
for (unsigned i = 0; i < fiemap->fm_mapped_extents; i++) {
result = compare_extent(fd_sparse, fd_block, fiemap->fm_extents[i].fe_logical, fiemap->fm_extents[i].fe_length);
printf("%d:\t%-16.16llx %-16.16llx ", i, fiemap->fm_extents[i].fe_logical, fiemap->fm_extents[i].fe_length);
if (result) {
printf("ERR (%lx)\n", result);
}
else {
printf("OK\n");
}
if (result) {
if (result >= 0) {
fprintf(stderr, "Error: Data mismatch at offset %ld\n", result);
}
else {
perror("System error (Verify):");
}
break;
}
}
close(fd_sparse);
close(fd_block);
free(fiemap);
return (result ? EXIT_FAILURE : EXIT_SUCCESS);
}
static int write_image(const char *image_file, const char *block_device)
{
struct stat sbuf;
if (stat(image_file, &sbuf)) {
perror("System error (stat image_file):");
return EXIT_FAILURE;
}
if (!S_ISREG(sbuf.st_mode)) {
fprintf(stderr, "Error: %s is not a regular file\n", image_file);
return EXIT_FAILURE;
}
if (stat(block_device, &sbuf)) {
perror("System error (stat block_device):");
return EXIT_FAILURE;
}
if (!S_ISBLK(sbuf.st_mode)) {
fprintf(stderr, "Error: %s is not a block device\n", block_device);
return EXIT_FAILURE;
}
int fd_sparse, fd_block;
if ((fd_sparse = open(image_file, O_RDONLY)) < 0) {
fprintf(stderr, "Error: Cannot open sparse file %s\n", image_file);
return EXIT_FAILURE;
}
if ((fd_block = open(block_device, O_WRONLY)) < 0) {
fprintf(stderr, "Error: Cannot open block device %s\n", block_device);
close(fd_sparse);
return EXIT_FAILURE;
}
struct fiemap *fiemap;
if (!(fiemap = read_fiemap(fd_sparse))) {
fprintf(stderr, "Error: Unable to read fiemap %s\n", image_file);
close(fd_block);
close(fd_sparse);
return EXIT_FAILURE;
}
printf("File %s copy %d extents:\n", image_file, fiemap->fm_mapped_extents);
printf("#\tOffset Length Status\n");
off_t result = -1;
for (unsigned i = 0; i < fiemap->fm_mapped_extents; i++) {
result = copy_extent(fd_block, fd_sparse, fiemap->fm_extents[i].fe_logical, fiemap->fm_extents[i].fe_length);
printf("%d:\t%-16.16llx %-16.16llx %s\n",
i,
fiemap->fm_extents[i].fe_logical,
fiemap->fm_extents[i].fe_length,
result ? "FAIL" : "OK");
if (result) {
if (errno)
perror("System error (Write copy_extent):");
break;
}
}
free(fiemap);
// Sync block filesystem
syncfs(fd_block);
// Re-read partition table on the device
if (ioctl(fd_block, BLKRRPART, NULL)) {
fprintf(stderr, "Warning: Unable to re-read kernel partition table\n");
}
close(fd_block);
close(fd_sparse);
return result ? EXIT_FAILURE : EXIT_SUCCESS;
}
int main(int argc, char **argv)
{
const char *img_file, *blk_dev;
if (argc == 3) {
img_file = argv[1];
blk_dev = argv[2];
}
else {
syntax(argv);
return EXIT_FAILURE;
}
if (write_image(img_file, blk_dev)) {
return EXIT_FAILURE;
}
int result = verify_image(img_file, blk_dev);
fprintf(stderr, "Write image %s to %s %s\n", img_file, blk_dev, result ? "FAILED" : "SUCCESS");
return result;
}
|
the_stack_data/32949032.c |
//#define GLOBAL_DECLARE
#ifdef GLOBAL_DECLARE
int x, y;
int *x_ptr, *y_ptr;
#endif
void swap_pointers(int **de_ptr1, int **de_ptr2);
int main()
{
#ifndef GLOBAL_DECLARE
int x, y;
int *x_ptr, *y_ptr;
#endif
x = 2000000;
y = 1000000;
x_ptr = &x;
y_ptr = &y;
swap_pointers(&x_ptr, &y_ptr);
while (1) {
;
}
return 0;
}
void swap_pointers(int **de_ptr1, int **de_ptr2)
{
int *tmpt_ptr;
tmpt_ptr = *de_ptr1;
*de_ptr1 = *de_ptr2;
*de_ptr2 = tmpt_ptr;
} |
the_stack_data/87832.c | // gcc -Wall -W -lm double-to-float-with-rounding-modes.c -o double-to-float-with-rounding-modes -frounding-math -fsignaling-nans -ffp-contract=off -msse2 -mfpmath=sse
#ifdef __GNUC__
#include <assert.h>
#include <fenv.h>
#include <math.h>
float setRoundingModeAndCast(int mode, double d)
{
fesetround(mode);
return (float)d;
}
void test(int mode, double d, float result)
{
float f = setRoundingModeAndCast(mode, d);
assert(f == result);
return;
}
#endif
int main(void)
{
#ifdef __GNUC__
test(FE_TONEAREST, 0x1.fffffffffffffp+1023, +INFINITY);
#endif
return 1;
}
|
the_stack_data/107287.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memcpy.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: awindham <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/27 17:18:11 by awindham #+# #+# */
/* Updated: 2018/12/01 13:17:47 by awindham ### ########.fr */
/* */
/* ************************************************************************** */
#include <string.h>
void *ft_memcpy(void *dst, const void *src, size_t n)
{
char *d;
const char *s;
d = dst;
s = src;
while (n--)
d[n] = s[n];
return (dst);
}
|
the_stack_data/28070.c | #include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TMP_STR_BUF_LEN 2 * 1024
#define SHORT_BUF 1024
#define LIFE_STEP_NUM 5
#define DESCRIPTION_0 "在一个奇妙而且美妙的时刻,我在不知道中即将诞生了,\
精彩马上开始..."
#define DESCRIPTION_1 "HI, 大家好,我是一个小蝌蚪"
#define DESCRIPTION_2 "我还是一个小蝌蚪,但经过一段时间的进化,我长出了兩条腿"
#define DESCRIPTION_3 "我依然可以算是一个小蝌蚪,但经过一段时间的进化,\
我有了四条腿,但尾巴却没有退去,我好想去陆地上看看呀"
#define DESCRIPTION_4 "感谢郭嘉,我终于进化成为一只青蛙,可以享受兩栖的快乐了!"
#define NO_LIFE "None"
#define ORIGINAL_LIFE "tabpole"
#define EVOLUTION_LIFE "frog"
typedef struct _life_common_t
{
int head;
int eyes;
int mouth;
} life_common_t;
typedef struct _life_evolution_t
{
char life_stat[SHORT_BUF];
char *description;
int breath;
int legs;
int tail;
} life_evolution_t;
static char life_des[LIFE_STEP_NUM][TMP_STR_BUF_LEN] = {
DESCRIPTION_0,
DESCRIPTION_1,
DESCRIPTION_2,
DESCRIPTION_3,
DESCRIPTION_4,
};
static life_common_t life_common;
int print_life(life_evolution_t *life)
{
if (NULL == life)
{
fprintf(stderr, "It is empty point: life\n");
goto FINISH;
}
fprintf(stderr, "生命姿态: %s\n", life->life_stat);
fprintf(stderr, "生命自述: %s\n", life->description);
fprintf(stderr, "我有 %d 个头\n", life_common.head);
fprintf(stderr, "有 %d 个眼睛\n", life_common.eyes);
fprintf(stderr, "有 %d 个嘴\n", life_common.mouth);
fprintf(stderr, "有 %d 条腿\n", life->legs);
fprintf(stderr, "有 %d 条尾巴\n", life->tail);
fprintf(stderr, "我用 %s 呼吸\n", life->breath ? "肺" : "腮");
fprintf(stderr, "进化\n...\n");
FINISH:
return 0;
}
int main(int argc, char *argv[])
{
int i = 0;
int step = 0;
life_evolution_t life_evolution[LIFE_STEP_NUM];
memset(life_evolution, 0, sizeof(life_evolution_t) * LIFE_STEP_NUM);
life_common.head = 1;
life_common.eyes = 2;
life_common.mouth= 1;
for (i = 0; i < LIFE_STEP_NUM; i++)
{
snprintf(life_evolution[i].life_stat, SHORT_BUF, "%s", ORIGINAL_LIFE);
life_evolution[i].description = life_des[i];
switch (i)
{
case 0:
snprintf(life_evolution[i].life_stat, SHORT_BUF, "%s", NO_LIFE);
break;
case 1:
life_evolution[i].tail = 1;
break;
case 2:
life_evolution[i].tail = 1;
life_evolution[i].legs = 2;
break;
case 3:
life_evolution[i].tail = 1;
life_evolution[i].legs = 4;
break;
case 4:
snprintf(life_evolution[i].life_stat, SHORT_BUF, "%s", EVOLUTION_LIFE);
life_evolution[i].tail = 0;
life_evolution[i].legs = 4;
life_evolution[i].breath = 1;
break;
default:
fprintf(stderr, "Get wrong life step\n");
}
}
if (argc > 1 && 0 != argv[1][0])
{
step = atoi(argv[1]);
}
if (step > -1 && step < LIFE_STEP_NUM)
{
print_life(&(life_evolution[step]));
}
else
{
fprintf(stderr, "Get wrong life step:[%d]\n", step);
fprintf(stderr, "It should be 0~%d\n", LIFE_STEP_NUM);
}
return 0;
}
|
the_stack_data/42761.c | #include "syscall.h"
#include "stdio.h"
#include "stdlib.h"
int main(void) {
/*Creates n processes, runs them until they are finished, and repeats. Checks to make sure that memory is being^M
* properly deallocated at the end of a process.^M
*/
int n = 10;
int childPID[n];
int *exitStatus;
char *cpargv[10] = {"TESTING"};
int i;
for(i = 0; i<n; i++){
childPID[i] = exec("test.coff", 1, cpargv);
join(childPID[i], exitStatus);
printf("child pid: %d \n", childPID[i]);
}
printf("FINISHED!");
} |
the_stack_data/363948.c | //Pallindrome of a number
#include <stdio.h>
#include<string.h>
void main()
{
char *rev;
char str[15];
scanf("%[^\n]",str);
int i,j;
for(i=strlen(str)-1,j=0;i>=0;i--,j++)
rev[j]=str[i];
rev[j]='\0';
if(strcmp(rev,str))
printf("\nThe string is not a palindrome");
else
printf("\nThe string is a palindrome");
}
|
the_stack_data/65027.c | /*numPass=7, numTotal=7
Verdict:ACCEPTED, Visibility:1, Input:"14", ExpOutput:"17
", Output:"17"
Verdict:ACCEPTED, Visibility:1, Input:"24", ExpOutput:"29
", Output:"29"
Verdict:ACCEPTED, Visibility:1, Input:"1", ExpOutput:"2
", Output:"2"
Verdict:ACCEPTED, Visibility:1, Input:"68", ExpOutput:"71
", Output:"71"
Verdict:ACCEPTED, Visibility:0, Input:"99", ExpOutput:"101
", Output:"101"
Verdict:ACCEPTED, Visibility:0, Input:"150", ExpOutput:"151
", Output:"151"
Verdict:ACCEPTED, Visibility:0, Input:"200", ExpOutput:"211
", Output:"211"
*/
#include<stdio.h>
int check_prime(int num){
int i,j,a,p;
for(i=num;;i++){p=1;
for(j=2;j<=i-1;j++){
a=i%j;
if(a==0)break;
}
if(a!=0)
return(i);
else
continue;
}
}
int main(){
int N,p;
scanf("%d",&N);
if((N==1)||(N==2))
printf("%d",2);
else{
p = check_prime(N);
printf("%d",p);
}
return 0;
} |
the_stack_data/405789.c | /*
* Copyright (C) 2007-2013 Gil Mendes
*
* 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.
*/
/**
* @file
* @brief Memory copying function.
*/
#include <stddef.h>
#include <stdint.h>
#include <string.h>
/**
* Copy data in memory.
*
* Copies bytes from a source memory area to a destination memory area,
* where both areas may not overlap.
*
* @note This function does not like unaligned addresses. Giving
* it unaligned addresses might make it sad. :(
*
* @param dest The memory area to copy to.
* @param src The memory area to copy from.
* @param count The number of bytes to copy.
*
* @return Destination location.
*/
void *memcpy(void *restrict dest, const void *restrict src, size_t count) {
const char *s = (const char *)src;
const unsigned long *ns;
char *d = (char *)dest;
unsigned long *nd;
/* Align the destination. */
while((uintptr_t)d & (sizeof(unsigned long) - 1)) {
if(count--) {
*d++ = *s++;
} else {
return dest;
}
}
/* Write in native-sized blocks if we can. */
if(count >= sizeof(unsigned long)) {
nd = (unsigned long *)d;
ns = (const unsigned long *)s;
/* Unroll the loop if possible. */
while(count >= (sizeof(unsigned long) * 4)) {
*nd++ = *ns++;
*nd++ = *ns++;
*nd++ = *ns++;
*nd++ = *ns++;
count -= sizeof(unsigned long) * 4;
}
while(count >= sizeof(unsigned long)) {
*nd++ = *ns++;
count -= sizeof(unsigned long);
}
d = (char *)nd;
s = (const char *)ns;
}
/* Write remaining bytes. */
while(count--)
*d++ = *s++;
return dest;
}
|
the_stack_data/122892.c | #include <time.h>
static struct timespec startTicks;
void ticksInitialize()
{
clock_gettime(CLOCK_MONOTONIC, &startTicks);
}
unsigned int ticksGetTicks()
{
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (now.tv_sec - startTicks.tv_sec) * 1000 +
(now.tv_nsec - startTicks.tv_nsec) / 1000000;
}
|
the_stack_data/85561.c | /*
* Chinese Comment by UTF-8
*
* 题目内容
* 有五个各不相同的正整数,它们的和是135,且按照从小到大的顺序,后面一个数是前面一个数的整倍数。
* 编写程序求这几个数。
*
* 分析
* 翻译题。将题意用编程语言重新写一遍即可。鉴于数字很小,选用五重循环。
*/
#include <stdio.h>
int main() {
for (unsigned int i = 1; i <= 135; i++)
for (unsigned int j = 2; i * j <= 135; j++)
for (unsigned int k = 2; i * j * k <= 135; k++)
for (unsigned int l = 2; i * j * k * l <= 135; l++)
for (unsigned int m = 2; i * j * k * l * m <= 135; m++)
if (i + i * j + i * j * k + i * j * k * l + i * j * k * l * m == 135)
printf("%ud, %ud, %ud, %ud, %ud\n", i, i * j, i * j * k, i * j * k * l, i * j * k * l * m);
return 0;
} |
the_stack_data/165766282.c | #include <stdio.h>
#include <stdlib.h>
int main(int amount,char * content[])
{
char charVar=254;
int intVar=0;
short int sintVar=0;
long int lintVar=0L;
unsigned char ucharVar=0;
unsigned int uintVar=0;
float fVar=0;
/* ISO c90 does not support 'long long' */
long long llVar=0LL; /* long long int */
unsigned long long ullVar=0ULL; /* unsigned long long int */
printf("Bytes (charVar): %d\n",sizeof(charVar));
printf("Bytes (intVar): %d\n",sizeof(intVar));
printf("Bytes (sintVar): %d\n",sizeof(sintVar));
printf("Bytes (lintVar): %d\n",sizeof(lintVar));
printf("Bytes (ucharVar): %d\n",sizeof(ucharVar));
printf("Bytes (uintVar): %d\n",sizeof(uintVar));
printf("Bytes (fVar): %d\n",sizeof(fVar));
printf("Bytes (llVar): %d\n",sizeof(llVar));
printf("Bytes (ullVar): %d\n",sizeof(ullVar));
/* Execute really long long time :D */
/* while(llVar<1234567890) { printf("%d, ",llVar); llVar++;} */
return 0;
}
|
the_stack_data/43888104.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_countwords.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: awindham <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/01 15:26:01 by awindham #+# #+# */
/* Updated: 2018/12/02 17:12:29 by awindham ### ########.fr */
/* */
/* ************************************************************************** */
/*
** this is a comment
*/
int ft_countwords(char const *str, char c)
{
int count;
int i;
i = 0;
count = 0;
while (str[i])
{
while (str[i] == c)
i++;
if (str[i] != c && str[i] != '\0')
count++;
while (str[i] != c && str[i] != '\0')
i++;
}
return (count);
}
|
the_stack_data/154014.c | #define __CRT__NO_INLINE /* Don't let mingw insert code */
#include <math.h>
#define fma_def(type, name, isnan_func, isinf_func, signbit_func, fma_func) \
type name(type x, type y, type z) \
{ \
__ESBMC_HIDE:; \
return fma_func(x, y, z); \
} \
\
type __##name(type x, type y, type z) \
{ \
__ESBMC_HIDE:; \
return name(x, y, z); \
}
fma_def(float, fmaf, isnanf, isinff, __signbitf, __ESBMC_fmaf);
fma_def(double, fma, isnan, isinf, __signbit, __ESBMC_fmad);
fma_def(long double, fmal, isnanl, isinfl, __signbitl, __ESBMC_fmald);
#undef fma_def
|
the_stack_data/68887129.c | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_13__ TYPE_4__ ;
typedef struct TYPE_12__ TYPE_3__ ;
typedef struct TYPE_11__ TYPE_2__ ;
typedef struct TYPE_10__ TYPE_1__ ;
/* Type definitions */
typedef long uintmax_t ;
typedef double ufs2_daddr_t ;
struct statfs {char* f_mntfromname; int f_flags; char* f_mntonname; } ;
struct stat {int /*<<< orphan*/ st_mode; } ;
struct iovec {int dummy; } ;
struct group {int /*<<< orphan*/ gr_gid; } ;
struct dups {scalar_t__ dup; struct dups* next; } ;
typedef long intmax_t ;
typedef int /*<<< orphan*/ errmsg ;
struct TYPE_13__ {int /*<<< orphan*/ * il_stat; } ;
struct TYPE_12__ {scalar_t__ b_dirty; } ;
struct TYPE_10__ {int cs_nffree; int cs_nbfree; long cs_nifree; long cs_ndir; } ;
struct TYPE_11__ {int fs_flags; int fs_clean; int fs_frag; double fs_dsize; int fs_metackhash; scalar_t__ fs_magic; char* fs_fsmnt; int fs_ncg; void* fs_time; TYPE_1__ fs_cstotal; int /*<<< orphan*/ fs_fsize; int /*<<< orphan*/ fs_cssize; void* fs_mtime; } ;
/* Variables and functions */
int CK_CYLGRP ;
int CK_DIR ;
int CK_INDIR ;
int CK_INODE ;
int CK_SUPERBLOCK ;
int /*<<< orphan*/ CLOCK_REALTIME_PRECISE ;
scalar_t__ EEXIST ;
scalar_t__ ENOENT ;
int ERERUN ;
int ERESTART ;
int FS_DOSOFTDEP ;
int FS_GJOURNAL ;
int FS_METACKHASH ;
int FS_NEEDSFSCK ;
int FS_SUJ ;
scalar_t__ FS_UFS1_MAGIC ;
int FS_UNCLEAN ;
int /*<<< orphan*/ IOstats (char*) ;
size_t MIBSIZE ;
int MNT_RDONLY ;
int MNT_ROOTFS ;
int MNT_SOFTDEP ;
int /*<<< orphan*/ O_RDONLY ;
scalar_t__ P_OSREL_CK_CYLGRP ;
scalar_t__ P_OSREL_CK_DIR ;
scalar_t__ P_OSREL_CK_INDIR ;
scalar_t__ P_OSREL_CK_INODE ;
scalar_t__ P_OSREL_CK_SUPERBLOCK ;
int /*<<< orphan*/ SBLOCKSIZE ;
int /*<<< orphan*/ S_ISDIR (int /*<<< orphan*/ ) ;
long UFS_ROOTINO ;
int /*<<< orphan*/ adjrefcnt ;
scalar_t__ bkgrdcheck ;
scalar_t__ bkgrdflag ;
char* blockcheck (char*) ;
int /*<<< orphan*/ blwrite (int,char*,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ build_iovec (struct iovec**,int*,char*,char*,int) ;
char* cdevname ;
int cgbase (TYPE_2__*,int /*<<< orphan*/ ) ;
int cgdmin (TYPE_2__*,int /*<<< orphan*/ ) ;
int cgsblock (TYPE_2__*,int) ;
scalar_t__ chkdoreload (struct statfs*) ;
scalar_t__ chmod (char*,int) ;
scalar_t__ chown (char*,int,int /*<<< orphan*/ ) ;
scalar_t__ ckclean ;
int /*<<< orphan*/ ckfini (int) ;
int ckhashadd ;
int /*<<< orphan*/ clock_gettime (int /*<<< orphan*/ ,int /*<<< orphan*/ *) ;
int /*<<< orphan*/ close (int /*<<< orphan*/ ) ;
long countdirs ;
scalar_t__ cvtlevel ;
scalar_t__ debug ;
struct dups* duplist ;
scalar_t__ errno ;
int /*<<< orphan*/ exit (int) ;
int /*<<< orphan*/ finalIOstats () ;
int /*<<< orphan*/ flush (int,TYPE_3__*) ;
int /*<<< orphan*/ free (char*) ;
int /*<<< orphan*/ fsbtodb (TYPE_2__*,int) ;
int /*<<< orphan*/ fsckinit () ;
int fsmodified ;
int /*<<< orphan*/ fsreadfd ;
int /*<<< orphan*/ fsutilinit () ;
int fswritefd ;
struct group* getgrnam (char*) ;
struct statfs* getmntpt (char*) ;
scalar_t__ getosreldate () ;
int /*<<< orphan*/ gjournal_check (char*) ;
scalar_t__ howmany (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ inocleanup () ;
TYPE_4__* inostathead ;
double maxfsblock ;
long maxino ;
scalar_t__ mkdir (char*,int) ;
struct dups* muldup ;
long n_blks ;
long n_files ;
scalar_t__ nmount (struct iovec*,int,int) ;
int /*<<< orphan*/ open (char*,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ pass1 () ;
int /*<<< orphan*/ pass1b () ;
int /*<<< orphan*/ pass2 () ;
int /*<<< orphan*/ pass3 () ;
int /*<<< orphan*/ pass4 () ;
int /*<<< orphan*/ pass5 () ;
int /*<<< orphan*/ pfatal (char*,...) ;
scalar_t__ preen ;
int /*<<< orphan*/ printf (char*,...) ;
int /*<<< orphan*/ pwarn (char*,...) ;
scalar_t__ readsb (int /*<<< orphan*/ ) ;
scalar_t__ reply (char*) ;
scalar_t__ rerun ;
int resolved ;
int /*<<< orphan*/ restarts ;
int /*<<< orphan*/ sbdirty () ;
TYPE_3__ sblk ;
TYPE_2__ sblock ;
int /*<<< orphan*/ sblock_init () ;
int setup (char*) ;
scalar_t__ skipclean ;
char* snapname ;
int /*<<< orphan*/ snprintf (char*,int,char*,char*) ;
int /*<<< orphan*/ startprog ;
scalar_t__ stat (char*,struct stat*) ;
char* strerror (scalar_t__) ;
scalar_t__ suj_check (char*) ;
int /*<<< orphan*/ sync () ;
scalar_t__ sysctlnametomib (char*,int /*<<< orphan*/ ,size_t*) ;
void* time (int /*<<< orphan*/ *) ;
scalar_t__ unlink (char*) ;
scalar_t__ usedsoftdep ;
scalar_t__ wantrestart ;
scalar_t__ yflag ;
__attribute__((used)) static int
checkfilesys(char *filesys)
{
ufs2_daddr_t n_ffree, n_bfree;
struct dups *dp;
struct statfs *mntp;
struct stat snapdir;
struct group *grp;
struct iovec *iov;
char errmsg[255];
int ofsmodified;
int iovlen;
int cylno;
intmax_t blks, files;
size_t size;
iov = NULL;
iovlen = 0;
errmsg[0] = '\0';
fsutilinit();
fsckinit();
cdevname = filesys;
if (debug && ckclean)
pwarn("starting\n");
/*
* Make best effort to get the disk name. Check first to see
* if it is listed among the mounted file systems. Failing that
* check to see if it is listed in /etc/fstab.
*/
mntp = getmntpt(filesys);
if (mntp != NULL)
filesys = mntp->f_mntfromname;
else
filesys = blockcheck(filesys);
/*
* If -F flag specified, check to see whether a background check
* is possible and needed. If possible and needed, exit with
* status zero. Otherwise exit with status non-zero. A non-zero
* exit status will cause a foreground check to be run.
*/
sblock_init();
if (bkgrdcheck) {
if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
exit(3); /* Cannot read superblock */
close(fsreadfd);
/* Earlier background failed or journaled */
if (sblock.fs_flags & (FS_NEEDSFSCK | FS_SUJ))
exit(4);
if ((sblock.fs_flags & FS_DOSOFTDEP) == 0)
exit(5); /* Not running soft updates */
size = MIBSIZE;
if (sysctlnametomib("vfs.ffs.adjrefcnt", adjrefcnt, &size) < 0)
exit(6); /* Lacks kernel support */
if ((mntp == NULL && sblock.fs_clean == 1) ||
(mntp != NULL && (sblock.fs_flags & FS_UNCLEAN) == 0))
exit(7); /* Filesystem clean, report it now */
exit(0);
}
if (ckclean && skipclean) {
/*
* If file system is gjournaled, check it here.
*/
if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
exit(3); /* Cannot read superblock */
close(fsreadfd);
if ((sblock.fs_flags & FS_GJOURNAL) != 0) {
//printf("GJournaled file system detected on %s.\n",
// filesys);
if (sblock.fs_clean == 1) {
pwarn("FILE SYSTEM CLEAN; SKIPPING CHECKS\n");
exit(0);
}
if ((sblock.fs_flags & (FS_UNCLEAN | FS_NEEDSFSCK)) == 0) {
gjournal_check(filesys);
if (chkdoreload(mntp) == 0)
exit(0);
exit(4);
} else {
pfatal(
"UNEXPECTED INCONSISTENCY, CANNOT RUN FAST FSCK\n");
}
}
}
/*
* If we are to do a background check:
* Get the mount point information of the file system
* create snapshot file
* return created snapshot file
* if not found, clear bkgrdflag and proceed with normal fsck
*/
if (bkgrdflag) {
if (mntp == NULL) {
bkgrdflag = 0;
pfatal("NOT MOUNTED, CANNOT RUN IN BACKGROUND\n");
} else if ((mntp->f_flags & MNT_SOFTDEP) == 0) {
bkgrdflag = 0;
pfatal(
"NOT USING SOFT UPDATES, CANNOT RUN IN BACKGROUND\n");
} else if ((mntp->f_flags & MNT_RDONLY) != 0) {
bkgrdflag = 0;
pfatal("MOUNTED READ-ONLY, CANNOT RUN IN BACKGROUND\n");
} else if ((fsreadfd = open(filesys, O_RDONLY)) >= 0) {
if (readsb(0) != 0) {
if (sblock.fs_flags & (FS_NEEDSFSCK | FS_SUJ)) {
bkgrdflag = 0;
pfatal(
"UNEXPECTED INCONSISTENCY, CANNOT RUN IN BACKGROUND\n");
}
if ((sblock.fs_flags & FS_UNCLEAN) == 0 &&
skipclean && ckclean) {
/*
* file system is clean;
* skip snapshot and report it clean
*/
pwarn(
"FILE SYSTEM CLEAN; SKIPPING CHECKS\n");
goto clean;
}
}
close(fsreadfd);
}
if (bkgrdflag) {
snprintf(snapname, sizeof snapname, "%s/.snap",
mntp->f_mntonname);
if (stat(snapname, &snapdir) < 0) {
if (errno != ENOENT) {
bkgrdflag = 0;
pfatal(
"CANNOT FIND SNAPSHOT DIRECTORY %s: %s, CANNOT RUN IN BACKGROUND\n",
snapname, strerror(errno));
} else if ((grp = getgrnam("operator")) == NULL ||
mkdir(snapname, 0770) < 0 ||
chown(snapname, -1, grp->gr_gid) < 0 ||
chmod(snapname, 0770) < 0) {
bkgrdflag = 0;
pfatal(
"CANNOT CREATE SNAPSHOT DIRECTORY %s: %s, CANNOT RUN IN BACKGROUND\n",
snapname, strerror(errno));
}
} else if (!S_ISDIR(snapdir.st_mode)) {
bkgrdflag = 0;
pfatal(
"%s IS NOT A DIRECTORY, CANNOT RUN IN BACKGROUND\n",
snapname);
}
}
if (bkgrdflag) {
snprintf(snapname, sizeof snapname,
"%s/.snap/fsck_snapshot", mntp->f_mntonname);
build_iovec(&iov, &iovlen, "fstype", "ffs", 4);
build_iovec(&iov, &iovlen, "from", snapname,
(size_t)-1);
build_iovec(&iov, &iovlen, "fspath", mntp->f_mntonname,
(size_t)-1);
build_iovec(&iov, &iovlen, "errmsg", errmsg,
sizeof(errmsg));
build_iovec(&iov, &iovlen, "update", NULL, 0);
build_iovec(&iov, &iovlen, "snapshot", NULL, 0);
while (nmount(iov, iovlen, mntp->f_flags) < 0) {
if (errno == EEXIST && unlink(snapname) == 0)
continue;
bkgrdflag = 0;
pfatal("CANNOT CREATE SNAPSHOT %s: %s %s\n",
snapname, strerror(errno), errmsg);
break;
}
if (bkgrdflag != 0)
filesys = snapname;
}
}
switch (setup(filesys)) {
case 0:
if (preen)
pfatal("CAN'T CHECK FILE SYSTEM.");
return (0);
case -1:
clean:
pwarn("clean, %ld free ", (long)(sblock.fs_cstotal.cs_nffree +
sblock.fs_frag * sblock.fs_cstotal.cs_nbfree));
printf("(%jd frags, %jd blocks, %.1f%% fragmentation)\n",
(intmax_t)sblock.fs_cstotal.cs_nffree,
(intmax_t)sblock.fs_cstotal.cs_nbfree,
sblock.fs_cstotal.cs_nffree * 100.0 / sblock.fs_dsize);
return (0);
}
/*
* Determine if we can and should do journal recovery.
*/
if ((sblock.fs_flags & FS_SUJ) == FS_SUJ) {
if ((sblock.fs_flags & FS_NEEDSFSCK) != FS_NEEDSFSCK && skipclean) {
if (preen || reply("USE JOURNAL")) {
if (suj_check(filesys) == 0) {
printf("\n***** FILE SYSTEM MARKED CLEAN *****\n");
if (chkdoreload(mntp) == 0)
exit(0);
exit(4);
}
}
printf("** Skipping journal, falling through to full fsck\n\n");
}
/*
* Write the superblock so we don't try to recover the
* journal on another pass. If this is the only change
* to the filesystem, we do not want it to be called
* out as modified.
*/
sblock.fs_mtime = time(NULL);
sbdirty();
ofsmodified = fsmodified;
flush(fswritefd, &sblk);
fsmodified = ofsmodified;
}
/*
* If the filesystem was run on an old kernel that did not
* support check hashes, clear the check-hash flags so that
* we do not try to verify them.
*/
if ((sblock.fs_flags & FS_METACKHASH) == 0)
sblock.fs_metackhash = 0;
/*
* If we are running on a kernel that can provide check hashes
* that are not yet enabled for the filesystem and we are
* running manually without the -y flag, offer to add any
* supported check hashes that are not already enabled.
*/
ckhashadd = 0;
if (preen == 0 && yflag == 0 && sblock.fs_magic != FS_UFS1_MAGIC &&
fswritefd != -1 && getosreldate() >= P_OSREL_CK_CYLGRP) {
if ((sblock.fs_metackhash & CK_CYLGRP) == 0 &&
reply("ADD CYLINDER GROUP CHECK-HASH PROTECTION") != 0) {
ckhashadd |= CK_CYLGRP;
sblock.fs_metackhash |= CK_CYLGRP;
}
if ((sblock.fs_metackhash & CK_SUPERBLOCK) == 0 &&
getosreldate() >= P_OSREL_CK_SUPERBLOCK &&
reply("ADD SUPERBLOCK CHECK-HASH PROTECTION") != 0) {
ckhashadd |= CK_SUPERBLOCK;
sblock.fs_metackhash |= CK_SUPERBLOCK;
}
if ((sblock.fs_metackhash & CK_INODE) == 0 &&
getosreldate() >= P_OSREL_CK_INODE &&
reply("ADD INODE CHECK-HASH PROTECTION") != 0) {
ckhashadd |= CK_INODE;
sblock.fs_metackhash |= CK_INODE;
}
#ifdef notyet
if ((sblock.fs_metackhash & CK_INDIR) == 0 &&
getosreldate() >= P_OSREL_CK_INDIR &&
reply("ADD INDIRECT BLOCK CHECK-HASH PROTECTION") != 0) {
ckhashadd |= CK_INDIR;
sblock.fs_metackhash |= CK_INDIR;
}
if ((sblock.fs_metackhash & CK_DIR) == 0 &&
getosreldate() >= P_OSREL_CK_DIR &&
reply("ADD DIRECTORY CHECK-HASH PROTECTION") != 0) {
ckhashadd |= CK_DIR;
sblock.fs_metackhash |= CK_DIR;
}
#endif /* notyet */
if (ckhashadd != 0) {
sblock.fs_flags |= FS_METACKHASH;
sbdirty();
}
}
/*
* Cleared if any questions answered no. Used to decide if
* the superblock should be marked clean.
*/
resolved = 1;
/*
* 1: scan inodes tallying blocks used
*/
if (preen == 0) {
printf("** Last Mounted on %s\n", sblock.fs_fsmnt);
if (mntp != NULL && mntp->f_flags & MNT_ROOTFS)
printf("** Root file system\n");
printf("** Phase 1 - Check Blocks and Sizes\n");
}
clock_gettime(CLOCK_REALTIME_PRECISE, &startprog);
pass1();
IOstats("Pass1");
/*
* 1b: locate first references to duplicates, if any
*/
if (duplist) {
if (preen || usedsoftdep)
pfatal("INTERNAL ERROR: dups with %s%s%s",
preen ? "-p" : "",
(preen && usedsoftdep) ? " and " : "",
usedsoftdep ? "softupdates" : "");
printf("** Phase 1b - Rescan For More DUPS\n");
pass1b();
IOstats("Pass1b");
}
/*
* 2: traverse directories from root to mark all connected directories
*/
if (preen == 0)
printf("** Phase 2 - Check Pathnames\n");
pass2();
IOstats("Pass2");
/*
* 3: scan inodes looking for disconnected directories
*/
if (preen == 0)
printf("** Phase 3 - Check Connectivity\n");
pass3();
IOstats("Pass3");
/*
* 4: scan inodes looking for disconnected files; check reference counts
*/
if (preen == 0)
printf("** Phase 4 - Check Reference Counts\n");
pass4();
IOstats("Pass4");
/*
* 5: check and repair resource counts in cylinder groups
*/
if (preen == 0)
printf("** Phase 5 - Check Cyl groups\n");
pass5();
IOstats("Pass5");
/*
* print out summary statistics
*/
n_ffree = sblock.fs_cstotal.cs_nffree;
n_bfree = sblock.fs_cstotal.cs_nbfree;
files = maxino - UFS_ROOTINO - sblock.fs_cstotal.cs_nifree - n_files;
blks = n_blks +
sblock.fs_ncg * (cgdmin(&sblock, 0) - cgsblock(&sblock, 0));
blks += cgsblock(&sblock, 0) - cgbase(&sblock, 0);
blks += howmany(sblock.fs_cssize, sblock.fs_fsize);
blks = maxfsblock - (n_ffree + sblock.fs_frag * n_bfree) - blks;
if (bkgrdflag && (files > 0 || blks > 0)) {
countdirs = sblock.fs_cstotal.cs_ndir - countdirs;
pwarn("Reclaimed: %ld directories, %jd files, %jd fragments\n",
countdirs, files - countdirs, blks);
}
pwarn("%ld files, %jd used, %ju free ",
(long)n_files, (intmax_t)n_blks,
(uintmax_t)n_ffree + sblock.fs_frag * n_bfree);
printf("(%ju frags, %ju blocks, %.1f%% fragmentation)\n",
(uintmax_t)n_ffree, (uintmax_t)n_bfree,
n_ffree * 100.0 / sblock.fs_dsize);
if (debug) {
if (files < 0)
printf("%jd inodes missing\n", -files);
if (blks < 0)
printf("%jd blocks missing\n", -blks);
if (duplist != NULL) {
printf("The following duplicate blocks remain:");
for (dp = duplist; dp; dp = dp->next)
printf(" %jd,", (intmax_t)dp->dup);
printf("\n");
}
}
duplist = (struct dups *)0;
muldup = (struct dups *)0;
inocleanup();
if (fsmodified) {
sblock.fs_time = time(NULL);
sbdirty();
}
if (cvtlevel && sblk.b_dirty) {
/*
* Write out the duplicate super blocks
*/
for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
blwrite(fswritefd, (char *)&sblock,
fsbtodb(&sblock, cgsblock(&sblock, cylno)),
SBLOCKSIZE);
}
if (rerun)
resolved = 0;
finalIOstats();
/*
* Check to see if the file system is mounted read-write.
*/
if (bkgrdflag == 0 && mntp != NULL && (mntp->f_flags & MNT_RDONLY) == 0)
resolved = 0;
ckfini(resolved);
for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
if (inostathead[cylno].il_stat != NULL)
free((char *)inostathead[cylno].il_stat);
free((char *)inostathead);
inostathead = NULL;
if (fsmodified && !preen)
printf("\n***** FILE SYSTEM WAS MODIFIED *****\n");
if (rerun) {
if (wantrestart && (restarts++ < 10) &&
(preen || reply("RESTART")))
return (ERESTART);
printf("\n***** PLEASE RERUN FSCK *****\n");
}
if (chkdoreload(mntp) != 0) {
if (!fsmodified)
return (0);
if (!preen)
printf("\n***** REBOOT NOW *****\n");
sync();
return (4);
}
return (rerun ? ERERUN : 0);
} |
the_stack_data/161080079.c | #include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <limits.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <termio.h>
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define TIME_OUT 5 //time in seconds
#define STRINGSIZ 256
int open_files(int *files, int num, char **paths);
int multiplexed_read(int *files, int num);
int main(int argc, char *argv[]) {
if(argc < 2) {
return EINVAL;
}
int *files = (int*)malloc(sizeof(int) * MIN((argc - 1), _POSIX_OPEN_MAX));
if(open_files(files, argc - 1, argv + 1) == -1) {
return errno;
}
if(multiplexed_read(files, argc - 1) == -1) {
return errno;
}
free(files);
return 0;
}
int open_files(int *files, int num, char **paths) {
int i;
for(i = 0; i < num; i++) {
if((files[i] = open(paths[i], O_RDONLY)) == -1) {
perror("Can't open the file");
return -1;
}
}
return 0;
}
void sig_alarm(int signum) { }
int multiplexed_read(int *files, int num) {
/* set signal handler */
struct sigaction act;
act.sa_handler = sig_alarm;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_INTERRUPT;
sigaction(SIGALRM, &act, NULL);
/* main part of the function */
char buffer[STRINGSIZ];
int current_file = -1, opened_num = num, length;
while(opened_num) {
if(++current_file == num) {
current_file = 0;
}
if(files[current_file] == -1) {
continue;
}
alarm(TIME_OUT); //set alarm
if((length = read(files[current_file], buffer, STRINGSIZ)) == -1) {
alarm(0); //stop alarm
if(errno == EINTR) {
continue;
} else {
close(files[current_file]);
files[current_file] = -1;
opened_num--;
}
} else {
alarm(0); //stop alarm
//write to stdout
if(write(1, buffer, length) == -1) {
perror("Can't write to stdout");
return -1;
}
}
}
return 0;
} |
the_stack_data/156392631.c | #include <omp.h>
#include <stdio.h>
#define N 1024
int A[N];
int B[N];
int C[N];
int main()
{
int i, errors;
for(i=0; i<N; i++) {
A[i] = i;
B[i] = i;
}
// map data A & B and move to
#pragma omp target enter data map(to: A, B) depend(out: A[0]) nowait
// no data move since already mapped
#pragma omp target map(A, B) depend(out: A[0]) nowait
{
int i;
for(int i=0; i<N; i++) A[i]++;
for(int i=0; i<N; i++) B[i]++;
}
// no data move since already mapped
#pragma omp target map(A, B) depend(out: A[0]) nowait
{
int i;
for(int i=0; i<N; i++) A[i]++;
for(int i=0; i<N; i++) B[i]++;
}
// A updated via update
#pragma omp target update from(A) depend(out: A[0]) nowait
// B updated via exit, A just released
#pragma omp target exit data map(release: A) map(from: B) depend(out: A[0]) nowait
#pragma omp taskwait
errors = 0;
for(i=0; i<N; i++) {
if (A[i] != i+2) printf("%d: A got %d, expected %d; error %d\n", i, A[i], i+2, ++errors);
if (B[i] != i+2) printf("%d: B got %d, expected %d; error %d\n", i, B[i], i+2, ++errors);
if (errors>25) break;
}
printf("completed with %d errors\n", errors);
return 1;
}
|
the_stack_data/1102495.c | # include <stdio.h>
# include <stdlib.h>
# include <string.h>
typedef struct treenode_t *Tree;
struct treenode_t {
int key;
Tree left;
Tree right;
int height;
};
Tree newTree(int key) {
Tree tree = (Tree) calloc(1, sizeof(struct treenode_t));
tree->key = key;
tree->height = 1; // A node is assigned at a leaf
return tree;
}
int max(int a, int b) {
return a > b? a : b;
}
int findHeight(Tree tree) {
if (tree == NULL) {
return 0;
}
int leftHeight = findHeight(tree->left);
int rightHeight = findHeight(tree->right);
return max(leftHeight, rightHeight) + 1;
}
int isBalancedTreeHelper(Tree tree, int *pIsBalanced)
{
if (tree == NULL) {
return 0;
}
int leftHeight = isBalancedTreeHelper(tree->left, pIsBalanced);
int rightHeight = isBalancedTreeHelper(tree->right, pIsBalanced);
int balanceFactor = leftHeight - rightHeight;
if (balanceFactor < -1 || balanceFactor > 1) {
*pIsBalanced = 0;
}
return max(leftHeight, rightHeight) + 1;
}
int isBalancedTree(Tree tree) {
int isBalanced = 1;
isBalancedTreeHelper(tree, &isBalanced);
return isBalanced;
}
int getHeight(Tree tree) {
return tree == NULL ? 0 : tree->height;
}
/*
x y
/ \ rotateRight(x) / \
/ \ / \
y T3 ===> T1 x
/ \ / \
/ \ / \
T1 T2 T2 T3
*/
Tree rotateRight(Tree tree) {
printf("rotateRight(%d)\n", tree->key);
Tree x = tree;
Tree y = x->left;
//Tree T1 = y->left;
Tree T2 = y->right;
//Tree T3 = x->right;
// Now rotate right
y->right = x;
x->left = T2;
x->height = max(getHeight(x->left), getHeight(x->right)) + 1;
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
return y;
}
Tree rotateLeft(Tree tree) {
printf("rotateLeft(%d)\n", tree->key);
Tree x = tree;
Tree y = x->right;
//Tree T1 = x->left;
Tree T2 = y->left;
//Tree T3 = y->right;
x->right = T2;
y->left = x;
x->height = max(getHeight(x->left), getHeight(x->right)) + 1;
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
return y;
}
Tree insertIntoBST(Tree tree, int key) {
if (tree == NULL) {
return newTree(key);
} else if (key < tree->key) { // go left
printf("BST~insert>> Going left at %d to insert %d\n", tree->key, key);
tree->left = insertIntoBST(tree->left, key);
} else if (key > tree->key) { // go right
printf("BST~insert>> Going right at %d to insert %d\n", tree->key, key);
tree->right = insertIntoBST(tree->right, key);
} else { // tree-> == key
printf("BST~insert>> Duplicate key %d\n");
return tree;
}
tree->height = max(getHeight(tree->left), getHeight(tree->right)) + 1;
return tree;
}
Tree insertIntoAVLTree(Tree tree, int key) {
if (tree == NULL) {
return newTree(key);
} else if (key < tree->key) { // go left
printf("AVL~insert>> Going left at %d to insert %d\n", tree->key, key);
tree->left = insertIntoAVLTree(tree->left, key);
} else if (key > tree->key) { // go right
printf("AVL~insert>> Going right at %d to insert %d\n", tree->key, key);
tree->right = insertIntoAVLTree(tree->right, key);
} else { // tree-> == key
printf("AVL~insert>> Duplicate key %d\n");
return tree;
}
tree->height = max(getHeight(tree->left), getHeight(tree->right)) + 1;
int balanceFactor = getHeight(tree->left) - getHeight(tree->right);
// Left left
if (balanceFactor > 1 && key < tree->left->key) {
printf("AVL~insert>> LL at %d while inserting %d\n", tree->key, key);
return rotateRight(tree);
}
// Left Right
if (balanceFactor > 1 && key > tree->left->key) {
printf("AVL~insert>> LR at %d while inserting %d\n", tree->key, key);
tree->left = rotateLeft(tree->left);
return rotateRight(tree);
}
// Right Right
if (balanceFactor < -1 && key > tree->right->key) {
printf("AVL~insert>> RR at %d while inserting %d\n", tree->key, key);
return rotateLeft(tree);
}
// Right Left
if (balanceFactor < -1 && key < tree->right->key) {
printf("AVL~insert>> RL at %d while inserting %d\n", tree->key, key);
tree->right = rotateRight(tree->right);
return rotateLeft(tree);
}
return tree;
}
Tree findMinTreeInBST(Tree tree) {
for (; tree && tree->left; tree = tree->left)
;
return tree;
}
int getBalanceFactor(Tree tree) {
return tree == NULL ? 0 : getHeight(tree->left) - getHeight(tree->right);
}
Tree deleteFromBST(Tree tree, int key) {
if (tree == NULL) {
printf("BST~delete>> Key %d is not found\n", key);
return NULL;
} else if (key < tree->key) {
printf("BST~delete>> Going left at %d to delete %d\n", tree->key, key);
tree->left = deleteFromBST(tree->left, key);
} else if (key > tree->key) {
printf("BST~delete>> Going right at %d to delete %d\n", tree->key, key);
tree->right = deleteFromBST(tree->right, key);
} else {
if (tree->left == NULL && tree->right == NULL) {
printf("BST~delete>> Both the subtrees are NULL at %d\n", tree->key, key);
free(tree);
return NULL;
} else if (tree->left && tree->right == NULL) {
printf("BST~delete>> The right subtree is NULL at %d\n", tree->key, key);
Tree tempTree = tree;
tree = tree->left;
free(tempTree);
} else if (tree->left == NULL && tree->right) {
printf("BST~delete>> The left subtree is NULL at %d\n", tree->key, key);
Tree tempTree = tree;
tree = tree->right;
free(tempTree);
} else {
Tree tempTree = findMinTreeInBST(tree->right);
printf("BST~delete>> Need to delete %d to delete %d\n", tempTree->key, key);
tree->key = tempTree->key;
tree->right = deleteFromBST(tree->right, tempTree->key);
}
}
tree->height = max(getHeight(tree->left), getHeight(tree->right)) + 1;
return tree;
}
Tree deleteFromAVLTree(Tree tree, int key) {
if (tree == NULL) {
printf("AVL~delete>> Key %d is not found\n", key);
return NULL;
} else if (key < tree->key) {
printf("AVL~delete>> Going left at %d to delete %d\n", tree->key, key);
tree->left = deleteFromAVLTree(tree->left, key);
} else if (key > tree->key) {
printf("AVL~delete>> Going right at %d to delete %d\n", tree->key, key);
tree->right = deleteFromAVLTree(tree->right, key);
} else {
if (tree->left == NULL && tree->right == NULL) {
printf("AVL~delete>> Both the subtrees are NULL at %d\n", tree->key, key);
free(tree);
return NULL;
} else if (tree->left && tree->right == NULL) {
printf("AVL~delete>> The right subtree is NULL at %d\n", tree->key, key);
Tree tempTree = tree;
tree = tree->left;
free(tempTree);
} else if (tree->left == NULL && tree->right) {
printf("AVL~delete>> The left subtree is NULL at %d\n", tree->key, key);
Tree tempTree = tree;
tree = tree->right;
free(tempTree);
} else {
Tree tempTree = findMinTreeInBST(tree->right);
printf("AVL~delete>> Need to delete %d to delete %d\n", tempTree->key, key);
tree->key = tempTree->key;
tree->right = deleteFromAVLTree(tree->right, tempTree->key);
}
}
tree->height = max(getHeight(tree->left), getHeight(tree->right)) + 1;
int balanceFactor = getBalanceFactor(tree);
// Left left
if (balanceFactor > 1 && getBalanceFactor(tree->left) >= 0) {
printf("AVL~delete>> LL at %d while inserting %d\n", tree->key, key);
return rotateRight(tree);
}
// Left right
if (balanceFactor > 1 && getBalanceFactor(tree->left) < 0) {
printf("AVL~delete>> LR at %d while inserting %d\n", tree->key, key);
tree->left = rotateLeft(tree->left);
return rotateRight(tree);
}
// Right right
if (balanceFactor < -1 && getBalanceFactor(tree->right) <= 0) {
printf("AVL~delete>> RR at %d while inserting %d\n", tree->key, key);
return rotateLeft(tree);
}
// Right left
if (balanceFactor < -1 && getBalanceFactor(tree->right) > 0) {
printf("AVL~delete>> RL at %d while inserting %d\n", tree->key, key);
tree->right = rotateRight(tree->right);
return rotateLeft(tree);
}
return tree;
}
void inorder(Tree tree) {
if (tree == NULL) {
return;
}
inorder(tree->left);
printf("%d ", tree->key);
inorder(tree->right);
}
void driver1() {
int a[] = {9, 35, 70, 0, 78, 71, 72, 84, 66, 56, 88, 15};
//int a[] = {1, 2, 3 ,4, 5 , 6, 7, 8, 9, 10, 11, 12};
int n = 12;
Tree tree = NULL;
for (int i = 0; i < n; i++) {
printf("Inserting %d\n", a[i]);
tree = insertIntoAVLTree(tree, a[i]);
inorder(tree);
printf(" --> %d\n\n", isBalancedTree(tree));
}
printf("Tree creation complete!\n\n");
printf("Press a key to continue...");
getchar();
for (int i = 0; i < n; i++) {
printf("Deleting %d\n", a[i]);
tree = deleteFromAVLTree(tree, a[i]);
inorder(tree);
printf(" --> %d\n\n", isBalancedTree(tree));
}
}
# define COMPACT
int _print_t(Tree tree, int is_left, int offset, int depth, char s[20][255])
{
char b[20];
int width = 5;
if (!tree) return 0;
sprintf(b, "(%03d)", tree->key);
int left = _print_t(tree->left, 1, offset, depth + 1, s);
int right = _print_t(tree->right, 0, offset + left + width, depth + 1, s);
#ifdef COMPACT
for (int i = 0; i < width; i++)
s[depth][offset + left + i] = b[i];
if (depth && is_left) {
for (int i = 0; i < width + right; i++)
s[depth - 1][offset + left + width/2 + i] = '-';
s[depth - 1][offset + left + width/2] = '.';
} else if (depth && !is_left) {
for (int i = 0; i < left + width; i++)
s[depth - 1][offset - width/2 + i] = '-';
s[depth - 1][offset + left + width/2] = '.';
}
#else
for (int i = 0; i < width; i++)
s[2 * depth][offset + left + i] = b[i];
if (depth && is_left) {
for (int i = 0; i < width + right; i++)
s[2 * depth - 1][offset + left + width/2 + i] = '-';
s[2 * depth - 1][offset + left + width/2] = '+';
s[2 * depth - 1][offset + left + width + right + width/2] = '+';
} else if (depth && !is_left) {
for (int i = 0; i < left + width; i++)
s[2 * depth - 1][offset - width/2 + i] = '-';
s[2 * depth - 1][offset + left + width/2] = '+';
s[2 * depth - 1][offset - width/2 - 1] = '+';
}
#endif
return left + width + right;
}
void print_t(Tree tree)
{
char s[20][255];
for (int i = 0; i < 20; i++)
sprintf(s[i], "%80s", " ");
_print_t(tree, 0, 0, 0, s);
for (int i = 0; i < 20; i++)
printf("%s\n", s[i]);
}
void driver2() {
Tree bst = NULL;
Tree avl = NULL;
char command[80];
while (1) {
printf("[bs-avl@tree ~]$ ");
scanf("%s", command);
if (strcmpi(command, "exit") == 0) {
break;
} else if (strcmpi(command, "insert") == 0) {
int key = 0;
scanf("%d", &key);
bst = insertIntoBST(bst, key);
avl = insertIntoAVLTree(avl, key);
} else if (strcmpi(command, "delete") == 0) {
int key = 0;
scanf("%d", &key);
bst = deleteFromBST(bst, key);
avl = deleteFromAVLTree(avl, key);
} else if (strcmpi(command, "print") == 0) {
scanf("%s", command);
if (strcmpi(command, "avl") == 0) {
print_t(avl);
} else if (strcmpi(command, "bst") == 0) {
print_t(bst);
}
}
}
}
int main(int argc, char *argv[]) {
driver1();
return 0;
}
|
the_stack_data/179831038.c | #include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
static int fork_exec(const char *command_name)
{
switch (fork())
{
case -1:
perror("fork");
exit(EXIT_FAILURE);
case 0:
if (-1 == execlp(command_name, command_name, NULL))
{
perror("execlp");
exit(EXIT_FAILURE);
}
}
int status;
if (-1 == wait(&status))
{
perror("wait");
exit(EXIT_FAILURE);
}
return WEXITSTATUS(status);
}
int main(int argc, const char *const *argv)
{
int exit_status = EXIT_SUCCESS;
for (int i = 1; i < argc; i++)
{
exit_status = fork_exec(argv[i]);
if (EXIT_SUCCESS != exit_status)
return exit_status;
}
return exit_status;
} |
the_stack_data/218894369.c | int XXX(int* nums, int numsSize){
int curnum = nums[0];
int maxnum = nums[0];
for(int i=1;i<numsSize;i++){
curnum = curnum>0?curnum+nums[i]:nums[i];
maxnum = maxnum>curnum?maxnum:curnum;
}
return maxnum;
}
|
the_stack_data/946323.c | #include <stdio.h>
#include <stdlib.h>
int int_cmp(const void* a, const void* b) {
return *(int*)a - *(int*)b;
}
int main() {
int N, M;
scanf("%d%d", &N, &M);
int* from = malloc(sizeof(int)*M);
int* to = malloc(sizeof(int)*M);
int* indegree = calloc(N, sizeof(int));
int* outdegree = calloc(N, sizeof(int));
int* inpos = calloc(N, sizeof(int));
int* outpos = calloc(N, sizeof(int));
int** inedges = malloc(sizeof(int*)*N);
int** outedges = malloc(sizeof(int*)*N);
int i, j;
for (i=0; i<M; i++) {
int a, b;
scanf("%d%d", &a, &b);
from[i] = a;
to[i] = b;
outdegree[a]++;
indegree[b]++;
}
for (i=0; i<N; i++) {
inedges[i] = malloc(sizeof(int)*indegree[i]);
outedges[i] = malloc(sizeof(int)*outdegree[i]);
}
for (i=0; i<M; i++) {
int a = from[i];
int b = to[i];
inedges[b][inpos[b]++] = a;
outedges[a][outpos[a]++] = b;
}
free(inpos);
free(outpos);
free(from);
free(to);
for (i=0; i<N; i++) {
qsort(inedges[i], indegree[i], sizeof(int), int_cmp);
qsort(outedges[i], outdegree[i], sizeof(int), int_cmp);
}
for (i=0; i<N; i++) {
for (j=0; j<indegree[i]; j++)
printf("%d ", inedges[i][j]);
printf("\n");
}
}
|
the_stack_data/43887112.c | #include <stdio.h>
#include <string.h>
#define ERR_UNKNOWN_LINE_TYPE 0x10
#define ERR_BACKWARDS_TIMESTAMP 0x11
typedef struct
{
unsigned int address;
unsigned int bitmask;
int result;
int hadFirstTimestamp;
unsigned long long timestamp;
char value;
FILE *fdOut;
} TranslationState;
static int parseArgs(TranslationState *state, int argc, char *argv[]);
static void translate(TranslationState *state, FILE *fdIn, FILE *fdOut);
static void translateLine(TranslationState *state, const char *line);
static void translateTimestampLine(TranslationState *state, const char *line);
static void translateReadOrWriteLine(TranslationState *state, const char *line);
int main(int argc, char *argv[])
{
TranslationState state;
memset(&state, 0, sizeof(TranslationState));
state.value = '0';
if (!parseArgs(&state, argc, argv))
{
printf("Usage: %s <address_hex> <bit_number>\n", argv[0]);
return 1;
}
translate(&state, stdin, stdout);
return state.result;
}
static int parseArgs(TranslationState *state, int argc, char *argv[])
{
unsigned int bitNumber;
if (argc != 3)
return 0;
if (sscanf(argv[1], "%i", &state->address) != 1)
return 0;
if (sscanf(argv[2], "%u", &bitNumber) != 1)
return 0;
if (bitNumber > 7)
return 0;
state->bitmask = (1 << bitNumber);
return 1;
}
static void translate(TranslationState *state, FILE *fdIn, FILE *fdOut)
{
char line[256];
state->fdOut = fdOut;
while (fgets(line, sizeof(line) - 1, fdIn) > 0)
{
translateLine(state, line);
if (state->result != 0)
return;
}
}
static void translateLine(TranslationState *state, const char *line)
{
if (line[0] == '0')
translateTimestampLine(state, line);
else if (line[0] == ' ')
translateReadOrWriteLine(state, line);
else
state->result = ERR_UNKNOWN_LINE_TYPE;
}
static void translateTimestampLine(TranslationState *state, const char *line)
{
unsigned long long i;
unsigned long long timestamp;
sscanf(line, "%Li", ×tamp);
if (timestamp < state->timestamp)
{
state->result = ERR_BACKWARDS_TIMESTAMP;
return;
}
if (state->hadFirstTimestamp)
{
for (i = state->timestamp + 1; i < timestamp; i++)
printf("0x%.16Lx %c\n", i, state->value);
}
else
state->hadFirstTimestamp = 1;
state->timestamp = timestamp;
}
static void translateReadOrWriteLine(TranslationState *state, const char *line)
{
char value[8];
char junk[128];
unsigned int address;
unsigned int valueAsInt;
if (sscanf(line, " Wrote: 0x%4s to %127[^(](%x)", value, junk, &address) != 3)
return;
if (address != state->address)
return;
value[0] = value[0] == '?' ? '0' : value[0];
value[1] = value[1] == '?' ? '0' : value[1];
value[2] = value[2] == '?' ? '0' : value[2];
value[3] = value[3] == '?' ? '0' : value[3];
sscanf(value, "%x", &valueAsInt);
state->value = (valueAsInt & state->bitmask) ? '1' : '0';
fprintf(state->fdOut, "0x%.16Lx %c\n", state->timestamp, state->value);
}
|
the_stack_data/212641954.c | #include <stdio.h>
#include <string.h>
typedef struct {
char nome[15];
int dataNasc;
int idade;
} dados;
void main () {
dados pessoa[6];
int i, j;
int maiorIdade = 0, menorIdade;
char nomePessoaMaisVelha[15] = " ";
char nomePessoaMaisNova[15] = " ";
for (i = 0; i < 6; i++) {
setbuf(stdin, NULL);
printf("\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
printf("----------------- Pessoa #%i -----------------\n", i+1);
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n");
printf("Nome ?\b ");
setbuf(stdin, NULL);
fgets(pessoa[i].nome, 15, stdin);
printf("Data Nasc. ?\b ");
setbuf(stdin, NULL);
scanf("%i", &pessoa[i].dataNasc);
pessoa[i].idade = 2020 - pessoa[i].dataNasc;
}
maiorIdade = pessoa[0].idade;
menorIdade = pessoa[0].idade;
for (i = 0; i < 6; i++) {
if (pessoa[i].idade > maiorIdade) {
maiorIdade = pessoa[i].idade;
strcpy(nomePessoaMaisVelha, pessoa[i].nome);
} else if (pessoa[i].idade < menorIdade) {
menorIdade = pessoa[i].idade;
strcpy(nomePessoaMaisNova, pessoa[i].nome);
}
}
printf("\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
printf("---> Pessoa mais velha: %s", nomePessoaMaisVelha);
printf("---> Pessoa mais nova: %s\n", nomePessoaMaisNova);
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n");
} |
the_stack_data/150141953.c | #include "stdio.h"
#define IN 1
#define OUT 0
void main()
{
int c, t;
int state;
state = OUT;
while( (c = getchar()) != EOF)
{
if(c == ' ' || c == '\n' || c == '\t')
{
state = OUT;
if(t == 1)
{
printf("\n");
}
t = 0;
}else if(state == OUT)
{
state = IN;
t = 1;
}
if(t == 1)
{
putchar(c);
}
}
}
|
the_stack_data/1032162.c | #include <stdio.h>
int main(void){
int v, w, d, ans = 0;
scanf("%d %d %d", &v, &w, &d);
double cnt = 0.0;
double vv = v;
while(cnt<d){
double tmp = 5*(double)(w*w)/(double)(vv*vv);
if(cnt + tmp <= d) cnt += tmp;
else break;
vv = vv*4.0/5.0;
ans++;
}
printf("%d", ans);
return 0;
}
|
the_stack_data/165769294.c |
void *shift(int *mem) { return mem + 20; }
int main(void) {
int array[10];
int *a = shift(array);
int *p = a - 16;
*p = 3;
test_assert(array[4] == 3);
return 0;
}
|
the_stack_data/305094.c | foo ()
{
return 0;
}
main()
{
int i, j, k, ccp_bad = 0;
for (i = 0; i < 10; i++)
{
for (j = 0; j < 10; j++)
if (foo ())
ccp_bad = 1;
k = ccp_bad != 0;
if (k)
abort ();
}
exit (0);
}
|
the_stack_data/26701158.c | /* Copyright (C) 1991, 1996 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <stdlib.h>
#undef rand
/* Return a random integer between 0 and RAND_MAX. */
int
rand ()
{
return (int) __random ();
}
|
the_stack_data/67325522.c | #include <stdio.h>
double areaCirculo(double r);
int main(void){
double area = areaCirculo(2);
printf("Area: %f\n", area);
return 0;
}
double areaCirculo(double r){
const double PI = 3.14159;
return PI * r * r;
} |
the_stack_data/785430.c | #include <stdio.h>
int main()
{
int n,k,i,a[100001]={},b,max=0;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&b);
a[b]++;
if(b>max){
max=b;
}
}
scanf("%d",&k);
for(i=max;i>=0;i--){
if(a[i]!=0){
k--;
}
if(k==0){
break;
}
}
printf("%d %d",i,a[i]);
} |
the_stack_data/248580719.c | typedef unsigned char u8;
typedef struct {} empty_s;
struct contains_empty {
u8 a;
empty_s empty;
u8 b;
};
struct contains_empty ce = { { (1) }, (empty_s){}, 022, };
/* The following decl of 'q' would demonstrate the TCC bug in init_putv when
handling copying compound literals. (Compound literals
aren't acceptable constant initializers in isoc99, but
we accept them like gcc, except for this case)
//char *q = (char *){ "trara" }; */
struct SS {u8 a[3], b; };
struct SS sinit16[] = { { 1 }, 2 };
struct S
{
u8 a,b;
u8 c[2];
};
struct T
{
u8 s[16];
u8 a;
};
struct U
{
u8 a;
struct S s;
u8 b;
struct T t;
};
struct V
{
struct S s;
struct T t;
u8 a;
};
struct W
{
struct V t;
struct S s[];
};
struct S gs = ((struct S){1, 2, 3, 4});
struct S gs2 = {1, 2, {3, 4}};
struct T gt = {"hello", 42};
struct U gu = {3, 5,6,7,8, 4, "huhu", 43};
struct U gu2 = {3, {5,6,7,8}, 4, {"huhu", 43}};
/* Optional braces around scalar initializers. Accepted, but with
a warning. */
struct U gu3 = { {3}, {5,6,7,8,}, 4, {"huhu", 43}};
/* Many superfluous braces and leaving out one initializer for U.s.c[1] */
struct U gu4 = { 3, {5,6,7,}, 5, { "bla", {44}} };
/* Superfluous braces and useless parens around values */
struct S gs3 = { (1), {(2)}, {(((3))), {4}}};
/* Superfluous braces, and leaving out braces for V.t, plus cast */
struct V gv = {{{3},4,{5,6}}, "haha", (u8)45, 46};
/* Compound literal */
struct V gv2 = {(struct S){7,8,{9,10}}, {"hihi", 47}, 48};
/* Parens around compound literal */
struct V gv3 = {((struct S){7,8,{9,10}}), {"hoho", 49}, 50};
/* Initialization of a flex array member (warns in GCC) */
struct W gw = {{1,2,3,4}, {1,2,3,4,5}};
union UU {
u8 a;
u8 b;
};
struct SU {
union UU u;
u8 c;
};
struct SU gsu = {5,6};
/* Unnamed struct/union members aren't ISO C, but it's a widely accepted
extension. See below for further extensions to that under -fms-extension.*/
union UV {
struct {u8 a,b;};
struct S s;
};
union UV guv = {{6,5}};
union UV guv2 = {{.b = 7, .a = 8}};
union UV guv3 = {.b = 8, .a = 7};
struct SSU {
int y;
struct { int x; };
};
struct SSU gssu1 = { .y = 5, .x = 3 };
struct SSU gssu2 = { 5, 3 };
/* Under -fms-extensions also the following is valid:
union UV2 {
struct Anon {u8 a,b;}; // unnamed member, but tagged struct, ...
struct S s;
};
struct Anon gan = { 10, 11 }; // ... which makes it available here.
union UV2 guv4 = {{4,3}}; // and the other inits from above as well
*/
struct in6_addr {
union {
u8 u6_addr8[16];
unsigned short u6_addr16[8];
} u;
};
struct flowi6 {
struct in6_addr saddr, daddr;
};
struct pkthdr {
struct in6_addr daddr, saddr;
};
struct pkthdr phdr = { { { 6,5,4,3 } }, { { 9,8,7,6 } } };
struct Wrap {
void *func;
};
int global;
void inc_global (void)
{
global++;
}
struct Wrap global_wrap[] = {
((struct Wrap) {inc_global}),
inc_global,
};
#include <stdio.h>
void print_ (const char *name, const u8 *p, long size)
{
printf ("%s:", name);
while (size--) {
printf (" %x", *p++);
}
printf ("\n");
}
#define print(x) print_(#x, (u8*)&x, sizeof (x))
#if 1
void foo (struct W *w, struct pkthdr *phdr_)
{
struct S ls = {1, 2, 3, 4};
struct S ls2 = {1, 2, {3, 4}};
struct T lt = {"hello", 42};
struct U lu = {3, 5,6,7,8, 4, "huhu", 43};
struct U lu1 = {3, ls, 4, {"huhu", 43}};
struct U lu2 = {3, (ls), 4, {"huhu", 43}};
const struct S *pls = &ls;
struct S ls21 = *pls;
struct U lu22 = {3, *pls, 4, {"huhu", 43}};
/* Incomplete bracing. */
struct U lu21 = {3, ls, 4, "huhu", 43};
/* Optional braces around scalar initializers. Accepted, but with
a warning. */
struct U lu3 = { 3, {5,6,7,8,}, 4, {"huhu", 43}};
/* Many superfluous braces and leaving out one initializer for U.s.c[1] */
struct U lu4 = { 3, {5,6,7,}, 5, { "bla", 44} };
/* Superfluous braces and useless parens around values */
struct S ls3 = { (1), (2), {(((3))), 4}};
/* Superfluous braces, and leaving out braces for V.t, plus cast */
struct V lv = {{3,4,{5,6}}, "haha", (u8)45, 46};
/* Compound literal */
struct V lv2 = {(struct S)w->t.s, {"hihi", 47}, 48};
/* Parens around compound literal */
struct V lv3 = {((struct S){7,8,{9,10}}), ((const struct W *)w)->t.t, 50};
const struct pkthdr *phdr = phdr_;
struct flowi6 flow = { .daddr = phdr->daddr, .saddr = phdr->saddr };
int elt = 0x42;
/* Range init, overlapping */
struct T lt2 = { { [1 ... 5] = 9, [6 ... 10] = elt, [4 ... 7] = elt+1 }, 1 };
struct SSU lssu1 = { 5, 3 };
struct SSU lssu2 = { .y = 5, .x = 3 };
print(ls);
print(ls2);
print(lt);
print(lu);
print(lu1);
print(lu2);
print(ls21);
print(lu21);
print(lu22);
print(lu3);
print(lu4);
print(ls3);
print(lv);
print(lv2);
print(lv3);
print(lt2);
print(lssu1);
print(lssu2);
print(flow);
}
#endif
void test_compound_with_relocs (void)
{
struct Wrap local_wrap[] = {
((struct Wrap) {inc_global}),
inc_global,
};
void (*p)(void);
p = global_wrap[0].func; p();
p = global_wrap[1].func; p();
p = local_wrap[0].func; p();
p = local_wrap[1].func; p();
}
void sys_ni(void) { printf("ni\n"); }
void sys_one(void) { printf("one\n"); }
void sys_two(void) { printf("two\n"); }
void sys_three(void) { printf("three\n"); }
typedef void (*fptr)(void);
const fptr table[3] = {
[0 ... 2] = &sys_ni,
[0] = sys_one,
[1] = sys_two,
[2] = sys_three,
};
void test_multi_relocs(void)
{
int i;
for (i = 0; i < sizeof(table)/sizeof(table[0]); i++)
table[i]();
}
/* Following is from GCC gcc.c-torture/execute/20050613-1.c. */
struct SEA { int i; int j; int k; int l; };
struct SEB { struct SEA a; int r[1]; };
struct SEC { struct SEA a; int r[0]; };
struct SED { struct SEA a; int r[]; };
static void
test_correct_filling (struct SEA *x)
{
static int i;
if (x->i != 0 || x->j != 5 || x->k != 0 || x->l != 0)
printf("sea_fill%d: wrong\n", i);
else
printf("sea_fill%d: okay\n", i);
i++;
}
int
test_zero_init (void)
{
/* The peculiarity here is that only a.j is initialized. That
means that all other members must be zero initialized. TCC
once didn't do that for sub-level designators. */
struct SEB b = { .a.j = 5 };
struct SEC c = { .a.j = 5 };
struct SED d = { .a.j = 5 };
test_correct_filling (&b.a);
test_correct_filling (&c.a);
test_correct_filling (&d.a);
return 0;
}
int main()
{
print(ce);
print(gs);
print(gs2);
print(gt);
print(gu);
print(gu2);
print(gu3);
print(gu4);
print(gs3);
print(gv);
print(gv2);
print(gv3);
print(sinit16);
print(gw);
print(gsu);
print(guv);
print(guv.b);
print(guv2);
print(guv3);
print(gssu1);
print(gssu2);
print(phdr);
foo(&gw, &phdr);
//printf("q: %s\n", q);
test_compound_with_relocs();
test_multi_relocs();
test_zero_init();
return 0;
}
|
the_stack_data/27066.c | #include <stdio.h>
void main()
{
int a[100];
int i, n, sum=0;
printf("\n\nFind sum of all elements of array:\n");
printf("--------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&a[i]);
}
for(i=0; i<n; i++)
{
sum += a[i];
}
printf("Sum of all elements stored in the array is : %d\n\n", sum);
}
|
the_stack_data/61075862.c | /**************************************************************************/
/*!
@file test_cdc_rndis_host.c
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2013, hathach (tinyusb.org)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This file is part of the tinyusb stack.
*/
/**************************************************************************/
void setUp(void)
{
}
void tearDown(void)
{
}
#if 0 // TODO enable
#include "stdlib.h"
#include "unity.h"
#include "tusb_option.h"
#include "tusb_errors.h"
#include "binary.h"
#include "type_helper.h"
#include "mock_osal.h"
#include "mock_hcd.h"
#include "mock_usbh.h"
#include "mock_cdc_callback.h"
#include "descriptor_cdc.h"
#include "cdc_host.h"
#include "cdc_rndis_host.h"
static uint8_t dev_addr;
static uint16_t length;
static tusb_desc_interface_t const * p_comm_interface = &rndis_config_descriptor.cdc_comm_interface;
static tusb_desc_endpoint_t const * p_endpoint_notification = &rndis_config_descriptor.cdc_endpoint_notification;
static tusb_desc_endpoint_t const * p_endpoint_out = &rndis_config_descriptor.cdc_endpoint_out;
static tusb_desc_endpoint_t const * p_endpoint_in = &rndis_config_descriptor.cdc_endpoint_in;
static pipe_handle_t pipe_notification = { .dev_addr = 1, .xfer_type = TUSB_XFER_INTERRUPT };
static pipe_handle_t pipe_out = { .dev_addr = 1, .xfer_type = TUSB_XFER_BULK, .index = 0 };
static pipe_handle_t pipe_in = { .dev_addr = 1, .xfer_type = TUSB_XFER_BULK, .index = 1 };
extern cdch_data_t cdch_data[CFG_TUSB_HOST_DEVICE_MAX];
extern rndish_data_t rndish_data[CFG_TUSB_HOST_DEVICE_MAX];
static cdch_data_t * p_cdc = &cdch_data[0];
static rndish_data_t * p_rndis = &rndish_data[0];
enum {
bmrequest_send = 0x21,
bmrequest_get = 0xA1
};
void stub_mutex_wait(osal_mutex_handle_t mutex_hdl, uint32_t msec, tusb_error_t *p_error, int num_call)
{
*p_error = TUSB_ERROR_NONE;
}
void setUp(void)
{
length = 0;
dev_addr = 1;
for (uint8_t i=0; i<CFG_TUSB_HOST_DEVICE_MAX; i++)
{
osal_semaphore_create_ExpectAndReturn( &rndish_data[i].semaphore_notification, &rndish_data[i].semaphore_notification);
}
cdch_init();
osal_mutex_wait_StubWithCallback(stub_mutex_wait);
osal_mutex_release_IgnoreAndReturn(TUSB_ERROR_NONE);
hcd_pipe_open_ExpectAndReturn(dev_addr, p_endpoint_notification, TUSB_CLASS_CDC, pipe_notification);
hcd_pipe_open_ExpectAndReturn(dev_addr, p_endpoint_out, TUSB_CLASS_CDC, pipe_out);
hcd_pipe_open_ExpectAndReturn(dev_addr, p_endpoint_in, TUSB_CLASS_CDC, pipe_in);
}
void tearDown(void)
{
}
static rndis_msg_initialize_t msg_init =
{
.type = RNDIS_MSG_INITIALIZE,
.length = sizeof(rndis_msg_initialize_t),
.request_id = 1, // TODO should use some magic number
.major_version = 1,
.minor_version = 0,
.max_xfer_size = 0x4000 // TODO mimic windows
};
static rndis_msg_initialize_cmplt_t msg_init_cmplt =
{
.type = RNDIS_MSG_INITIALIZE_CMPLT,
.length = sizeof(rndis_msg_initialize_cmplt_t),
.request_id = 1,
.status = RNDIS_STATUS_SUCCESS,
.major_version = 1,
.minor_version = 0,
.device_flags = 0x10,
.medium = 0, // TODO cannot find info on this
.max_packet_per_xfer = 1,
.max_xfer_size = 0x100, // TODO change later
.packet_alignment_factor = 5 // aligment of each RNDIS message (payload) = 2^factor
};
static rndis_msg_query_t msg_query_permanent_addr =
{
.type = RNDIS_MSG_QUERY,
.length = sizeof(rndis_msg_query_t)+6,
.request_id = 1,
.oid = RNDIS_OID_802_3_PERMANENT_ADDRESS,
.buffer_length = 6,
.buffer_offset = 20,
.oid_buffer = {0, 0, 0, 0, 0, 0}
};
static rndis_msg_query_cmplt_t msg_query_permanent_addr_cmplt =
{
.type = RNDIS_MSG_QUERY_CMPLT,
.length = sizeof(rndis_msg_query_cmplt_t)+6,
.request_id = 1,
.status = RNDIS_STATUS_SUCCESS,
.buffer_length = 6,
.buffer_offset = 16,
.oid_buffer = "CAFEBB"
};
static rndis_msg_set_t msg_set_packet_filter =
{
.type = RNDIS_MSG_SET,
.length = sizeof(rndis_msg_set_t)+4,
.request_id = 1,
.oid = RNDIS_OID_GEN_CURRENT_PACKET_FILTER,
.buffer_length = 4,
.buffer_offset = 20,
.oid_buffer = {RNDIS_PACKET_TYPE_DIRECTED | RNDIS_PACKET_TYPE_MULTICAST | RNDIS_PACKET_TYPE_BROADCAST, 0, 0, 0}
};
static rndis_msg_set_cmplt_t msg_set_packet_filter_cmplt =
{
.type = RNDIS_MSG_SET_CMPLT,
.length = sizeof(rndis_msg_set_cmplt_t),
.request_id = 1,
.status = RNDIS_STATUS_SUCCESS
};
static tusb_error_t stub_pipe_notification_xfer(pipe_handle_t pipe_hdl, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete, int num_call)
{
TEST_ASSERT( pipehandle_is_equal(pipe_notification, pipe_hdl) );
TEST_ASSERT_EQUAL( 8, total_bytes );
TEST_ASSERT( int_on_complete );
buffer[0] = 1; // response available
cdch_isr(pipe_hdl, XFER_RESULT_SUCCESS, 8);
return TUSB_ERROR_NONE;
}
void stub_sem_wait_success(osal_semaphore_handle_t const sem_hdl, uint32_t msec, tusb_error_t *p_error, int num_call)
{
TEST_ASSERT_EQUAL_HEX(p_rndis->sem_notification_hdl, sem_hdl);
(*p_error) = TUSB_ERROR_NONE;
}
void stub_sem_wait_timeout(osal_semaphore_handle_t const sem_hdl, uint32_t msec, tusb_error_t *p_error, int num_call)
{
(*p_error) = TUSB_ERROR_OSAL_TIMEOUT;
}
//------------- Test Code -------------//
void test_rndis_send_initalize_failed(void)
{
usbh_control_xfer_subtask_ExpectWithArrayAndReturn(
dev_addr, bmrequest_send, SEND_ENCAPSULATED_COMMAND, 0, p_comm_interface->bInterfaceNumber,
sizeof(rndis_msg_initialize_t), (uint8_t*)&msg_init, sizeof(rndis_msg_initialize_t), TUSB_ERROR_OSAL_TIMEOUT);
tusbh_cdc_mounted_cb_Expect(dev_addr);
//------------- Code Under Test -------------//
TEST_ASSERT_EQUAL( TUSB_ERROR_NONE, cdch_open_subtask(dev_addr, p_comm_interface, &length) );
}
void test_rndis_initialization_notification_timeout(void)
{
usbh_control_xfer_subtask_ExpectWithArrayAndReturn(
dev_addr, bmrequest_send, SEND_ENCAPSULATED_COMMAND, 0, p_comm_interface->bInterfaceNumber,
sizeof(rndis_msg_initialize_t), (uint8_t*)&msg_init, sizeof(rndis_msg_initialize_t), TUSB_ERROR_NONE);
hcd_pipe_xfer_IgnoreAndReturn(TUSB_ERROR_NONE);
osal_semaphore_wait_StubWithCallback(stub_sem_wait_timeout);
tusbh_cdc_mounted_cb_Expect(dev_addr);
//------------- Code Under Test -------------//
TEST_ASSERT_STATUS( cdch_open_subtask(dev_addr, p_comm_interface, &length) );
TEST_ASSERT_FALSE(p_cdc->is_rndis);
}
tusb_error_t stub_control_xfer(uint8_t addr, uint8_t bmRequestType, uint8_t bRequest,
uint16_t wValue, uint16_t wIndex, uint16_t wLength, uint8_t* data, int num_call )
{
TEST_ASSERT_EQUAL(p_comm_interface->bInterfaceNumber, wIndex);
TEST_ASSERT_EQUAL(0, wValue);
TEST_ASSERT_EQUAL(dev_addr, addr);
switch(num_call)
{
//------------- Initialize -------------//
case 0*2+0: // initialize
TEST_ASSERT_EQUAL(bmrequest_send, bmRequestType);
TEST_ASSERT_EQUAL(SEND_ENCAPSULATED_COMMAND, bRequest);
TEST_ASSERT_EQUAL(sizeof(rndis_msg_initialize_t), wLength);
TEST_ASSERT_EQUAL_HEX8_ARRAY(&msg_init, data, wLength);
break;
case 0*2+1: // initialize complete
TEST_ASSERT_EQUAL(bmrequest_get, bmRequestType);
TEST_ASSERT_EQUAL(GET_ENCAPSULATED_RESPONSE, bRequest);
TEST_ASSERT( wLength >= 0x0400 ); // Microsoft Specs
memcpy(data, &msg_init_cmplt, sizeof(rndis_msg_initialize_cmplt_t));
break;
// query for RNDIS_OID_802_3_PERMANENT_ADDRESS
case 1*2+0:
TEST_ASSERT_EQUAL(bmrequest_send, bmRequestType);
TEST_ASSERT_EQUAL(SEND_ENCAPSULATED_COMMAND, bRequest);
TEST_ASSERT_EQUAL(sizeof(rndis_msg_query_t) + 6, wLength); // 6 bytes for MAC address
TEST_ASSERT_EQUAL_HEX8_ARRAY(&msg_query_permanent_addr, data, wLength);
break;
case 1*2+1: // query complete for RNDIS_OID_802_3_PERMANENT_ADDRESS
TEST_ASSERT_EQUAL(bmrequest_get, bmRequestType);
TEST_ASSERT_EQUAL(GET_ENCAPSULATED_RESPONSE, bRequest);
TEST_ASSERT( wLength >= 0x0400 ); // Microsoft Specs
memcpy(data, &msg_query_permanent_addr_cmplt, sizeof(rndis_msg_query_cmplt_t) + 6);
break;
// set RNDIS_OID_GEN_CURRENT_PACKET_FILTER to DIRECTED | MULTICAST | BROADCAST
case 2*2+0:
TEST_ASSERT_EQUAL(bmrequest_send, bmRequestType);
TEST_ASSERT_EQUAL(SEND_ENCAPSULATED_COMMAND, bRequest);
TEST_ASSERT_EQUAL(sizeof(rndis_msg_set_t)+4, wLength);
TEST_ASSERT_EQUAL_HEX8_ARRAY(&msg_set_packet_filter, data, wLength);
break;
case 2*2+1: // query complete for RNDIS_OID_802_3_PERMANENT_ADDRESS
TEST_ASSERT_EQUAL(bmrequest_get, bmRequestType);
TEST_ASSERT_EQUAL(GET_ENCAPSULATED_RESPONSE, bRequest);
TEST_ASSERT( wLength >= 0x0400 ); // Microsoft Specs
memcpy(data, &msg_set_packet_filter_cmplt, sizeof(rndis_msg_set_cmplt_t) );
break;
default:
return TUSB_ERROR_OSAL_TIMEOUT;
}
return TUSB_ERROR_NONE;
}
void test_rndis_initialization_sequence_ok(void)
{
usbh_control_xfer_subtask_StubWithCallback(stub_control_xfer);
hcd_pipe_xfer_StubWithCallback(stub_pipe_notification_xfer);
osal_semaphore_wait_StubWithCallback(stub_sem_wait_success);
osal_semaphore_post_ExpectAndReturn(p_rndis->sem_notification_hdl, TUSB_ERROR_NONE);
osal_semaphore_post_ExpectAndReturn(p_rndis->sem_notification_hdl, TUSB_ERROR_NONE);
osal_semaphore_post_ExpectAndReturn(p_rndis->sem_notification_hdl, TUSB_ERROR_NONE);
tusbh_cdc_rndis_mounted_cb_Expect(dev_addr);
//------------- Code Under Test -------------//
TEST_ASSERT_STATUS( cdch_open_subtask(dev_addr, p_comm_interface, &length) );
TEST_ASSERT(p_cdc->is_rndis);
TEST_ASSERT_EQUAL(msg_init_cmplt.max_xfer_size, p_rndis->max_xfer_size);
TEST_ASSERT_EQUAL_HEX8_ARRAY("CAFEBB", p_rndis->mac_address, 6);
}
#endif
|
the_stack_data/108291.c | /*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* 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.
*/
/*===========================================================================
limProcessTdls.c
OVERVIEW:
DEPENDENCIES:
Are listed for each API below.
Copyright (c) 2010 Qualcomm Technologies, Inc.
All Rights Reserved.
Qualcomm Technologies Confidential and Proprietary
===========================================================================*/
/*===========================================================================
EDIT HISTORY FOR FILE
This section contains comments describing changes made to the module.
Notice that changes are listed in reverse chronological order.
$Header$$DateTime$$Author$
when who what, where, why
---------- --- --------------------------------------------------------
05/05/2010 Ashwani Initial Creation, added TDLS action frame functionality,
TDLS message exchange with SME..etc..
===========================================================================*/
/**
* \file limProcessTdls.c
*
* \brief Code for preparing,processing and sending 802.11z action frames
*
*/
#ifdef FEATURE_WLAN_TDLS
#include "sirApi.h"
#include "aniGlobal.h"
#include "sirMacProtDef.h"
#include "cfgApi.h"
#include "utilsApi.h"
#include "limTypes.h"
#include "limUtils.h"
#include "limSecurityUtils.h"
#include "dot11f.h"
#include "limStaHashApi.h"
#include "schApi.h"
#include "limSendMessages.h"
#include "utilsParser.h"
#include "limAssocUtils.h"
#include "dphHashTable.h"
#include "wlan_qct_wda.h"
/* define NO_PAD_TDLS_MIN_8023_SIZE to NOT padding: See CR#447630
There was IOT issue with cisco 1252 open mode, where it pads
discovery req/teardown frame with some junk value up to min size.
To avoid this issue, we pad QCOM_VENDOR_IE.
If there is other IOT issue because of this bandage, define NO_PAD...
*/
#ifndef NO_PAD_TDLS_MIN_8023_SIZE
#define MIN_IEEE_8023_SIZE 46
#define MIN_VENDOR_SPECIFIC_IE_SIZE 5
#endif
#ifdef WLAN_FEATURE_TDLS_DEBUG
#define TDLS_DEBUG_LOG_LEVEL VOS_TRACE_LEVEL_ERROR
#else
#define TDLS_DEBUG_LOG_LEVEL VOS_TRACE_LEVEL_INFO
#endif
#ifdef FEATURE_WLAN_TDLS_INTERNAL
/* forword declarations */
static tSirRetStatus limTdlsDisAddSta(tpAniSirGlobal pMac, tSirMacAddr peerMac,
tSirTdlsPeerInfo *peerInfo, tpPESession psessionEntry) ;
static eHalStatus limSendSmeTdlsLinkSetupInd(tpAniSirGlobal pMac,
tSirMacAddr peerMac, tANI_U8 status);
static eHalStatus limSendSmeTdlsDelPeerInd(tpAniSirGlobal pMac,
tANI_U8 sessionId, tDphHashNode *pStaDs, tANI_U8 status) ;
static tSirTdlsPeerInfo *limTdlsFindDisPeerByState(tpAniSirGlobal pMac,
tANI_U8 state);
static tANI_U8 limTdlsFindSetupPeerByState(tpAniSirGlobal pMac, tANI_U8 state,
tLimTdlsLinkSetupPeer **setupPeer) ;
static tSirRetStatus limTdlsLinkEstablish(tpAniSirGlobal pMac, tSirMacAddr peer_mac);
static tSirRetStatus limTdlsLinkTeardown(tpAniSirGlobal pMac, tSirMacAddr peer_mac);
static tpDphHashNode limTdlsDelSta(tpAniSirGlobal pMac, tSirMacAddr peerMac,
tpPESession psessionEntry) ;
#endif
static tSirRetStatus limTdlsSetupAddSta(tpAniSirGlobal pMac,
tSirTdlsAddStaReq *pAddStaReq,
tpPESession psessionEntry) ;
void PopulateDot11fLinkIden(tpAniSirGlobal pMac, tpPESession psessionEntry,
tDot11fIELinkIdentifier *linkIden,
tSirMacAddr peerMac, tANI_U8 reqType) ;
void PopulateDot11fTdlsExtCapability(tpAniSirGlobal pMac,
tDot11fIEExtCap *extCapability) ;
void limLogVHTCap(tpAniSirGlobal pMac,
tDot11fIEVHTCaps *pDot11f);
tSirRetStatus limPopulateVhtMcsSet(tpAniSirGlobal pMac,
tpSirSupportedRates pRates,
tDot11fIEVHTCaps *pPeerVHTCaps,
tpPESession psessionEntry);
ePhyChanBondState limGetHTCBState(ePhyChanBondState aniCBMode);
/*
* TDLS data frames will go out/come in as non-qos data.
* so, eth_890d_header will be aligned access..
*/
static const tANI_U8 eth_890d_header[] =
{
0xaa, 0xaa, 0x03, 0x00,
0x00, 0x00, 0x89, 0x0d,
} ;
/*
* type of links used in TDLS
*/
enum tdlsLinks
{
TDLS_LINK_AP,
TDLS_LINK_DIRECT
} eTdlsLink ;
/*
* node status in node searching
*/
enum tdlsLinkNodeStatus
{
TDLS_NODE_NOT_FOUND,
TDLS_NODE_FOUND
} eTdlsLinkNodeStatus ;
enum tdlsReqType
{
TDLS_INITIATOR,
TDLS_RESPONDER
} eTdlsReqType ;
typedef enum tdlsLinkSetupStatus
{
TDLS_SETUP_STATUS_SUCCESS = 0,
TDLS_SETUP_STATUS_FAILURE = 37
}etdlsLinkSetupStatus ;
/* some local defines */
#define LINK_IDEN_BSSID_OFFSET (0)
#define PEER_MAC_OFFSET (12)
#define STA_MAC_OFFSET (6)
#define LINK_IDEN_ELE_ID (101)
//#define LINK_IDEN_LENGTH (18)
#define LINK_IDEN_ADDR_OFFSET(x) (&x.LinkIdentifier)
#define PTI_LINK_IDEN_OFFSET (5)
#define PTI_BUF_STATUS_OFFSET (25)
/* TODO, Move this parameters to configuration */
#define PEER_PSM_SUPPORT (0)
#define PEER_BUFFER_STA_SUPPORT (0)
#define CH_SWITCH_SUPPORT (0)
#define TDLS_SUPPORT (1)
#define TDLS_PROHIBITED (0)
#define TDLS_CH_SWITCH_PROHIBITED (1)
/** @brief Set bit manipulation macro */
#define SET_BIT(value,mask) ((value) |= (1 << (mask)))
/** @brief Clear bit manipulation macro */
#define CLEAR_BIT(value,mask) ((value) &= ~(1 << (mask)))
/** @brief Check bit manipulation macro */
#define CHECK_BIT(value, mask) ((value) & (1 << (mask)))
#define SET_PEER_AID_BITMAP(peer_bitmap, aid) \
if ((aid) < (sizeof(tANI_U32) << 3)) \
SET_BIT(peer_bitmap[0], (aid)); \
else if ((aid) < (sizeof(tANI_U32) << 4)) \
SET_BIT(peer_bitmap[1], ((aid) - (sizeof(tANI_U32) << 3)));
#define CLEAR_PEER_AID_BITMAP(peer_bitmap, aid) \
if ((aid) < (sizeof(tANI_U32) << 3)) \
CLEAR_BIT(peer_bitmap[0], (aid)); \
else if ((aid) < (sizeof(tANI_U32) << 4)) \
CLEAR_BIT(peer_bitmap[1], ((aid) - (sizeof(tANI_U32) << 3)));
#ifdef LIM_DEBUG_TDLS
#define TDLS_CASE_RETURN_STRING(x) case (x): return( ((const tANI_U8*)#x) + 8); /* 8 = remove redundant SIR_MAC_ */
#ifdef FEATURE_WLAN_TDLS
#define WNI_CFG_TDLS_DISCOVERY_RSP_WAIT (100)
#define WNI_CFG_TDLS_LINK_SETUP_RSP_TIMEOUT (800)
#define WNI_CFG_TDLS_LINK_SETUP_CNF_TIMEOUT (200)
#endif
#define IS_QOS_ENABLED(psessionEntry) ((((psessionEntry)->limQosEnabled) && \
SIR_MAC_GET_QOS((psessionEntry)->limCurrentBssCaps)) || \
(((psessionEntry)->limWmeEnabled ) && \
LIM_BSS_CAPS_GET(WME, (psessionEntry)->limCurrentBssQosCaps)))
#define TID_AC_VI 4
#define TID_AC_BK 1
const tANI_U8* limTraceTdlsActionString( tANI_U8 tdlsActionCode )
{
switch( tdlsActionCode )
{
TDLS_CASE_RETURN_STRING(SIR_MAC_TDLS_SETUP_REQ);
TDLS_CASE_RETURN_STRING(SIR_MAC_TDLS_SETUP_RSP);
TDLS_CASE_RETURN_STRING(SIR_MAC_TDLS_SETUP_CNF);
TDLS_CASE_RETURN_STRING(SIR_MAC_TDLS_TEARDOWN);
TDLS_CASE_RETURN_STRING(SIR_MAC_TDLS_PEER_TRAFFIC_IND);
TDLS_CASE_RETURN_STRING(SIR_MAC_TDLS_CH_SWITCH_REQ);
TDLS_CASE_RETURN_STRING(SIR_MAC_TDLS_CH_SWITCH_RSP);
TDLS_CASE_RETURN_STRING(SIR_MAC_TDLS_PEER_TRAFFIC_RSP);
TDLS_CASE_RETURN_STRING(SIR_MAC_TDLS_DIS_REQ);
TDLS_CASE_RETURN_STRING(SIR_MAC_TDLS_DIS_RSP);
}
return (const tANI_U8*)"UNKNOWN";
}
#endif
#if 0
static void printMacAddr(tSirMacAddr macAddr)
{
int i = 0 ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, (" Mac Addr: "));
for(i = 0 ; i < 6; i++)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
(" %02x "), macAddr[i]);
}
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, (""));
return ;
}
#endif
/*
* initialize TDLS setup list and related data structures.
*/
void limInitTdlsData(tpAniSirGlobal pMac, tpPESession pSessionEntry)
{
#ifdef FEATURE_WLAN_TDLS_INTERNAL
pMac->lim.gLimTdlsDisResultList = NULL ;
pMac->lim.gLimTdlsDisStaCount = 0 ;
vos_mem_set(&pMac->lim.gLimTdlsDisReq, sizeof(tSirTdlsDisReq), 0);
vos_mem_set(&pMac->lim.gLimTdlsLinkSetupInfo, sizeof(tLimTdlsLinkSetupInfo), 0);
pMac->lim.gAddStaDisRspWait = 0 ;
#ifdef FEATURE_WLAN_TDLS_NEGATIVE
/* when reassociated, negative behavior will not be kept */
/* you have to explicitly enable negative behavior per (re)association */
pMac->lim.gLimTdlsNegativeBehavior = 0;
#endif
#endif
limInitPeerIdxpool(pMac, pSessionEntry) ;
return ;
}
#ifdef FEATURE_WLAN_TDLS_NEGATIVE
void limTdlsSetNegativeBehavior(tpAniSirGlobal pMac, tANI_U8 value, tANI_BOOLEAN on)
{
if(on) {
if(value == 255)
pMac->lim.gLimTdlsNegativeBehavior = 0XFFFFFFFF;
else
pMac->lim.gLimTdlsNegativeBehavior |= (1 << (value-1));
}
else {
if(value == 255)
pMac->lim.gLimTdlsNegativeBehavior = 0;
else
pMac->lim.gLimTdlsNegativeBehavior &= ~(1 << (value-1));
}
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,("%d %d -> gLimTdlsNegativeBehavior= 0x%lx"), \
value, on, pMac->lim.gLimTdlsNegativeBehavior));
}
#endif
#if 0
/*
* This function is used for creating TDLS public Action frame to
* transmit on Direct link
*/
static void limPreparesActionFrameHdr(tpAniSirGlobal pMac, tANI_U8 *pFrame,
tANI_U8 type, tANI_U8 subType,
tANI_U8 *link_iden )
{
tpSirMacMgmtHdr pMacHdr ;
tANI_U8 *bssid = link_iden ;
#if 0
tANI_U8 *staMac = (tANI_U8 *)(bssid + sizeof(tSirMacAddr)) ;
tANI_U8 *peerMac = (tANI_U8 *) (staMac + sizeof(tSirMacAddr)) ;
#else
tANI_U8 *peerMac = (tANI_U8 *) (bssid + sizeof(tSirMacAddr)) ;
tANI_U8 *staMac = (tANI_U8 *)(peerMac + sizeof(tSirMacAddr)) ;
#endif
tANI_U8 toDs = ANI_TXDIR_IBSS ;
pMacHdr = (tpSirMacMgmtHdr) (pFrame);
/*
* prepare 802.11 header
*/
pMacHdr->fc.protVer = SIR_MAC_PROTOCOL_VERSION;
pMacHdr->fc.type = type ;
pMacHdr->fc.subType = subType ;
/*
* TL is not setting up below fields, so we are doing it here
*/
pMacHdr->fc.toDS = toDs ;
pMacHdr->fc.powerMgmt = 0 ;
vos_mem_copy( (tANI_U8 *) pMacHdr->da, peerMac, sizeof( tSirMacAddr ));
vos_mem_copy( (tANI_U8 *) pMacHdr->sa,
staMac, sizeof( tSirMacAddr ));
vos_mem_copy( (tANI_U8 *) pMacHdr->bssId,
bssid, sizeof( tSirMacAddr ));
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_WARN, ("Preparing TDLS action frame\n%02x:%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x:%02x"), \
pMacHdr->da[0], pMacHdr->da[1], pMacHdr->da[2], pMacHdr->da[3], pMacHdr->da[4], pMacHdr->da[5], \
pMacHdr->sa[0], pMacHdr->sa[1], pMacHdr->sa[2], pMacHdr->sa[3], pMacHdr->sa[4], pMacHdr->sa[5], \
pMacHdr->bssId[0], pMacHdr->bssId[1], pMacHdr->bssId[2], \
pMacHdr->bssId[3], pMacHdr->bssId[4], pMacHdr->bssId[5]));
return ;
}
#endif
/*
* prepare TDLS frame header, it includes
* | | | |
* |802.11 header|RFC1042 header|TDLS_PYLOAD_TYPE|PAYLOAD
* | | | |
*/
static tANI_U32 limPrepareTdlsFrameHeader(tpAniSirGlobal pMac, tANI_U8* pFrame,
tDot11fIELinkIdentifier *link_iden, tANI_U8 tdlsLinkType, tANI_U8 reqType,
tANI_U8 tid, tpPESession psessionEntry)
{
tpSirMacDataHdr3a pMacHdr ;
tANI_U32 header_offset = 0 ;
tANI_U8 *addr1 = NULL ;
tANI_U8 *addr3 = NULL ;
tANI_U8 toDs = (tdlsLinkType == TDLS_LINK_AP)
? ANI_TXDIR_TODS :ANI_TXDIR_IBSS ;
tANI_U8 *peerMac = (reqType == TDLS_INITIATOR)
? link_iden->RespStaAddr : link_iden->InitStaAddr;
tANI_U8 *staMac = (reqType == TDLS_INITIATOR)
? link_iden->InitStaAddr : link_iden->RespStaAddr;
pMacHdr = (tpSirMacDataHdr3a) (pFrame);
/*
* if TDLS frame goes through the AP link, it follows normal address
* pattern, if TDLS frame goes thorugh the direct link, then
* A1--> Peer STA addr, A2-->Self STA address, A3--> BSSID
*/
(tdlsLinkType == TDLS_LINK_AP) ? ((addr1 = (link_iden->bssid)),
(addr3 = (peerMac)))
: ((addr1 = (peerMac)),
(addr3 = (link_iden->bssid))) ;
/*
* prepare 802.11 header
*/
pMacHdr->fc.protVer = SIR_MAC_PROTOCOL_VERSION;
pMacHdr->fc.type = SIR_MAC_DATA_FRAME ;
pMacHdr->fc.subType = IS_QOS_ENABLED(psessionEntry) ? SIR_MAC_DATA_QOS_DATA : SIR_MAC_DATA_DATA;
/*
* TL is not setting up below fields, so we are doing it here
*/
pMacHdr->fc.toDS = toDs ;
pMacHdr->fc.powerMgmt = 0 ;
pMacHdr->fc.wep = (psessionEntry->encryptType == eSIR_ED_NONE)? 0 : 1;
vos_mem_copy( (tANI_U8 *) pMacHdr->addr1,
(tANI_U8 *)addr1,
sizeof( tSirMacAddr ));
vos_mem_copy( (tANI_U8 *) pMacHdr->addr2,
(tANI_U8 *) staMac,
sizeof( tSirMacAddr ));
vos_mem_copy( (tANI_U8 *) pMacHdr->addr3,
(tANI_U8 *) (addr3),
sizeof( tSirMacAddr ));
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_WARN, ("Preparing TDLS frame header to %s\n%02x:%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x:%02x"), \
(tdlsLinkType == TDLS_LINK_AP) ? "AP" : "TD", \
pMacHdr->addr1[0], pMacHdr->addr1[1], pMacHdr->addr1[2], pMacHdr->addr1[3], pMacHdr->addr1[4], pMacHdr->addr1[5], \
pMacHdr->addr2[0], pMacHdr->addr2[1], pMacHdr->addr2[2], pMacHdr->addr2[3], pMacHdr->addr2[4], pMacHdr->addr2[5], \
pMacHdr->addr3[0], pMacHdr->addr3[1], pMacHdr->addr3[2], pMacHdr->addr3[3], pMacHdr->addr3[4], pMacHdr->addr3[5]));
//printMacAddr(pMacHdr->bssId) ;
//printMacAddr(pMacHdr->sa) ;
//printMacAddr(pMacHdr->da) ;
if (IS_QOS_ENABLED(psessionEntry))
{
pMacHdr->qosControl.tid = tid;
header_offset += sizeof(tSirMacDataHdr3a);
}
else
header_offset += sizeof(tSirMacMgmtHdr);
/*
* Now form RFC1042 header
*/
vos_mem_copy((tANI_U8 *)(pFrame + header_offset),
(tANI_U8 *)eth_890d_header, sizeof(eth_890d_header)) ;
header_offset += sizeof(eth_890d_header) ;
/* add payload type as TDLS */
*(pFrame + header_offset) = PAYLOAD_TYPE_TDLS ;
return(header_offset += PAYLOAD_TYPE_TDLS_SIZE) ;
}
/*
* TX Complete for Management frames
*/
eHalStatus limMgmtTXComplete(tpAniSirGlobal pMac,
tANI_U32 txCompleteSuccess)
{
tpPESession psessionEntry = NULL ;
if (0xff != pMac->lim.mgmtFrameSessionId)
{
psessionEntry = peFindSessionBySessionId(pMac, pMac->lim.mgmtFrameSessionId);
if (NULL == psessionEntry)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("%s: sessionID %d is not found"), __func__, pMac->lim.mgmtFrameSessionId);
return eHAL_STATUS_FAILURE;
}
limSendSmeMgmtTXCompletion(pMac, psessionEntry, txCompleteSuccess);
pMac->lim.mgmtFrameSessionId = 0xff;
}
return eHAL_STATUS_SUCCESS;
}
/*
* This function can be used for bacst or unicast discovery request
* We are not differentiating it here, it will all depnds on peer MAC address,
*/
tSirRetStatus limSendTdlsDisReqFrame(tpAniSirGlobal pMac, tSirMacAddr peer_mac,
tANI_U8 dialog, tpPESession psessionEntry)
{
tDot11fTDLSDisReq tdlsDisReq ;
tANI_U32 status = 0 ;
tANI_U32 nPayload = 0 ;
tANI_U32 size = 0 ;
tANI_U32 nBytes = 0 ;
tANI_U32 header_offset = 0 ;
tANI_U8 *pFrame;
void *pPacket;
eHalStatus halstatus;
#ifndef NO_PAD_TDLS_MIN_8023_SIZE
tANI_U32 padLen = 0;
#endif
/*
* The scheme here is to fill out a 'tDot11fProbeRequest' structure
* and then hand it off to 'dot11fPackProbeRequest' (for
* serialization). We start by zero-initializing the structure:
*/
vos_mem_set( (tANI_U8*)&tdlsDisReq,
sizeof( tDot11fTDLSDisReq ), 0 );
/*
* setup Fixed fields,
*/
tdlsDisReq.Category.category = SIR_MAC_ACTION_TDLS ;
tdlsDisReq.Action.action = SIR_MAC_TDLS_DIS_REQ ;
tdlsDisReq.DialogToken.token = dialog ;
size = sizeof(tSirMacAddr) ;
PopulateDot11fLinkIden( pMac, psessionEntry, &tdlsDisReq.LinkIdentifier,
peer_mac, TDLS_INITIATOR) ;
/*
* now we pack it. First, how much space are we going to need?
*/
status = dot11fGetPackedTDLSDisReqSize( pMac, &tdlsDisReq, &nPayload);
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGP, FL("Failed to calculate the packed size f"
"or a discovery Request (0x%08x)."), status );
/* We'll fall back on the worst case scenario: */
nPayload = sizeof( tDot11fTDLSDisReq );
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while calculating"
"the packed size for a discovery Request ("
"0x%08x)."), status );
}
/*
* This frame is going out from PE as data frames with special ethertype
* 89-0d.
* 8 bytes of RFC 1042 header
*/
nBytes = nPayload + ((IS_QOS_ENABLED(psessionEntry))
? sizeof(tSirMacDataHdr3a) : sizeof(tSirMacMgmtHdr))
+ sizeof( eth_890d_header )
+ PAYLOAD_TYPE_TDLS_SIZE ;
#ifndef NO_PAD_TDLS_MIN_8023_SIZE
/* IOT issue with some AP : some AP doesn't like the data packet size < minimum 802.3 frame length (64)
Hence AP itself padding some bytes, which caused teardown packet is dropped at
receiver side. To avoid such IOT issue, we added some extra bytes to meet data frame size >= 64
*/
if (nPayload + PAYLOAD_TYPE_TDLS_SIZE < MIN_IEEE_8023_SIZE)
{
padLen = MIN_IEEE_8023_SIZE - (nPayload + PAYLOAD_TYPE_TDLS_SIZE ) ;
/* if padLen is less than minimum vendorSpecific (5), pad up to 5 */
if (padLen < MIN_VENDOR_SPECIFIC_IE_SIZE)
padLen = MIN_VENDOR_SPECIFIC_IE_SIZE;
nBytes += padLen;
}
#endif
/* Ok-- try to allocate memory from MGMT PKT pool */
halstatus = palPktAlloc( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( tANI_U16 )nBytes, ( void** ) &pFrame,
( void** ) &pPacket );
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
limLog( pMac, LOGP, FL("Failed to allocate %d bytes for a TDLS"
"Discovery Request."), nBytes );
return eSIR_MEM_ALLOC_FAILED;
}
/* zero out the memory */
vos_mem_set( pFrame, nBytes, 0 );
/*
* IE formation, memory allocation is completed, Now form TDLS discovery
* request frame
*/
/* fill out the buffer descriptor */
header_offset = limPrepareTdlsFrameHeader(pMac, pFrame,
LINK_IDEN_ADDR_OFFSET(tdlsDisReq), TDLS_LINK_AP, TDLS_INITIATOR, TID_AC_VI, psessionEntry) ;
#ifdef FEATURE_WLAN_TDLS_NEGATIVE
if(pMac->lim.gLimTdlsNegativeBehavior & LIM_TDLS_NEGATIVE_WRONG_BSSID_IN_DSCV_REQ)
{
tdlsDisReq.LinkIdentifier.bssid[4] = 0xde;
tdlsDisReq.LinkIdentifier.bssid[5] = 0xad;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("TDLS negative running: wrong BSSID %02x:%02x:%02x:%02x:%02x:%02x in TDLS Discovery Req"), \
tdlsDisReq.LinkIdentifier.bssid[0],
tdlsDisReq.LinkIdentifier.bssid[1],
tdlsDisReq.LinkIdentifier.bssid[2],
tdlsDisReq.LinkIdentifier.bssid[3],
tdlsDisReq.LinkIdentifier.bssid[4],
tdlsDisReq.LinkIdentifier.bssid[5]);
}
#endif
status = dot11fPackTDLSDisReq( pMac, &tdlsDisReq, pFrame
+ header_offset, nPayload, &nPayload );
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGE, FL("Failed to pack a TDLS discovery req \
(0x%08x)."), status );
palPktFree( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( void* ) pFrame, ( void* ) pPacket );
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while packing TDLS"
"Discovery Request (0x%08x).") );
}
#ifndef NO_PAD_TDLS_MIN_8023_SIZE
if (padLen != 0)
{
/* QCOM VENDOR OUI = { 0x00, 0xA0, 0xC6, type = 0x0000 }; */
tANI_U8 *padVendorSpecific = pFrame + header_offset + nPayload;
/* make QCOM_VENDOR_OUI, and type = 0x0000, and all the payload to be zero */
padVendorSpecific[0] = 221;
padVendorSpecific[1] = padLen - 2;
padVendorSpecific[2] = 0x00;
padVendorSpecific[3] = 0xA0;
padVendorSpecific[4] = 0xC6;
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO, ("Padding Vendor Specific Ie Len = %d"),
padLen ));
/* padding zero if more than 5 bytes are required */
if (padLen > MIN_VENDOR_SPECIFIC_IE_SIZE)
vos_mem_set( pFrame + header_offset + nPayload + MIN_VENDOR_SPECIFIC_IE_SIZE,
padLen - MIN_VENDOR_SPECIFIC_IE_SIZE, 0);
}
#endif
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, TDLS_DEBUG_LOG_LEVEL, ("[TDLS] action %d (%s) -AP-> OTA "),
SIR_MAC_TDLS_DIS_REQ, limTraceTdlsActionString(SIR_MAC_TDLS_DIS_REQ) ));
halstatus = halTxFrameWithTxComplete( pMac, pPacket, ( tANI_U16 ) nBytes,
HAL_TXRX_FRM_802_11_DATA,
ANI_TXDIR_TODS,
TID_AC_VI,
limTxComplete, pFrame,
limMgmtTXComplete,
HAL_USE_BD_RATE2_FOR_MANAGEMENT_FRAME);
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
pMac->lim.mgmtFrameSessionId = 0xff;
limLog( pMac, LOGE, FL("could not send TDLS Dis Request frame!" ));
return eSIR_FAILURE;
}
pMac->lim.mgmtFrameSessionId = psessionEntry->peSessionId;
return eSIR_SUCCESS;
}
#ifdef FEATURE_WLAN_TDLS_INTERNAL
/*
* Once Discovery response is sent successfully (or failure) on air, now send
* response to PE and send del STA to HAL.
*/
eHalStatus limTdlsDisRspTxComplete(tpAniSirGlobal pMac,
tANI_U32 txCompleteSuccess)
{
eHalStatus status = eHAL_STATUS_SUCCESS ;
tpDphHashNode pStaDs = NULL ;
tSirTdlsPeerInfo *peerInfo = 0 ;
/* find peer by looking into the list by expected state */
peerInfo = limTdlsFindDisPeerByState(pMac, TDLS_DIS_RSP_SENT_WAIT_STATE) ;
if(NULL == peerInfo)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("DisRspTxComplete: No TDLS state machine waits for this event"));
VOS_ASSERT(0) ;
return eHAL_STATUS_FAILURE;
}
peerInfo->tdlsPeerState = TDLS_DIS_RSP_SENT_DONE_STATE ;
if(peerInfo->delStaNeeded)
{
tpPESession psessionEntry;
peerInfo->delStaNeeded = false ;
psessionEntry = peFindSessionBySessionId (pMac, peerInfo->sessionId);
if(NULL == psessionEntry)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("DisRspTxComplete: sessionID %d is not found"), peerInfo->sessionId);
return eHAL_STATUS_FAILURE;
}
/* send del STA to remove context for this TDLS STA */
pStaDs = limTdlsDelSta(pMac, peerInfo->peerMac, psessionEntry) ;
/* now send indication to SME-->HDD->TL to remove STA from TL */
if(pStaDs)
{
limSendSmeTdlsDelPeerInd(pMac, psessionEntry->smeSessionId,
pStaDs, eSIR_SUCCESS) ;
}
else
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("DisRspTxComplete: staDs not found for %02x:%02x:%02x:%02x:%02x:%02x"),
(peerInfo)->peerMac[0],
(peerInfo)->peerMac[1],
(peerInfo)->peerMac[2],
(peerInfo)->peerMac[3],
(peerInfo)->peerMac[4],
(peerInfo)->peerMac[5]) ;
VOS_ASSERT(0) ;
return eHAL_STATUS_FAILURE;
}
}
if(!txCompleteSuccess)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("TX complete failure for Dis RSP"));
limSendSmeTdlsDisRsp(pMac, eSIR_FAILURE,
eWNI_SME_TDLS_DISCOVERY_START_IND) ;
status = eHAL_STATUS_FAILURE;
}
else
{
limSendSmeTdlsDisRsp(pMac, eSIR_SUCCESS,
eWNI_SME_TDLS_DISCOVERY_START_IND) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("TX complete Success for Dis RSP"));
status = eHAL_STATUS_SUCCESS ;
}
//pMac->hal.pCBackFnTxComp = NULL ;
return status ;
}
#endif
#ifdef FEATURE_WLAN_TDLS_INTERNAL
/*
* Once setup CNF is sent successfully (or failure) on air, now send
* response to PE and send del STA to HAL.
*/
eHalStatus limTdlsSetupCnfTxComplete(tpAniSirGlobal pMac,
tANI_U32 txCompleteSuccess)
{
eHalStatus status = eHAL_STATUS_SUCCESS ;
tLimTdlsLinkSetupPeer *peerInfo = 0 ;
/* find peer by looking into the list by expected state */
limTdlsFindSetupPeerByState(pMac,
TDLS_LINK_SETUP_RSP_WAIT_STATE, &peerInfo) ;
if(NULL == peerInfo)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("limTdlsSetupCnfTxComplete: No TDLS state machine waits for this event"));
VOS_ASSERT(0) ;
return eHAL_STATUS_FAILURE;
}
(peerInfo)->tdls_prev_link_state = (peerInfo)->tdls_link_state ;
(peerInfo)->tdls_link_state = TDLS_LINK_SETUP_DONE_STATE ;
if(!txCompleteSuccess)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("TX complete Failure for setup CNF"));
limSendSmeTdlsLinkStartRsp(pMac, eSIR_FAILURE, (peerInfo)->peerMac,
eWNI_SME_TDLS_LINK_START_RSP) ;
status = eHAL_STATUS_FAILURE;
}
else
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("RSP-->SME peer MAC = %02x,%02x,%02x,%02x,%02x,%02x"),
(peerInfo)->peerMac[0],
(peerInfo)->peerMac[1],
(peerInfo)->peerMac[2],
(peerInfo)->peerMac[3],
(peerInfo)->peerMac[4],
(peerInfo)->peerMac[5]) ;
limSendSmeTdlsLinkStartRsp(pMac, eSIR_SUCCESS, (peerInfo)->peerMac,
eWNI_SME_TDLS_LINK_START_RSP) ;
/* tdls_hklee: prepare PTI template and send it to HAL */
limTdlsLinkEstablish(pMac, (peerInfo)->peerMac);
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("TX complete Success for setup CNF"));
status = eHAL_STATUS_SUCCESS ;
}
//pMac->hal.pCBackFnTxComp = NULL ;
return status ;
}
#endif
#ifdef FEATURE_WLAN_TDLS_INTERNAL
/*
* Tx Complete for Teardown frame
*/
eHalStatus limTdlsTeardownTxComplete(tpAniSirGlobal pMac,
tANI_U32 txCompleteSuccess)
{
eHalStatus status = eHAL_STATUS_SUCCESS ;
tpDphHashNode pStaDs = NULL ;
tLimTdlsLinkSetupPeer *peerInfo = 0 ;
tpPESession psessionEntry = NULL ;
//tANI_U16 msgType = 0 ;
//tSirMacAddr peerMac = {0} ;
/* find peer by looking into the list by expected state */
limTdlsFindSetupPeerByState(pMac,
TDLS_LINK_TEARDOWN_START_STATE, &peerInfo) ;
if(NULL == peerInfo)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("limTdlsTeardownTxComplete: No TDLS state machine waits for this event"));
VOS_ASSERT(0) ;
return eHAL_STATUS_FAILURE;
}
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("teardown peer Mac = %02x,%02x,%02x,%02x,%02x,%02x"),
(peerInfo)->peerMac[0],
(peerInfo)->peerMac[1],
(peerInfo)->peerMac[2],
(peerInfo)->peerMac[3],
(peerInfo)->peerMac[4],
(peerInfo)->peerMac[5]);
//pMac->hal.pCBackFnTxComp = NULL ;
psessionEntry = peFindSessionBySessionId(pMac, (peerInfo)->tdls_sessionId);
if(NULL == psessionEntry)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("limTdlsTeardownTxComplete: sessionID %d is not found"), (peerInfo)->tdls_sessionId);
VOS_ASSERT(0) ;
return eHAL_STATUS_FAILURE;
}
if(!txCompleteSuccess)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("TX complete failure for Teardown ")) ;
/*
* we should be sending Teradown to AP with status code
* eSIR_MAC_TDLS_TEARDOWN_PEER_UNREACHABLE, we are not worried if
* that is delivered or not, any way we removing this peer STA from our
* list
*/
if(NULL != psessionEntry)
{
limSendTdlsTeardownFrame(pMac, (peerInfo)->peerMac,
eSIR_MAC_TDLS_TEARDOWN_PEER_UNREACHABLE, psessionEntry, NULL, 0) ;
}
}
if(TDLS_LINK_SETUP_WAIT_STATE != (peerInfo)->tdls_prev_link_state)
{
(peerInfo)->tdls_prev_link_state = (peerInfo)->tdls_link_state ;
(peerInfo)->tdls_link_state = TDLS_LINK_TEARDOWN_DONE_STATE ;
/* send del STA to remove context for this TDLS STA */
if(NULL != psessionEntry)
{
/* tdls_hklee: send message to HAL before it is deleted */
limTdlsLinkTeardown(pMac, (peerInfo)->peerMac) ;
pStaDs = limTdlsDelSta(pMac, (peerInfo)->peerMac, psessionEntry) ;
}
/* now send indication to SME-->HDD->TL to remove STA from TL */
if(!pStaDs)
{
VOS_ASSERT(0) ;
return eSIR_FAILURE ;
}
limSendSmeTdlsDelPeerInd(pMac, psessionEntry->smeSessionId,
pStaDs, eSIR_SUCCESS) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("TX complete SUCCESS for Teardown")) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Prev State = %d"), (peerInfo)->tdls_prev_link_state) ;
limSendSmeTdlsTeardownRsp(pMac, eSIR_SUCCESS, (peerInfo)->peerMac,
eWNI_SME_TDLS_TEARDOWN_RSP) ;
/* Delete Peer for Link Peer List */
limTdlsDelLinkPeer(pMac, (peerInfo)->peerMac) ;
}
else
{
(peerInfo)->tdls_prev_link_state = (peerInfo)->tdls_link_state ;
(peerInfo)->tdls_link_state = TDLS_LINK_TEARDOWN_DONE_STATE ;
limSendSmeTdlsTeardownRsp(pMac, eSIR_SUCCESS, (peerInfo)->peerMac,
eWNI_SME_TDLS_TEARDOWN_IND) ;
}
#if 0
/* if previous state is link restart, then restart link setup again */
if(TDLS_LINK_SETUP_RESTART_STATE == (peerInfo)->tdls_prev_link_state)
{
tLimTdlsLinkSetupInfo *setupInfo = &pMac->lim.gLimTdlsLinkSetupInfo ;
limTdlsPrepareSetupReqFrame(pMac, setupInfo, 37,
peerMac, psessionEntry) ;
}
#endif
status = eHAL_STATUS_SUCCESS ;
return status ;
}
#endif
/*
* This static function is consistent with any kind of TDLS management
* frames we are sending. Currently it is being used by limSendTdlsDisRspFrame,
* limSendTdlsLinkSetupReqFrame and limSendTdlsSetupRspFrame
*/
static void PopulateDot11fTdlsHtVhtCap(tpAniSirGlobal pMac, uint32 selfDot11Mode,
tDot11fIEHTCaps *htCap, tDot11fIEVHTCaps *vhtCap,
tpPESession psessionEntry)
{
if (IS_DOT11_MODE_HT(selfDot11Mode))
{
/* Include HT Capability IE */
PopulateDot11fHTCaps( pMac, NULL, htCap );
htCap->present = 1;
if (psessionEntry->currentOperChannel <= SIR_11B_CHANNEL_END)
{
/* hardcode NO channel bonding in 2.4Ghz */
htCap->supportedChannelWidthSet = 0;
}
else
{
//Placeholder to support different channel bonding mode of TDLS than AP.
//wlan_cfgGetInt(pMac,WNI_CFG_TDLS_CHANNEL_BONDING_MODE,&tdlsChannelBondingMode);
//htCap->supportedChannelWidthSet = tdlsChannelBondingMode ? 1 : 0;
htCap->supportedChannelWidthSet = 1; // hardcode it to max
}
}
else
{
htCap->present = 0;
}
#ifdef WLAN_FEATURE_11AC
if (((psessionEntry->currentOperChannel <= SIR_11B_CHANNEL_END) &&
pMac->roam.configParam.enableVhtFor24GHz) ||
(psessionEntry->currentOperChannel >= SIR_11B_CHANNEL_END))
{
if (IS_DOT11_MODE_VHT(selfDot11Mode) &&
IS_FEATURE_SUPPORTED_BY_FW(DOT11AC))
{
/* Include VHT Capability IE */
PopulateDot11fVHTCaps( pMac, vhtCap );
}
else
{
vhtCap->present = 0;
}
}
else
{
/* Vht Disable from ini in 2.4 GHz */
vhtCap->present = 0;
}
#endif
}
/*
* Send TDLS discovery response frame on direct link.
*/
static tSirRetStatus limSendTdlsDisRspFrame(tpAniSirGlobal pMac,
tSirMacAddr peerMac, tANI_U8 dialog, tpPESession psessionEntry)
{
tDot11fTDLSDisRsp tdlsDisRsp ;
tANI_U16 caps = 0 ;
tANI_U32 status = 0 ;
tANI_U32 nPayload = 0 ;
tANI_U32 nBytes = 0 ;
tANI_U8 *pFrame;
void *pPacket;
eHalStatus halstatus;
uint32 selfDot11Mode;
// Placeholder to support different channel bonding mode of TDLS than AP.
// Today, WNI_CFG_CHANNEL_BONDING_MODE will be overwritten when connecting to AP
// To support this feature, we need to introduce WNI_CFG_TDLS_CHANNEL_BONDING_MODE
// As of now, we hardcoded to max channel bonding of dot11Mode (i.e HT80 for 11ac/HT40 for 11n)
// uint32 tdlsChannelBondingMode;
/*
* The scheme here is to fill out a 'tDot11fProbeRequest' structure
* and then hand it off to 'dot11fPackProbeRequest' (for
* serialization). We start by zero-initializing the structure:
*/
vos_mem_set( ( tANI_U8* )&tdlsDisRsp,
sizeof( tDot11fTDLSDisRsp ), 0 );
/*
* setup Fixed fields,
*/
tdlsDisRsp.Category.category = SIR_MAC_ACTION_PUBLIC_USAGE;
tdlsDisRsp.Action.action = SIR_MAC_TDLS_DIS_RSP ;
tdlsDisRsp.DialogToken.token = dialog ;
PopulateDot11fLinkIden( pMac, psessionEntry, &tdlsDisRsp.LinkIdentifier,
peerMac, TDLS_RESPONDER) ;
if (cfgGetCapabilityInfo(pMac, &caps, psessionEntry) != eSIR_SUCCESS)
{
/*
* Could not get Capabilities value
* from CFG. Log error.
*/
limLog(pMac, LOGP,
FL("could not retrieve Capabilities value"));
}
swapBitField16(caps, ( tANI_U16* )&tdlsDisRsp.Capabilities );
/* populate supported rate IE */
PopulateDot11fSuppRates( pMac, POPULATE_DOT11F_RATES_OPERATIONAL,
&tdlsDisRsp.SuppRates, psessionEntry );
/* Populate extended supported rates */
PopulateDot11fExtSuppRates( pMac, POPULATE_DOT11F_RATES_OPERATIONAL,
&tdlsDisRsp.ExtSuppRates, psessionEntry );
/* Populate extended supported rates */
PopulateDot11fTdlsExtCapability( pMac, &tdlsDisRsp.ExtCap );
wlan_cfgGetInt(pMac,WNI_CFG_DOT11_MODE,&selfDot11Mode);
/* Populate HT/VHT Capabilities */
PopulateDot11fTdlsHtVhtCap( pMac, selfDot11Mode, &tdlsDisRsp.HTCaps,
&tdlsDisRsp.VHTCaps, psessionEntry );
/*
* now we pack it. First, how much space are we going to need?
*/
status = dot11fGetPackedTDLSDisRspSize( pMac, &tdlsDisRsp, &nPayload);
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGP, FL("Failed to calculate the packed size f"
"or a discovery Request (0x%08x)."), status );
/* We'll fall back on the worst case scenario: */
nPayload = sizeof( tDot11fProbeRequest );
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while calculating"
"the packed size for a discovery Request ("
"0x%08x)."), status );
}
/*
* This frame is going out from PE as data frames with special ethertype
* 89-0d.
* 8 bytes of RFC 1042 header
*/
nBytes = nPayload + sizeof( tSirMacMgmtHdr ) ;
/* Ok-- try to allocate memory from MGMT PKT pool */
halstatus = palPktAlloc( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( tANI_U16 )nBytes, ( void** ) &pFrame,
( void** ) &pPacket );
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
limLog( pMac, LOGP, FL("Failed to allocate %d bytes for a TDLS"
"Discovery Request."), nBytes );
return eSIR_MEM_ALLOC_FAILED;
}
/* zero out the memory */
vos_mem_set( pFrame, nBytes, 0 );
/*
* IE formation, memory allocation is completed, Now form TDLS discovery
* response frame
*/
/* Make public Action Frame */
#if 0
limPreparesActionFrameHdr(pMac, pFrame, SIR_MAC_MGMT_FRAME,
SIR_MAC_MGMT_ACTION,
LINK_IDEN_ADDR_OFFSET(tdlsDisRsp)) ;
#endif
limPopulateMacHeader( pMac, pFrame, SIR_MAC_MGMT_FRAME,
SIR_MAC_MGMT_ACTION, peerMac, psessionEntry->selfMacAddr);
{
tpSirMacMgmtHdr pMacHdr;
pMacHdr = ( tpSirMacMgmtHdr ) pFrame;
pMacHdr->fc.toDS = ANI_TXDIR_IBSS;
pMacHdr->fc.powerMgmt = 0 ;
sirCopyMacAddr(pMacHdr->bssId,psessionEntry->bssId);
}
#ifdef FEATURE_WLAN_TDLS_NEGATIVE
if(pMac->lim.gLimTdlsNegativeBehavior & LIM_TDLS_NEGATIVE_WRONG_BSSID_IN_DSCV_RSP)
{
tdlsDisRsp.LinkIdentifier.bssid[4] = 0xde;
tdlsDisRsp.LinkIdentifier.bssid[5] = 0xad;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("TDLS negative running: wrong BSSID %02x:%02x:%02x:%02x:%02x:%02x in TDLS Discovery Rsp"), \
tdlsDisRsp.LinkIdentifier.bssid[0],
tdlsDisRsp.LinkIdentifier.bssid[1],
tdlsDisRsp.LinkIdentifier.bssid[2],
tdlsDisRsp.LinkIdentifier.bssid[3],
tdlsDisRsp.LinkIdentifier.bssid[4],
tdlsDisRsp.LinkIdentifier.bssid[5]);
}
#endif
status = dot11fPackTDLSDisRsp( pMac, &tdlsDisRsp, pFrame +
sizeof( tSirMacMgmtHdr ),
nPayload, &nPayload );
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGE, FL("Failed to pack a TDLS discovery req \
(0x%08x)."), status );
palPktFree( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( void* ) pFrame, ( void* ) pPacket );
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while packing TDLS"
"Discovery Request (0x%08x).") );
}
#if 0
if(pMac->hal.pCBackFnTxComp == NULL)
{
pMac->hal.pCBackFnTxComp = (tpCBackFnTxComp)limTdlsDisRspTxComplete;
if(TX_SUCCESS != tx_timer_activate(&pMac->hal.txCompTimer))
{
status = eHAL_STATUS_FAILURE;
return status;
}
}
#endif
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("transmitting Discovery response on direct link")) ;
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, TDLS_DEBUG_LOG_LEVEL, ("[TDLS] action %d (%s) -DIRECT-> OTA"),
SIR_MAC_TDLS_DIS_RSP, limTraceTdlsActionString(SIR_MAC_TDLS_DIS_RSP) ));
/*
* Transmit Discovery response and watch if this is delivered to
* peer STA.
*/
halstatus = halTxFrameWithTxComplete( pMac, pPacket, ( tANI_U16 ) nBytes,
HAL_TXRX_FRM_802_11_DATA,
ANI_TXDIR_IBSS,
0,
limTxComplete, pFrame,
limMgmtTXComplete,
HAL_USE_SELF_STA_REQUESTED_MASK );
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
pMac->lim.mgmtFrameSessionId = 0xff;
limLog( pMac, LOGE, FL("could not send TDLS Dis Request frame!" ));
return eSIR_FAILURE;
}
pMac->lim.mgmtFrameSessionId = psessionEntry->peSessionId;
return eSIR_SUCCESS;
}
/*
* This static function is currently used by limSendTdlsLinkSetupReqFrame and
* limSendTdlsSetupRspFrame to populate the AID if device is 11ac capable.
*/
static void PopulateDotfTdlsVhtAID(tpAniSirGlobal pMac, uint32 selfDot11Mode,
tSirMacAddr peerMac, tDot11fIEAID *Aid,
tpPESession psessionEntry)
{
if (((psessionEntry->currentOperChannel <= SIR_11B_CHANNEL_END) &&
pMac->roam.configParam.enableVhtFor24GHz) ||
(psessionEntry->currentOperChannel >= SIR_11B_CHANNEL_END))
{
if (IS_DOT11_MODE_VHT(selfDot11Mode) &&
IS_FEATURE_SUPPORTED_BY_FW(DOT11AC))
{
tANI_U16 aid;
tpDphHashNode pStaDs;
pStaDs = dphLookupHashEntry(pMac, peerMac, &aid, &psessionEntry->dph.dphHashTable);
if (NULL != pStaDs)
{
Aid->present = 1;
Aid->assocId = aid | LIM_AID_MASK; // set bit 14 and 15 1's
}
else
{
Aid->present = 0;
limLog( pMac, LOGE, FL("pStaDs is NULL for " MAC_ADDRESS_STR ),
MAC_ADDR_ARRAY(peerMac));
}
}
}
else
{
Aid->present = 0;
limLog( pMac, LOGW, FL("Vht not enable from ini for 2.4GHz."));
}
}
/*
* TDLS setup Request frame on AP link
*/
tSirRetStatus limSendTdlsLinkSetupReqFrame(tpAniSirGlobal pMac,
tSirMacAddr peerMac, tANI_U8 dialog, tpPESession psessionEntry,
tANI_U8 *addIe, tANI_U16 addIeLen)
{
tDot11fTDLSSetupReq tdlsSetupReq ;
tANI_U16 caps = 0 ;
tANI_U32 status = 0 ;
tANI_U32 nPayload = 0 ;
tANI_U32 nBytes = 0 ;
tANI_U32 header_offset = 0 ;
tANI_U8 *pFrame;
void *pPacket;
eHalStatus halstatus;
uint32 selfDot11Mode;
// Placeholder to support different channel bonding mode of TDLS than AP.
// Today, WNI_CFG_CHANNEL_BONDING_MODE will be overwritten when connecting to AP
// To support this feature, we need to introduce WNI_CFG_TDLS_CHANNEL_BONDING_MODE
// As of now, we hardcoded to max channel bonding of dot11Mode (i.e HT80 for 11ac/HT40 for 11n)
// uint32 tdlsChannelBondingMode;
/*
* The scheme here is to fill out a 'tDot11fProbeRequest' structure
* and then hand it off to 'dot11fPackProbeRequest' (for
* serialization). We start by zero-initializing the structure:
*/
vos_mem_set(( tANI_U8* )&tdlsSetupReq, sizeof( tDot11fTDLSSetupReq ), 0);
tdlsSetupReq.Category.category = SIR_MAC_ACTION_TDLS ;
tdlsSetupReq.Action.action = SIR_MAC_TDLS_SETUP_REQ ;
tdlsSetupReq.DialogToken.token = dialog ;
PopulateDot11fLinkIden( pMac, psessionEntry, &tdlsSetupReq.LinkIdentifier,
peerMac, TDLS_INITIATOR) ;
if (cfgGetCapabilityInfo(pMac, &caps, psessionEntry) != eSIR_SUCCESS)
{
/*
* Could not get Capabilities value
* from CFG. Log error.
*/
limLog(pMac, LOGP,
FL("could not retrieve Capabilities value"));
}
swapBitField16(caps, ( tANI_U16* )&tdlsSetupReq.Capabilities );
/* populate supported rate IE */
PopulateDot11fSuppRates( pMac, POPULATE_DOT11F_RATES_OPERATIONAL,
&tdlsSetupReq.SuppRates, psessionEntry );
/* Populate extended supported rates */
PopulateDot11fExtSuppRates( pMac, POPULATE_DOT11F_RATES_OPERATIONAL,
&tdlsSetupReq.ExtSuppRates, psessionEntry );
/* Populate extended supported rates */
PopulateDot11fTdlsExtCapability( pMac, &tdlsSetupReq.ExtCap );
/*
* TODO: we need to see if we have to support conditions where we have
* EDCA parameter info element is needed a) if we need different QOS
* parameters for off channel operations or QOS is not supported on
* AP link and we wanted to QOS on direct link.
*/
/* Populate QOS info, needed for Peer U-APSD session */
/* TODO: Now hardcoded, because PopulateDot11fQOSCapsStation() depends on AP's capability, and
TDLS doesn't want to depend on AP's capability */
tdlsSetupReq.QOSCapsStation.present = 1;
tdlsSetupReq.QOSCapsStation.max_sp_length = 0;
tdlsSetupReq.QOSCapsStation.qack = 0;
tdlsSetupReq.QOSCapsStation.acbe_uapsd = ((pMac->lim.gLimTDLSUapsdMask & 0x08) >> 3) ;
tdlsSetupReq.QOSCapsStation.acbk_uapsd = ((pMac->lim.gLimTDLSUapsdMask & 0x04)>> 2);
tdlsSetupReq.QOSCapsStation.acvi_uapsd = ((pMac->lim.gLimTDLSUapsdMask & 0x02)>> 1);
tdlsSetupReq.QOSCapsStation.acvo_uapsd = (pMac->lim.gLimTDLSUapsdMask & 0x01);
/*
* we will always try to init TDLS link with 11n capabilities
* let TDLS setup response to come, and we will set our caps based
* of peer caps
*/
wlan_cfgGetInt(pMac,WNI_CFG_DOT11_MODE,&selfDot11Mode);
/* Populate HT/VHT Capabilities */
PopulateDot11fTdlsHtVhtCap( pMac, selfDot11Mode, &tdlsSetupReq.HTCaps,
&tdlsSetupReq.VHTCaps, psessionEntry );
/* Populate AID */
PopulateDotfTdlsVhtAID( pMac, selfDot11Mode, peerMac,
&tdlsSetupReq.AID, psessionEntry );
/*
* now we pack it. First, how much space are we going to need?
*/
status = dot11fGetPackedTDLSSetupReqSize( pMac, &tdlsSetupReq,
&nPayload);
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGP, FL("Failed to calculate the packed size f"
"or a discovery Request (0x%08x)."), status );
/* We'll fall back on the worst case scenario: */
nPayload = sizeof( tDot11fProbeRequest );
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while calculating"
"the packed size for a discovery Request ("
"0x%08x)."), status );
}
/*
* This frame is going out from PE as data frames with special ethertype
* 89-0d.
* 8 bytes of RFC 1042 header
*/
nBytes = nPayload + ((IS_QOS_ENABLED(psessionEntry))
? sizeof(tSirMacDataHdr3a) : sizeof(tSirMacMgmtHdr))
+ sizeof( eth_890d_header )
+ PAYLOAD_TYPE_TDLS_SIZE
+ addIeLen;
/* Ok-- try to allocate memory from MGMT PKT pool */
halstatus = palPktAlloc( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( tANI_U16 )nBytes, ( void** ) &pFrame,
( void** ) &pPacket );
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
limLog( pMac, LOGP, FL("Failed to allocate %d bytes for a TDLS"
"Discovery Request."), nBytes );
return eSIR_MEM_ALLOC_FAILED;
}
/* zero out the memory */
vos_mem_set( pFrame, nBytes, 0);
/*
* IE formation, memory allocation is completed, Now form TDLS discovery
* request frame
*/
/* fill out the buffer descriptor */
header_offset = limPrepareTdlsFrameHeader(pMac, pFrame,
LINK_IDEN_ADDR_OFFSET(tdlsSetupReq), TDLS_LINK_AP, TDLS_INITIATOR, TID_AC_BK, psessionEntry) ;
#ifdef FEATURE_WLAN_TDLS_NEGATIVE
if(pMac->lim.gLimTdlsNegativeBehavior & LIM_TDLS_NEGATIVE_WRONG_BSSID_IN_SETUP_REQ)
{
tdlsSetupReq.LinkIdentifier.bssid[4] = 0xde;
tdlsSetupReq.LinkIdentifier.bssid[5] = 0xad;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("TDLS negative running: wrong BSSID %02x:%02x:%02x:%02x:%02x:%02x in TDLS Setup Req"), \
tdlsSetupReq.LinkIdentifier.bssid[0],
tdlsSetupReq.LinkIdentifier.bssid[1],
tdlsSetupReq.LinkIdentifier.bssid[2],
tdlsSetupReq.LinkIdentifier.bssid[3],
tdlsSetupReq.LinkIdentifier.bssid[4],
tdlsSetupReq.LinkIdentifier.bssid[5]);
}
#endif
limLog( pMac, LOGW, FL("%s: SupportedChnlWidth %x rxMCSMap %x rxMCSMap %x txSupDataRate %x"),
__func__, tdlsSetupReq.VHTCaps.supportedChannelWidthSet, tdlsSetupReq.VHTCaps.rxMCSMap,
tdlsSetupReq.VHTCaps.txMCSMap, tdlsSetupReq.VHTCaps.txSupDataRate );
status = dot11fPackTDLSSetupReq( pMac, &tdlsSetupReq, pFrame
+ header_offset, nPayload, &nPayload );
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGE, FL("Failed to pack a TDLS discovery req \
(0x%08x)."), status );
palPktFree( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( void* ) pFrame, ( void* ) pPacket );
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while packing TDLS"
"Discovery Request (0x%08x).") );
}
//Copy the additional IE.
//TODO : addIe is added at the end of the frame. This means it doesnt
//follow the order. This should be ok, but we should consider changing this
//if there is any IOT issue.
if( addIeLen != 0 )
{
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, ("Copy Additional Ie Len = %d"),
addIeLen ));
vos_mem_copy( pFrame + header_offset + nPayload, addIe, addIeLen );
}
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, TDLS_DEBUG_LOG_LEVEL, ("[TDLS] action %d (%s) -AP-> OTA"),
SIR_MAC_TDLS_SETUP_REQ, limTraceTdlsActionString(SIR_MAC_TDLS_SETUP_REQ) ));
halstatus = halTxFrameWithTxComplete( pMac, pPacket, ( tANI_U16 ) nBytes,
HAL_TXRX_FRM_802_11_DATA,
ANI_TXDIR_TODS,
TID_AC_BK,
limTxComplete, pFrame,
limMgmtTXComplete,
HAL_USE_BD_RATE2_FOR_MANAGEMENT_FRAME );
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
pMac->lim.mgmtFrameSessionId = 0xff;
limLog( pMac, LOGE, FL("could not send TDLS Dis Request frame!" ));
return eSIR_FAILURE;
}
pMac->lim.mgmtFrameSessionId = psessionEntry->peSessionId;
return eSIR_SUCCESS;
}
/*
* Send TDLS Teardown frame on Direct link or AP link, depends on reason code.
*/
tSirRetStatus limSendTdlsTeardownFrame(tpAniSirGlobal pMac,
tSirMacAddr peerMac, tANI_U16 reason, tANI_U8 responder, tpPESession psessionEntry,
tANI_U8 *addIe, tANI_U16 addIeLen)
{
tDot11fTDLSTeardown teardown ;
tANI_U32 status = 0 ;
tANI_U32 nPayload = 0 ;
tANI_U32 nBytes = 0 ;
tANI_U32 header_offset = 0 ;
tANI_U8 *pFrame;
void *pPacket;
eHalStatus halstatus;
#ifndef NO_PAD_TDLS_MIN_8023_SIZE
tANI_U32 padLen = 0;
#endif
/*
* The scheme here is to fill out a 'tDot11fProbeRequest' structure
* and then hand it off to 'dot11fPackProbeRequest' (for
* serialization). We start by zero-initializing the structure:
*/
vos_mem_set( ( tANI_U8* )&teardown, sizeof( tDot11fTDLSTeardown ), 0 );
teardown.Category.category = SIR_MAC_ACTION_TDLS ;
teardown.Action.action = SIR_MAC_TDLS_TEARDOWN ;
teardown.Reason.code = reason ;
PopulateDot11fLinkIden( pMac, psessionEntry, &teardown.LinkIdentifier,
peerMac, (responder == TRUE) ? TDLS_RESPONDER : TDLS_INITIATOR) ;
/*
* now we pack it. First, how much space are we going to need?
*/
status = dot11fGetPackedTDLSTeardownSize( pMac, &teardown, &nPayload);
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGP, FL("Failed to calculate the packed size f"
"or a discovery Request (0x%08x)."), status );
/* We'll fall back on the worst case scenario: */
nPayload = sizeof( tDot11fProbeRequest );
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while calculating"
"the packed size for a discovery Request ("
"0x%08x)."), status );
}
/*
* This frame is going out from PE as data frames with special ethertype
* 89-0d.
* 8 bytes of RFC 1042 header
*/
nBytes = nPayload + ((IS_QOS_ENABLED(psessionEntry))
? sizeof(tSirMacDataHdr3a) : sizeof(tSirMacMgmtHdr))
+ sizeof( eth_890d_header )
+ PAYLOAD_TYPE_TDLS_SIZE
+ addIeLen;
#ifndef NO_PAD_TDLS_MIN_8023_SIZE
/* IOT issue with some AP : some AP doesn't like the data packet size < minimum 802.3 frame length (64)
Hence AP itself padding some bytes, which caused teardown packet is dropped at
receiver side. To avoid such IOT issue, we added some extra bytes to meet data frame size >= 64
*/
if (nPayload + PAYLOAD_TYPE_TDLS_SIZE < MIN_IEEE_8023_SIZE)
{
padLen = MIN_IEEE_8023_SIZE - (nPayload + PAYLOAD_TYPE_TDLS_SIZE ) ;
/* if padLen is less than minimum vendorSpecific (5), pad up to 5 */
if (padLen < MIN_VENDOR_SPECIFIC_IE_SIZE)
padLen = MIN_VENDOR_SPECIFIC_IE_SIZE;
nBytes += padLen;
}
#endif
/* Ok-- try to allocate memory from MGMT PKT pool */
halstatus = palPktAlloc( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( tANI_U16 )nBytes, ( void** ) &pFrame,
( void** ) &pPacket );
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
limLog( pMac, LOGP, FL("Failed to allocate %d bytes for a TDLS"
"Discovery Request."), nBytes );
return eSIR_MEM_ALLOC_FAILED;
}
/* zero out the memory */
vos_mem_set( pFrame, nBytes, 0 );
/*
* IE formation, memory allocation is completed, Now form TDLS discovery
* request frame
*/
/* fill out the buffer descriptor */
header_offset = limPrepareTdlsFrameHeader(pMac, pFrame,
LINK_IDEN_ADDR_OFFSET(teardown),
(reason == eSIR_MAC_TDLS_TEARDOWN_PEER_UNREACHABLE)
? TDLS_LINK_AP : TDLS_LINK_DIRECT,
(responder == TRUE) ? TDLS_RESPONDER : TDLS_INITIATOR,
TID_AC_VI, psessionEntry) ;
status = dot11fPackTDLSTeardown( pMac, &teardown, pFrame
+ header_offset, nPayload, &nPayload );
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGE, FL("Failed to pack a TDLS Teardown req \
(0x%08x)."), status );
palPktFree( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( void* ) pFrame, ( void* ) pPacket );
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while packing TDLS"
"Teardown Request (0x%08x).") );
}
#if 0
if(pMac->hal.pCBackFnTxComp == NULL)
{
pMac->hal.pCBackFnTxComp = (tpCBackFnTxComp)limTdlsTeardownTxComplete;
if(TX_SUCCESS != tx_timer_activate(&pMac->hal.txCompTimer))
{
status = eHAL_STATUS_FAILURE;
return status;
}
}
else
{
VOS_ASSERT(0) ;
return status ;
}
#endif
if( addIeLen != 0 )
{
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, ("Copy Additional Ie Len = %d"),
addIeLen ));
vos_mem_copy( pFrame + header_offset + nPayload, addIe, addIeLen );
}
#ifndef NO_PAD_TDLS_MIN_8023_SIZE
if (padLen != 0)
{
/* QCOM VENDOR OUI = { 0x00, 0xA0, 0xC6, type = 0x0000 }; */
tANI_U8 *padVendorSpecific = pFrame + header_offset + nPayload + addIeLen;
/* make QCOM_VENDOR_OUI, and type = 0x0000, and all the payload to be zero */
padVendorSpecific[0] = 221;
padVendorSpecific[1] = padLen - 2;
padVendorSpecific[2] = 0x00;
padVendorSpecific[3] = 0xA0;
padVendorSpecific[4] = 0xC6;
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO, ("Padding Vendor Specific Ie Len = %d"),
padLen ));
/* padding zero if more than 5 bytes are required */
if (padLen > MIN_VENDOR_SPECIFIC_IE_SIZE)
vos_mem_set( pFrame + header_offset + nPayload + addIeLen + MIN_VENDOR_SPECIFIC_IE_SIZE,
padLen - MIN_VENDOR_SPECIFIC_IE_SIZE, 0);
}
#endif
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, TDLS_DEBUG_LOG_LEVEL, ("[TDLS] action %d (%s) -%s-> OTA"),
SIR_MAC_TDLS_TEARDOWN, limTraceTdlsActionString(SIR_MAC_TDLS_TEARDOWN),
(reason == eSIR_MAC_TDLS_TEARDOWN_PEER_UNREACHABLE) ? "AP": "DIRECT" ));
halstatus = halTxFrameWithTxComplete( pMac, pPacket, ( tANI_U16 ) nBytes,
HAL_TXRX_FRM_802_11_DATA,
ANI_TXDIR_TODS,
TID_AC_VI,
limTxComplete, pFrame,
limMgmtTXComplete,
HAL_USE_BD_RATE2_FOR_MANAGEMENT_FRAME );
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
pMac->lim.mgmtFrameSessionId = 0xff;
limLog( pMac, LOGE, FL("could not send TDLS Dis Request frame!" ));
return eSIR_FAILURE;
}
pMac->lim.mgmtFrameSessionId = psessionEntry->peSessionId;
return eSIR_SUCCESS;
}
/*
* Send Setup RSP frame on AP link.
*/
static tSirRetStatus limSendTdlsSetupRspFrame(tpAniSirGlobal pMac,
tSirMacAddr peerMac, tANI_U8 dialog, tpPESession psessionEntry,
etdlsLinkSetupStatus setupStatus, tANI_U8 *addIe, tANI_U16 addIeLen )
{
tDot11fTDLSSetupRsp tdlsSetupRsp ;
tANI_U32 status = 0 ;
tANI_U16 caps = 0 ;
tANI_U32 nPayload = 0 ;
tANI_U32 header_offset = 0 ;
tANI_U32 nBytes = 0 ;
tANI_U8 *pFrame;
void *pPacket;
eHalStatus halstatus;
uint32 selfDot11Mode;
// Placeholder to support different channel bonding mode of TDLS than AP.
// Today, WNI_CFG_CHANNEL_BONDING_MODE will be overwritten when connecting to AP
// To support this feature, we need to introduce WNI_CFG_TDLS_CHANNEL_BONDING_MODE
// As of now, we hardcoded to max channel bonding of dot11Mode (i.e HT80 for 11ac/HT40 for 11n)
// uint32 tdlsChannelBondingMode;
/*
* The scheme here is to fill out a 'tDot11fProbeRequest' structure
* and then hand it off to 'dot11fPackProbeRequest' (for
* serialization). We start by zero-initializing the structure:
*/
vos_mem_set( ( tANI_U8* )&tdlsSetupRsp, sizeof( tDot11fTDLSSetupRsp ),0 );
/*
* setup Fixed fields,
*/
tdlsSetupRsp.Category.category = SIR_MAC_ACTION_TDLS;
tdlsSetupRsp.Action.action = SIR_MAC_TDLS_SETUP_RSP ;
tdlsSetupRsp.DialogToken.token = dialog;
PopulateDot11fLinkIden( pMac, psessionEntry, &tdlsSetupRsp.LinkIdentifier,
peerMac, TDLS_RESPONDER) ;
if (cfgGetCapabilityInfo(pMac, &caps, psessionEntry) != eSIR_SUCCESS)
{
/*
* Could not get Capabilities value
* from CFG. Log error.
*/
limLog(pMac, LOGP,
FL("could not retrieve Capabilities value"));
}
swapBitField16(caps, ( tANI_U16* )&tdlsSetupRsp.Capabilities );
/* ipopulate supported rate IE */
PopulateDot11fSuppRates( pMac, POPULATE_DOT11F_RATES_OPERATIONAL,
&tdlsSetupRsp.SuppRates, psessionEntry );
/* Populate extended supported rates */
PopulateDot11fExtSuppRates( pMac, POPULATE_DOT11F_RATES_OPERATIONAL,
&tdlsSetupRsp.ExtSuppRates, psessionEntry );
/* Populate extended supported rates */
PopulateDot11fTdlsExtCapability( pMac, &tdlsSetupRsp.ExtCap );
/*
* TODO: we need to see if we have to support conditions where we have
* EDCA parameter info element is needed a) if we need different QOS
* parameters for off channel operations or QOS is not supported on
* AP link and we wanted to QOS on direct link.
*/
/* Populate QOS info, needed for Peer U-APSD session */
/* TODO: Now hardcoded, because PopulateDot11fQOSCapsStation() depends on AP's capability, and
TDLS doesn't want to depend on AP's capability */
tdlsSetupRsp.QOSCapsStation.present = 1;
tdlsSetupRsp.QOSCapsStation.max_sp_length = 0;
tdlsSetupRsp.QOSCapsStation.qack = 0;
tdlsSetupRsp.QOSCapsStation.acbe_uapsd = ((pMac->lim.gLimTDLSUapsdMask & 0x08) >> 3);
tdlsSetupRsp.QOSCapsStation.acbk_uapsd = ((pMac->lim.gLimTDLSUapsdMask & 0x04) >> 2);
tdlsSetupRsp.QOSCapsStation.acvi_uapsd = ((pMac->lim.gLimTDLSUapsdMask & 0x02) >> 1);
tdlsSetupRsp.QOSCapsStation.acvo_uapsd = (pMac->lim.gLimTDLSUapsdMask & 0x01);
wlan_cfgGetInt(pMac,WNI_CFG_DOT11_MODE,&selfDot11Mode);
/* Populate HT/VHT Capabilities */
PopulateDot11fTdlsHtVhtCap( pMac, selfDot11Mode, &tdlsSetupRsp.HTCaps,
&tdlsSetupRsp.VHTCaps, psessionEntry );
/* Populate AID */
PopulateDotfTdlsVhtAID( pMac, selfDot11Mode, peerMac,
&tdlsSetupRsp.AID, psessionEntry );
tdlsSetupRsp.Status.status = setupStatus ;
/*
* now we pack it. First, how much space are we going to need?
*/
status = dot11fGetPackedTDLSSetupRspSize( pMac, &tdlsSetupRsp,
&nPayload);
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGP, FL("Failed to calculate the packed size f"
"or a discovery Request (0x%08x)."), status );
/* We'll fall back on the worst case scenario: */
nPayload = sizeof( tDot11fProbeRequest );
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while calculating"
"the packed size for a discovery Request ("
"0x%08x)."), status );
}
/*
* This frame is going out from PE as data frames with special ethertype
* 89-0d.
* 8 bytes of RFC 1042 header
*/
nBytes = nPayload + ((IS_QOS_ENABLED(psessionEntry))
? sizeof(tSirMacDataHdr3a) : sizeof(tSirMacMgmtHdr))
+ sizeof( eth_890d_header )
+ PAYLOAD_TYPE_TDLS_SIZE
+ addIeLen;
/* Ok-- try to allocate memory from MGMT PKT pool */
halstatus = palPktAlloc( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( tANI_U16 )nBytes, ( void** ) &pFrame,
( void** ) &pPacket );
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
limLog( pMac, LOGP, FL("Failed to allocate %d bytes for a TDLS"
"Discovery Request."), nBytes );
return eSIR_MEM_ALLOC_FAILED;
}
/* zero out the memory */
vos_mem_set( pFrame, nBytes, 0 );
/*
* IE formation, memory allocation is completed, Now form TDLS discovery
* request frame
*/
/* fill out the buffer descriptor */
header_offset = limPrepareTdlsFrameHeader(pMac, pFrame,
LINK_IDEN_ADDR_OFFSET(tdlsSetupRsp),
TDLS_LINK_AP, TDLS_RESPONDER,
TID_AC_BK, psessionEntry) ;
#ifdef FEATURE_WLAN_TDLS_NEGATIVE
if(pMac->lim.gLimTdlsNegativeBehavior & LIM_TDLS_NEGATIVE_WRONG_BSSID_IN_SETUP_RSP)
{
tdlsSetupRsp.LinkIdentifier.bssid[4] = 0xde;
tdlsSetupRsp.LinkIdentifier.bssid[5] = 0xad;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("TDLS negative running: wrong BSSID %02x:%02x:%02x:%02x:%02x:%02x in TDLS Setup Rsp"), \
tdlsSetupRsp.LinkIdentifier.bssid[0],
tdlsSetupRsp.LinkIdentifier.bssid[1],
tdlsSetupRsp.LinkIdentifier.bssid[2],
tdlsSetupRsp.LinkIdentifier.bssid[3],
tdlsSetupRsp.LinkIdentifier.bssid[4],
tdlsSetupRsp.LinkIdentifier.bssid[5]);
}
#endif
limLog( pMac, LOGW, FL("%s: SupportedChnlWidth %x rxMCSMap %x rxMCSMap %x txSupDataRate %x"),
__func__, tdlsSetupRsp.VHTCaps.supportedChannelWidthSet, tdlsSetupRsp.VHTCaps.rxMCSMap,
tdlsSetupRsp.VHTCaps.txMCSMap, tdlsSetupRsp.VHTCaps.txSupDataRate );
status = dot11fPackTDLSSetupRsp( pMac, &tdlsSetupRsp, pFrame
+ header_offset, nPayload, &nPayload );
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGE, FL("Failed to pack a TDLS discovery req \
(0x%08x)."), status );
palPktFree( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( void* ) pFrame, ( void* ) pPacket );
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while packing TDLS"
"Discovery Request (0x%08x).") );
}
//Copy the additional IE.
//TODO : addIe is added at the end of the frame. This means it doesnt
//follow the order. This should be ok, but we should consider changing this
//if there is any IOT issue.
if( addIeLen != 0 )
{
vos_mem_copy( pFrame + header_offset + nPayload, addIe, addIeLen );
}
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, TDLS_DEBUG_LOG_LEVEL, ("[TDLS] action %d (%s) -AP-> OTA"),
SIR_MAC_TDLS_SETUP_RSP, limTraceTdlsActionString(SIR_MAC_TDLS_SETUP_RSP) ));
halstatus = halTxFrameWithTxComplete( pMac, pPacket, ( tANI_U16 ) nBytes,
HAL_TXRX_FRM_802_11_DATA,
ANI_TXDIR_TODS,
//ANI_TXDIR_IBSS,
TID_AC_BK,
limTxComplete, pFrame,
limMgmtTXComplete,
HAL_USE_BD_RATE2_FOR_MANAGEMENT_FRAME );
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
pMac->lim.mgmtFrameSessionId = 0xff;
limLog( pMac, LOGE, FL("could not send TDLS Dis Request frame!" ));
return eSIR_FAILURE;
}
pMac->lim.mgmtFrameSessionId = psessionEntry->peSessionId;
return eSIR_SUCCESS;
}
/*
* Send TDLS setup CNF frame on AP link
*/
tSirRetStatus limSendTdlsLinkSetupCnfFrame(tpAniSirGlobal pMac, tSirMacAddr peerMac,
tANI_U8 dialog, tpPESession psessionEntry, tANI_U8* addIe, tANI_U16 addIeLen)
{
tDot11fTDLSSetupCnf tdlsSetupCnf ;
tANI_U32 status = 0 ;
tANI_U32 nPayload = 0 ;
tANI_U32 nBytes = 0 ;
tANI_U32 header_offset = 0 ;
tANI_U8 *pFrame;
void *pPacket;
eHalStatus halstatus;
#ifndef NO_PAD_TDLS_MIN_8023_SIZE
tANI_U32 padLen = 0;
#endif
/*
* The scheme here is to fill out a 'tDot11fProbeRequest' structure
* and then hand it off to 'dot11fPackProbeRequest' (for
* serialization). We start by zero-initializing the structure:
*/
vos_mem_set( ( tANI_U8* )&tdlsSetupCnf, sizeof( tDot11fTDLSSetupCnf ), 0 );
/*
* setup Fixed fields,
*/
tdlsSetupCnf.Category.category = SIR_MAC_ACTION_TDLS;
tdlsSetupCnf.Action.action = SIR_MAC_TDLS_SETUP_CNF ;
tdlsSetupCnf.DialogToken.token = dialog ;
#if 1
PopulateDot11fLinkIden( pMac, psessionEntry, &tdlsSetupCnf.LinkIdentifier,
peerMac, TDLS_INITIATOR) ;
#else
vos_mem_copy( (tANI_U8 *)&tdlsSetupCnf.LinkIdentifier,
(tANI_U8 *)&setupRsp->LinkIdentifier, sizeof(tDot11fIELinkIdentifier)) ;
#endif
/*
* TODO: we need to see if we have to support conditions where we have
* EDCA parameter info element is needed a) if we need different QOS
* parameters for off channel operations or QOS is not supported on
* AP link and we wanted to QOS on direct link.
*/
/* Include HT Info IE */
/* Need to also check the Self Capability ??? TODO Sunil */
if ( true == psessionEntry->htCapability)
{
PopulateDot11fHTInfo( pMac, &tdlsSetupCnf.HTInfo, psessionEntry );
}
if ( true == psessionEntry->vhtCapability)
{
PopulateDot11fVHTOperation( pMac, &tdlsSetupCnf.VHTOperation);
}
/*
* now we pack it. First, how much space are we going to need?
*/
status = dot11fGetPackedTDLSSetupCnfSize( pMac, &tdlsSetupCnf,
&nPayload);
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGP, FL("Failed to calculate the packed size f"
"or a discovery Request (0x%08x)."), status );
/* We'll fall back on the worst case scenario: */
nPayload = sizeof( tDot11fProbeRequest );
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while calculating"
"the packed size for a discovery Request ("
"0x%08x)."), status );
}
/*
* This frame is going out from PE as data frames with special ethertype
* 89-0d.
* 8 bytes of RFC 1042 header
*/
nBytes = nPayload + ((IS_QOS_ENABLED(psessionEntry))
? sizeof(tSirMacDataHdr3a) : sizeof(tSirMacMgmtHdr))
+ sizeof( eth_890d_header )
+ PAYLOAD_TYPE_TDLS_SIZE
+ addIeLen;
#ifndef NO_PAD_TDLS_MIN_8023_SIZE
/* IOT issue with some AP : some AP doesn't like the data packet size < minimum 802.3 frame length (64)
Hence AP itself padding some bytes, which caused teardown packet is dropped at
receiver side. To avoid such IOT issue, we added some extra bytes to meet data frame size >= 64
*/
if (nPayload + PAYLOAD_TYPE_TDLS_SIZE < MIN_IEEE_8023_SIZE)
{
padLen = MIN_IEEE_8023_SIZE - (nPayload + PAYLOAD_TYPE_TDLS_SIZE ) ;
/* if padLen is less than minimum vendorSpecific (5), pad up to 5 */
if (padLen < MIN_VENDOR_SPECIFIC_IE_SIZE)
padLen = MIN_VENDOR_SPECIFIC_IE_SIZE;
nBytes += padLen;
}
#endif
/* Ok-- try to allocate memory from MGMT PKT pool */
halstatus = palPktAlloc( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( tANI_U16 )nBytes, ( void** ) &pFrame,
( void** ) &pPacket );
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
limLog( pMac, LOGP, FL("Failed to allocate %d bytes for a TDLS"
"Discovery Request."), nBytes );
return eSIR_MEM_ALLOC_FAILED;
}
/* zero out the memory */
vos_mem_set( pFrame, nBytes, 0 );
/*
* IE formation, memory allocation is completed, Now form TDLS discovery
* request frame
*/
/* fill out the buffer descriptor */
header_offset = limPrepareTdlsFrameHeader(pMac, pFrame,
LINK_IDEN_ADDR_OFFSET(tdlsSetupCnf), TDLS_LINK_AP, TDLS_INITIATOR,
TID_AC_VI, psessionEntry) ;
#ifdef FEATURE_WLAN_TDLS_NEGATIVE
if(pMac->lim.gLimTdlsNegativeBehavior & LIM_TDLS_NEGATIVE_STATUS_37_IN_SETUP_CNF) {
tdlsSetupCnf.StatusCode.statusCode = 37;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("TDLS negative running: StatusCode = 37 in TDLS Setup Cnf"));
}
#endif
status = dot11fPackTDLSSetupCnf( pMac, &tdlsSetupCnf, pFrame
+ header_offset, nPayload, &nPayload );
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGE, FL("Failed to pack a TDLS discovery req \
(0x%08x)."), status );
palPktFree( pMac->hHdd, HAL_TXRX_FRM_802_11_MGMT,
( void* ) pFrame, ( void* ) pPacket );
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while packing TDLS"
"Discovery Request (0x%08x).") );
}
#if 0
if(pMac->hal.pCBackFnTxComp == NULL)
{
pMac->hal.pCBackFnTxComp = (tpCBackFnTxComp)limTdlsSetupCnfTxComplete;
if(TX_SUCCESS != tx_timer_activate(&pMac->hal.txCompTimer))
{
status = eHAL_STATUS_FAILURE;
return status;
}
}
else
{
VOS_ASSERT(0) ;
return status ;
}
#endif
//Copy the additional IE.
//TODO : addIe is added at the end of the frame. This means it doesnt
//follow the order. This should be ok, but we should consider changing this
//if there is any IOT issue.
if( addIeLen != 0 )
{
vos_mem_copy( pFrame + header_offset + nPayload, addIe, addIeLen );
}
#ifndef NO_PAD_TDLS_MIN_8023_SIZE
if (padLen != 0)
{
/* QCOM VENDOR OUI = { 0x00, 0xA0, 0xC6, type = 0x0000 }; */
tANI_U8 *padVendorSpecific = pFrame + header_offset + nPayload + addIeLen;
/* make QCOM_VENDOR_OUI, and type = 0x0000, and all the payload to be zero */
padVendorSpecific[0] = 221;
padVendorSpecific[1] = padLen - 2;
padVendorSpecific[2] = 0x00;
padVendorSpecific[3] = 0xA0;
padVendorSpecific[4] = 0xC6;
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO, ("Padding Vendor Specific Ie Len = %d"),
padLen ));
/* padding zero if more than 5 bytes are required */
if (padLen > MIN_VENDOR_SPECIFIC_IE_SIZE)
vos_mem_set( pFrame + header_offset + nPayload + addIeLen + MIN_VENDOR_SPECIFIC_IE_SIZE,
padLen - MIN_VENDOR_SPECIFIC_IE_SIZE, 0);
}
#endif
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, TDLS_DEBUG_LOG_LEVEL, ("[TDLS] action %d (%s) -AP-> OTA"),
SIR_MAC_TDLS_SETUP_CNF, limTraceTdlsActionString(SIR_MAC_TDLS_SETUP_CNF) ));
halstatus = halTxFrameWithTxComplete( pMac, pPacket, ( tANI_U16 ) nBytes,
HAL_TXRX_FRM_802_11_DATA,
ANI_TXDIR_TODS,
TID_AC_VI,
limTxComplete, pFrame,
limMgmtTXComplete,
HAL_USE_BD_RATE2_FOR_MANAGEMENT_FRAME );
if ( ! HAL_STATUS_SUCCESS ( halstatus ) )
{
pMac->lim.mgmtFrameSessionId = 0xff;
limLog( pMac, LOGE, FL("could not send TDLS Dis Request frame!" ));
return eSIR_FAILURE;
}
pMac->lim.mgmtFrameSessionId = psessionEntry->peSessionId;
return eSIR_SUCCESS;
}
#ifdef FEATURE_WLAN_TDLS_INTERNAL
/*
* Convert HT caps to lim based HT caps
*/
static void limTdlsCovertHTCaps(tpAniSirGlobal pMac,
tSirTdlsPeerInfo *peerInfo, tDot11fIEHTCaps *HTCaps)
{
/* HT Capability Info */
peerInfo->tdlsPeerHtCaps.advCodingCap = HTCaps->advCodingCap ;
peerInfo->tdlsPeerHtCaps.supportedChannelWidthSet =
HTCaps->supportedChannelWidthSet ;
peerInfo->tdlsPeerHtCaps.mimoPowerSave = HTCaps->mimoPowerSave ;
peerInfo->tdlsPeerHtCaps.greenField = HTCaps->greenField ;
peerInfo->tdlsPeerHtCaps.shortGI20MHz = HTCaps->shortGI20MHz ;
peerInfo->tdlsPeerHtCaps.shortGI40MHz = HTCaps->shortGI40MHz ;
peerInfo->tdlsPeerHtCaps.txSTBC = HTCaps->txSTBC ;
peerInfo->tdlsPeerHtCaps.rxSTBC = HTCaps->rxSTBC ;
peerInfo->tdlsPeerHtCaps.delayedBA = HTCaps->delayedBA;
peerInfo->tdlsPeerHtCaps.maximalAMSDUsize = HTCaps->maximalAMSDUsize ;
peerInfo->tdlsPeerHtCaps.dsssCckMode40MHz = HTCaps->dsssCckMode40MHz ;
peerInfo->tdlsPeerHtCaps.psmp = HTCaps->stbcControlFrame ;
peerInfo->tdlsPeerHtCaps.stbcControlFrame = HTCaps->stbcControlFrame ;
peerInfo->tdlsPeerHtCaps.lsigTXOPProtection =
HTCaps->lsigTXOPProtection ;
/* HT Capa parameters */
peerInfo->tdlsPeerHtParams.maxRxAMPDUFactor = HTCaps->maxRxAMPDUFactor ;
peerInfo->tdlsPeerHtParams.mpduDensity = HTCaps->mpduDensity ;
peerInfo->tdlsPeerHtParams.reserved = HTCaps->reserved1 ;
/* Extended HT caps */
peerInfo->tdlsPeerHtExtCaps.pco = HTCaps->pco ;
peerInfo->tdlsPeerHtExtCaps.transitionTime = HTCaps->transitionTime ;
peerInfo->tdlsPeerHtExtCaps.mcsFeedback = HTCaps->mcsFeedback ;
vos_mem_copy( peerInfo->supportedMCSSet,
HTCaps->supportedMCSSet, SIZE_OF_SUPPORTED_MCS_SET) ;
return ;
}
/*
* update capability info..
*/
void tdlsUpdateCapInfo(tSirMacCapabilityInfo *capabilityInfo,
tDot11fFfCapabilities *Capabilities)
{
capabilityInfo->ess = Capabilities->ess;
capabilityInfo->ibss = Capabilities->ibss;
capabilityInfo->cfPollable = Capabilities->cfPollable;
capabilityInfo->cfPollReq = Capabilities->cfPollReq;
capabilityInfo->privacy = Capabilities->privacy;
capabilityInfo->shortPreamble = Capabilities->shortPreamble;
capabilityInfo->pbcc = Capabilities->pbcc;
capabilityInfo->channelAgility = Capabilities->channelAgility;
capabilityInfo->spectrumMgt = Capabilities->spectrumMgt;
capabilityInfo->qos = Capabilities->qos;
capabilityInfo->shortSlotTime = Capabilities->shortSlotTime;
capabilityInfo->apsd = Capabilities->apsd;
capabilityInfo->rrm = Capabilities->rrm;
capabilityInfo->dsssOfdm = Capabilities->dsssOfdm;
capabilityInfo->immediateBA = Capabilities->immediateBA;
return ;
}
/*
* update Peer info from the link request frame recieved from Peer..
* in list of STA participating in TDLS link setup
*/
void limTdlsUpdateLinkReqPeerInfo(tpAniSirGlobal pMac,
tLimTdlsLinkSetupPeer *setupPeer,
tDot11fTDLSSetupReq *setupReq)
{
/* Populate peer info of tdls discovery result */
tdlsUpdateCapInfo(&setupPeer->capabilityInfo, &setupReq->Capabilities) ;
if(setupReq->SuppRates.present)
{
ConvertSuppRates( pMac, &setupPeer->supportedRates,
&setupReq->SuppRates );
}
/* update QOS info, needed for Peer U-APSD session */
if(setupReq->QOSCapsStation.present)
{
ConvertQOSCapsStation(pMac->hHdd, &setupPeer->qosCaps,
&setupReq->QOSCapsStation) ;
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,("setupReq->SPLen=%d (be %d %d %d %d vo) more %d qack %d."), \
setupReq->QOSCapsStation.max_sp_length, setupReq->QOSCapsStation.acbe_uapsd, \
setupReq->QOSCapsStation.acbk_uapsd, setupReq->QOSCapsStation.acvi_uapsd, \
setupReq->QOSCapsStation.acvo_uapsd, setupReq->QOSCapsStation.more_data_ack, \
setupReq->QOSCapsStation.qack));
}
if (setupReq->ExtSuppRates.present)
{
setupPeer->ExtRatesPresent = 1;
ConvertExtSuppRates( pMac, &setupPeer->extendedRates,
&setupReq->ExtSuppRates );
}
/* update HT caps */
if (setupReq->HTCaps.present)
{
vos_mem_copy( &setupPeer->tdlsPeerHTCaps,
&setupReq->HTCaps, sizeof(tDot11fIEHTCaps)) ;
}
/* Update EXT caps */
if (setupReq->ExtCap.present)
{
vos_mem_copy( &setupPeer->tdlsPeerExtCaps,
&setupReq->ExtCap, sizeof(tDot11fIEExtCap)) ;
}
return ;
}
/*
* update peer Info recieved with TDLS setup RSP
*/
void limTdlsUpdateLinkRspPeerInfo(tpAniSirGlobal pMac,
tLimTdlsLinkSetupPeer *setupPeer,
tDot11fTDLSSetupRsp *setupRsp)
{
/* Populate peer info of tdls discovery result */
tdlsUpdateCapInfo(&setupPeer->capabilityInfo, &setupRsp->Capabilities) ;
if(setupRsp->SuppRates.present)
{
tDot11fIESuppRates *suppRates = &setupRsp->SuppRates ;
ConvertSuppRates( pMac, &setupPeer->supportedRates, suppRates);
}
/* update QOS info, needed for Peer U-APSD session */
if(setupRsp->QOSCapsStation.present)
{
ConvertQOSCapsStation(pMac->hHdd, &setupPeer->qosCaps,
&setupRsp->QOSCapsStation) ;
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, ("setupRsp->SPLen=%d (be %d %d %d %d vo) more %d qack %d."), \
setupRsp->QOSCapsStation.max_sp_length, setupRsp->QOSCapsStation.acbe_uapsd, \
setupRsp->QOSCapsStation.acbk_uapsd, setupRsp->QOSCapsStation.acvi_uapsd, \
setupRsp->QOSCapsStation.acvo_uapsd, setupRsp->QOSCapsStation.more_data_ack, \
setupRsp->QOSCapsStation.qack));
}
if(setupRsp->ExtSuppRates.present)
{
setupPeer->ExtRatesPresent = 1;
ConvertExtSuppRates( pMac, &setupPeer->extendedRates,
&setupRsp->ExtSuppRates );
}
/* update HT caps */
if (setupRsp->HTCaps.present)
{
vos_mem_copy(&setupPeer->tdlsPeerHTCaps,
&setupRsp->HTCaps, sizeof(tDot11fIEHTCaps)) ;
}
/* update EXT caps */
if (setupRsp->ExtCap.present)
{
vos_mem_copy( &setupPeer->tdlsPeerExtCaps,
&setupRsp->ExtCap, sizeof(tDot11fIEExtCap)) ;
}
return ;
}
#endif
/* This Function is similar to PopulateDot11fHTCaps, except that the HT Capabilities
* are considered from the AddStaReq rather from the cfg.dat as in PopulateDot11fHTCaps
*/
static tSirRetStatus limTdlsPopulateDot11fHTCaps(tpAniSirGlobal pMac, tpPESession psessionEntry,
tSirTdlsAddStaReq *pTdlsAddStaReq, tDot11fIEHTCaps *pDot11f)
{
tANI_U32 nCfgValue;
tANI_U8 nCfgValue8;
tSirMacHTParametersInfo *pHTParametersInfo;
union {
tANI_U16 nCfgValue16;
tSirMacHTCapabilityInfo htCapInfo;
tSirMacExtendedHTCapabilityInfo extHtCapInfo;
} uHTCapabilityInfo;
tSirMacTxBFCapabilityInfo *pTxBFCapabilityInfo;
tSirMacASCapabilityInfo *pASCapabilityInfo;
nCfgValue = pTdlsAddStaReq->htCap.capInfo;
uHTCapabilityInfo.nCfgValue16 = nCfgValue & 0xFFFF;
pDot11f->advCodingCap = uHTCapabilityInfo.htCapInfo.advCodingCap;
pDot11f->mimoPowerSave = uHTCapabilityInfo.htCapInfo.mimoPowerSave;
pDot11f->greenField = uHTCapabilityInfo.htCapInfo.greenField;
pDot11f->shortGI20MHz = uHTCapabilityInfo.htCapInfo.shortGI20MHz;
pDot11f->shortGI40MHz = uHTCapabilityInfo.htCapInfo.shortGI40MHz;
pDot11f->txSTBC = uHTCapabilityInfo.htCapInfo.txSTBC;
pDot11f->rxSTBC = uHTCapabilityInfo.htCapInfo.rxSTBC;
pDot11f->delayedBA = uHTCapabilityInfo.htCapInfo.delayedBA;
pDot11f->maximalAMSDUsize = uHTCapabilityInfo.htCapInfo.maximalAMSDUsize;
pDot11f->dsssCckMode40MHz = uHTCapabilityInfo.htCapInfo.dsssCckMode40MHz;
pDot11f->psmp = uHTCapabilityInfo.htCapInfo.psmp;
pDot11f->stbcControlFrame = uHTCapabilityInfo.htCapInfo.stbcControlFrame;
pDot11f->lsigTXOPProtection = uHTCapabilityInfo.htCapInfo.lsigTXOPProtection;
// All sessionized entries will need the check below
if (psessionEntry == NULL) // Only in case of NO session
{
pDot11f->supportedChannelWidthSet = uHTCapabilityInfo.htCapInfo.supportedChannelWidthSet;
}
else
{
pDot11f->supportedChannelWidthSet = psessionEntry->htSupportedChannelWidthSet;
}
/* Ensure that shortGI40MHz is Disabled if supportedChannelWidthSet is
eHT_CHANNEL_WIDTH_20MHZ */
if(pDot11f->supportedChannelWidthSet == eHT_CHANNEL_WIDTH_20MHZ)
{
pDot11f->shortGI40MHz = 0;
}
dot11fLog(pMac, LOG2, FL("SupportedChnlWidth: %d, mimoPS: %d, GF: %d, shortGI20:%d, shortGI40: %d, dsssCck: %d"),
pDot11f->supportedChannelWidthSet, pDot11f->mimoPowerSave, pDot11f->greenField,
pDot11f->shortGI20MHz, pDot11f->shortGI40MHz, pDot11f->dsssCckMode40MHz);
nCfgValue = pTdlsAddStaReq->htCap.ampduParamsInfo;
nCfgValue8 = ( tANI_U8 ) nCfgValue;
pHTParametersInfo = ( tSirMacHTParametersInfo* ) &nCfgValue8;
pDot11f->maxRxAMPDUFactor = pHTParametersInfo->maxRxAMPDUFactor;
pDot11f->mpduDensity = pHTParametersInfo->mpduDensity;
pDot11f->reserved1 = pHTParametersInfo->reserved;
dot11fLog( pMac, LOG2, FL( "AMPDU Param: %x" ), nCfgValue);
vos_mem_copy( pDot11f->supportedMCSSet, pTdlsAddStaReq->htCap.suppMcsSet,
SIZE_OF_SUPPORTED_MCS_SET);
nCfgValue = pTdlsAddStaReq->htCap.extendedHtCapInfo;
uHTCapabilityInfo.nCfgValue16 = nCfgValue & 0xFFFF;
pDot11f->pco = uHTCapabilityInfo.extHtCapInfo.pco;
pDot11f->transitionTime = uHTCapabilityInfo.extHtCapInfo.transitionTime;
pDot11f->mcsFeedback = uHTCapabilityInfo.extHtCapInfo.mcsFeedback;
nCfgValue = pTdlsAddStaReq->htCap.txBFCapInfo;
pTxBFCapabilityInfo = ( tSirMacTxBFCapabilityInfo* ) &nCfgValue;
pDot11f->txBF = pTxBFCapabilityInfo->txBF;
pDot11f->rxStaggeredSounding = pTxBFCapabilityInfo->rxStaggeredSounding;
pDot11f->txStaggeredSounding = pTxBFCapabilityInfo->txStaggeredSounding;
pDot11f->rxZLF = pTxBFCapabilityInfo->rxZLF;
pDot11f->txZLF = pTxBFCapabilityInfo->txZLF;
pDot11f->implicitTxBF = pTxBFCapabilityInfo->implicitTxBF;
pDot11f->calibration = pTxBFCapabilityInfo->calibration;
pDot11f->explicitCSITxBF = pTxBFCapabilityInfo->explicitCSITxBF;
pDot11f->explicitUncompressedSteeringMatrix = pTxBFCapabilityInfo->explicitUncompressedSteeringMatrix;
pDot11f->explicitBFCSIFeedback = pTxBFCapabilityInfo->explicitBFCSIFeedback;
pDot11f->explicitUncompressedSteeringMatrixFeedback = pTxBFCapabilityInfo->explicitUncompressedSteeringMatrixFeedback;
pDot11f->explicitCompressedSteeringMatrixFeedback = pTxBFCapabilityInfo->explicitCompressedSteeringMatrixFeedback;
pDot11f->csiNumBFAntennae = pTxBFCapabilityInfo->csiNumBFAntennae;
pDot11f->uncompressedSteeringMatrixBFAntennae = pTxBFCapabilityInfo->uncompressedSteeringMatrixBFAntennae;
pDot11f->compressedSteeringMatrixBFAntennae = pTxBFCapabilityInfo->compressedSteeringMatrixBFAntennae;
nCfgValue = pTdlsAddStaReq->htCap.antennaSelectionInfo;
nCfgValue8 = ( tANI_U8 ) nCfgValue;
pASCapabilityInfo = ( tSirMacASCapabilityInfo* ) &nCfgValue8;
pDot11f->antennaSelection = pASCapabilityInfo->antennaSelection;
pDot11f->explicitCSIFeedbackTx = pASCapabilityInfo->explicitCSIFeedbackTx;
pDot11f->antennaIndicesFeedbackTx = pASCapabilityInfo->antennaIndicesFeedbackTx;
pDot11f->explicitCSIFeedback = pASCapabilityInfo->explicitCSIFeedback;
pDot11f->antennaIndicesFeedback = pASCapabilityInfo->antennaIndicesFeedback;
pDot11f->rxAS = pASCapabilityInfo->rxAS;
pDot11f->txSoundingPPDUs = pASCapabilityInfo->txSoundingPPDUs;
pDot11f->present = pTdlsAddStaReq->htcap_present;
return eSIR_SUCCESS;
}
tSirRetStatus
limTdlsPopulateDot11fVHTCaps(tpAniSirGlobal pMac,
tSirTdlsAddStaReq *pTdlsAddStaReq,
tDot11fIEVHTCaps *pDot11f)
{
tANI_U32 nCfgValue=0;
union {
tANI_U32 nCfgValue32;
tSirMacVHTCapabilityInfo vhtCapInfo;
} uVHTCapabilityInfo;
union {
tANI_U16 nCfgValue16;
tSirMacVHTTxSupDataRateInfo vhtTxSupDataRateInfo;
tSirMacVHTRxSupDataRateInfo vhtRxsupDataRateInfo;
} uVHTSupDataRateInfo;
pDot11f->present = pTdlsAddStaReq->vhtcap_present;
nCfgValue = pTdlsAddStaReq->vhtCap.vhtCapInfo;
uVHTCapabilityInfo.nCfgValue32 = nCfgValue;
pDot11f->maxMPDULen = uVHTCapabilityInfo.vhtCapInfo.maxMPDULen;
pDot11f->supportedChannelWidthSet = uVHTCapabilityInfo.vhtCapInfo.supportedChannelWidthSet;
pDot11f->ldpcCodingCap = uVHTCapabilityInfo.vhtCapInfo.ldpcCodingCap;
pDot11f->shortGI80MHz = uVHTCapabilityInfo.vhtCapInfo.shortGI80MHz;
pDot11f->shortGI160and80plus80MHz = uVHTCapabilityInfo.vhtCapInfo.shortGI160and80plus80MHz;
pDot11f->txSTBC = uVHTCapabilityInfo.vhtCapInfo.txSTBC;
pDot11f->rxSTBC = uVHTCapabilityInfo.vhtCapInfo.rxSTBC;
pDot11f->suBeamFormerCap = uVHTCapabilityInfo.vhtCapInfo.suBeamFormerCap;
pDot11f->suBeamformeeCap = uVHTCapabilityInfo.vhtCapInfo.suBeamformeeCap;
pDot11f->csnofBeamformerAntSup = uVHTCapabilityInfo.vhtCapInfo.csnofBeamformerAntSup;
pDot11f->numSoundingDim = uVHTCapabilityInfo.vhtCapInfo.numSoundingDim;
pDot11f->muBeamformerCap = uVHTCapabilityInfo.vhtCapInfo.muBeamformerCap;
pDot11f->muBeamformeeCap = uVHTCapabilityInfo.vhtCapInfo.muBeamformeeCap;
pDot11f->vhtTXOPPS = uVHTCapabilityInfo.vhtCapInfo.vhtTXOPPS;
pDot11f->htcVHTCap = uVHTCapabilityInfo.vhtCapInfo.htcVHTCap;
pDot11f->maxAMPDULenExp = uVHTCapabilityInfo.vhtCapInfo.maxAMPDULenExp;
pDot11f->vhtLinkAdaptCap = uVHTCapabilityInfo.vhtCapInfo.vhtLinkAdaptCap;
pDot11f->rxAntPattern = uVHTCapabilityInfo.vhtCapInfo.rxAntPattern;
pDot11f->txAntPattern = uVHTCapabilityInfo.vhtCapInfo.txAntPattern;
pDot11f->reserved1= uVHTCapabilityInfo.vhtCapInfo.reserved1;
pDot11f->rxMCSMap = pTdlsAddStaReq->vhtCap.suppMcs.rxMcsMap;
nCfgValue = pTdlsAddStaReq->vhtCap.suppMcs.rxHighest;
uVHTSupDataRateInfo.nCfgValue16 = nCfgValue & 0xffff;
pDot11f->rxHighSupDataRate = uVHTSupDataRateInfo.vhtRxsupDataRateInfo.rxSupDataRate;
pDot11f->txMCSMap = pTdlsAddStaReq->vhtCap.suppMcs.txMcsMap;
nCfgValue = pTdlsAddStaReq->vhtCap.suppMcs.txHighest;
uVHTSupDataRateInfo.nCfgValue16 = nCfgValue & 0xffff;
pDot11f->txSupDataRate = uVHTSupDataRateInfo.vhtTxSupDataRateInfo.txSupDataRate;
pDot11f->reserved3= uVHTSupDataRateInfo.vhtTxSupDataRateInfo.reserved;
limLogVHTCap(pMac, pDot11f);
return eSIR_SUCCESS;
}
static tSirRetStatus
limTdlsPopulateMatchingRateSet(tpAniSirGlobal pMac,
tpDphHashNode pStaDs,
tANI_U8 *pSupportedRateSet,
tANI_U8 supporteRatesLength,
tANI_U8* pSupportedMCSSet,
tSirMacPropRateSet *pAniLegRateSet,
tpPESession psessionEntry,
tDot11fIEVHTCaps *pVHTCaps)
{
tSirMacRateSet tempRateSet;
tANI_U32 i,j,val,min,isArate;
tSirMacRateSet tempRateSet2;
tANI_U32 phyMode;
tANI_U8 mcsSet[SIZE_OF_SUPPORTED_MCS_SET];
isArate=0;
// limGetPhyMode(pMac, &phyMode);
limGetPhyMode(pMac, &phyMode, NULL);
// get own rate set
val = WNI_CFG_OPERATIONAL_RATE_SET_LEN;
if (wlan_cfgGetStr(pMac, WNI_CFG_OPERATIONAL_RATE_SET,
(tANI_U8 *) &tempRateSet.rate,
&val) != eSIR_SUCCESS)
{
/// Could not get rateset from CFG. Log error.
limLog(pMac, LOGP, FL("could not retrieve rateset"));
val = 0;
}
tempRateSet.numRates = val;
if (phyMode == WNI_CFG_PHY_MODE_11G)
{
// get own extended rate set
val = WNI_CFG_EXTENDED_OPERATIONAL_RATE_SET_LEN;
if (wlan_cfgGetStr(pMac, WNI_CFG_EXTENDED_OPERATIONAL_RATE_SET,
(tANI_U8 *) &tempRateSet2.rate,
&val) != eSIR_SUCCESS)
tempRateSet2.numRates = val;
}
else
tempRateSet2.numRates = 0;
if ((tempRateSet.numRates + tempRateSet2.numRates) > 12)
{
PELOGE(limLog(pMac, LOGE, FL("more than 12 rates in CFG"));)
goto error;
}
/**
* Handling of the rate set IEs is the following:
* - keep only rates that we support and that the station supports
* - sort and the rates into the pSta->rate array
*/
// Copy all rates in tempRateSet, there are 12 rates max
for (i = 0; i < tempRateSet2.numRates; i++)
tempRateSet.rate[i + tempRateSet.numRates] = tempRateSet2.rate[i];
tempRateSet.numRates += tempRateSet2.numRates;
/**
* Sort rates in tempRateSet (they are likely to be already sorted)
* put the result in tempRateSet2
*/
tempRateSet2.numRates = 0;
for (i = 0;i < tempRateSet.numRates; i++)
{
min = 0;
val = 0xff;
for(j = 0;j < tempRateSet.numRates; j++)
if ((tANI_U32) (tempRateSet.rate[j] & 0x7f) < val)
{
val = tempRateSet.rate[j] & 0x7f;
min = j;
}
tempRateSet2.rate[tempRateSet2.numRates++] = tempRateSet.rate[min];
tempRateSet.rate[min] = 0xff;
}
/**
* Copy received rates in tempRateSet, the parser has ensured
* unicity of the rates so there cannot be more than 12 . Need to Check this
* TODO Sunil.
*/
for (i = 0; i < supporteRatesLength; i++)
{
tempRateSet.rate[i] = pSupportedRateSet[i];
}
tempRateSet.numRates = supporteRatesLength;
{
tpSirSupportedRates rates = &pStaDs->supportedRates;
tANI_U8 aRateIndex = 0;
tANI_U8 bRateIndex = 0;
vos_mem_set( (tANI_U8 *) rates, sizeof(tSirSupportedRates), 0);
for (i = 0;i < tempRateSet2.numRates; i++)
{
for (j = 0;j < tempRateSet.numRates; j++)
{
if ((tempRateSet2.rate[i] & 0x7F) ==
(tempRateSet.rate[j] & 0x7F))
{
#ifdef FEATURE_WLAN_NON_INTEGRATED_SOC
if ((bRateIndex > HAL_NUM_11B_RATES) || (aRateIndex > HAL_NUM_11A_RATES))
{
limLog(pMac, LOGE, FL("Invalid number of rates (11b->%d, 11a->%d)"),
bRateIndex, aRateIndex);
return eSIR_FAILURE;
}
#endif
if (sirIsArate(tempRateSet2.rate[i] & 0x7f))
{
isArate=1;
rates->llaRates[aRateIndex++] = tempRateSet2.rate[i];
}
else
rates->llbRates[bRateIndex++] = tempRateSet2.rate[i];
break;
}
}
}
}
//compute the matching MCS rate set, if peer is 11n capable and self mode is 11n
#ifdef FEATURE_WLAN_TDLS
if (pStaDs->mlmStaContext.htCapability)
#else
if (IS_DOT11_MODE_HT(psessionEntry->dot11mode) &&
(pStaDs->mlmStaContext.htCapability))
#endif
{
val = SIZE_OF_SUPPORTED_MCS_SET;
if (wlan_cfgGetStr(pMac, WNI_CFG_SUPPORTED_MCS_SET,
mcsSet,
&val) != eSIR_SUCCESS)
{
/// Could not get rateset from CFG. Log error.
limLog(pMac, LOGP, FL("could not retrieve supportedMCSSet"));
goto error;
}
for (i=0; i<val; i++)
pStaDs->supportedRates.supportedMCSSet[i] = mcsSet[i] & pSupportedMCSSet[i];
PELOG2(limLog(pMac, LOG2, FL("limPopulateMatchingRateSet: MCS Rate Set Bitmap from CFG and DPH :"));)
for (i=0; i<SIR_MAC_MAX_SUPPORTED_MCS_SET; i++)
{
PELOG2(limLog(pMac, LOG2,FL("%x %x "), mcsSet[i], pStaDs->supportedRates.supportedMCSSet[i]);)
}
}
#ifdef WLAN_FEATURE_11AC
limPopulateVhtMcsSet(pMac, &pStaDs->supportedRates, pVHTCaps, psessionEntry);
#endif
/**
* Set the erpEnabled bit iff the phy is in G mode and at least
* one A rate is supported
*/
if ((phyMode == WNI_CFG_PHY_MODE_11G) && isArate)
pStaDs->erpEnabled = eHAL_SET;
return eSIR_SUCCESS;
error:
return eSIR_FAILURE;
}
static int limTdlsSelectCBMode(tDphHashNode *pStaDs, tpPESession psessionEntry)
{
tANI_U8 channel = psessionEntry->currentOperChannel;
if ( pStaDs->mlmStaContext.vhtCapability )
{
if ( channel== 36 || channel == 52 || channel == 100 ||
channel == 116 || channel == 149 )
{
return PHY_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_LOW - 1;
}
else if ( channel == 40 || channel == 56 || channel == 104 ||
channel == 120 || channel == 153 )
{
return PHY_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_LOW - 1;
}
else if ( channel == 44 || channel == 60 || channel == 108 ||
channel == 124 || channel == 157 )
{
return PHY_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_HIGH -1;
}
else if ( channel == 48 || channel == 64 || channel == 112 ||
channel == 128 || channel == 161 )
{
return PHY_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_HIGH - 1;
}
else if ( channel == 165 )
{
return 0;
}
}
else if ( pStaDs->mlmStaContext.htCapability )
{
if ( channel== 40 || channel == 48 || channel == 56 ||
channel == 64 || channel == 104 || channel == 112 ||
channel == 120 || channel == 128 || channel == 136 ||
channel == 144 || channel == 153 || channel == 161 )
{
return 1;
}
else if ( channel== 36 || channel == 44 || channel == 52 ||
channel == 60 || channel == 100 || channel == 108 ||
channel == 116 || channel == 124 || channel == 132 ||
channel == 140 || channel == 149 || channel == 157 )
{
return 2;
}
else if ( channel == 165 )
{
return 0;
}
}
return 0;
}
/*
* update HASH node entry info
*/
static void limTdlsUpdateHashNodeInfo(tpAniSirGlobal pMac, tDphHashNode *pStaDs,
tSirTdlsAddStaReq *pTdlsAddStaReq, tpPESession psessionEntry)
{
//tDot11fIEHTCaps *htCaps = &setupPeerInfo->tdlsPeerHTCaps ;
tDot11fIEHTCaps htCap, *htCaps;
tDot11fIEVHTCaps *pVhtCaps = NULL;
#ifdef WLAN_FEATURE_11AC
tDot11fIEVHTCaps vhtCap;
tANI_U8 cbMode;
#endif
tpDphHashNode pSessStaDs = NULL;
tANI_U16 aid;
if (pTdlsAddStaReq->tdlsAddOper == TDLS_OPER_ADD)
{
PopulateDot11fHTCaps(pMac, psessionEntry, &htCap);
}
else if (pTdlsAddStaReq->tdlsAddOper == TDLS_OPER_UPDATE)
{
limTdlsPopulateDot11fHTCaps(pMac, NULL, pTdlsAddStaReq, &htCap);
}
htCaps = &htCap;
if (htCaps->present)
{
pStaDs->mlmStaContext.htCapability = 1 ;
pStaDs->htGreenfield = htCaps->greenField ;
pStaDs->htSupportedChannelWidthSet = htCaps->supportedChannelWidthSet ;
pStaDs->htMIMOPSState = htCaps->mimoPowerSave ;
pStaDs->htMaxAmsduLength = htCaps->maximalAMSDUsize;
pStaDs->htAMpduDensity = htCaps->mpduDensity;
pStaDs->htDsssCckRate40MHzSupport = htCaps->dsssCckMode40MHz ;
pStaDs->htShortGI20Mhz = htCaps->shortGI20MHz;
pStaDs->htShortGI40Mhz = htCaps->shortGI40MHz;
pStaDs->htMaxRxAMpduFactor = htCaps->maxRxAMPDUFactor;
limFillRxHighestSupportedRate(pMac,
&pStaDs->supportedRates.rxHighestDataRate,
htCaps->supportedMCSSet);
pStaDs->baPolicyFlag = 0xFF;
pMac->lim.gLimTdlsLinkMode = TDLS_LINK_MODE_N ;
}
else
{
pStaDs->mlmStaContext.htCapability = 0 ;
pMac->lim.gLimTdlsLinkMode = TDLS_LINK_MODE_BG ;
}
#ifdef WLAN_FEATURE_11AC
limTdlsPopulateDot11fVHTCaps(pMac, pTdlsAddStaReq, &vhtCap);
pVhtCaps = &vhtCap;
if (pVhtCaps->present)
{
pStaDs->mlmStaContext.vhtCapability = 1 ;
if ((psessionEntry->currentOperChannel <= SIR_11B_CHANNEL_END) &&
pMac->roam.configParam.enableVhtFor24GHz)
{
pStaDs->vhtSupportedChannelWidthSet = WNI_CFG_VHT_CHANNEL_WIDTH_20_40MHZ;
pStaDs->htSupportedChannelWidthSet = eHT_CHANNEL_WIDTH_20MHZ;
}
else
{
pStaDs->vhtSupportedChannelWidthSet = WNI_CFG_VHT_CHANNEL_WIDTH_80MHZ;
pStaDs->htSupportedChannelWidthSet = eHT_CHANNEL_WIDTH_40MHZ ;
}
pStaDs->vhtLdpcCapable = pVhtCaps->ldpcCodingCap;
pStaDs->vhtBeamFormerCapable= pVhtCaps->suBeamFormerCap;
// TODO , is it necessary , Sunil???
pMac->lim.gLimTdlsLinkMode = TDLS_LINK_MODE_AC;
}
else
{
pStaDs->mlmStaContext.vhtCapability = 0 ;
pStaDs->vhtSupportedChannelWidthSet = WNI_CFG_VHT_CHANNEL_WIDTH_20_40MHZ;
}
#endif
/*Calculate the Secondary Coannel Offset */
cbMode = limTdlsSelectCBMode(pStaDs, psessionEntry);
pStaDs->htSecondaryChannelOffset = cbMode;
#ifdef WLAN_FEATURE_11AC
if ( pStaDs->mlmStaContext.vhtCapability )
{
pStaDs->htSecondaryChannelOffset = limGetHTCBState(cbMode);
}
#endif
pSessStaDs = dphLookupHashEntry(pMac, psessionEntry->bssId, &aid,
&psessionEntry->dph.dphHashTable) ;
/* Lets enable QOS parameter */
pStaDs->qosMode = 1;
pStaDs->wmeEnabled = 1;
pStaDs->lleEnabled = 0;
/* TDLS Dummy AddSTA does not have qosInfo , is it OK ??
*/
pStaDs->qos.capability.qosInfo = (*(tSirMacQosInfoStation *) &pTdlsAddStaReq->uapsd_queues);
/* populate matching rate set */
/* TDLS Dummy AddSTA does not have HTCap,VHTCap,Rates info , is it OK ??
*/
limTdlsPopulateMatchingRateSet(pMac, pStaDs, pTdlsAddStaReq->supported_rates,
pTdlsAddStaReq->supported_rates_length,
(tANI_U8 *)pTdlsAddStaReq->htCap.suppMcsSet,
&pStaDs->mlmStaContext.propRateSet,
psessionEntry, pVhtCaps);
/* TDLS Dummy AddSTA does not have right capability , is it OK ??
*/
pStaDs->mlmStaContext.capabilityInfo = ( *(tSirMacCapabilityInfo *) &pTdlsAddStaReq->capability);
return ;
}
#ifdef FEATURE_WLAN_TDLS_INTERNAL
/*
* find Peer in setup link list.
*/
tANI_U8 limTdlsFindLinkPeer(tpAniSirGlobal pMac, tSirMacAddr peerMac,
tLimTdlsLinkSetupPeer **setupPeer)
{
tLimTdlsLinkSetupInfo *setupInfo = &pMac->lim.gLimTdlsLinkSetupInfo ;
tLimTdlsLinkSetupPeer *linkSetupList = setupInfo->tdlsLinkSetupList ;
tANI_U8 checkNode = TDLS_NODE_NOT_FOUND ;
while (linkSetupList != NULL)
{
if (vos_mem_compare((tANI_U8 *) peerMac,
(tANI_U8 *) linkSetupList->peerMac,
sizeof(tSirMacAddr)) )
{
checkNode = TDLS_NODE_FOUND ;
*setupPeer = linkSetupList ;
break ;
}
linkSetupList = linkSetupList->next;
}
return ((TDLS_NODE_FOUND == checkNode) ? eSIR_SUCCESS : eSIR_FAILURE ) ;
}
/*
* find peer in Discovery list.
* Dicovery list get populated in two instances, a) Recieved responses in reply
* to discovery request b) If discover request is received from TDLS peer STA
*/
tSirTdlsPeerInfo *limTdlsFindDisPeer(tpAniSirGlobal pMac, tSirMacAddr peerMac)
{
tLimDisResultList *discoveryList = pMac->lim.gLimTdlsDisResultList ;
tSirTdlsPeerInfo *peerInfo = NULL ;
while (discoveryList != NULL)
{
peerInfo = &discoveryList->tdlsDisPeerInfo ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Peer in discovery list = %02x, %02x, %02x, %02x, %02x, %02x "),
peerInfo->peerMac[0],
peerInfo->peerMac[1],
peerInfo->peerMac[2],
peerInfo->peerMac[3],
peerInfo->peerMac[4],
peerInfo->peerMac[5]) ;
if (vos_mem_compare((tANI_U8 *) peerMac,
(tANI_U8 *) &peerInfo->peerMac, sizeof(tSirMacAddr)) )
{
break ;
}
discoveryList = discoveryList->next;
}
return peerInfo ;
}
/*
* find peer in Discovery list by looking into peer state.
* Dicovery list get populated in two instances, a) Recieved responses in reply
* to discovery request b) If discover request is received from TDLS peer STA
*/
static tSirTdlsPeerInfo *limTdlsFindDisPeerByState(tpAniSirGlobal pMac,
tANI_U8 state)
{
tLimDisResultList *discoveryList = pMac->lim.gLimTdlsDisResultList ;
tSirTdlsPeerInfo *peerInfo = NULL ;
while (discoveryList != NULL)
{
peerInfo = &discoveryList->tdlsDisPeerInfo ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("peerInfo Mac = %02x, %02x, %02x, %02x, %02x, %02x "),
peerInfo->peerMac[0],
peerInfo->peerMac[1],
peerInfo->peerMac[2],
peerInfo->peerMac[3],
peerInfo->peerMac[4],
peerInfo->peerMac[5]) ;
if (peerInfo->tdlsPeerState == state)
{
break ;
}
discoveryList = discoveryList->next;
}
return peerInfo ;
}
/*
* find peer in Setup list by looking into peer state.
* setup list get populated in two instances, a) Recieved responses in reply
* to setup request b) If discover request is received from TDLS peer STA
*/
static tANI_U8 limTdlsFindSetupPeerByState(tpAniSirGlobal pMac, tANI_U8 state,
tLimTdlsLinkSetupPeer **setupPeer)
{
tLimTdlsLinkSetupInfo *setupInfo = &pMac->lim.gLimTdlsLinkSetupInfo ;
tLimTdlsLinkSetupPeer *linkSetupList = setupInfo->tdlsLinkSetupList ;
tANI_U8 checkNode = TDLS_NODE_NOT_FOUND ;
while (linkSetupList != NULL)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("peer state = %02x"), (linkSetupList)->tdls_link_state) ;
if((linkSetupList)->tdls_link_state == state)
{
checkNode = TDLS_NODE_FOUND ;
*setupPeer = linkSetupList ;
break ;
}
linkSetupList = (linkSetupList)->next;
}
return ((TDLS_NODE_FOUND == checkNode) ? eSIR_SUCCESS: eSIR_FAILURE) ;
}
/*
* delete Peer from Setup Link
*/
void limTdlsDelLinkPeer(tpAniSirGlobal pMac, tSirMacAddr peerMac)
{
tLimTdlsLinkSetupInfo *setupInfo = &pMac->lim.gLimTdlsLinkSetupInfo ;
tLimTdlsLinkSetupPeer **linkSetupList = &setupInfo->tdlsLinkSetupList ;
tLimTdlsLinkSetupPeer *currentNode = NULL ;
tLimTdlsLinkSetupPeer *prevNode = NULL ;
for(currentNode = *linkSetupList ; currentNode != NULL ;
prevNode = currentNode, currentNode = currentNode->next)
{
if (vos_mem_compare( (tANI_U8 *) peerMac,
(tANI_U8 *) currentNode->peerMac,
sizeof(tSirMacAddr)) )
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Del Node for Peer = %02x,%02x,%02x,%02x,%02x,%02x"),
currentNode->peerMac[0],
currentNode->peerMac[1],
currentNode->peerMac[2],
currentNode->peerMac[3],
currentNode->peerMac[4],
currentNode->peerMac[5]) ;
/* if it's first Node */
if(NULL == prevNode)
{
*linkSetupList = currentNode->next ;
}
else
{
prevNode->next = currentNode->next ;
}
vos_mem_free(currentNode) ;
return ;
}
}
return ;
}
/*
* TDLS discovery request frame received from TDLS peer STA..
*/
static tSirRetStatus limProcessTdlsDisReqFrame(tpAniSirGlobal pMac,
tANI_U8 *pBody, tANI_U32 frmLen )
{
tDot11fTDLSDisReq tdlsDisReq = {{0}} ;
tANI_U32 status = 0 ;
tLimDisResultList *tdlsDisResult = NULL ;
tLimDisResultList **disResultList = &pMac->lim.gLimTdlsDisResultList ;
tSirMacAddr peerMac = {0} ;
tLimTdlsLinkSetupPeer *setupPeer = NULL ;
tSirTdlsPeerInfo *peerInfo = NULL ;
tpPESession psessionEntry = NULL ;
tANI_U8 sessionId = 0 ;
status = dot11fUnpackTDLSDisReq(pMac, pBody, frmLen, &tdlsDisReq) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_WARN,
("TDLS dis request dialog = %d"), tdlsDisReq.DialogToken.token);
if ( DOT11F_FAILED( status ) )
{
limLog(pMac, LOGE, FL("Failed to parse TDLS discovery Request \
frame (0x%08x, %d bytes):"),status, frmLen);
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pBody, frmLen);)
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while unpacking an\
TDLS discovery Request frame (0x%08x," "%d bytes):"),
status, frmLen );
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pBody, frmLen);)
}
/*
* find session entry using BSSID in link identifier, not using MAC
* header beacuse, there is cases in TDLS, there may be BSSID will not
* be present in header
*/
psessionEntry = peFindSessionByBssid(pMac,
&tdlsDisReq.LinkIdentifier.bssid[0], &sessionId) ;
if(NULL == psessionEntry)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, \
("no Seesion entry for TDLS session (bssid %02x:%02x:%02x:%02x:%02x:%02x)"), \
tdlsDisReq.LinkIdentifier.bssid[0],
tdlsDisReq.LinkIdentifier.bssid[1],
tdlsDisReq.LinkIdentifier.bssid[2],
tdlsDisReq.LinkIdentifier.bssid[3],
tdlsDisReq.LinkIdentifier.bssid[4],
tdlsDisReq.LinkIdentifier.bssid[5]) ;
//VOS_ASSERT(0) ;
return eSIR_FAILURE;
}
/* varify BSSID */
status = vos_mem_compare( &psessionEntry->bssId[0],
&tdlsDisReq.LinkIdentifier.bssid[0], sizeof(tSirMacAddr)) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("lim BSSID %02x, %02x, %02x, %02x, %02x, %02x"),
psessionEntry->bssId[0],
psessionEntry->bssId[1],
psessionEntry->bssId[2],
psessionEntry->bssId[3],
psessionEntry->bssId[4],
psessionEntry->bssId[5]) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Dis req from BSSID %02x, %02x, %02x, %02x, %02x, %02x"),
tdlsDisReq.LinkIdentifier.bssid[0],
tdlsDisReq.LinkIdentifier.bssid[1],
tdlsDisReq.LinkIdentifier.bssid[2],
tdlsDisReq.LinkIdentifier.bssid[3],
tdlsDisReq.LinkIdentifier.bssid[4],
tdlsDisReq.LinkIdentifier.bssid[5]
) ;
if(!status)
{
limLog( pMac, LOGE, FL("TDLS discovery request frame from other BSS -> something wrong. Check RXP filter")) ;
return eSIR_FAILURE ;
}
/*
* check if this is echo of our transmitted discovery request
* drop it here, TODO: better to drop this in TL.
*/
status = vos_mem_compare( psessionEntry->selfMacAddr,
&tdlsDisReq.LinkIdentifier.InitStaAddr[0],
sizeof(tSirMacAddr)) ;
if(status)
{
limLog( pMac, LOGE, FL("Echo of our TDLS discovery request frame")) ;
return eSIR_FAILURE ;
}
/*
* while processing Discovery request from Peer,
* STA_MAC--> MAC of TDLS discovery initiator
* STA_PEER_MAC--> MAC of TDLS discovery responder.
*/
vos_mem_copy( peerMac,
&tdlsDisReq.LinkIdentifier.InitStaAddr[0],
sizeof(tSirMacAddr)) ;
/* TODO, do more validation */
/* see if discovery is already in progress */
peerInfo = limTdlsFindDisPeer(pMac, peerMac) ;
if(NULL == peerInfo)
{
/*
* we are allocating peer info for individual peers found in TDLS
* discovery, we need to keep adding TDLS peers till we have timed
* out. We are freeing this memory at the time we are sending this
* collected peer info to SME.
*/
tdlsDisResult = vos_mem_malloc(sizeof(tLimDisResultList));
if ( NULL == tdlsDisResult )
{
limLog(pMac, LOGP, FL("alloc fail for TDLS discovery \
reponse info")) ;
return eSIR_FAILURE ;
}
peerInfo = &tdlsDisResult->tdlsDisPeerInfo ;
peerInfo->tdlsPeerState = TDLS_DIS_REQ_PROCESS_STATE ;
peerInfo->dialog = tdlsDisReq.DialogToken.token ;
peerInfo->sessionId = psessionEntry->peSessionId;
/* Populate peer info of tdls discovery result */
vos_mem_copy( peerInfo->peerMac, peerMac, sizeof(tSirMacAddr)) ;
/*
* Now, as per D13, there will not be any Supp rates, ext Supp rates
* info in Discovery request frames, so we are populating this info
* locally to pass it to ADD STA.
*/
do
{
tDot11fIESuppRates suppRates = {0} ;
tDot11fIEExtSuppRates extSuppRates = {0} ;
tANI_U16 caps = 0 ;
tDot11fFfCapabilities capsInfo = {0} ;
tDot11fIEHTCaps HTCaps = {0} ;
/* populate supported rate IE */
PopulateDot11fSuppRates( pMac, POPULATE_DOT11F_RATES_OPERATIONAL,
&suppRates, psessionEntry );
ConvertSuppRates( pMac, &peerInfo->tdlsPeerSuppRates,
&suppRates);
/* Populate extended supported rates */
PopulateDot11fExtSuppRates( pMac, POPULATE_DOT11F_RATES_OPERATIONAL,
&extSuppRates, psessionEntry );
peerInfo->ExtRatesPresent = 1;
ConvertExtSuppRates( pMac, &peerInfo->tdlsPeerExtRates,
&extSuppRates);
if(cfgGetCapabilityInfo(pMac, &caps, psessionEntry) != eSIR_SUCCESS)
{
/*
* Could not get Capabilities value
* from CFG. Log error.
*/
limLog(pMac, LOGP,
FL("could not retrieve Capabilities value"));
}
swapBitField16(caps, ( tANI_U16* )&capsInfo );
/* update Caps Info */
tdlsUpdateCapInfo(&peerInfo->capabilityInfo, &capsInfo) ;
PopulateDot11fHTCaps( pMac, psessionEntry, &HTCaps );
limTdlsCovertHTCaps(pMac, peerInfo, &HTCaps) ;
} while (0) ;
/* now add this new found discovery node into tdls discovery list */
tdlsDisResult->next = *disResultList ;
*disResultList = tdlsDisResult ;
pMac->lim.gLimTdlsDisStaCount++ ;
/* See if for this peer already entry in setup Link */
limTdlsFindLinkPeer(pMac, peerMac, &setupPeer) ;
/*
* if there is no entry for this peer in setup list, we need to
* do add sta for this peer to transmit discovery rsp.
*/
if(NULL == setupPeer)
{
/* To start with, send add STA request to HAL */
pMac->lim.gLimAddStaTdls = true ;
peerInfo->delStaNeeded = true ;
if(eSIR_FAILURE == limTdlsDisAddSta(pMac, peerMac,
peerInfo, psessionEntry))
{
VOS_ASSERT(0) ;
limLog(pMac, LOGE, "Add STA for dis response is failed ") ;
return eSIR_FAILURE ;
}
} /* use setup link sta ID for discovery rsp */
else
{
peerInfo->delStaNeeded = false ;
limSendTdlsDisRspFrame(pMac, peerInfo->peerMac, peerInfo->dialog, psessionEntry) ;
peerInfo->tdlsPeerState = TDLS_DIS_RSP_SENT_WAIT_STATE ;
}
}
else
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("discovery procedure in progress for this peer")) ;
}
return eSIR_SUCCESS ;
}
/* Process TDLS setup Request Frame */
static tSirRetStatus limProcessTdlsSetupReqFrame(tpAniSirGlobal pMac,
tANI_U8 *pBody, tANI_U32 frmLen)
{
tDot11fTDLSSetupReq tdlsSetupReq = {{0}} ;
tANI_U32 status = 0 ;
tpPESession psessionEntry = NULL ;
tANI_U8 sessionId = 0 ;
tANI_U8 currentState = TDLS_LINK_SETUP_WAIT_STATE ;
tANI_U8 previousState = TDLS_LINK_IDLE_STATE ;
/* create node for Link setup */
tLimTdlsLinkSetupInfo *linkSetupInfo = &pMac->lim.gLimTdlsLinkSetupInfo ;
tLimTdlsLinkSetupPeer *setupPeer = NULL ;
tLimTdlsLinkSetupPeer *tmpSetupPeer = NULL ;
status = dot11fUnpackTDLSSetupReq(pMac, pBody, frmLen, &tdlsSetupReq) ;
if ( DOT11F_FAILED( status ) )
{
limLog(pMac, LOGE, FL("Failed to parse TDLS discovery Request \
frame (0x%08x, %d bytes):"),status, frmLen);
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pBody, frmLen);)
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while unpacking an\
TDLS setup Request frame (0x%08x," "%d bytes):"),
status, pBody );
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pBody, frmLen);)
}
/*
* find session entry using BSSID in link identifier, not using MAC
* header beacuse, there is cases in TDLS, there may be BSSID will not
* be present in header
*/
psessionEntry = peFindSessionByBssid(pMac,
&tdlsSetupReq.LinkIdentifier.bssid[0], &sessionId) ;
if(NULL == psessionEntry)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, \
("no Seesion entry for TDLS session (bssid %02x:%02x:%02x:%02x:%02x:%02x)"), \
tdlsSetupReq.LinkIdentifier.bssid[0],
tdlsSetupReq.LinkIdentifier.bssid[1],
tdlsSetupReq.LinkIdentifier.bssid[2],
tdlsSetupReq.LinkIdentifier.bssid[3],
tdlsSetupReq.LinkIdentifier.bssid[4],
tdlsSetupReq.LinkIdentifier.bssid[5]) ;
//VOS_ASSERT(0) ;
return eSIR_FAILURE ;
}
/* TODO: we don;t need this check now, varify BSSID */
status = vos_mem_compare( psessionEntry->bssId,
&tdlsSetupReq.LinkIdentifier.bssid[0],
sizeof(tSirMacAddr)) ;
if(!status)
{
limLog( pMac, LOGE, FL("TDLS setup request frame from other BSS -> something wrong. Check RXP filter")) ;
limSendTdlsSetupRspFrame(pMac, tdlsSetupReq.LinkIdentifier.InitStaAddr,
tdlsSetupReq.DialogToken.token, psessionEntry,
TDLS_SETUP_STATUS_FAILURE, NULL, 0 ) ;
return eSIR_FAILURE ;
}
#ifdef FEATURE_WLAN_TDLS_NEGATIVE
if(pMac->lim.gLimTdlsNegativeBehavior & LIM_TDLS_NEGATIVE_RSP_TIMEOUT_TO_SETUP_REQ)
{
/* simply ignore this setup request packet */
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("TDLS negative running: ignore TDLS Setup Req packet"));
return eSIR_SUCCESS ;
}
if(pMac->lim.gLimTdlsNegativeBehavior & LIM_TDLS_NEGATIVE_SEND_REQ_TO_SETUP_REQ)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("TDLS negative running: send TDLS Setup Req to peer TDLS Setup Req"));
/* format TDLS discovery request frame and transmit it */
limSendTdlsLinkSetupReqFrame(pMac, tdlsSetupReq.LinkIdentifier.InitStaAddr, tdlsSetupReq.DialogToken.token, psessionEntry,
NULL, 0) ;
}
#endif
/* TODO, do more validation */
if(!limTdlsFindLinkPeer(pMac,
&tdlsSetupReq.LinkIdentifier.InitStaAddr[0],
&tmpSetupPeer))
{
tANI_U32 tdlsStateStatus = TDLS_LINK_SETUP_START_STATE ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("Link is already setup with this peer" )) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("state = %d"), tmpSetupPeer->tdls_link_state) ;
//return eSIR_FAILURE ;
if(tmpSetupPeer == NULL)
{
VOS_ASSERT(0) ;
return eSIR_FAILURE ;
}
switch(tmpSetupPeer->tdls_link_state)
{
case TDLS_LINK_SETUP_START_STATE:
{
v_SINT_t macCompare = 0 ;
macCompare= vos_mem_compare2(tmpSetupPeer->peerMac,
psessionEntry->selfMacAddr, sizeof(tSirMacAddr)) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("MAC comparison Rslt = %d"), macCompare ) ;
if(0 > macCompare)
{
/*
* Delete our Setup Request/Peer info and honour Peer
* Setup Request, go ahead and respond for this
*/
/* Deactivate the timer */
tx_timer_deactivate(&tmpSetupPeer->gLimTdlsLinkSetupRspTimeoutTimer) ;
#ifdef FEATURE_WLAN_TDLS_NEGATIVE
if((pMac->lim.gLimTdlsNegativeBehavior & LIM_TDLS_NEGATIVE_SEND_REQ_TO_SETUP_REQ)
!= LIM_TDLS_NEGATIVE_SEND_REQ_TO_SETUP_REQ)
#endif
limSendSmeTdlsLinkStartRsp(pMac, eSIR_FAILURE,
tmpSetupPeer->peerMac, eWNI_SME_TDLS_LINK_START_RSP);
limTdlsDelLinkPeer(pMac, tmpSetupPeer->peerMac) ;
tdlsStateStatus = TDLS_LINK_IDLE_STATE ;
}
else if(0 < macCompare)
{
/*
* Go ahead with current setup as peer is going to
* respond for setup request
*/
tdlsStateStatus = TDLS_LINK_SETUP_START_STATE ;
}
else
{
/* same MAC, not possible */
VOS_ASSERT(0) ;
}
break ;
}
#if 1
case TDLS_LINK_SETUP_DONE_STATE:
{
tpDphHashNode pStaDs = NULL ;
previousState = TDLS_LINK_SETUP_WAIT_STATE ;
currentState = TDLS_LINK_TEARDOWN_START_STATE ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("link Setup Done state " )) ;
tmpSetupPeer->tdls_prev_link_state = previousState ;
tmpSetupPeer->tdls_link_state = currentState ;
setupPeer = tmpSetupPeer ;
#if 0
/* Send Teardown to this Peer and Initiate new TDLS Setup */
limSendTdlsTeardownFrame(pMac,
&tdlsSetupReq.LinkIdentifier.InitStaAddr[0],
eSIR_MAC_TDLS_TEARDOWN_UNSPEC_REASON, psessionEntry) ;
#else
/* tdls_hklee: send message to HAL before it is deleted, cause */
limTdlsLinkTeardown(pMac, (setupPeer)->peerMac) ;
/* send del STA to remove context for this TDLS STA */
pStaDs = limTdlsDelSta(pMac, (setupPeer)->peerMac, psessionEntry) ;
/* now send indication to SME-->HDD->TL to remove STA from TL */
if(pStaDs)
{
limSendSmeTdlsDelPeerInd(pMac, psessionEntry->smeSessionId,
pStaDs, eSIR_SUCCESS) ;
/* send Teardown Ind to SME */
limSendSmeTdlsTeardownRsp(pMac, eSIR_SUCCESS, (setupPeer)->peerMac,
eWNI_SME_TDLS_TEARDOWN_IND) ;
/* remove node from setup list */
limTdlsDelLinkPeer(pMac, (setupPeer)->peerMac) ;
}
#endif
//setupPeer->tdls_prev_link_state = TDLS_LINK_SETUP_RESTART_STATE;
tdlsStateStatus = TDLS_LINK_IDLE_STATE ;
break ;
}
default:
{
VOS_ASSERT(0) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("link Setup is Recieved in unknown state" )) ;
break ;
}
#endif
}
if(tdlsStateStatus == TDLS_LINK_SETUP_START_STATE)
return eSIR_FAILURE ;
}
if(currentState != TDLS_LINK_TEARDOWN_START_STATE)
{
/*
* Now we are sure to send discovery response frame to TDLS discovery
* initiator, we don't care, if this request is unicast ro broadcast,
* we simply, send discovery response frame on direct link.
*/
setupPeer = vos_mem_malloc(sizeof( tLimTdlsLinkSetupPeer ));
if ( NULL == setupPeer )
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
( "Unable to allocate memory during ADD_STA" ));
return eSIR_MEM_ALLOC_FAILED;
}
setupPeer->dialog = tdlsSetupReq.DialogToken.token ;
//setupPeer->tdls_prev_link_state = setupPeer->tdls_link_state ;
//setupPeer->tdls_link_state = TDLS_LINK_SETUP_WAIT_STATE ;
setupPeer->tdls_prev_link_state = previousState ;
setupPeer->tdls_link_state = currentState ;
/* TDLS_sessionize: remember sessionId for future */
setupPeer->tdls_sessionId = psessionEntry->peSessionId;
setupPeer->tdls_bIsResponder = 0;
vos_mem_copy(setupPeer->peerMac,
&tdlsSetupReq.LinkIdentifier.InitStaAddr[0],
sizeof(tSirMacAddr)) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Setup REQ MAC = %02x,%02x, %02x, %02x, %02x, %02x"),
setupPeer->peerMac[0],
setupPeer->peerMac[1],
setupPeer->peerMac[2],
setupPeer->peerMac[3],
setupPeer->peerMac[4],
setupPeer->peerMac[5] ) ;
limTdlsUpdateLinkReqPeerInfo(pMac, setupPeer, &tdlsSetupReq) ;
pMac->lim.gLimAddStaTdls = true ;
/* To start with, send add STA request to HAL */
if(eSIR_FAILURE == limTdlsSetupAddSta(pMac, setupPeer->peerMac,
setupPeer, psessionEntry))
{
VOS_ASSERT(0) ;
vos_mem_free((void **) &setupPeer) ;
return eSIR_FAILURE ;
}
limSendTdlsSetupRspFrame(pMac, tdlsSetupReq.LinkIdentifier.InitStaAddr,
tdlsSetupReq.DialogToken.token, psessionEntry,
TDLS_SETUP_STATUS_SUCCESS, NULL, 0) ;
limStartTdlsTimer(pMac, psessionEntry->peSessionId,
&setupPeer->gLimTdlsLinkSetupCnfTimeoutTimer,
(tANI_U32)setupPeer->peerMac,
WNI_CFG_TDLS_LINK_SETUP_CNF_TIMEOUT,
SIR_LIM_TDLS_LINK_SETUP_CNF_TIMEOUT) ;
/* update setup peer list */
setupPeer->next = linkSetupInfo->tdlsLinkSetupList ;
linkSetupInfo->tdlsLinkSetupList = setupPeer ;
}
else
{
setupPeer->dialog = tdlsSetupReq.DialogToken.token ;
//setupPeer->tdls_prev_link_state = setupPeer->tdls_link_state ;
//setupPeer->tdls_link_state = TDLS_LINK_SETUP_WAIT_STATE ;
setupPeer->tdls_prev_link_state = previousState ;
setupPeer->tdls_link_state = currentState ;
/* TDLS_sessionize: remember sessionId for future */
setupPeer->tdls_sessionId = psessionEntry->peSessionId;
setupPeer->tdls_bIsResponder = 0;
vos_mem_copy( setupPeer->peerMac,
&tdlsSetupReq.LinkIdentifier.InitStaAddr[0],
sizeof(tSirMacAddr)) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Setup REQ MAC = %02x,%02x, %02x, %02x, %02x, %02x"),
setupPeer->peerMac[0],
setupPeer->peerMac[1],
setupPeer->peerMac[2],
setupPeer->peerMac[3],
setupPeer->peerMac[4],
setupPeer->peerMac[5] ) ;
limTdlsUpdateLinkReqPeerInfo(pMac, setupPeer, &tdlsSetupReq) ;
limSendTdlsSetupRspFrame(pMac, tdlsSetupReq.LinkIdentifier.InitStaAddr,
tdlsSetupReq.DialogToken.token, psessionEntry,
TDLS_SETUP_STATUS_SUCCESS, NULL, 0) ;
limStartTdlsTimer(pMac, psessionEntry->peSessionId,
&setupPeer->gLimTdlsLinkSetupCnfTimeoutTimer,
(tANI_U32)setupPeer->peerMac,
WNI_CFG_TDLS_LINK_SETUP_CNF_TIMEOUT,
SIR_LIM_TDLS_LINK_SETUP_CNF_TIMEOUT) ;
}
return eSIR_SUCCESS ;
}
/*
* TDLS discovery request frame received from TDLS peer STA..
*/
static tSirRetStatus limProcessTdlsSetupRspFrame(tpAniSirGlobal pMac,
tANI_U8 *pBody, tANI_U32 frmLen )
{
tDot11fTDLSSetupRsp tdlsSetupRsp = {{0}} ;
tANI_U32 status = 0 ;
tSirMacAddr peerMac = {0} ;
tLimTdlsLinkSetupPeer *setupPeer = NULL ;
tpPESession psessionEntry = NULL ;
tANI_U8 sessionId = 0 ;
status = dot11fUnpackTDLSSetupRsp(pMac, pBody, frmLen, &tdlsSetupRsp) ;
if ( DOT11F_FAILED( status ) )
{
limLog(pMac, LOGE, FL("Failed to parse TDLS discovery Request \
frame (0x%08x, %d bytes):"),status, frmLen);
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pBody, frmLen);)
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while unpacking an\
TDLS discovery Request frame (0x%08x," "%d bytes):"),
status, frmLen );
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pBody, frmLen);)
}
/*
* find session entry using BSSID in link identifier, not using MAC
* header beacuse, there is cases in TDLS, there may be BSSID will not
* be present in header
*/
psessionEntry = peFindSessionByBssid(pMac,
&tdlsSetupRsp.LinkIdentifier.bssid[0], &sessionId) ;
if(NULL == psessionEntry)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, \
("no Seesion entry for TDLS session (bssid %02x:%02x:%02x:%02x:%02x:%02x)"), \
tdlsSetupRsp.LinkIdentifier.bssid[0],
tdlsSetupRsp.LinkIdentifier.bssid[1],
tdlsSetupRsp.LinkIdentifier.bssid[2],
tdlsSetupRsp.LinkIdentifier.bssid[3],
tdlsSetupRsp.LinkIdentifier.bssid[4],
tdlsSetupRsp.LinkIdentifier.bssid[5]) ;
//VOS_ASSERT(0) ;
return eSIR_FAILURE;
}
/* varify BSSID */
status = vos_mem_compare( psessionEntry->bssId,
&tdlsSetupRsp.LinkIdentifier.bssid[0],
sizeof(tSirMacAddr)) ;
if(!status)
{
limLog( pMac, LOGE, FL("TDLS discovery request frame from other BSS -> something wrong. Check RXP filter")) ;
VOS_ASSERT(0) ;
return eSIR_FAILURE ;
}
vos_mem_copy( peerMac,
&tdlsSetupRsp.LinkIdentifier.RespStaAddr[0],
sizeof(tSirMacAddr)) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("TDLS setup RSP peer = %02x,%02x,%02x,%02x,%02x,%02x"),
peerMac[0],
peerMac[1],
peerMac[2],
peerMac[3],
peerMac[4],
peerMac[5]) ;
limTdlsFindLinkPeer(pMac, peerMac, &setupPeer) ;
if(NULL == setupPeer)
{
limLog( pMac, LOGE, FL(" unknown setup Response frame \
other BSS")) ;
return eSIR_FAILURE ;
}
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("deactivating Setup RSP timer")) ;
/* Deactivate the timer */
tx_timer_deactivate(&(setupPeer)->gLimTdlsLinkSetupRspTimeoutTimer) ;
/*
* TDLS Setup RSP is recieved with Failure, Delete this STA entry
* don't respond with TDLS CNF frame.
*/
if(TDLS_SETUP_STATUS_SUCCESS != tdlsSetupRsp.Status.status)
{
limTdlsDelLinkPeer(pMac, (setupPeer)->peerMac) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("setup RSP with Failure Code")) ;
return eSIR_FAILURE ;
}
/* update Link Info */
limTdlsUpdateLinkRspPeerInfo(pMac, setupPeer, &tdlsSetupRsp) ;
/* TODO, do more validation */
/*
* Now we are sure to send link setup CNF frame to TDLS link setup
* reponded, now we will create dph hash entry and send add STA to HAL
*/
pMac->lim.gLimAddStaTdls = true ;
if(eSIR_FAILURE == limTdlsSetupAddSta(pMac, peerMac,
setupPeer, psessionEntry))
{
/* through error */
VOS_ASSERT(0) ;
return eSIR_FAILURE ;
}
/* TDLS_HKLEE_FIXME: now we add some delay for AddSta_Rsp comes */
/* send TDLS confim frame to TDLS Peer STA */
limSendTdlsLinkSetupCnfFrame(pMac, peerMac, tdlsSetupRsp.DialogToken.token, psessionEntry, NULL, 0) ;
/*
* set the tdls_link_state to TDLS_LINK_SETUP_RSP_WAIT_STATE, and
* wait for Setup CNF transmission on air, once we receive tx complete
* message, we will change the peer state and send message to SME
* callback..
*/
(setupPeer)->tdls_prev_link_state = (setupPeer)->tdls_link_state ;
(setupPeer)->tdls_link_state = TDLS_LINK_SETUP_RSP_WAIT_STATE ;
return eSIR_SUCCESS ;
}
/*
* TDLS setup CNF frame processing ..
*/
static tSirRetStatus limProcessTdlsSetupCnfFrame(tpAniSirGlobal pMac,
tANI_U8 *pBody, tANI_U32 frmLen)
{
tDot11fTDLSSetupCnf tdlsSetupCnf = {{0}} ;
tANI_U32 status = 0 ;
tLimTdlsLinkSetupPeer *setupPeer = NULL ;
tpPESession psessionEntry = NULL ;
tANI_U8 sessionId = 0 ;
status = dot11fUnpackTDLSSetupCnf(pMac, pBody, frmLen, &tdlsSetupCnf) ;
if ( DOT11F_FAILED( status ) )
{
limLog(pMac, LOGE, FL("Failed to parse an TDLS discovery Response \
frame (0x%08x, %d bytes):"),status, frmLen);
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pBody, frmLen);)
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while unpacking an\
TDLS discovery Response frame (0x%08x," "%d bytes):"),
status, frmLen );
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pBody, frmLen);)
}
/*
* find session entry using BSSID in link identifier, not using MAC
* header beacuse, there is cases in TDLS, there may be BSSID will not
* be present in header
*/
psessionEntry = peFindSessionByBssid(pMac,
&tdlsSetupCnf.LinkIdentifier.bssid[0], &sessionId) ;
if(NULL == psessionEntry)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, \
("no Seesion entry for TDLS session (bssid %02x:%02x:%02x:%02x:%02x:%02x)"), \
tdlsSetupCnf.LinkIdentifier.bssid[0],
tdlsSetupCnf.LinkIdentifier.bssid[1],
tdlsSetupCnf.LinkIdentifier.bssid[2],
tdlsSetupCnf.LinkIdentifier.bssid[3],
tdlsSetupCnf.LinkIdentifier.bssid[4],
tdlsSetupCnf.LinkIdentifier.bssid[5]) ;
//VOS_ASSERT(0) ;
return eSIR_FAILURE;
}
/* varify BSSID */
status = vos_mem_compare( psessionEntry->bssId,
&tdlsSetupCnf.LinkIdentifier.bssid[0],
sizeof(tSirMacAddr)) ;
if(!status)
{
limLog( pMac, LOGE, FL("TDLS setup CNF frame other BSS -> something wrong. Check RXP filter")) ;
VOS_ASSERT(0) ;
return eSIR_FAILURE ;
}
/* TODO, do more validation */
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("setup Cnf peer MAc = %02x,%02x,%02x,%02x,%02x,%02x"),
tdlsSetupCnf.LinkIdentifier.InitStaAddr[0],
tdlsSetupCnf.LinkIdentifier.InitStaAddr[1],
tdlsSetupCnf.LinkIdentifier.InitStaAddr[2],
tdlsSetupCnf.LinkIdentifier.InitStaAddr[3],
tdlsSetupCnf.LinkIdentifier.InitStaAddr[4],
tdlsSetupCnf.LinkIdentifier.InitStaAddr[5]
) ;
limTdlsFindLinkPeer(pMac,
&tdlsSetupCnf.LinkIdentifier.InitStaAddr[0],
&setupPeer) ;
if(NULL == setupPeer)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
(" unknown setup CNF frame")) ;
VOS_ASSERT(0) ;
return eSIR_FAILURE ;
}
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("setup CNF peer MAC = %02x,%02x,%02x,%02x,%02x,%02x"),
(setupPeer)->peerMac[0],
(setupPeer)->peerMac[1],
(setupPeer)->peerMac[2],
(setupPeer)->peerMac[3],
(setupPeer)->peerMac[4],
(setupPeer)->peerMac[5]) ;
/*T match dialog token, before proceeding further */
if((setupPeer)->dialog != tdlsSetupCnf.DialogToken.token)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("setup CNF frame not matching with setup RSP")) ;
VOS_ASSERT(0) ;
return eSIR_FAILURE ;
}
/*
* Now we are sure that, this set CNF is for us, now stop
* the running timer..
*/
tx_timer_deactivate(&(setupPeer)->gLimTdlsLinkSetupCnfTimeoutTimer) ;
/* change TDLS peer State */
(setupPeer)->tdls_prev_link_state = (setupPeer)->tdls_link_state ;
(setupPeer)->tdls_link_state = TDLS_LINK_SETUP_DONE_STATE ;
/* send indication to SME that, new link is setup */
limSendSmeTdlsLinkSetupInd(pMac, (setupPeer)->peerMac, eSIR_SUCCESS) ;
/* tdls_hklee: prepare PTI template and send it to HAL */
limTdlsLinkEstablish(pMac, (setupPeer)->peerMac);
return eSIR_SUCCESS ;
}
/*
* TDLS discovery response frame processing ..
*/
static tSirRetStatus limProcessTdlsDisRspFrame(tpAniSirGlobal pMac,
tANI_U8 *pBody, tANI_U32 frmLen,
tANI_S8 rssi, tpPESession psessionEntry)
{
tDot11fTDLSDisRsp tdlsDisRsp = {{0}} ;
tANI_U32 status = 0 ;
tLimDisResultList *tdlsDisResult = NULL ;
tLimDisResultList **disResultList = &pMac->lim.gLimTdlsDisResultList ;
tSirTdlsDisReq *prevDisReq = &pMac->lim.gLimTdlsDisReq ;
status = dot11fUnpackTDLSDisRsp(pMac, pBody, frmLen, &tdlsDisRsp) ;
if ( DOT11F_FAILED( status ) )
{
limLog(pMac, LOGE, FL("Failed to parse an TDLS discovery Response \
frame (0x%08x, %d bytes):"),status, frmLen);
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pBody, frmLen);)
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while unpacking an\
TDLS discovery Response frame (0x%08x," "%d bytes):"),
status, frmLen );
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pFrame, nFrame);)
}
/*TODO: match dialog token, before proceeding further */
/* varify BSSID */
status = vos_mem_compare( psessionEntry->bssId,
&tdlsDisRsp.LinkIdentifier.bssid[0],
sizeof(tSirMacAddr)) ;
if(!status)
{
limLog( pMac, LOGW, FL(" TDLS discovery Response frame other BSS")) ;
return eSIR_FAILURE ;
}
/* TODO, do more validation */
if(tdlsDisRsp.DialogToken.token != prevDisReq->dialog)
{
limLog( pMac, LOGW, FL(" wrong TDLS discovery Response frame")) ;
return eSIR_FAILURE ;
}
pMac->lim.gLimTdlsDisStaCount++ ;
/*
* we are allocating peer info for individual peers found in TDLS
* discovery, we need to keep adding TDLS peers till we have timed
* out. We are freeing this memory at the time we are sending this
* collected peer info to SME.
*/
tdlsDisResult = vos_mem_malloc(sizeof(tLimDisResultList));
if ( NULL == tdlsDisResult )
{
limLog(pMac, LOGP, FL("alloc fail for TDLS discovery reponse info")) ;
return eSIR_FAILURE ;
}
do
{
tSirTdlsPeerInfo *peerInfo = &tdlsDisResult->tdlsDisPeerInfo ;
/* Populate peer info of tdls discovery result */
peerInfo->sessionId = psessionEntry->peSessionId;
/*
* When we receive DIS RSP from peer MAC,
* STA_MAC_OFFSET will carry peer MAC address and PEER MAC OFFSET
* will carry our MAC.
*/
vos_mem_copy( peerInfo->peerMac,
&tdlsDisRsp.LinkIdentifier.RespStaAddr[0],
sizeof(tSirMacAddr)) ;
/* update RSSI for this TDLS peer STA */
peerInfo->tdlsPeerRssi = rssi ;
/* update Caps Info */
tdlsUpdateCapInfo(&peerInfo->capabilityInfo,
&tdlsDisRsp.Capabilities) ;
/* update Supp rates */
if(tdlsDisRsp.SuppRates.present)
{
ConvertSuppRates( pMac, &peerInfo->tdlsPeerSuppRates,
&tdlsDisRsp.SuppRates );
}
/* update EXT supp rates */
if(tdlsDisRsp.ExtSuppRates.present)
{
peerInfo->ExtRatesPresent = 1;
ConvertExtSuppRates( pMac, &peerInfo->tdlsPeerExtRates,
&tdlsDisRsp.ExtSuppRates );
}
/* update HT caps */
if (tdlsDisRsp.HTCaps.present)
{
vos_mem_copy( &peerInfo->tdlsPeerHtCaps, &tdlsDisRsp.HTCaps,
sizeof( tDot11fIEHTCaps ) );
}
} while(0) ;
/* now add this new found discovery node into tdls discovery list */
tdlsDisResult->next = *disResultList ;
*disResultList = tdlsDisResult ;
return eSIR_SUCCESS ;
}
/*
* Process TDLS Teardown request frame from TDLS peer STA
*/
static tSirRetStatus limProcessTdlsTeardownFrame(tpAniSirGlobal pMac,
tANI_U8 *pBody, tANI_U32 frmLen )
{
tDot11fTDLSTeardown tdlsTeardown = {{0}} ;
tANI_U32 status = 0 ;
tLimTdlsLinkSetupPeer *setupPeer = NULL ;
tpPESession psessionEntry = NULL ;
tANI_U8 sessionId = 0 ;
status = dot11fUnpackTDLSTeardown(pMac, pBody, frmLen, &tdlsTeardown) ;
if ( DOT11F_FAILED( status ) )
{
limLog(pMac, LOGE, FL("Failed to parse an TDLS discovery Response \
frame (0x%08x, %d bytes):"),status, frmLen);
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pBody, frmLen);)
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while unpacking an\
TDLS discovery Response frame (0x%08x," "%d bytes):"),
status, frmLen );
PELOG2(sirDumpBuf(pMac, SIR_DBG_MODULE_ID, LOG2, pBody, frmLen);)
}
/*
* find session entry using BSSID in link identifier, not using MAC
* header beacuse, there is cases in TDLS, there may be BSSID will not
* be present in header
*/
psessionEntry = peFindSessionByBssid(pMac,
&tdlsTeardown.LinkIdentifier.bssid[0], &sessionId) ;
if(NULL == psessionEntry)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, \
("no Seesion entry for TDLS session (bssid %02x:%02x:%02x:%02x:%02x:%02x)"), \
tdlsTeardown.LinkIdentifier.bssid[0],
tdlsTeardown.LinkIdentifier.bssid[1],
tdlsTeardown.LinkIdentifier.bssid[2],
tdlsTeardown.LinkIdentifier.bssid[3],
tdlsTeardown.LinkIdentifier.bssid[4],
tdlsTeardown.LinkIdentifier.bssid[5]) ;
//VOS_ASSERT(0) ;
return eSIR_FAILURE;
}
/* varify BSSID */
status = vos_mem_compare( psessionEntry->bssId,
&tdlsTeardown.LinkIdentifier.bssid[0],
sizeof(tSirMacAddr)) ;
if(!status)
{
limLog( pMac, LOGE, FL("Teardown from other BSS -> something wrong. Check RXP filter")) ;
VOS_ASSERT(0) ;
return eSIR_FAILURE ;
}
limTdlsFindLinkPeer(pMac,
&tdlsTeardown.LinkIdentifier.InitStaAddr[0],
&setupPeer) ;
if(NULL == setupPeer)
{
//ignore
//VOS_ASSERT(0) ;
limLog( pMac, LOGE, FL("Teardown from unknown peer. --> ignored") );
return eSIR_FAILURE ;
}
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("teardown for peer %02x,%02x,%02x,%02x,%02x,%02x"),
(setupPeer)->peerMac[0],
(setupPeer)->peerMac[1],
(setupPeer)->peerMac[2],
(setupPeer)->peerMac[3],
(setupPeer)->peerMac[4],
(setupPeer)->peerMac[5]) ;
switch(tdlsTeardown.Reason.code)
{
case eSIR_MAC_TDLS_TEARDOWN_UNSPEC_REASON:
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("teardown with unspecified reason")) ;
break ;
}
case eSIR_MAC_TDLS_TEARDOWN_PEER_UNREACHABLE:
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
(" Teardown from AP, TDLS peer unreachable")) ;
break ;
}
default:
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
(" unknown teardown")) ;
break ;
}
}
/* change TDLS peer State */
(setupPeer)->tdls_prev_link_state = (setupPeer)->tdls_link_state ;
(setupPeer)->tdls_link_state = TDLS_LINK_TEARDOWN_START_STATE ;
do
{
tpDphHashNode pStaDs = NULL ;
/* tdls_hklee: send message to HAL before it is deleted, cause */
limTdlsLinkTeardown(pMac, (setupPeer)->peerMac) ;
/* send del STA to remove context for this TDLS STA */
pStaDs = limTdlsDelSta(pMac, (setupPeer)->peerMac, psessionEntry) ;
/* now send indication to SME-->HDD->TL to remove STA from TL */
if(pStaDs)
{
limSendSmeTdlsDelPeerInd(pMac, psessionEntry->smeSessionId,
pStaDs, eSIR_SUCCESS) ;
/* send Teardown Ind to SME */
limSendSmeTdlsTeardownRsp(pMac, eSIR_SUCCESS, (setupPeer)->peerMac,
eWNI_SME_TDLS_TEARDOWN_IND) ;
/* remove node from setup list */
limTdlsDelLinkPeer(pMac, (setupPeer)->peerMac) ;
}
}while(0) ;
return status ;
}
/*
* Common processing of TDLS action frames recieved
*/
void limProcessTdlsFrame(tpAniSirGlobal pMac, tANI_U32 *pBd)
{
tANI_U8 *pBody = WDA_GET_RX_MPDU_DATA(pBd);
tANI_U8 pOffset = ((0 == WDA_GET_RX_FT_DONE(pBd))
? (( sizeof( eth_890d_header ))) :(0)) ;
tANI_U8 category = (pBody + pOffset + PAYLOAD_TYPE_TDLS_SIZE)[0] ;
tANI_U8 action = (pBody + pOffset + PAYLOAD_TYPE_TDLS_SIZE)[1] ;
tANI_U32 frameLen = WDA_GET_RX_PAYLOAD_LEN(pBd) ;
tANI_U8 *tdlsFrameBody = (pBody + pOffset + PAYLOAD_TYPE_TDLS_SIZE) ;
//tANI_S8 rssi = (tANI_S8)SIR_MAC_BD_TO_RSSI_DB(pBd);
if(category != SIR_MAC_ACTION_TDLS)
{
limLog( pMac, LOGE, FL("Invalid TDLS action frame=(%d). Ignored"), category );
return ;
}
frameLen -= (pOffset + PAYLOAD_TYPE_TDLS_SIZE) ;
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, ("Received TDLS action %d (%s)"), \
action, limTraceTdlsActionString(action) ));
switch(action)
{
case SIR_MAC_TDLS_SETUP_REQ:
{
limProcessTdlsSetupReqFrame(pMac, tdlsFrameBody, frameLen) ;
break ;
}
case SIR_MAC_TDLS_SETUP_RSP:
{
limProcessTdlsSetupRspFrame(pMac, tdlsFrameBody, frameLen) ;
break ;
}
case SIR_MAC_TDLS_SETUP_CNF:
{
limProcessTdlsSetupCnfFrame(pMac, tdlsFrameBody, frameLen) ;
break ;
}
case SIR_MAC_TDLS_TEARDOWN:
{
limProcessTdlsTeardownFrame(pMac, tdlsFrameBody, frameLen) ;
break ;
}
case SIR_MAC_TDLS_DIS_REQ:
{
limProcessTdlsDisReqFrame(pMac, tdlsFrameBody, frameLen) ;
break ;
}
case SIR_MAC_TDLS_PEER_TRAFFIC_IND:
case SIR_MAC_TDLS_CH_SWITCH_REQ:
case SIR_MAC_TDLS_CH_SWITCH_RSP:
case SIR_MAC_TDLS_PEER_TRAFFIC_RSP:
default:
{
break ;
}
}
return ;
}
/*
* ADD sta for dis response fame sent on direct link
*/
static tSirRetStatus limTdlsDisAddSta(tpAniSirGlobal pMac, tSirMacAddr peerMac,
tSirTdlsPeerInfo *peerInfo, tpPESession psessionEntry)
{
tpDphHashNode pStaDs = NULL ;
tSirRetStatus status = eSIR_SUCCESS ;
tANI_U16 aid = 0 ;
if(NULL == peerInfo)
{
VOS_ASSERT(0) ;
return status ;
}
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("ADD STA peer MAC: %02x, %02x, %02x, %02x, %02x, %02x"),
peerMac[0],
peerMac[1],
peerMac[2],
peerMac[3],
peerMac[4],
peerMac[5]) ;
if(NULL != dphLookupHashEntry(pMac, peerMac,
&aid, &psessionEntry->dph.dphHashTable))
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
(" there is hash entry for this client")) ;
status = eSIR_FAILURE ;
VOS_ASSERT(0) ;
return status ;
}
aid = limAssignPeerIdx(pMac, psessionEntry) ;
/* Set the aid in peerAIDBitmap as it has been assigned to TDLS peer */
SET_PEER_AID_BITMAP(psessionEntry->peerAIDBitmap, aid);
pStaDs = dphGetHashEntry(pMac, aid, &psessionEntry->dph.dphHashTable);
if (pStaDs)
{
(void) limDelSta(pMac, pStaDs, false /*asynchronous*/, psessionEntry);
limDeleteDphHashEntry(pMac, pStaDs->staAddr, aid, psessionEntry);
}
pStaDs = dphAddHashEntry(pMac, peerMac, aid,
&psessionEntry->dph.dphHashTable) ;
if(NULL == pStaDs)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
(" add hash entry failed")) ;
status = eSIR_FAILURE ;
VOS_ASSERT(0) ;
return status;
}
if(eSIR_SUCCESS == status)
{
#ifdef TDLS_RATE_DEBUG
tSirMacRateSet *suppRates = &peerInfo->tdlsPeerSuppRates ;
tSirMacRateSet *extRates = &peerInfo->tdlsPeerExtRates ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("pSta DS [%p] "), pStaDs) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("peerInfo->tdlsPeerSuppRates = [%p]"),
(tANI_U8 *)&peerInfo->tdlsPeerSuppRates) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("peerInfo->tdlsPeerExtRates = [%p]"),
(tANI_U8 *)&peerInfo->tdlsPeerExtRates) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("peerInfo->tdlsPeerPropRates = [%p]"),
(tANI_U8 *)&pStaDs->mlmStaContext.propRateSet) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("peerInfo->mcs = [%p]"),
(tANI_U8 *)peerInfo->supportedMCSSet) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("num of supp rates = %02x"), suppRates->numRates) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("num of ext rates = %01x"), extRates->numRates) ;
#endif
/* Populate matching rate set */
#ifdef WLAN_FEATURE_11AC
if(eSIR_FAILURE == limPopulateMatchingRateSet(pMac, pStaDs,
&peerInfo->tdlsPeerSuppRates,
&peerInfo->tdlsPeerExtRates,
peerInfo->supportedMCSSet,
&pStaDs->mlmStaContext.propRateSet,
psessionEntry, NULL))
#else
if(eSIR_FAILURE == limPopulateMatchingRateSet(pMac, pStaDs,
&peerInfo->tdlsPeerSuppRates,
&peerInfo->tdlsPeerExtRates,
peerInfo->supportedMCSSet,
&pStaDs->mlmStaContext.propRateSet,
psessionEntry))
#endif
{
VOS_ASSERT(0) ;
}
pStaDs->mlmStaContext.capabilityInfo = peerInfo->capabilityInfo;
vos_mem_copy( pStaDs->staAddr, peerMac, sizeof(tSirMacAddr)) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Add STA for Peer: %02x, %02x, %02x, %02x, %02x, %02x"),
pStaDs->staAddr[0],
pStaDs->staAddr[1],
pStaDs->staAddr[2],
pStaDs->staAddr[3],
pStaDs->staAddr[4],
pStaDs->staAddr[5]) ;
pStaDs->staType = STA_ENTRY_TDLS_PEER ;
status = limAddSta(pMac, pStaDs, false, psessionEntry);
if(eSIR_SUCCESS != status)
{
/* should not fail */
VOS_ASSERT(0) ;
}
}
return status ;
}
#endif
/*
* Add STA for TDLS setup procedure
*/
static tSirRetStatus limTdlsSetupAddSta(tpAniSirGlobal pMac,
tSirTdlsAddStaReq *pAddStaReq,
tpPESession psessionEntry)
{
tpDphHashNode pStaDs = NULL ;
tSirRetStatus status = eSIR_SUCCESS ;
tANI_U16 aid = 0 ;
pStaDs = dphLookupHashEntry(pMac, pAddStaReq->peerMac, &aid,
&psessionEntry->dph.dphHashTable);
if(NULL == pStaDs)
{
aid = limAssignPeerIdx(pMac, psessionEntry) ;
if( !aid )
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("%s: No more free AID for peer " MAC_ADDRESS_STR),
__func__, MAC_ADDR_ARRAY(pAddStaReq->peerMac)) ;
return eSIR_FAILURE;
}
/* Set the aid in peerAIDBitmap as it has been assigned to TDLS peer */
SET_PEER_AID_BITMAP(psessionEntry->peerAIDBitmap, aid);
VOS_TRACE(VOS_MODULE_ID_PE, TDLS_DEBUG_LOG_LEVEL,
("limTdlsSetupAddSta: Aid = %d, for peer =" MAC_ADDRESS_STR),
aid, MAC_ADDR_ARRAY(pAddStaReq->peerMac));
pStaDs = dphGetHashEntry(pMac, aid, &psessionEntry->dph.dphHashTable);
if (pStaDs)
{
(void) limDelSta(pMac, pStaDs, false /*asynchronous*/, psessionEntry);
limDeleteDphHashEntry(pMac, pStaDs->staAddr, aid, psessionEntry);
}
pStaDs = dphAddHashEntry(pMac, pAddStaReq->peerMac, aid,
&psessionEntry->dph.dphHashTable) ;
if(NULL == pStaDs)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
(" add hash entry failed")) ;
VOS_ASSERT(0) ;
return eSIR_FAILURE;
}
}
limTdlsUpdateHashNodeInfo(pMac, pStaDs, pAddStaReq, psessionEntry) ;
pStaDs->staType = STA_ENTRY_TDLS_PEER ;
status = limAddSta(pMac, pStaDs, (pAddStaReq->tdlsAddOper == TDLS_OPER_UPDATE) ? true: false, psessionEntry);
if(eSIR_SUCCESS != status)
{
/* should not fail */
VOS_ASSERT(0) ;
}
return status ;
}
/*
* Del STA, after Link is teardown or discovery response sent on direct link
*/
static tpDphHashNode limTdlsDelSta(tpAniSirGlobal pMac, tSirMacAddr peerMac,
tpPESession psessionEntry)
{
tSirRetStatus status = eSIR_SUCCESS ;
tANI_U16 peerIdx = 0 ;
tpDphHashNode pStaDs = NULL ;
pStaDs = dphLookupHashEntry(pMac, peerMac, &peerIdx,
&psessionEntry->dph.dphHashTable) ;
if(pStaDs)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("DEL STA peer MAC: %02x, %02x, %02x, %02x, %02x, %02x "),
pStaDs->staAddr[0],
pStaDs->staAddr[1],
pStaDs->staAddr[2],
pStaDs->staAddr[3],
pStaDs->staAddr[4],
pStaDs->staAddr[5]
) ;
VOS_TRACE(VOS_MODULE_ID_PE, TDLS_DEBUG_LOG_LEVEL,
("limTdlsDelSta: STA type = %x, sta idx = %x"),pStaDs->staType,
pStaDs->staIndex) ;
status = limDelSta(pMac, pStaDs, false, psessionEntry) ;
#ifdef FEATURE_WLAN_TDLS_INTERNAL
if(eSIR_SUCCESS == status)
{
limDeleteDphHashEntry(pMac, pStaDs->staAddr, peerIdx, psessionEntry) ;
limReleasePeerIdx(pMac, peerIdx, psessionEntry) ;
}
else
{
VOS_ASSERT(0) ;
}
#endif
}
return pStaDs ;
}
#ifdef FEATURE_WLAN_TDLS_INTERNAL
/*
* Prepare link establish message for HAL, construct PTI template.
*
*/
static tSirRetStatus limTdlsLinkEstablish(tpAniSirGlobal pMac, tSirMacAddr peerMac)
{
tANI_U8 pFrame[64] ;
tDot11fTDLSPeerTrafficInd tdlsPtiTemplate ;
tANI_U32 status = 0 ;
tANI_U32 nPayload = 0 ;
tANI_U32 nBytes = 0 ;
tANI_U32 header_offset = 0 ;
tANI_U16 aid = 0 ;
tDphHashNode *pStaDs = NULL ;
tLimTdlsLinkSetupPeer *setupPeer = NULL ;
tpPESession psessionEntry = NULL ;
limTdlsFindLinkPeer(pMac, peerMac, &setupPeer) ;
if(NULL == setupPeer) {
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("limTdlsLinkEstablish: cannot find peer mac in tdls linksetup list: %02X %02X %02X %02X %02X %02X"), \
peerMac[0], peerMac[1], peerMac[2], \
peerMac[3], peerMac[4], peerMac[5]);
return eSIR_FAILURE;
}
psessionEntry = peFindSessionBySessionId(pMac,
setupPeer->tdls_sessionId) ;
if(NULL == psessionEntry)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("limTdlsLinkEstablish: sessionID %d is not found"), setupPeer->tdls_sessionId);
VOS_ASSERT(0) ;
return eHAL_STATUS_FAILURE;
}
/* */
pStaDs = dphLookupHashEntry(pMac, peerMac, &aid, &psessionEntry->dph.dphHashTable) ;
if(pStaDs == NULL) {
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("limTdlsLinkEstablish: cannot find peer mac in hash table: %02X %02X %02X %02X %02X %02X"), \
peerMac[0], peerMac[1], peerMac[2], \
peerMac[3], peerMac[4], peerMac[5]);
return eSIR_FAILURE;
}
vos_mem_set( ( tANI_U8* )&tdlsPtiTemplate,
sizeof( tDot11fTDLSPeerTrafficInd ), 0 );
/*
* setup Fixed fields,
*/
tdlsPtiTemplate.Category.category = SIR_MAC_ACTION_TDLS;
tdlsPtiTemplate.Action.action = SIR_MAC_TDLS_PEER_TRAFFIC_IND;
tdlsPtiTemplate.DialogToken.token = 0 ; /* filled by firmware at the time of transmission */
#if 1
/* CHECK_PTI_LINK_IDENTIFIER_INITIATOR_ADDRESS: initator address should be TDLS link setup's initiator address,
then below code makes such an way */
PopulateDot11fLinkIden( pMac, psessionEntry, &tdlsPtiTemplate.LinkIdentifier,
peerMac, !setupPeer->tdls_bIsResponder) ;
#else
/* below code will make PTI's linkIdentifier's initiator address be selfAddr */
PopulateDot11fLinkIden( pMac, psessionEntry, &tdlsPtiTemplate.LinkIdentifier,
peerMac, TDLS_INITIATOR) ;
#endif
/* PUBufferStatus will be filled by firmware at the time of transmission */
tdlsPtiTemplate.PUBufferStatus.present = 1;
/* TODO: get ExtendedCapabilities IE */
/*
* now we pack it. First, how much space are we going to need?
*/
status = dot11fGetPackedTDLSPeerTrafficIndSize ( pMac, &tdlsPtiTemplate, &nPayload);
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGP, FL("Failed to calculate the packed size for a PTI template (0x%08x)."), status );
/* We'll fall back on the worst case scenario: */
nPayload = sizeof( tdlsPtiTemplate );
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while calculating the packed size for a PTI template (0x%08x)."), status );
}
/*
* This frame is going out from PE as data frames with special ethertype
* 89-0d.
* 8 bytes of RFC 1042 header
*/
nBytes = nPayload + sizeof( tSirMacMgmtHdr )
+ sizeof( eth_890d_header )
+ PAYLOAD_TYPE_TDLS_SIZE ;
if(nBytes > 64) {
limLog( pMac, LOGE, FL("required memory for PTI frame is %ld, but reserved only 64."), nBytes);
nBytes = 64;
}
/* zero out the memory */
vos_mem_set( pFrame, sizeof(pFrame), 0 );
/* fill out the buffer descriptor */
header_offset = limPrepareTdlsFrameHeader(pMac, pFrame,
LINK_IDEN_ADDR_OFFSET(tdlsPtiTemplate), TDLS_LINK_AP, !setupPeer->tdls_bIsResponder, psessionEntry) ;
status = dot11fPackTDLSPeerTrafficInd ( pMac, &tdlsPtiTemplate, pFrame
+ header_offset, nPayload, &nPayload );
if ( DOT11F_FAILED( status ) )
{
limLog( pMac, LOGE, FL("Failed to pack a PTI template \
(0x%08x)."), status );
return eSIR_FAILURE;
}
else if ( DOT11F_WARNED( status ) )
{
limLog( pMac, LOGW, FL("There were warnings while packing TDLS"
"Peer Traffic Indication (0x%08x).") );
}
LIM_LOG_TDLS(VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR, ("bIsResponder=%d, header_offset=%ld, linkIdenOffset=%d, ptiBufStatusOffset=%d "), \
setupPeer->tdls_bIsResponder, header_offset, PTI_LINK_IDEN_OFFSET, PTI_BUF_STATUS_OFFSET));
limSendTdlsLinkEstablish(pMac, setupPeer->tdls_bIsResponder,
header_offset+PTI_LINK_IDEN_OFFSET, header_offset+PTI_BUF_STATUS_OFFSET,
nBytes, pFrame, (tANI_U8 *)&setupPeer->tdlsPeerExtCaps);
return eSIR_SUCCESS;
}
/*
* Prepare link teardown message for HAL from peer_mac
*
*/
static tSirRetStatus limTdlsLinkTeardown(tpAniSirGlobal pMac, tSirMacAddr peerMac)
{
tDphHashNode *pStaDs = NULL ;
tANI_U16 aid = 0 ;
tLimTdlsLinkSetupPeer *setupPeer = NULL ;
tpPESession psessionEntry = NULL ;
limTdlsFindLinkPeer(pMac, peerMac, &setupPeer) ;
if(NULL == setupPeer) {
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("limTdlsLinkTeardown: cannot find peer mac in tdls linksetup list: %02X %02X %02X %02X %02X %02X"), \
peerMac[0], peerMac[1], peerMac[2], \
peerMac[3], peerMac[4], peerMac[5]);
return eSIR_FAILURE;
}
psessionEntry = peFindSessionBySessionId(pMac,
setupPeer->tdls_sessionId) ;
if(NULL == psessionEntry)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("limTdlsLinkTeardown: sessionID %d is not found"), setupPeer->tdls_sessionId);
VOS_ASSERT(0) ;
return eHAL_STATUS_FAILURE;
}
/* */
pStaDs = dphLookupHashEntry(pMac, peerMac, &aid, &psessionEntry->dph.dphHashTable);
if(pStaDs == NULL) {
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("limTdlsLinkTeardown: cannot find peer mac in hash table: %02X %02X %02X %02X %02X %02X"), \
peerMac[0], peerMac[1], peerMac[2], \
peerMac[3], peerMac[4], peerMac[5]);
return eSIR_FAILURE;
}
limSendTdlsLinkTeardown(pMac, pStaDs->staIndex);
return eSIR_SUCCESS;
}
/*
* Prepare Discovery RSP message for SME, collect peerINfo for all the
* peers discovered and delete/clean discovery lists in PE.
*/
static tSirTdlsDisRsp *tdlsPrepareTdlsDisRsp(tpAniSirGlobal pMac,
tSirTdlsDisRsp *disRsp, tANI_U8 disStaCount)
{
tANI_U32 disMsgRspSize = sizeof(tSirTdlsDisRsp);
tANI_U8 status = eHAL_STATUS_SUCCESS ;
/*
* allocate memory for tdls discovery response, allocated memory should
* be alloc_mem = tdlsStaCount * sizeof(peerinfo)
* + siezeof tSirTdlsDisRsp.
*/
disMsgRspSize += (disStaCount * sizeof(tSirTdlsPeerInfo));
/* now allocate memory */
disRsp = vos_mem_malloc(disMsgRspSize);
if ( NULL == disRsp )
{
limLog(pMac, LOGP, FL("AllocateMemory failed for DIS RSP"));
return NULL ;
}
if(disStaCount)
{
tLimDisResultList *tdlsDisRspList = pMac->lim.gLimTdlsDisResultList ;
tSirTdlsPeerInfo *peerInfo = &disRsp->tdlsDisPeerInfo[0] ;
tLimDisResultList *currentNode = tdlsDisRspList ;
while(tdlsDisRspList != NULL)
{
vos_mem_copy( (tANI_U8 *)peerInfo,
(tANI_U8 *) &tdlsDisRspList->tdlsDisPeerInfo,
sizeof(tSirTdlsPeerInfo));
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Msg Sent to PE, peer MAC: %02x, %02x, %02x, %02x, %02x, %02x"),
peerInfo->peerMac[0],
peerInfo->peerMac[1],
peerInfo->peerMac[2],
peerInfo->peerMac[3],
peerInfo->peerMac[4],
peerInfo->peerMac[5]);
disStaCount-- ;
peerInfo++ ;
currentNode = tdlsDisRspList ;
tdlsDisRspList = tdlsDisRspList->next ;
vos_mem_free(currentNode) ;
/* boundary condition check, may be fatal */
if(((!disStaCount) && (tdlsDisRspList))
|| ((!tdlsDisRspList) && disStaCount))
{
limLog(pMac, LOG1, FL("mismatch in dis sta count and\
and number of nodes in list")) ;
VOS_ASSERT(0) ;
return NULL ;
}
} /* end of while */
/* All discovery STA processed */
pMac->lim.gLimTdlsDisResultList = NULL ;
} /* end of if dis STA count */
return (disRsp) ;
}
/* Send Teardown response back to PE */
void limSendSmeTdlsTeardownRsp(tpAniSirGlobal pMac, tSirResultCodes statusCode,
tSirMacAddr peerMac, tANI_U16 msgType)
{
tSirMsgQ mmhMsg = {0} ;
tSirTdlsTeardownRsp *teardownRspMsg = NULL ;
tANI_U8 status = eHAL_STATUS_SUCCESS ;
mmhMsg.type = msgType ;
teardownRspMsg = vos_mem_malloc(sizeof(tSirTdlsTeardownRsp));
if ( NULL == teardownRspMsg )
{
VOS_ASSERT(0) ;
}
vos_mem_copy( teardownRspMsg->peerMac, (tANI_U8 *)peerMac,
sizeof(tSirMacAddr)) ;
teardownRspMsg->statusCode = statusCode ;
mmhMsg.bodyptr = teardownRspMsg ;
mmhMsg.bodyval = 0;
limSysProcessMmhMsgApi(pMac, &mmhMsg, ePROT);
return ;
}
/*
* Send Link start RSP back to SME after link is setup or failed
*/
void limSendSmeTdlsLinkStartRsp(tpAniSirGlobal pMac,
tSirResultCodes statusCode,
tSirMacAddr peerMac,
tANI_U16 msgType)
{
tSirMsgQ mmhMsg = {0} ;
tSirTdlsLinksetupRsp *setupRspMsg = NULL ;
tANI_U8 status = eHAL_STATUS_SUCCESS ;
mmhMsg.type = msgType ;
setupRspMsg = vos_mem_malloc(sizeof(tSirTdlsLinksetupRsp));
if ( NULL == setupRspMsg )
{
VOS_ASSERT(0) ;
}
vos_mem_copy( setupRspMsg->peerMac, (tANI_U8 *)peerMac,
sizeof(tSirMacAddr)) ;
setupRspMsg->statusCode = statusCode ;
mmhMsg.bodyptr = setupRspMsg ;
mmhMsg.bodyval = 0;
limSysProcessMmhMsgApi(pMac, &mmhMsg, ePROT);
return ;
}
/*
* Send TDLS discovery RSP back to SME
*/
void limSendSmeTdlsDisRsp(tpAniSirGlobal pMac, tSirResultCodes statusCode,
tANI_U16 msgType)
{
tSirMsgQ mmhMsg = {0} ;
tSirTdlsDisRsp *tdlsDisRsp = NULL ;
mmhMsg.type = msgType ;
if(eSIR_SME_SUCCESS == statusCode)
{
tANI_U8 tdlsStaCount = pMac->lim.gLimTdlsDisStaCount ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("no of TDLS STA discovered: %d"), tdlsStaCount) ;
tdlsDisRsp = tdlsPrepareTdlsDisRsp(pMac, tdlsDisRsp, tdlsStaCount) ;
if(tdlsDisRsp)
{
tdlsDisRsp->numDisSta = tdlsStaCount ;
}
else
{
limLog(pMac, LOGP, FL("fatal failure for TDLS DIS RSP"));
VOS_ASSERT(0) ;
return ;
}
/* all Discovery STA is processed */
pMac->lim.gLimTdlsDisStaCount = 0 ;
}
else
{
tdlsDisRsp = tdlsPrepareTdlsDisRsp(pMac, tdlsDisRsp, 0) ;
}
tdlsDisRsp->statusCode = statusCode ;
mmhMsg.bodyptr = tdlsDisRsp ;
mmhMsg.bodyval = 0;
limSysProcessMmhMsgApi(pMac, &mmhMsg, ePROT);
return ;
}
/*
* Once Link is setup with PEER, send Add STA ind to SME
*/
static eHalStatus limSendSmeTdlsAddPeerInd(tpAniSirGlobal pMac,
tANI_U8 sessionId, tDphHashNode *pStaDs, tANI_U8 status)
{
tSirMsgQ mmhMsg = {0} ;
tSirTdlsPeerInd *peerInd = NULL ;
mmhMsg.type = eWNI_SME_ADD_TDLS_PEER_IND ;
peerInd = vos_mem_malloc(sizeof(tSirTdlsPeerInd));
if ( NULL == peerInd )
{
PELOGE(limLog(pMac, LOGE, FL("Failed to allocate memory"));)
return eSIR_FAILURE;
}
vos_mem_copy( peerInd->peerMac,
(tANI_U8 *) pStaDs->staAddr, sizeof(tSirMacAddr));
peerInd->sessionId = sessionId;
peerInd->staId = pStaDs->staIndex ;
peerInd->ucastSig = pStaDs->ucUcastSig ;
peerInd->bcastSig = pStaDs->ucBcastSig ;
peerInd->length = sizeof(tSmeIbssPeerInd) ;
mmhMsg.bodyptr = peerInd ;
mmhMsg.bodyval = 0;
limSysProcessMmhMsgApi(pMac, &mmhMsg, ePROT);
return eSIR_SUCCESS ;
}
/*
* Once link is teardown, send Del Peer Ind to SME
*/
static eHalStatus limSendSmeTdlsDelPeerInd(tpAniSirGlobal pMac,
tANI_U8 sessionId, tDphHashNode *pStaDs, tANI_U8 status)
{
tSirMsgQ mmhMsg = {0} ;
tSirTdlsPeerInd *peerInd = NULL ;
mmhMsg.type = eWNI_SME_DELETE_TDLS_PEER_IND ;
peerInd = vos_mem_malloc(sizeof(tSirTdlsPeerInd));
if ( NULL == peerInd )
{
PELOGE(limLog(pMac, LOGE, FL("Failed to allocate memory"));)
return eSIR_FAILURE;
}
vos_mem_copy( peerInd->peerMac,
(tANI_U8 *) pStaDs->staAddr, sizeof(tSirMacAddr));
peerInd->sessionId = sessionId;
peerInd->staId = pStaDs->staIndex ;
peerInd->ucastSig = pStaDs->ucUcastSig ;
peerInd->bcastSig = pStaDs->ucBcastSig ;
peerInd->length = sizeof(tSmeIbssPeerInd) ;
mmhMsg.bodyptr = peerInd ;
//peerInd->statusCode = status ;
mmhMsg.bodyval = 0;
limSysProcessMmhMsgApi(pMac, &mmhMsg, ePROT);
return eSIR_SUCCESS ;
}
/*
* Send Link setup Ind to SME, This is the case where, link setup is
* initiated by peer STA
*/
static eHalStatus limSendSmeTdlsLinkSetupInd(tpAniSirGlobal pMac,
tSirMacAddr peerMac, tANI_U8 status)
{
tSirMsgQ mmhMsg = {0} ;
tSirTdlsLinkSetupInd *setupInd = NULL ;
mmhMsg.type = eWNI_SME_TDLS_LINK_START_IND ;
setupInd = vos_mem_malloc(sizeof(tSirTdlsLinkSetupInd));
if ( NULL == setupInd )
{
PELOGE(limLog(pMac, LOGE, FL("Failed to allocate memory"));)
return eSIR_FAILURE;
}
vos_mem_copy( setupInd->peerMac,
(tANI_U8 *) peerMac, sizeof(tSirMacAddr));
setupInd->length = sizeof(tSirTdlsLinkSetupInd);
setupInd->statusCode = status ;
mmhMsg.bodyptr = setupInd ;
mmhMsg.bodyval = 0;
limSysProcessMmhMsgApi(pMac, &mmhMsg, ePROT);
return eSIR_SUCCESS ;
}
/*
* Setup RSP timer handler
*/
void limTdlsLinkSetupRspTimerHandler(void *pMacGlobal, tANI_U32 timerId)
{
tANI_U32 statusCode;
tSirMsgQ msg;
tpAniSirGlobal pMac = (tpAniSirGlobal)pMacGlobal;
/* Prepare and post message to LIM Message Queue */
msg.type = SIR_LIM_TDLS_LINK_SETUP_RSP_TIMEOUT;
msg.bodyptr = NULL ;
msg.bodyval = timerId ;
if ((statusCode = limPostMsgApi(pMac, &msg)) != eSIR_SUCCESS)
limLog(pMac, LOGE,
FL("posting message %X to LIM failed, reason=%d"),
msg.type, statusCode);
return ;
}
/*
* Link setup CNF timer
*/
void limTdlsLinkSetupCnfTimerHandler(void *pMacGlobal, tANI_U32 timerId)
{
tANI_U32 statusCode;
tSirMsgQ msg;
tpAniSirGlobal pMac = (tpAniSirGlobal)pMacGlobal;
// Prepare and post message to LIM Message Queue
msg.type = SIR_LIM_TDLS_LINK_SETUP_CNF_TIMEOUT;
msg.bodyptr = NULL ;
msg.bodyval = timerId ;
if ((statusCode = limPostMsgApi(pMac, &msg)) != eSIR_SUCCESS)
limLog(pMac, LOGE,
FL("posting message %X to LIM failed, reason=%d"),
msg.type, statusCode);
return ;
}
/*
* start TDLS timer
*/
void limStartTdlsTimer(tpAniSirGlobal pMac, tANI_U8 sessionId, TX_TIMER *timer,
tANI_U32 timerId, tANI_U16 timerType, tANI_U32 timerMsg)
{
tANI_U32 cfgValue = (timerMsg == SIR_LIM_TDLS_LINK_SETUP_RSP_TIMEOUT)
? WNI_CFG_TDLS_LINK_SETUP_RSP_TIMEOUT
: WNI_CFG_TDLS_LINK_SETUP_CNF_TIMEOUT ;
void *timerFunc = (timerMsg == SIR_LIM_TDLS_LINK_SETUP_RSP_TIMEOUT)
? (limTdlsLinkSetupRspTimerHandler)
: limTdlsLinkSetupCnfTimerHandler ;
/* TODO: Read timer vals from CFG */
cfgValue = SYS_MS_TO_TICKS(cfgValue);
/*
* create TDLS discovery response wait timer and activate it
*/
if (tx_timer_create(timer, "TDLS link setup timers", timerFunc,
timerId, cfgValue, 0, TX_NO_ACTIVATE) != TX_SUCCESS)
{
limLog(pMac, LOGP,
FL("could not create TDLS discovery response wait timer"));
return;
}
//assign appropriate sessionId to the timer object
timer->sessionId = sessionId;
MTRACE(macTrace(pMac, TRACE_CODE_TIMER_ACTIVATE, 0,
eLIM_TDLS_DISCOVERY_RSP_WAIT));
if (tx_timer_activate(timer) != TX_SUCCESS)
{
limLog(pMac, LOGP, FL("TDLS link setup timer activation failed!"));
return ;
}
return ;
}
#endif
/*
* Once Link is setup with PEER, send Add STA ind to SME
*/
static eHalStatus limSendSmeTdlsAddStaRsp(tpAniSirGlobal pMac,
tANI_U8 sessionId, tSirMacAddr peerMac, tANI_U8 updateSta,
tDphHashNode *pStaDs, tANI_U8 status)
{
tSirMsgQ mmhMsg = {0} ;
tSirTdlsAddStaRsp *addStaRsp = NULL ;
mmhMsg.type = eWNI_SME_TDLS_ADD_STA_RSP ;
addStaRsp = vos_mem_malloc(sizeof(tSirTdlsAddStaRsp));
if ( NULL == addStaRsp )
{
PELOGE(limLog(pMac, LOGE, FL("Failed to allocate memory"));)
return eSIR_FAILURE;
}
addStaRsp->sessionId = sessionId;
addStaRsp->statusCode = status;
if( pStaDs )
{
addStaRsp->staId = pStaDs->staIndex ;
addStaRsp->ucastSig = pStaDs->ucUcastSig ;
addStaRsp->bcastSig = pStaDs->ucBcastSig ;
}
if( peerMac )
{
vos_mem_copy( addStaRsp->peerMac,
(tANI_U8 *) peerMac, sizeof(tSirMacAddr));
}
if (updateSta)
addStaRsp->tdlsAddOper = TDLS_OPER_UPDATE;
else
addStaRsp->tdlsAddOper = TDLS_OPER_ADD;
addStaRsp->length = sizeof(tSirTdlsAddStaRsp) ;
addStaRsp->messageType = eWNI_SME_TDLS_ADD_STA_RSP ;
mmhMsg.bodyptr = addStaRsp;
mmhMsg.bodyval = 0;
limSysProcessMmhMsgApi(pMac, &mmhMsg, ePROT);
return eSIR_SUCCESS ;
}
/*
* STA RSP received from HAL
*/
eHalStatus limProcessTdlsAddStaRsp(tpAniSirGlobal pMac, void *msg,
tpPESession psessionEntry)
{
tAddStaParams *pAddStaParams = (tAddStaParams *) msg ;
tANI_U8 status = eSIR_SUCCESS ;
tDphHashNode *pStaDs = NULL ;
tANI_U16 aid = 0 ;
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
VOS_TRACE(VOS_MODULE_ID_PE, TDLS_DEBUG_LOG_LEVEL,
("limTdlsAddStaRsp: staIdx=%d, staMac=%02x:%02x:%02x:%02x:%02x:%02x"), pAddStaParams->staIdx, \
pAddStaParams->staMac[0],
pAddStaParams->staMac[1],
pAddStaParams->staMac[2],
pAddStaParams->staMac[3],
pAddStaParams->staMac[4],
pAddStaParams->staMac[5] ) ;
if (pAddStaParams->status != eHAL_STATUS_SUCCESS)
{
VOS_ASSERT(0) ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("Add sta failed ")) ;
status = eSIR_FAILURE;
goto add_sta_error;
}
pStaDs = dphLookupHashEntry(pMac, pAddStaParams->staMac, &aid,
&psessionEntry->dph.dphHashTable);
if(NULL == pStaDs)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("pStaDs is NULL ")) ;
status = eSIR_FAILURE;
goto add_sta_error;
}
pStaDs->bssId = pAddStaParams->bssIdx;
pStaDs->staIndex = pAddStaParams->staIdx;
pStaDs->ucUcastSig = pAddStaParams->ucUcastSig;
pStaDs->ucBcastSig = pAddStaParams->ucBcastSig;
pStaDs->mlmStaContext.mlmState = eLIM_MLM_LINK_ESTABLISHED_STATE;
pStaDs->valid = 1 ;
#ifdef FEATURE_WLAN_TDLS_INTERNAL
status = limSendSmeTdlsAddPeerInd(pMac, psessionEntry->smeSessionId,
pStaDs, eSIR_SUCCESS ) ;
if(eSIR_FAILURE == status)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
("Peer IND msg to SME failed")) ;
vos_mem_free( pAddStaParams );
return eSIR_FAILURE ;
}
/*
* Now, there is two things a) ADD STA RSP for ADD STA request sent
* after recieving discovery request from Peer.
* now we have to send discovery response, if there is any pending
* discovery equest..
*/
do
{
tSirTdlsPeerInfo *peerInfo = limTdlsFindDisPeer(pMac,
pAddStaParams->staMac) ;
if(peerInfo)
{
/*
* send TDLS discovery response frame on direct link, state machine
* is rolling.., once discovery response is get Acked, we will
* send response to SME based on TxComplete callback results
*/
limSendTdlsDisRspFrame(pMac, peerInfo->peerMac, peerInfo->dialog, psessionEntry) ;
peerInfo->tdlsPeerState = TDLS_DIS_RSP_SENT_WAIT_STATE ;
}
} while(0) ;
#endif
add_sta_error:
status = limSendSmeTdlsAddStaRsp(pMac, psessionEntry->smeSessionId,
pAddStaParams->staMac, pAddStaParams->updateSta, pStaDs, status) ;
vos_mem_free( pAddStaParams );
return status ;
}
/*
* FUNCTION: Populate Link Identifier element IE
*
*/
void PopulateDot11fLinkIden(tpAniSirGlobal pMac, tpPESession psessionEntry,
tDot11fIELinkIdentifier *linkIden,
tSirMacAddr peerMac, tANI_U8 reqType)
{
//tANI_U32 size = sizeof(tSirMacAddr) ;
tANI_U8 *initStaAddr = NULL ;
tANI_U8 *respStaAddr = NULL ;
(reqType == TDLS_INITIATOR) ? ((initStaAddr = linkIden->InitStaAddr),
(respStaAddr = linkIden->RespStaAddr))
: ((respStaAddr = linkIden->InitStaAddr ),
(initStaAddr = linkIden->RespStaAddr)) ;
vos_mem_copy( (tANI_U8 *)linkIden->bssid,
(tANI_U8 *) psessionEntry->bssId, sizeof(tSirMacAddr)) ;
vos_mem_copy( (tANI_U8 *)initStaAddr,
psessionEntry->selfMacAddr, sizeof(tSirMacAddr)) ;
vos_mem_copy( (tANI_U8 *)respStaAddr, (tANI_U8 *) peerMac,
sizeof( tSirMacAddr ));
linkIden->present = 1 ;
return ;
}
void PopulateDot11fTdlsExtCapability(tpAniSirGlobal pMac,
tDot11fIEExtCap *extCapability)
{
extCapability->TDLSPeerPSMSupp = PEER_PSM_SUPPORT ;
extCapability->TDLSPeerUAPSDBufferSTA = pMac->lim.gLimTDLSBufStaEnabled;
extCapability->TDLSChannelSwitching = CH_SWITCH_SUPPORT ;
extCapability->TDLSSupport = TDLS_SUPPORT ;
extCapability->TDLSProhibited = TDLS_PROHIBITED ;
extCapability->TDLSChanSwitProhibited = TDLS_CH_SWITCH_PROHIBITED ;
extCapability->present = 1 ;
return ;
}
#ifdef FEATURE_WLAN_TDLS_INTERNAL
/*
* Public Action frame common processing
* This Function will be moved/merged to appropriate place
* once other public action frames (particularly 802.11k)
* is in place
*/
void limProcessTdlsPublicActionFrame(tpAniSirGlobal pMac, tANI_U32 *pBd,
tpPESession psessionEntry)
{
tANI_U32 frameLen = WDA_GET_RX_PAYLOAD_LEN(pBd) ;
tANI_U8 *pBody = WDA_GET_RX_MPDU_DATA(pBd) ;
tANI_S8 rssi = (tANI_S8)WDA_GET_RX_RSSI_DB(pBd) ;
limProcessTdlsDisRspFrame(pMac, pBody, frameLen, rssi, psessionEntry) ;
return ;
}
eHalStatus limTdlsPrepareSetupReqFrame(tpAniSirGlobal pMac,
tLimTdlsLinkSetupInfo *linkSetupInfo,
tANI_U8 dialog, tSirMacAddr peerMac,
tpPESession psessionEntry)
{
tLimTdlsLinkSetupPeer *setupPeer = NULL ;
/*
* we allocate the TDLS setup Peer Memory here, we will free'd this
* memory after teardown, if the link is successfully setup or
* free this memory if any timeout is happen in link setup procedure
*/
setupPeer = vos_mem_malloc(sizeof( tLimTdlsLinkSetupPeer ));
if ( NULL == setupPeer )
{
limLog( pMac, LOGP,
FL( "Unable to allocate memory during ADD_STA" ));
VOS_ASSERT(0) ;
return eSIR_MEM_ALLOC_FAILED;
}
setupPeer->dialog = dialog ;
setupPeer->tdls_prev_link_state = setupPeer->tdls_link_state ;
setupPeer->tdls_link_state = TDLS_LINK_SETUP_START_STATE ;
/* TDLS_sessionize: remember sessionId for future */
setupPeer->tdls_sessionId = psessionEntry->peSessionId;
setupPeer->tdls_bIsResponder = 1;
/*
* we only populate peer MAC, so it can assit us to find the
* TDLS peer after response/or after response timeout
*/
vos_mem_copy(setupPeer->peerMac, peerMac,
sizeof(tSirMacAddr)) ;
/* format TDLS discovery request frame and transmit it */
limSendTdlsLinkSetupReqFrame(pMac, peerMac, dialog, psessionEntry, NULL, 0) ;
limStartTdlsTimer(pMac, psessionEntry->peSessionId,
&setupPeer->gLimTdlsLinkSetupRspTimeoutTimer,
(tANI_U32)setupPeer->peerMac,
WNI_CFG_TDLS_LINK_SETUP_RSP_TIMEOUT,
SIR_LIM_TDLS_LINK_SETUP_RSP_TIMEOUT) ;
/* update setup peer list */
setupPeer->next = linkSetupInfo->tdlsLinkSetupList ;
linkSetupInfo->tdlsLinkSetupList = setupPeer ;
/* in case of success, eWNI_SME_TDLS_LINK_START_RSP is sent back to
* SME later when TDLS setup cnf TX complete is successful. --> see
* limTdlsSetupCnfTxComplete()
*/
return eSIR_SUCCESS ;
}
#endif
/*
* Process Send Mgmt Request from SME and transmit to AP.
*/
tSirRetStatus limProcessSmeTdlsMgmtSendReq(tpAniSirGlobal pMac,
tANI_U32 *pMsgBuf)
{
/* get all discovery request parameters */
tSirTdlsSendMgmtReq *pSendMgmtReq = (tSirTdlsSendMgmtReq*) pMsgBuf ;
tpPESession psessionEntry;
tANI_U8 sessionId;
tSirResultCodes resultCode = eSIR_SME_INVALID_PARAMETERS;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Send Mgmt Recieved")) ;
if((psessionEntry = peFindSessionByBssid(pMac, pSendMgmtReq->bssid, &sessionId))
== NULL)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
"PE Session does not exist for given sme sessionId %d",
pSendMgmtReq->sessionId);
goto lim_tdls_send_mgmt_error;
}
/* check if we are in proper state to work as TDLS client */
if (psessionEntry->limSystemRole != eLIM_STA_ROLE)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
"send mgmt received in wrong system Role %d",
psessionEntry->limSystemRole);
goto lim_tdls_send_mgmt_error;
}
/*
* if we are still good, go ahead and check if we are in proper state to
* do TDLS discovery req/rsp/....frames.
*/
if ((psessionEntry->limSmeState != eLIM_SME_ASSOCIATED_STATE) &&
(psessionEntry->limSmeState != eLIM_SME_LINK_EST_STATE))
{
limLog(pMac, LOGE, "send mgmt received in invalid LIMsme \
state (%d)", psessionEntry->limSmeState);
goto lim_tdls_send_mgmt_error;
}
switch( pSendMgmtReq->reqType )
{
case SIR_MAC_TDLS_DIS_REQ:
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
"Transmit Discovery Request Frame") ;
/* format TDLS discovery request frame and transmit it */
limSendTdlsDisReqFrame(pMac, pSendMgmtReq->peerMac, pSendMgmtReq->dialog,
psessionEntry) ;
resultCode = eSIR_SME_SUCCESS;
break;
case SIR_MAC_TDLS_DIS_RSP:
{
//Send a response mgmt action frame
limSendTdlsDisRspFrame(pMac, pSendMgmtReq->peerMac,
pSendMgmtReq->dialog, psessionEntry) ;
resultCode = eSIR_SME_SUCCESS;
}
break;
case SIR_MAC_TDLS_SETUP_REQ:
{
limSendTdlsLinkSetupReqFrame(pMac,
pSendMgmtReq->peerMac, pSendMgmtReq->dialog, psessionEntry,
&pSendMgmtReq->addIe[0], (pSendMgmtReq->length - sizeof(tSirTdlsSendMgmtReq)));
resultCode = eSIR_SME_SUCCESS;
}
break;
case SIR_MAC_TDLS_SETUP_RSP:
{
limSendTdlsSetupRspFrame(pMac,
pSendMgmtReq->peerMac, pSendMgmtReq->dialog, psessionEntry, pSendMgmtReq->statusCode,
&pSendMgmtReq->addIe[0], (pSendMgmtReq->length - sizeof(tSirTdlsSendMgmtReq)));
resultCode = eSIR_SME_SUCCESS;
}
break;
case SIR_MAC_TDLS_SETUP_CNF:
{
limSendTdlsLinkSetupCnfFrame(pMac, pSendMgmtReq->peerMac, pSendMgmtReq->dialog,
psessionEntry, &pSendMgmtReq->addIe[0], (pSendMgmtReq->length - sizeof(tSirTdlsSendMgmtReq)));
resultCode = eSIR_SME_SUCCESS;
}
break;
case SIR_MAC_TDLS_TEARDOWN:
{
limSendTdlsTeardownFrame(pMac,
pSendMgmtReq->peerMac, pSendMgmtReq->statusCode, pSendMgmtReq->responder, psessionEntry,
&pSendMgmtReq->addIe[0], (pSendMgmtReq->length - sizeof(tSirTdlsSendMgmtReq)));
resultCode = eSIR_SME_SUCCESS;
}
break;
case SIR_MAC_TDLS_PEER_TRAFFIC_IND:
{
}
break;
case SIR_MAC_TDLS_CH_SWITCH_REQ:
{
}
break;
case SIR_MAC_TDLS_CH_SWITCH_RSP:
{
}
break;
case SIR_MAC_TDLS_PEER_TRAFFIC_RSP:
{
}
break;
default:
break;
}
lim_tdls_send_mgmt_error:
limSendSmeRsp( pMac, eWNI_SME_TDLS_SEND_MGMT_RSP,
resultCode, pSendMgmtReq->sessionId, pSendMgmtReq->transactionId);
return eSIR_SUCCESS;
}
/*
* Send Response to Link Establish Request to SME
*/
void limSendSmeTdlsLinkEstablishReqRsp(tpAniSirGlobal pMac,
tANI_U8 sessionId, tSirMacAddr peerMac, tDphHashNode *pStaDs,
tANI_U8 status)
{
tSirMsgQ mmhMsg = {0} ;
tSirTdlsLinkEstablishReqRsp *pTdlsLinkEstablishReqRsp = NULL ;
pTdlsLinkEstablishReqRsp = vos_mem_malloc(sizeof(tSirTdlsLinkEstablishReqRsp));
if ( NULL == pTdlsLinkEstablishReqRsp )
{
PELOGE(limLog(pMac, LOGE, FL("Failed to allocate memory"));)
return ;
}
pTdlsLinkEstablishReqRsp->statusCode = status ;
if ( peerMac )
{
vos_mem_copy(pTdlsLinkEstablishReqRsp->peerMac, peerMac, sizeof(tSirMacAddr));
}
pTdlsLinkEstablishReqRsp->sessionId = sessionId;
mmhMsg.type = eWNI_SME_TDLS_LINK_ESTABLISH_RSP ;
mmhMsg.bodyptr = pTdlsLinkEstablishReqRsp;
mmhMsg.bodyval = 0;
limSysProcessMmhMsgApi(pMac, &mmhMsg, ePROT);
return ;
}
/*
* Once link is teardown, send Del Peer Ind to SME
*/
static eHalStatus limSendSmeTdlsDelStaRsp(tpAniSirGlobal pMac,
tANI_U8 sessionId, tSirMacAddr peerMac, tDphHashNode *pStaDs,
tANI_U8 status)
{
tSirMsgQ mmhMsg = {0} ;
tSirTdlsDelStaRsp *pDelSta = NULL ;
mmhMsg.type = eWNI_SME_TDLS_DEL_STA_RSP ;
pDelSta = vos_mem_malloc(sizeof(tSirTdlsDelStaRsp));
if ( NULL == pDelSta )
{
PELOGE(limLog(pMac, LOGE, FL("Failed to allocate memory"));)
return eSIR_FAILURE;
}
pDelSta->sessionId = sessionId;
pDelSta->statusCode = status ;
if( pStaDs )
{
pDelSta->staId = pStaDs->staIndex ;
}
else
pDelSta->staId = HAL_STA_INVALID_IDX;
if( peerMac )
{
vos_mem_copy(pDelSta->peerMac, peerMac, sizeof(tSirMacAddr));
}
pDelSta->length = sizeof(tSirTdlsDelStaRsp) ;
pDelSta->messageType = eWNI_SME_TDLS_DEL_STA_RSP ;
mmhMsg.bodyptr = pDelSta;
mmhMsg.bodyval = 0;
limSysProcessMmhMsgApi(pMac, &mmhMsg, ePROT);
return eSIR_SUCCESS ;
}
/*
* Process Send Mgmt Request from SME and transmit to AP.
*/
tSirRetStatus limProcessSmeTdlsAddStaReq(tpAniSirGlobal pMac,
tANI_U32 *pMsgBuf)
{
/* get all discovery request parameters */
tSirTdlsAddStaReq *pAddStaReq = (tSirTdlsAddStaReq*) pMsgBuf ;
tpPESession psessionEntry;
tANI_U8 sessionId;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Send Mgmt Recieved")) ;
if((psessionEntry = peFindSessionByBssid(pMac, pAddStaReq->bssid, &sessionId))
== NULL)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
"PE Session does not exist for given sme sessionId %d",
pAddStaReq->sessionId);
goto lim_tdls_add_sta_error;
}
/* check if we are in proper state to work as TDLS client */
if (psessionEntry->limSystemRole != eLIM_STA_ROLE)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
"send mgmt received in wrong system Role %d",
psessionEntry->limSystemRole);
goto lim_tdls_add_sta_error;
}
/*
* if we are still good, go ahead and check if we are in proper state to
* do TDLS discovery req/rsp/....frames.
*/
if ((psessionEntry->limSmeState != eLIM_SME_ASSOCIATED_STATE) &&
(psessionEntry->limSmeState != eLIM_SME_LINK_EST_STATE))
{
limLog(pMac, LOGE, "send mgmt received in invalid LIMsme \
state (%d)", psessionEntry->limSmeState);
goto lim_tdls_add_sta_error;
}
pMac->lim.gLimAddStaTdls = true ;
/* To start with, send add STA request to HAL */
if (eSIR_FAILURE == limTdlsSetupAddSta(pMac, pAddStaReq, psessionEntry))
{
limLog(pMac, LOGE, "%s: Add TDLS Station request failed ", __func__);
goto lim_tdls_add_sta_error;
}
return eSIR_SUCCESS;
lim_tdls_add_sta_error:
limSendSmeTdlsAddStaRsp(pMac,
pAddStaReq->sessionId, pAddStaReq->peerMac,
(pAddStaReq->tdlsAddOper == TDLS_OPER_UPDATE), NULL, eSIR_FAILURE );
return eSIR_SUCCESS;
}
/*
* Process Del Sta Request from SME .
*/
tSirRetStatus limProcessSmeTdlsDelStaReq(tpAniSirGlobal pMac,
tANI_U32 *pMsgBuf)
{
/* get all discovery request parameters */
tSirTdlsDelStaReq *pDelStaReq = (tSirTdlsDelStaReq*) pMsgBuf ;
tpPESession psessionEntry;
tANI_U8 sessionId;
tpDphHashNode pStaDs = NULL ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Send Mgmt Recieved")) ;
if((psessionEntry = peFindSessionByBssid(pMac, pDelStaReq->bssid, &sessionId))
== NULL)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
"PE Session does not exist for given sme sessionId %d",
pDelStaReq->sessionId);
limSendSmeTdlsDelStaRsp(pMac, pDelStaReq->sessionId, pDelStaReq->peerMac,
NULL, eSIR_FAILURE) ;
return eSIR_FAILURE;
}
/* check if we are in proper state to work as TDLS client */
if (psessionEntry->limSystemRole != eLIM_STA_ROLE)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
"Del sta received in wrong system Role %d",
psessionEntry->limSystemRole);
goto lim_tdls_del_sta_error;
}
/*
* if we are still good, go ahead and check if we are in proper state to
* do TDLS discovery req/rsp/....frames.
*/
if ((psessionEntry->limSmeState != eLIM_SME_ASSOCIATED_STATE) &&
(psessionEntry->limSmeState != eLIM_SME_LINK_EST_STATE))
{
limLog(pMac, LOGE, "Del Sta received in invalid LIMsme \
state (%d)", psessionEntry->limSmeState);
goto lim_tdls_del_sta_error;
}
pStaDs = limTdlsDelSta(pMac, pDelStaReq->peerMac, psessionEntry) ;
/* now send indication to SME-->HDD->TL to remove STA from TL */
if(pStaDs)
{
limSendSmeTdlsDelStaRsp(pMac, psessionEntry->smeSessionId, pDelStaReq->peerMac,
pStaDs, eSIR_SUCCESS) ;
limReleasePeerIdx(pMac, pStaDs->assocId, psessionEntry) ;
/* Clear the aid in peerAIDBitmap as this aid is now in freepool */
CLEAR_PEER_AID_BITMAP(psessionEntry->peerAIDBitmap, pStaDs->assocId);
limDeleteDphHashEntry(pMac, pStaDs->staAddr, pStaDs->assocId, psessionEntry) ;
return eSIR_SUCCESS;
}
lim_tdls_del_sta_error:
limSendSmeTdlsDelStaRsp(pMac, psessionEntry->smeSessionId, pDelStaReq->peerMac,
NULL, eSIR_FAILURE) ;
return eSIR_SUCCESS;
}
/*
* Process Link Establishment Request from SME .
*/
tSirRetStatus limProcesSmeTdlsLinkEstablishReq(tpAniSirGlobal pMac,
tANI_U32 *pMsgBuf)
{
/* get all discovery request parameters */
tSirTdlsLinkEstablishReq *pTdlsLinkEstablishReq = (tSirTdlsLinkEstablishReq*) pMsgBuf ;
tpPESession psessionEntry;
tANI_U8 sessionId;
tpTdlsLinkEstablishParams pMsgTdlsLinkEstablishReq;
tSirMsgQ msg;
tANI_U16 peerIdx = 0 ;
tpDphHashNode pStaDs = NULL ;
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_INFO,
("Send Mgmt Recieved\n")) ;
if((psessionEntry = peFindSessionByBssid(pMac, pTdlsLinkEstablishReq->bssid, &sessionId))
== NULL)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
"PE Session does not exist for given sme sessionId %d\n",
pTdlsLinkEstablishReq->sessionId);
limSendSmeTdlsLinkEstablishReqRsp(pMac, pTdlsLinkEstablishReq->sessionId, pTdlsLinkEstablishReq->peerMac,
NULL, eSIR_FAILURE) ;
return eSIR_FAILURE;
}
/* check if we are in proper state to work as TDLS client */
if (psessionEntry->limSystemRole != eLIM_STA_ROLE)
{
VOS_TRACE(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ERROR,
"TDLS Link Establish Request received in wrong system Role %d\n",
psessionEntry->limSystemRole);
goto lim_tdls_link_establish_error;
}
/*
* if we are still good, go ahead and check if we are in proper state to
* do TDLS discovery req/rsp/....frames.
*/
if ((psessionEntry->limSmeState != eLIM_SME_ASSOCIATED_STATE) &&
(psessionEntry->limSmeState != eLIM_SME_LINK_EST_STATE))
{
limLog(pMac, LOGE, "TDLS Link Establish Request received in invalid LIMsme \
state (%d)\n", psessionEntry->limSmeState);
goto lim_tdls_link_establish_error;
}
/*TODO Sunil , TDLSPeer Entry has the STA ID , Use it */
pStaDs = dphLookupHashEntry(pMac, pTdlsLinkEstablishReq->peerMac, &peerIdx,
&psessionEntry->dph.dphHashTable) ;
if ( NULL == pStaDs )
{
limLog( pMac, LOGE, FL( "pStaDs is NULL \n" ));
goto lim_tdls_link_establish_error;
}
pMsgTdlsLinkEstablishReq = vos_mem_malloc(sizeof( tTdlsLinkEstablishParams ));
if ( NULL == pMsgTdlsLinkEstablishReq )
{
limLog( pMac, LOGE,
FL( "Unable to allocate memory TDLS Link Establish Request \n" ));
return eSIR_MEM_ALLOC_FAILED;
}
vos_mem_set( (tANI_U8 *)pMsgTdlsLinkEstablishReq, sizeof(tpTdlsLinkEstablishParams), 0);
pMsgTdlsLinkEstablishReq->staIdx = pStaDs->staIndex;
pMsgTdlsLinkEstablishReq->isResponder = pTdlsLinkEstablishReq->isResponder;
pMsgTdlsLinkEstablishReq->uapsdQueues = pTdlsLinkEstablishReq->uapsdQueues;
pMsgTdlsLinkEstablishReq->maxSp = pTdlsLinkEstablishReq->maxSp;
pMsgTdlsLinkEstablishReq->isBufsta = pTdlsLinkEstablishReq->isBufSta;
msg.type = WDA_SET_TDLS_LINK_ESTABLISH_REQ;
msg.reserved = 0;
msg.bodyptr = pMsgTdlsLinkEstablishReq;
msg.bodyval = 0;
if(eSIR_SUCCESS != wdaPostCtrlMsg(pMac, &msg))
{
limLog(pMac, LOGE, FL("halPostMsgApi failed\n"));
goto lim_tdls_link_establish_error;
}
return eSIR_SUCCESS;
lim_tdls_link_establish_error:
limSendSmeTdlsLinkEstablishReqRsp(pMac, psessionEntry->smeSessionId, pTdlsLinkEstablishReq->peerMac,
NULL, eSIR_FAILURE) ;
return eSIR_SUCCESS;
}
/* Delete all the TDLS peer connected before leaving the BSS */
tSirRetStatus limDeleteTDLSPeers(tpAniSirGlobal pMac, tpPESession psessionEntry)
{
tpDphHashNode pStaDs = NULL ;
int i, aid;
if (NULL == psessionEntry)
{
PELOGE(limLog(pMac, LOGE, FL("NULL psessionEntry"));)
return eSIR_FAILURE;
}
/* Check all the set bit in peerAIDBitmap and delete the peer (with that aid) entry
from the hash table and add the aid in free pool */
for (i = 0; i < sizeof(psessionEntry->peerAIDBitmap)/sizeof(tANI_U32); i++)
{
for (aid = 0; aid < (sizeof(tANI_U32) << 3); aid++)
{
if (CHECK_BIT(psessionEntry->peerAIDBitmap[i], aid))
{
pStaDs = dphGetHashEntry(pMac, (aid + i*(sizeof(tANI_U32) << 3)), &psessionEntry->dph.dphHashTable);
if (NULL != pStaDs)
{
PELOGE(limLog(pMac, LOGE, FL("Deleting %02x:%02x:%02x:%02x:%02x:%02x"),
pStaDs->staAddr[0], pStaDs->staAddr[1], pStaDs->staAddr[2],
pStaDs->staAddr[3], pStaDs->staAddr[4], pStaDs->staAddr[5]);)
limSendDeauthMgmtFrame(pMac, eSIR_MAC_DEAUTH_LEAVING_BSS_REASON,
pStaDs->staAddr, psessionEntry, FALSE);
dphDeleteHashEntry(pMac, pStaDs->staAddr, pStaDs->assocId, &psessionEntry->dph.dphHashTable);
}
limReleasePeerIdx(pMac, (aid + i*(sizeof(tANI_U32) << 3)), psessionEntry) ;
CLEAR_BIT(psessionEntry->peerAIDBitmap[i], aid);
}
}
}
limSendSmeTDLSDeleteAllPeerInd(pMac, psessionEntry);
return eSIR_SUCCESS;
}
#ifdef FEATURE_WLAN_TDLS_OXYGEN_DISAPPEAR_AP
/* Get the number of TDLS peer connected in the BSS */
int limGetTDLSPeerCount(tpAniSirGlobal pMac, tpPESession psessionEntry)
{
int i,tdlsPeerCount = 0;
/* Check all the set bit in peerAIDBitmap and return the number of TDLS peer counts */
for (i = 0; i < sizeof(psessionEntry->peerAIDBitmap)/sizeof(tANI_U32); i++)
{
tANI_U32 bitmap;
bitmap = psessionEntry->peerAIDBitmap[i];
while (bitmap)
{
tdlsPeerCount++;
bitmap >>= 1;
}
}
return tdlsPeerCount;
}
void limTDLSDisappearAPTrickInd(tpAniSirGlobal pMac, tpDphHashNode pStaDs, tpPESession psessionEntry)
{
tSirMsgQ mmhMsg;
tSirTdlsDisappearAPInd *pSirTdlsDisappearAPInd;
pSirTdlsDisappearAPInd = vos_mem_malloc(sizeof(tSirTdlsDisappearAPInd));
if ( NULL == pSirTdlsDisappearAPInd )
{
limLog(pMac, LOGP, FL("AllocateMemory failed for eWNI_SME_TDLS_DEL_ALL_PEER_IND"));
return;
}
//messageType
pSirTdlsDisappearAPInd->messageType = eWNI_SME_TDLS_AP_DISAPPEAR_IND;
pSirTdlsDisappearAPInd->length = sizeof(tSirTdlsDisappearAPInd);
//sessionId
pSirTdlsDisappearAPInd->sessionId = psessionEntry->smeSessionId;
pSirTdlsDisappearAPInd->staId = pStaDs->staIndex ;
vos_mem_copy( pSirTdlsDisappearAPInd->staAddr,
(tANI_U8 *) pStaDs->staAddr, sizeof(tSirMacAddr));
mmhMsg.type = eWNI_SME_TDLS_AP_DISAPPEAR_IND;
mmhMsg.bodyptr = pSirTdlsDisappearAPInd;
mmhMsg.bodyval = 0;
limSysProcessMmhMsgApi(pMac, &mmhMsg, ePROT);
}
#endif
#endif
|
the_stack_data/88824.c | /* This file contains an example program from The Little Book of
Semaphores, available from Green Tea Press, greenteapress.com
Copyright 2014 Allen B. Downey
License: Creative Commons Attribution-ShareAlike 3.0
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_CHILDREN 2
// UTILITY FUNCTIONS
/* perror_exit
*
* Prints an error message and exits.
*
* s: message to print
*
*/
void perror_exit (char *s)
{
perror (s);
exit (-1);
}
/* check_malloc
*
* Calls malloc and checks the result.
*
* size: number of bytes to allocate
*
*/
void *check_malloc(int size)
{
void *p = malloc (size);
if (p == NULL) perror_exit ("malloc failed");
return p;
}
// Semaphore
typedef sem_t Semaphore;
/* make_semaphore
*
* Allocates and initializes a Semaphore.
*
* n: initial value
*
* returns: pointer to new Semaphore
*/
Semaphore *make_semaphore (int n)
{
Semaphore *sem = check_malloc (sizeof(Semaphore));
int ret = sem_init(sem, 0, n);
if (ret == -1) perror_exit ("sem_init failed");
return sem;
}
/* sem_signal
*
* Signals a semaphore.
*
* sem: pointer to Semaphore
*
* returns: 0 on success, -1 on error
*/
int sem_signal(Semaphore *sem)
{
return sem_post(sem);
}
// Shared
typedef struct {
int counter;
int end;
int *array;
Semaphore *mutex;
} Shared;
/* make_shared
*
* Initializes the environment shared by threads.
*
* end: size of the shared array
*
* returns: pointer to new Shared
*/
Shared *make_shared (int end)
{
int i;
Shared *shared = check_malloc (sizeof (Shared));
shared->counter = 0;
shared->end = end;
shared->array = check_malloc (shared->end * sizeof(int));
for (i=0; i<shared->end; i++) {
shared->array[i] = 0;
}
shared->mutex = make_semaphore(1);
return shared;
}
/* make_thread
*
* Allocates and initializes a POSIX thread.
*
* entry: pointer to the entry function
* shared: pointer to the shared environment
*
* returns: ID of the new thread, which has integer semantics
*
*/
pthread_t make_thread(void *(*entry)(void *), Shared *shared)
{
int ret;
pthread_t thread;
ret = pthread_create (&thread, NULL, entry, (void *) shared);
if (ret != 0) perror_exit ("pthread_create failed");
return thread;
}
/* join_thread
*
* Waits for the given thread to exit.
*
* thread: ID of the thread we should wait for
*
*/
void join_thread (pthread_t thread)
{
int ret = pthread_join (thread, NULL);
if (ret == -1) perror_exit ("pthread_join failed");
}
/* child_code
*
* Increments the values in an array.
*
* If access to shared->counter is synchonized, every element in
* the array should be incremented exactly once.
*
* If there are race conditions, some elements will be incremented
* zero times or more than once. We can detect these synchronization
* errors by inspecting the array after all threads exit.
*
* shared: pointer to shared environment
*
*/
void child_code (Shared *shared)
{
printf ("Starting child at counter %d\n", shared->counter);
while (1) {
sem_wait(shared->mutex);
if (shared->counter >= shared->end) {
sem_signal(shared->mutex);
return;
}
shared->array[shared->counter]++;
shared->counter++;
if (shared->counter % 100000 == 0) {
printf ("%d\n", shared->counter);
}
sem_signal(shared->mutex);
}
}
/* entry
*
* Starting point for child threads,
*
* arg: pointer to the shared environment
*
*/
void *entry (void *arg)
{
Shared *shared = (Shared *) arg;
child_code (shared);
printf ("Child done.\n");
pthread_exit (NULL);
}
/* check_array
*
* Checks whether every element of the shared array is 1.
* Prints the number of synchronization errors.
*
* shared: pointer to shared environment
*
*/
void check_array (Shared *shared)
{
int i, errors=0;
printf ("Checking...\n");
for (i=0; i<shared->end; i++) {
if (shared->array[i] != 1) errors++;
}
printf ("%d errors.\n", errors);
}
/* main
*
* Creates the given number of children and runs them concurrently.
*
*/
int main ()
{
int i;
pthread_t child[NUM_CHILDREN];
Shared *shared = make_shared (100000);
for (i=0; i<NUM_CHILDREN; i++) {
child[i] = make_thread (entry, shared);
}
for (i=0; i<NUM_CHILDREN; i++) {
join_thread (child[i]);
}
check_array (shared);
return 0;
}
|
the_stack_data/248581491.c | #define SIMPLE_TEST(x) int main(){ x; return 0; }
#ifdef CXX_HAVE_OFFSETOF
#include <stdio.h>
#include <stddef.h>
#ifdef FC_DUMMY_MAIN
#ifndef FC_DUMMY_MAIN_EQ_F77
# ifdef __cplusplus
extern "C"
# endif
int FC_DUMMY_MAIN()
{ return 1;}
#endif
#endif
int
main ()
{
struct index_st
{
unsigned char type;
unsigned char num;
unsigned int len;
};
typedef struct index_st index_t;
int x,y;
x = offsetof(struct index_st, len);
y = offsetof(index_t, num)
;
return 0;
}
#endif
#ifdef HAVE_C99_DESIGNATED_INITIALIZER
#ifdef FC_DUMMY_MAIN
#ifndef FC_DUMMY_MAIN_EQ_F77
# ifdef __cplusplus
extern "C"
# endif
int FC_DUMMY_MAIN()
{ return 1;}
#endif
#endif
int
main ()
{
typedef struct
{
int x;
union
{
int i;
double d;
}u;
}di_struct_t;
di_struct_t x =
{ 0,
{ .d = 0.0}};
;
return 0;
}
#endif
#ifdef HAVE_C99_FUNC
#ifdef FC_DUMMY_MAIN
#ifndef FC_DUMMY_MAIN_EQ_F77
# ifdef __cplusplus
extern "C"
# endif
int FC_DUMMY_MAIN() { return 1; }
#endif
#endif
int
main ()
{
const char *fname = __func__;
;
return 0;
}
#endif
#ifdef VSNPRINTF_WORKS
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
int test_vsnprintf(const char *fmt,...)
{
va_list ap;
char *s = malloc(16);
int ret;
va_start(ap, fmt);
ret=vsnprintf(s,16,"%s",ap);
va_end(ap);
return(ret!=42 ? 1 : 0);
}
int main(void)
{
exit(test_vsnprintf("%s","A string that is longer than 16 characters"));
}
#endif
#ifdef TIME_WITH_SYS_TIME
/* Time with sys/time test */
#include <sys/types.h>
#include <sys/time.h>
#include <time.h>
int
main ()
{
if ((struct tm *) 0)
return 0;
;
return 0;
}
#endif
#ifdef STDC_HEADERS
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <float.h>
int main() { return 0; }
#endif /* STDC_HEADERS */
#ifdef HAVE_TM_ZONE
#include <sys/types.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <time.h>
SIMPLE_TEST(struct tm tm; tm.tm_zone);
#endif /* HAVE_TM_ZONE */
#ifdef HAVE_STRUCT_TM_TM_ZONE
#include <sys/types.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <time.h>
SIMPLE_TEST(struct tm tm; tm.tm_zone);
#endif /* HAVE_STRUCT_TM_TM_ZONE */
#ifdef HAVE_ATTRIBUTE
#if 0
static void test int __attribute((unused)) var)
{
int __attribute__((unused)) x = var;
}
int main(void)
{
test(19);
}
#else
int
main ()
{
int __attribute__((unused)) x
;
return 0;
}
#endif
#endif /* HAVE_ATTRIBUTE */
#ifdef HAVE_FUNCTION
#ifdef FC_DUMMY_MAIN
#ifndef FC_DUMMY_MAIN_EQ_F77
# ifdef __cplusplus
extern "C"
# endif
int FC_DUMMY_MAIN() { return 1; }
#endif
#endif
int
main ()
{
(void)__FUNCTION__
;
return 0;
}
#endif /* HAVE_FUNCTION */
#ifdef HAVE_TM_GMTOFF
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <time.h>
SIMPLE_TEST(struct tm tm; tm.tm_gmtoff=0);
#endif /* HAVE_TM_GMTOFF */
#ifdef HAVE_TIMEZONE
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <time.h>
SIMPLE_TEST(timezone=0);
#endif /* HAVE_TIMEZONE */
#ifdef HAVE_STRUCT_TIMEZONE
#include <sys/types.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <time.h>
SIMPLE_TEST(struct timezone tz; tz.tz_minuteswest=0);
#endif /* HAVE_STRUCT_TIMEZONE */
#ifdef HAVE_STAT_ST_BLOCKS
#include <sys/stat.h>
SIMPLE_TEST(struct stat sb; sb.st_blocks=0);
#endif /* HAVE_STAT_ST_BLOCKS */
#ifdef PRINTF_LL_WIDTH
#ifdef HAVE_LONG_LONG
# define LL_TYPE long long
#else /* HAVE_LONG_LONG */
# define LL_TYPE __int64
#endif /* HAVE_LONG_LONG */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *llwidthArgs[] = { "l64", "l", "L", "q", "ll", NULL };
char *s = malloc(128);
char **currentArg = NULL;
LL_TYPE x = (LL_TYPE)1048576 * (LL_TYPE)1048576;
for (currentArg = llwidthArgs; *currentArg != NULL; currentArg++)
{
char formatString[64];
sprintf(formatString, "%%%sd", *currentArg);
sprintf(s, formatString, x);
if (strcmp(s, "1099511627776") == 0)
{
printf("PRINTF_LL_WIDTH=[%s]\n", *currentArg);
exit(0);
}
}
exit(1);
}
#endif /* PRINTF_LL_WIDTH */
#ifdef SYSTEM_SCOPE_THREADS
#include <stdlib.h>
#include <pthread.h>
int main(void)
{
pthread_attr_t attribute;
int ret;
pthread_attr_init(&attribute);
ret=pthread_attr_setscope(&attribute, PTHREAD_SCOPE_SYSTEM);
exit(ret==0 ? 0 : 1);
}
#endif /* SYSTEM_SCOPE_THREADS */
#ifdef HAVE_SOCKLEN_T
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
SIMPLE_TEST(socklen_t foo);
#endif /* HAVE_SOCKLEN_T */
#ifdef DEV_T_IS_SCALAR
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
int main ()
{
dev_t d1, d2;
if(d1==d2)
return 0;
return 1;
}
#endif /* DEV_T_IS_SCALAR */
#ifdef HAVE_OFF64_T
#include <sys/types.h>
int main()
{
off64_t n = 0;
return (int)n;
}
#endif
#ifdef TEST_LFS_WORKS
/* Return 0 when LFS is available and 1 otherwise. */
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _LARGE_FILES
#define _FILE_OFFSET_BITS 64
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <stdio.h>
int main(int argc, char **argv)
{
/* check that off_t can hold 2^63 - 1 and perform basic operations... */
#define OFF_T_64 (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
if (OFF_T_64 % 2147483647 != 1)
return 1;
// stat breaks on SCO OpenServer
struct stat buf;
stat( argv[0], &buf );
if (!S_ISREG(buf.st_mode))
return 2;
FILE *file = fopen( argv[0], "r" );
off_t offset = ftello( file );
fseek( file, offset, SEEK_CUR );
fclose( file );
return 0;
}
#endif
#ifdef GETTIMEOFDAY_GIVES_TZ
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <time.h>
int main(void)
{
struct timeval tv;
struct timezone tz;
tz.tz_minuteswest = 7777; /* Initialize to an unreasonable number */
tz.tz_dsttime = 7;
gettimeofday(&tv, &tz);
/* Check whether the function returned any value at all */
if(tz.tz_minuteswest == 7777 && tz.tz_dsttime == 7)
exit(1);
else exit (0);
}
#endif
#ifdef LONE_COLON
int main(int argc, char * argv)
{
return 0;
}
#endif
#ifdef HAVE_GPFS
#include <gpfs.h>
int main ()
{
int fd = 0;
gpfs_fcntl(fd, (void *)0);
}
#endif /* HAVE_GPFS */
#ifdef HAVE_IOEO
#include <windows.h>
typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
int main ()
{
PGNSI pGNSI;
pGNSI = (PGNSI) GetProcAddress(
GetModuleHandle(TEXT("kernel32.dll")),
"InitOnceExecuteOnce");
if(NULL == pGNSI)
return 1;
else
return 0;
}
#endif /* HAVE_IOEO */
#if defined( INLINE_TEST_inline ) || defined( INLINE_TEST___inline__ ) || defined( INLINE_TEST___inline )
#ifndef __cplusplus
typedef int foo_t;
static INLINE_TEST_INLINE foo_t static_foo () { return 0; }
INLINE_TEST_INLINE foo_t foo () {return 0; }
int main() { return 0; }
#endif
#endif /* INLINE_TEST */
|
the_stack_data/1218421.c | // RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - | FileCheck %s
// Capture the type and name so matching later is cleaner.
struct CompoundTy { int a; };
// CHECK: @MyCLH = constant [[MY_CLH:[^,]+]]
const struct CompoundTy *const MyCLH = &(struct CompoundTy){3};
int* a = &(int){1};
struct s {int a, b, c;} * b = &(struct s) {1, 2, 3};
_Complex double * x = &(_Complex double){1.0f};
typedef int v4i32 __attribute((vector_size(16)));
v4i32 *y = &(v4i32){1,2,3,4};
void xxx() {
int* a = &(int){1};
struct s {int a, b, c;} * b = &(struct s) {1, 2, 3};
_Complex double * x = &(_Complex double){1.0f};
}
// CHECK-LABEL: define void @f()
void f() {
typedef struct S { int x,y; } S;
// CHECK: [[S:%[a-zA-Z0-9.]+]] = alloca [[STRUCT:%[a-zA-Z0-9.]+]],
struct S s;
// CHECK-NEXT: [[COMPOUNDLIT:%[a-zA-Z0-9.]+]] = alloca [[STRUCT]]
// CHECK-NEXT: [[CX:%[a-zA-Z0-9.]+]] = getelementptr inbounds [[STRUCT]], [[STRUCT]]* [[COMPOUNDLIT]], i32 0, i32 0
// CHECK-NEXT: [[SY:%[a-zA-Z0-9.]+]] = getelementptr inbounds [[STRUCT]], [[STRUCT]]* [[S]], i32 0, i32 1
// CHECK-NEXT: [[TMP:%[a-zA-Z0-9.]+]] = load i32, i32* [[SY]]
// CHECK-NEXT: store i32 [[TMP]], i32* [[CX]]
// CHECK-NEXT: [[CY:%[a-zA-Z0-9.]+]] = getelementptr inbounds [[STRUCT]], [[STRUCT]]* [[COMPOUNDLIT]], i32 0, i32 1
// CHECK-NEXT: [[SX:%[a-zA-Z0-9.]+]] = getelementptr inbounds [[STRUCT]], [[STRUCT]]* [[S]], i32 0, i32 0
// CHECK-NEXT: [[TMP:%[a-zA-Z0-9.]+]] = load i32, i32* [[SX]]
// CHECK-NEXT: store i32 [[TMP]], i32* [[CY]]
// CHECK-NEXT: [[SI8:%[a-zA-Z0-9.]+]] = bitcast [[STRUCT]]* [[S]] to i8*
// CHECK-NEXT: [[COMPOUNDLITI8:%[a-zA-Z0-9.]+]] = bitcast [[STRUCT]]* [[COMPOUNDLIT]] to i8*
// CHECK-NEXT: call void @llvm.memcpy{{.*}}(i8* [[SI8]], i8* [[COMPOUNDLITI8]]
s = (S){s.y,s.x};
// CHECK-NEXT: ret void
}
// CHECK-LABEL: define i48 @g(
struct G { short x, y, z; };
struct G g(int x, int y, int z) {
// CHECK: [[RESULT:%.*]] = alloca [[G:%.*]], align 2
// CHECK-NEXT: [[X:%.*]] = alloca i32, align 4
// CHECK-NEXT: [[Y:%.*]] = alloca i32, align 4
// CHECK-NEXT: [[Z:%.*]] = alloca i32, align 4
// CHECK-NEXT: [[COERCE_TEMP:%.*]] = alloca i48
// CHECK-NEXT: store i32
// CHECK-NEXT: store i32
// CHECK-NEXT: store i32
// Evaluate the compound literal directly in the result value slot.
// CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds [[G]], [[G]]* [[RESULT]], i32 0, i32 0
// CHECK-NEXT: [[T1:%.*]] = load i32, i32* [[X]], align 4
// CHECK-NEXT: [[T2:%.*]] = trunc i32 [[T1]] to i16
// CHECK-NEXT: store i16 [[T2]], i16* [[T0]], align 2
// CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds [[G]], [[G]]* [[RESULT]], i32 0, i32 1
// CHECK-NEXT: [[T1:%.*]] = load i32, i32* [[Y]], align 4
// CHECK-NEXT: [[T2:%.*]] = trunc i32 [[T1]] to i16
// CHECK-NEXT: store i16 [[T2]], i16* [[T0]], align 2
// CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds [[G]], [[G]]* [[RESULT]], i32 0, i32 2
// CHECK-NEXT: [[T1:%.*]] = load i32, i32* [[Z]], align 4
// CHECK-NEXT: [[T2:%.*]] = trunc i32 [[T1]] to i16
// CHECK-NEXT: store i16 [[T2]], i16* [[T0]], align 2
return (struct G) { x, y, z };
// CHECK-NEXT: [[T0:%.*]] = bitcast i48* [[COERCE_TEMP]] to i8*
// CHECK-NEXT: [[T1:%.*]] = bitcast [[G]]* [[RESULT]] to i8*
// CHECK-NEXT: call void @llvm.memcpy.p0i8.p0i8.i64(i8* [[T0]], i8* [[T1]], i64 6
// CHECK-NEXT: [[T0:%.*]] = load i48, i48* [[COERCE_TEMP]]
// CHECK-NEXT: ret i48 [[T0]]
}
// We had a bug where we'd emit a new GlobalVariable for each time we used a
// const pointer to a variable initialized by a compound literal.
// CHECK-LABEL: define i32 @compareMyCLH() #0
int compareMyCLH() {
// CHECK: store i8* bitcast ([[MY_CLH]] to i8*)
const void *a = MyCLH;
// CHECK: store i8* bitcast ([[MY_CLH]] to i8*)
const void *b = MyCLH;
return a == b;
}
|
the_stack_data/178266243.c | // jue 21 abr 2022 18:10:47 CST
// problema6.c
// Diego Sarceno ([email protected])
// Calculo de diversas sumatorias con limite superior ingresado por el usuario.
// Codificado del texto: UTF8
// Compiladores probados: GNU gcc (Ubuntu 20.04 Linux) 9.3.0
// Instruciones de Compilacion: no requiere nada mas
// gcc -Wall -pedantic -std=c11 -c -o problema6.o problema6.c
// gcc -o problema6.x problema6.o -lm
// Librerias
#include <stdio.h>
#include <math.h>
// 0. Prototipado de funciones
float a(int n);
float b(int n);
float c(int n);
float d(int n);
// 1. funcion main
int main(){
// 2. ingreso del limite superior
int n;
puts("Ingrese un número entero positivo.");
scanf("%d", &n);
printf("Inciso a) %.2f \n", a(n));
printf("Inciso b) %.2f \n", b(n));
printf("Inciso c) %.2f \n", c(n));
printf("Inciso d) %.2f \n", d(n));
}
/*
FUNCIONES
*/
float a(int n){
float sum1 = 0;
for (int i = 1; i <= n; i++){
sum1 += pow(i,2)*(i - 3);
}
return sum1;
} //END a
float b(int n){
float sum2 = 0;
for (int i = 2; i <= n; i++){
sum2 += 3/(i - 1);
}
return sum2;
} // END b
float c(int n){
float sum3 = 0;
for (int i = 1; i <= n; i++){
sum3 += (1/sqrt(5))*pow(((1 + sqrt(5))/2),i) - (1/sqrt(5))*pow(((1 - sqrt(5))/2),i);
}
return sum3;
} // END c
float d(int n){
float sum4 = 0;
for (int i = 2; i <= n; i++){
sum4 += 0.1*(3*pow(2,i - 2) + 4);
}
return sum4;
} // END d
//END PROGRAM lab4Problema6
|
the_stack_data/184517263.c | /* camellia.h ver 1.1.0
*
* Copyright (c) 2006
* NTT (Nippon Telegraph and Telephone Corporation) . All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer as
* the first lines of this file unmodified.
* 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 NTT ``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 NTT 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.
*/
/*
* Algorithm Specification
* http://info.isl.ntt.co.jp/crypt/eng/camellia/specifications.html
*/
|
the_stack_data/109119.c | #include <stdio.h>
#include <math.h>
#define esquerda (t[i] * findP1(t, i * 2, end))
#define direita (t[i] * findP1(t, (i * 2) + 1, end))
int max(int a, int b)
{
return(a > b ? a : b);
}
int findP1(int t[], int i, int end)
{
if (i * 2 >= end)
{
return(t[i]);
}
return(max(esquerda, direita));
}
int main()
{
int tam; scanf("%d", &tam);
int endOfTree = pow(2, tam);
int tree[endOfTree], valor, i;
for (i = 0; i < endOfTree; i ++)
{
tree[i] = 0;
} i = 1;
while (scanf("%d", &valor) != EOF)
{
tree[i] = valor;
i ++;
}
int P1 = findP1(tree, 1, endOfTree);
printf("%d\n", P1);
return(0);
}
|
the_stack_data/31387114.c | /* Test for fdopen bugs. */
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#define assert(x) \
if (!(x)) \
{ \
fputs ("test failed: " #x "\n", stderr); \
retval = 1; \
goto the_end; \
}
char buffer[256];
int
main (int argc, char *argv[])
{
char *name;
FILE *fp = NULL;
int retval = 0;
int fd;
name = tmpnam (NULL);
fp = fopen (name, "w");
assert (fp != NULL)
fputs ("foobar and baz", fp);
fclose (fp);
fp = NULL;
fd = open (name, O_RDWR|O_CREAT);
assert (fd != -1);
assert (lseek (fd, 5, SEEK_SET) == 5);
fp = fdopen (fd, "a");
assert (fp != NULL);
assert (ftell (fp) == 14);
the_end:
if (fp != NULL)
fclose (fp);
unlink (name);
return retval;
}
|
the_stack_data/1248869.c | /* Getopt for GNU.
NOTE: getopt is now part of the C library, so if you don't know what
"Keep this file name-space clean" means, talk to [email protected]
before changing it!
Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001,2002,2003,2004
Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
/* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
Ditto for AIX 3.2 and <stdlib.h>. */
#ifndef _NO_PROTO
# define _NO_PROTO
#endif
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
/* Comment out all this code if we are using the GNU C Library, and are not
actually compiling the library itself. This code is part of the GNU C
Library, but also included in many other GNU distributions. Compiling
and linking in this code is a waste when using the GNU C library
(especially if it is a shared library). Rather than having every GNU
program understand `configure --with-gnu-libc' and omit the object files,
it is simpler to just do this in the source for each such file. */
#define GETOPT_INTERFACE_VERSION 2
#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
# include <gnu-versions.h>
# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
# define ELIDE_CODE
# endif
#endif
#ifndef ELIDE_CODE
/* This needs to come after some library #include
to get __GNU_LIBRARY__ defined. */
#ifdef __GNU_LIBRARY__
/* Don't include stdlib.h for non-GNU C libraries because some of them
contain conflicting prototypes for getopt. */
# include <stdlib.h>
# include <unistd.h>
#endif /* GNU C library. */
#include <string.h>
#ifdef VMS
# include <unixlib.h>
#endif
#ifdef _LIBC
# include <libintl.h>
#else
#if defined(powerc) || defined(__SC__)
#define _(msgid) msgid
#else
# include "gettext.h"
# define _(msgid) gettext (msgid)
#endif
#endif
#if defined _LIBC && defined USE_IN_LIBIO
# include <wchar.h>
#endif
#ifndef attribute_hidden
# define attribute_hidden
#endif
/* This version of `getopt' appears to the caller like standard Unix `getopt'
but it behaves differently for the user, since it allows the user
to intersperse the options with the other arguments.
As `getopt' works, it permutes the elements of ARGV so that,
when it is done, all the options precede everything else. Thus
all application programs are extended to handle flexible argument order.
Setting the environment variable POSIXLY_CORRECT disables permutation.
Then the behavior is completely standard.
GNU application programs can use a third alternative mode in which
they can distinguish the relative order of options and other arguments. */
#include "getopt.h"
#include "getopt_int.h"
/* For communication from `getopt' to the caller.
When `getopt' finds an option that takes an argument,
the argument value is returned here.
Also, when `ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
char *optarg;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
and for communication between successive calls to `getopt'.
On entry to `getopt', zero means this is the first call; initialize.
When `getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
Otherwise, `optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
/* 1003.2 says this must be 1 before any call. */
int optind = 1;
/* Callers store zero here to inhibit the error message
for unrecognized options. */
int opterr = 1;
/* Set to an option character which was unrecognized.
This must be initialized on some systems to avoid linking in the
system's own getopt implementation. */
int optopt = '?';
/* Keep a global copy of all internal members of getopt_data. */
static struct _getopt_data getopt_data;
#ifndef __GNU_LIBRARY__
/* Avoid depending on library functions or files
whose names are inconsistent. */
#ifndef getenv
extern char *getenv ();
#endif
#endif /* not __GNU_LIBRARY__ */
#ifdef _LIBC
/* Stored original parameters.
XXX This is no good solution. We should rather copy the args so
that we can compare them later. But we must not use malloc(3). */
extern int __libc_argc;
extern char **__libc_argv;
/* Bash 2.0 gives us an environment variable containing flags
indicating ARGV elements that should not be considered arguments. */
# ifdef USE_NONOPTION_FLAGS
/* Defined in getopt_init.c */
extern char *__getopt_nonoption_flags;
# endif
# ifdef USE_NONOPTION_FLAGS
# define SWAP_FLAGS(ch1, ch2) \
if (d->__nonoption_flags_len > 0) \
{ \
char __tmp = __getopt_nonoption_flags[ch1]; \
__getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
__getopt_nonoption_flags[ch2] = __tmp; \
}
# else
# define SWAP_FLAGS(ch1, ch2)
# endif
#else /* !_LIBC */
# define SWAP_FLAGS(ch1, ch2)
#endif /* _LIBC */
/* Exchange two adjacent subsequences of ARGV.
One subsequence is elements [first_nonopt,last_nonopt)
which contains all the non-options that have been skipped so far.
The other is elements [last_nonopt,optind), which contains all
the options processed since those non-options were skipped.
`first_nonopt' and `last_nonopt' are relocated so that they describe
the new indices of the non-options in ARGV after they are moved. */
static void
exchange (char **argv, struct _getopt_data *d)
{
int bottom = d->__first_nonopt;
int middle = d->__last_nonopt;
int top = d->optind;
char *tem;
/* Exchange the shorter segment with the far end of the longer segment.
That puts the shorter segment into the right place.
It leaves the longer segment in the right place overall,
but it consists of two parts that need to be swapped next. */
#if defined _LIBC && defined USE_NONOPTION_FLAGS
/* First make sure the handling of the `__getopt_nonoption_flags'
string can work normally. Our top argument must be in the range
of the string. */
if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
{
/* We must extend the array. The user plays games with us and
presents new arguments. */
char *new_str = malloc (top + 1);
if (new_str == NULL)
d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
else
{
memset (__mempcpy (new_str, __getopt_nonoption_flags,
d->__nonoption_flags_max_len),
'\0', top + 1 - d->__nonoption_flags_max_len);
d->__nonoption_flags_max_len = top + 1;
__getopt_nonoption_flags = new_str;
}
}
#endif
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
{
/* Bottom segment is the short one. */
int len = middle - bottom;
register int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
}
else
{
/* Top segment is the short one. */
int len = top - middle;
register int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
SWAP_FLAGS (bottom + i, middle + i);
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
d->__first_nonopt += (d->optind - d->__last_nonopt);
d->__last_nonopt = d->optind;
}
/* Initialize the internal data when the first call is made. */
static const char *
_getopt_initialize (int argc, char *const *argv, const char *optstring,
struct _getopt_data *d)
{
/* Start processing options with ARGV-element 1 (since ARGV-element 0
is the program name); the sequence of previously skipped
non-option ARGV-elements is empty. */
d->__first_nonopt = d->__last_nonopt = d->optind;
d->__nextchar = NULL;
d->__posixly_correct = !!getenv ("POSIXLY_CORRECT");
/* Determine how to handle the ordering of options and nonoptions. */
if (optstring[0] == '-')
{
d->__ordering = RETURN_IN_ORDER;
++optstring;
}
else if (optstring[0] == '+')
{
d->__ordering = REQUIRE_ORDER;
++optstring;
}
else if (d->__posixly_correct)
d->__ordering = REQUIRE_ORDER;
else
d->__ordering = PERMUTE;
#if defined _LIBC && defined USE_NONOPTION_FLAGS
if (!d->__posixly_correct
&& argc == __libc_argc && argv == __libc_argv)
{
if (d->__nonoption_flags_max_len == 0)
{
if (__getopt_nonoption_flags == NULL
|| __getopt_nonoption_flags[0] == '\0')
d->__nonoption_flags_max_len = -1;
else
{
const char *orig_str = __getopt_nonoption_flags;
int len = d->__nonoption_flags_max_len = strlen (orig_str);
if (d->__nonoption_flags_max_len < argc)
d->__nonoption_flags_max_len = argc;
__getopt_nonoption_flags =
(char *) malloc (d->__nonoption_flags_max_len);
if (__getopt_nonoption_flags == NULL)
d->__nonoption_flags_max_len = -1;
else
memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
'\0', d->__nonoption_flags_max_len - len);
}
}
d->__nonoption_flags_len = d->__nonoption_flags_max_len;
}
else
d->__nonoption_flags_len = 0;
#endif
return optstring;
}
/* Scan elements of ARGV (whose length is ARGC) for option characters
given in OPTSTRING.
If an element of ARGV starts with '-', and is not exactly "-" or "--",
then it is an option element. The characters of this element
(aside from the initial '-') are option characters. If `getopt'
is called repeatedly, it returns successively each of the option characters
from each of the option elements.
If `getopt' finds another option character, it returns that character,
updating `optind' and `nextchar' so that the next call to `getopt' can
resume the scan with the following option character or ARGV-element.
If there are no more option characters, `getopt' returns -1.
Then `optind' is the index in ARGV of the first ARGV-element
that is not an option. (The ARGV-elements have been permuted
so that those that are not options now come last.)
OPTSTRING is a string containing the legitimate option characters.
If an option character is seen that is not listed in OPTSTRING,
return '?' after printing an error message. If you set `opterr' to
zero, the error message is suppressed but we still return '?'.
If a char in OPTSTRING is followed by a colon, that means it wants an arg,
so the following text in the same ARGV-element, or the text of the following
ARGV-element, is returned in `optarg'. Two colons mean an option that
wants an optional arg; if there is text in the current ARGV-element,
it is returned in `optarg', otherwise `optarg' is set to zero.
If OPTSTRING starts with `-' or `+', it requests different methods of
handling the non-option ARGV-elements.
See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
Long-named options begin with `--' instead of `-'.
Their names may be abbreviated as long as the abbreviation is unique
or is an exact match for some defined option. If they have an
argument, it follows the option name in the same ARGV-element, separated
from the option name by a `=', or else the in next ARGV-element.
When `getopt' finds a long-named option, it returns 0 if that option's
`flag' field is nonzero, the value of the option's `val' field
if the `flag' field is zero.
The elements of ARGV aren't really const, because we permute them.
But we pretend they're const in the prototype to be compatible
with other systems.
LONGOPTS is a vector of `struct option' terminated by an
element containing a name which is zero.
LONGIND returns the index in LONGOPT of the long-named option found.
It is only valid when a long-named option has been found by the most
recent call.
If LONG_ONLY is nonzero, '-' as well as '--' can introduce
long-named options. */
int
_getopt_internal_r (int argc, char *const *argv, const char *optstring,
const struct option *longopts, int *longind,
int long_only, struct _getopt_data *d)
{
int print_errors = d->opterr;
if (optstring[0] == ':')
print_errors = 0;
if (argc < 1)
return -1;
d->optarg = NULL;
if (d->optind == 0 || !d->__initialized)
{
if (d->optind == 0)
d->optind = 1; /* Don't scan ARGV[0], the program name. */
optstring = _getopt_initialize (argc, argv, optstring, d);
d->__initialized = 1;
}
/* Test whether ARGV[optind] points to a non-option argument.
Either it does not have option syntax, or there is an environment flag
from the shell indicating it is not an option. The later information
is only used when the used in the GNU libc. */
#if defined _LIBC && defined USE_NONOPTION_FLAGS
# define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
|| (d->optind < d->__nonoption_flags_len \
&& __getopt_nonoption_flags[d->optind] == '1'))
#else
# define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
#endif
if (d->__nextchar == NULL || *d->__nextchar == '\0')
{
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
moved back by the user (who may also have changed the arguments). */
if (d->__last_nonopt > d->optind)
d->__last_nonopt = d->optind;
if (d->__first_nonopt > d->optind)
d->__first_nonopt = d->optind;
if (d->__ordering == PERMUTE)
{
/* If we have just processed some options following some non-options,
exchange them so that the options come first. */
if (d->__first_nonopt != d->__last_nonopt
&& d->__last_nonopt != d->optind)
exchange ((char **) argv, d);
else if (d->__last_nonopt != d->optind)
d->__first_nonopt = d->optind;
/* Skip any additional non-options
and extend the range of non-options previously skipped. */
while (d->optind < argc && NONOPTION_P)
d->optind++;
d->__last_nonopt = d->optind;
}
/* The special ARGV-element `--' means premature end of options.
Skip it like a null option,
then exchange with previous non-options as if it were an option,
then skip everything else like a non-option. */
if (d->optind != argc && !strcmp (argv[d->optind], "--"))
{
d->optind++;
if (d->__first_nonopt != d->__last_nonopt
&& d->__last_nonopt != d->optind)
exchange ((char **) argv, d);
else if (d->__first_nonopt == d->__last_nonopt)
d->__first_nonopt = d->optind;
d->__last_nonopt = argc;
d->optind = argc;
}
/* If we have done all the ARGV-elements, stop the scan
and back over any non-options that we skipped and permuted. */
if (d->optind == argc)
{
/* Set the next-arg-index to point at the non-options
that we previously skipped, so the caller will digest them. */
if (d->__first_nonopt != d->__last_nonopt)
d->optind = d->__first_nonopt;
return -1;
}
/* If we have come to a non-option and did not permute it,
either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P)
{
if (d->__ordering == REQUIRE_ORDER)
return -1;
d->optarg = argv[d->optind++];
return 1;
}
/* We have found another option-ARGV-element.
Skip the initial punctuation. */
d->__nextchar = (argv[d->optind] + 1
+ (longopts != NULL && argv[d->optind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
/* Check whether the ARGV-element is a long option.
If long_only and the ARGV-element has the form "-f", where f is
a valid short option, don't consider it an abbreviated form of
a long option that starts with f. Otherwise there would be no
way to give the -f short option.
On the other hand, if there's a long option "fubar" and
the ARGV-element is "-fu", do consider that an abbreviation of
the long option, just like "--fu", and not "-f" with arg "u".
This distinction seems to be the most useful approach. */
if (longopts != NULL
&& (argv[d->optind][1] == '-'
|| (long_only && (argv[d->optind][2]
|| !strchr (optstring, argv[d->optind][1])))))
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
{
if ((unsigned int) (nameend - d->__nextchar)
== (unsigned int) strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else if (long_only
|| pfound->has_arg != p->has_arg
|| pfound->flag != p->flag
|| pfound->val != p->val)
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (print_errors)
{
#if defined _LIBC && defined USE_IN_LIBIO
char *buf;
if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
argv[0], argv[d->optind]) >= 0)
{
_IO_flockfile (stderr);
int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
__fxprintf (NULL, "%s", buf);
((_IO_FILE *) stderr)->_flags2 = old_flags2;
_IO_funlockfile (stderr);
free (buf);
}
#else
fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
argv[0], argv[d->optind]);
#endif
}
d->__nextchar += strlen (d->__nextchar);
d->optind++;
d->optopt = 0;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
d->optind++;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
d->optarg = nameend + 1;
else
{
if (print_errors)
{
#if defined _LIBC && defined USE_IN_LIBIO
char *buf;
int n;
#endif
if (argv[d->optind - 1][1] == '-')
{
/* --option */
#if defined _LIBC && defined USE_IN_LIBIO
n = __asprintf (&buf, _("\
%s: option `--%s' doesn't allow an argument\n"),
argv[0], pfound->name);
#else
fprintf (stderr, _("\
%s: option `--%s' doesn't allow an argument\n"),
argv[0], pfound->name);
#endif
}
else
{
/* +option or -option */
#if defined _LIBC && defined USE_IN_LIBIO
n = __asprintf (&buf, _("\
%s: option `%c%s' doesn't allow an argument\n"),
argv[0], argv[d->optind - 1][0],
pfound->name);
#else
fprintf (stderr, _("\
%s: option `%c%s' doesn't allow an argument\n"),
argv[0], argv[d->optind - 1][0],
pfound->name);
#endif
}
#if defined _LIBC && defined USE_IN_LIBIO
if (n >= 0)
{
_IO_flockfile (stderr);
int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
((_IO_FILE *) stderr)->_flags2
|= _IO_FLAGS2_NOTCANCEL;
__fxprintf (NULL, "%s", buf);
((_IO_FILE *) stderr)->_flags2 = old_flags2;
_IO_funlockfile (stderr);
free (buf);
}
#endif
}
d->__nextchar += strlen (d->__nextchar);
d->optopt = pfound->val;
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (d->optind < argc)
d->optarg = argv[d->optind++];
else
{
if (print_errors)
{
#if defined _LIBC && defined USE_IN_LIBIO
char *buf;
if (__asprintf (&buf, _("\
%s: option `%s' requires an argument\n"),
argv[0], argv[d->optind - 1]) >= 0)
{
_IO_flockfile (stderr);
int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
((_IO_FILE *) stderr)->_flags2
|= _IO_FLAGS2_NOTCANCEL;
__fxprintf (NULL, "%s", buf);
((_IO_FILE *) stderr)->_flags2 = old_flags2;
_IO_funlockfile (stderr);
free (buf);
}
#else
fprintf (stderr,
_("%s: option `%s' requires an argument\n"),
argv[0], argv[d->optind - 1]);
#endif
}
d->__nextchar += strlen (d->__nextchar);
d->optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
d->__nextchar += strlen (d->__nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/* Can't find it as a long option. If this is not getopt_long_only,
or the option starts with '--' or is not a valid short
option, then it's an error.
Otherwise interpret it as a short option. */
if (!long_only || argv[d->optind][1] == '-'
|| strchr (optstring, *d->__nextchar) == NULL)
{
if (print_errors)
{
#if defined _LIBC && defined USE_IN_LIBIO
char *buf;
int n;
#endif
if (argv[d->optind][1] == '-')
{
/* --option */
#if defined _LIBC && defined USE_IN_LIBIO
n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
argv[0], d->__nextchar);
#else
fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
argv[0], d->__nextchar);
#endif
}
else
{
/* +option or -option */
#if defined _LIBC && defined USE_IN_LIBIO
n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
argv[0], argv[d->optind][0], d->__nextchar);
#else
fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
argv[0], argv[d->optind][0], d->__nextchar);
#endif
}
#if defined _LIBC && defined USE_IN_LIBIO
if (n >= 0)
{
_IO_flockfile (stderr);
int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
__fxprintf (NULL, "%s", buf);
((_IO_FILE *) stderr)->_flags2 = old_flags2;
_IO_funlockfile (stderr);
free (buf);
}
#endif
}
d->__nextchar = (char *) "";
d->optind++;
d->optopt = 0;
return '?';
}
}
/* Look at and handle the next short option-character. */
{
char c = *d->__nextchar++;
char *temp = strchr (optstring, c);
/* Increment `optind' when we start to process its last character. */
if (*d->__nextchar == '\0')
++d->optind;
if (temp == NULL || c == ':')
{
if (print_errors)
{
#if defined _LIBC && defined USE_IN_LIBIO
char *buf;
int n;
#endif
if (d->__posixly_correct)
{
/* 1003.2 specifies the format of this message. */
#if defined _LIBC && defined USE_IN_LIBIO
n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
argv[0], c);
#else
fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
#endif
}
else
{
#if defined _LIBC && defined USE_IN_LIBIO
n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
argv[0], c);
#else
fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
#endif
}
#if defined _LIBC && defined USE_IN_LIBIO
if (n >= 0)
{
_IO_flockfile (stderr);
int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
__fxprintf (NULL, "%s", buf);
((_IO_FILE *) stderr)->_flags2 = old_flags2;
_IO_funlockfile (stderr);
free (buf);
}
#endif
}
d->optopt = c;
return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';')
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = 0;
int option_index;
/* This is an option that requires an argument. */
if (*d->__nextchar != '\0')
{
d->optarg = d->__nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
d->optind++;
}
else if (d->optind == argc)
{
if (print_errors)
{
/* 1003.2 specifies the format of this message. */
#if defined _LIBC && defined USE_IN_LIBIO
char *buf;
if (__asprintf (&buf,
_("%s: option requires an argument -- %c\n"),
argv[0], c) >= 0)
{
_IO_flockfile (stderr);
int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
__fxprintf (NULL, "%s", buf);
((_IO_FILE *) stderr)->_flags2 = old_flags2;
_IO_funlockfile (stderr);
free (buf);
}
#else
fprintf (stderr, _("%s: option requires an argument -- %c\n"),
argv[0], c);
#endif
}
d->optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
return c;
}
else
/* We already incremented `d->optind' once;
increment it again when taking next ARGV-elt as argument. */
d->optarg = argv[d->optind++];
/* optarg is now the argument, see if it's in the
table of longopts. */
for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
{
if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (print_errors)
{
#if defined _LIBC && defined USE_IN_LIBIO
char *buf;
if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
argv[0], argv[d->optind]) >= 0)
{
_IO_flockfile (stderr);
int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
__fxprintf (NULL, "%s", buf);
((_IO_FILE *) stderr)->_flags2 = old_flags2;
_IO_funlockfile (stderr);
free (buf);
}
#else
fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
argv[0], argv[d->optind]);
#endif
}
d->__nextchar += strlen (d->__nextchar);
d->optind++;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
d->optarg = nameend + 1;
else
{
if (print_errors)
{
#if defined _LIBC && defined USE_IN_LIBIO
char *buf;
if (__asprintf (&buf, _("\
%s: option `-W %s' doesn't allow an argument\n"),
argv[0], pfound->name) >= 0)
{
_IO_flockfile (stderr);
int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
((_IO_FILE *) stderr)->_flags2
|= _IO_FLAGS2_NOTCANCEL;
__fxprintf (NULL, "%s", buf);
((_IO_FILE *) stderr)->_flags2 = old_flags2;
_IO_funlockfile (stderr);
free (buf);
}
#else
fprintf (stderr, _("\
%s: option `-W %s' doesn't allow an argument\n"),
argv[0], pfound->name);
#endif
}
d->__nextchar += strlen (d->__nextchar);
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (d->optind < argc)
d->optarg = argv[d->optind++];
else
{
if (print_errors)
{
#if defined _LIBC && defined USE_IN_LIBIO
char *buf;
if (__asprintf (&buf, _("\
%s: option `%s' requires an argument\n"),
argv[0], argv[d->optind - 1]) >= 0)
{
_IO_flockfile (stderr);
int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
((_IO_FILE *) stderr)->_flags2
|= _IO_FLAGS2_NOTCANCEL;
__fxprintf (NULL, "%s", buf);
((_IO_FILE *) stderr)->_flags2 = old_flags2;
_IO_funlockfile (stderr);
free (buf);
}
#else
fprintf (stderr,
_("%s: option `%s' requires an argument\n"),
argv[0], argv[d->optind - 1]);
#endif
}
d->__nextchar += strlen (d->__nextchar);
return optstring[0] == ':' ? ':' : '?';
}
}
d->__nextchar += strlen (d->__nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
d->__nextchar = NULL;
return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':')
{
if (temp[2] == ':')
{
/* This is an option that accepts an argument optionally. */
if (*d->__nextchar != '\0')
{
d->optarg = d->__nextchar;
d->optind++;
}
else
d->optarg = NULL;
d->__nextchar = NULL;
}
else
{
/* This is an option that requires an argument. */
if (*d->__nextchar != '\0')
{
d->optarg = d->__nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
d->optind++;
}
else if (d->optind == argc)
{
if (print_errors)
{
/* 1003.2 specifies the format of this message. */
#if defined _LIBC && defined USE_IN_LIBIO
char *buf;
if (__asprintf (&buf, _("\
%s: option requires an argument -- %c\n"),
argv[0], c) >= 0)
{
_IO_flockfile (stderr);
int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
__fxprintf (NULL, "%s", buf);
((_IO_FILE *) stderr)->_flags2 = old_flags2;
_IO_funlockfile (stderr);
free (buf);
}
#else
fprintf (stderr,
_("%s: option requires an argument -- %c\n"),
argv[0], c);
#endif
}
d->optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
d->optarg = argv[d->optind++];
d->__nextchar = NULL;
}
}
return c;
}
}
int
_getopt_internal (int argc, char *const *argv, const char *optstring,
const struct option *longopts, int *longind, int long_only)
{
int result;
getopt_data.optind = optind;
getopt_data.opterr = opterr;
result = _getopt_internal_r (argc, argv, optstring, longopts,
longind, long_only, &getopt_data);
optind = getopt_data.optind;
optarg = getopt_data.optarg;
optopt = getopt_data.optopt;
return result;
}
int
getopt (int argc, char *const *argv, const char *optstring)
{
return _getopt_internal (argc, argv, optstring,
(const struct option *) 0,
(int *) 0,
0);
}
#endif /* Not ELIDE_CODE. */
#ifdef TEST
/* Compile with -DTEST to make an executable for use in testing
the above definition of `getopt'. */
int
main (int argc, char **argv)
{
int c;
int digit_optind = 0;
while (1)
{
int this_option_optind = optind ? optind : 1;
c = getopt (argc, argv, "abc:d:0123456789");
if (c == -1)
break;
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf ("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf ("option %c\n", c);
break;
case 'a':
printf ("option a\n");
break;
case 'b':
printf ("option b\n");
break;
case 'c':
printf ("option c with value `%s'\n", optarg);
break;
case '?':
break;
default:
printf ("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
printf ("\n");
}
exit (0);
}
#endif /* TEST */
|
the_stack_data/23574520.c | #define BeginProgram void main(int argc, char *argv[])
#define CloseBrace }
#define CommandLineArgument -1
#define Declare int i,j,n,Flag=1;
#define EndOfProgram return;
#define False 0;
#define ForLoop ;for
#define GetCommandLineArgument n=atoi(argv[1]);
#define i F1ag
#define If if
#define Increment ++
#define Is ==
#define LessThan *(c&64)*
#define LessThanOrEqualTo !=
#define Modulo %
#define OpenBrace {
#define PossibleFactor j
#define PossiblePrime i
#define Possib1ePrime (c=getchar())
#define PrimeNumber (c^(!i*n%64));
#define Print putchar
#define SetTo =
#define SmallestPrime 2
#define True 1
#define Variables char c;
#define Zero i%j
BeginProgram
OpenBrace
Declare Variables
GetCommandLineArgument
ForLoop (PossiblePrime SetTo SmallestPrime ;
Possib1ePrime LessThanOrEqualTo CommandLineArgument ;
Increment PossiblePrime)
OpenBrace
F1ag SetTo True
ForLoop (PossibleFactor SetTo SmallestPrime ;
PossibleFactor LessThan PossiblePrime ;
Increment PossibleFactor)
If (PossiblePrime Modulo PossibleFactor Is Zero)
F1ag SetTo False
If (Flag Is True)
Print PrimeNumber
CloseBrace
EndOfProgram
CloseBrace
|
the_stack_data/150142788.c | /* This file exists so that the C Library can be initialized, for when it is
used by a Cabna application. It is initialized before main is called. */
extern void start_threads();
int main (int argc, char** argv) {
start_threads();
return 0;
}
|
the_stack_data/416808.c | #include <stdio.h>
int main(void)
{
char ch;
int i = 0;
while ((ch = getchar()) != '#')
{
if (ch == '.')
{
i++;
putchar('!');
}
else if (ch == '!')
{
i++;
printf("!!");
}
else
putchar(ch);
}
printf("\n%d replaces.\n", i);
return 0;
}
|
the_stack_data/97968.c |
int scilab_rt_mul_i2i2_(int sin00, int sin01, int in0[sin00][sin01],
int sin10, int sin11, int in1[sin10][sin11])
{
int i;
int j;
int val0 = 0;
int val1 = 0;
for (i = 0; i < sin00; ++i) {
for (j = 0; j < sin01; ++j) {
val0 += in0[i][j];
}
}
for (i = 0; i < sin10; ++i) {
for (j = 0; j < sin11; ++j) {
val1 += in1[i][j];
}
}
return val0 + val1;
}
|
the_stack_data/150143400.c | //#include <stdio.h>
/* int for_body(int sum, int i){ */
/* return sum + i; */
/* } */
//int main(){
void main(){
//int i;
int i, sum;
sum = 0;
for (i = 1; i < 10; i++){
//sum = sum + i;
//sum = for_body(sum,i);
}
//printf("Value of sum %d \n",sum);
return;
}
|
the_stack_data/212643407.c | /* csinhl.c */
/*
Contributed by Danny Smith
2005-01-04
*/
#include <math.h>
#include <complex.h>
/* csinh (x + I * y) = sinh (x) * cos (y)
+ I * (cosh (x) * sin (y)) */
long double complex csinhl (long double complex Z)
{
long double complex Res;
__real__ Res = sinhl (__real__ Z) * cosl (__imag__ Z);
__imag__ Res = coshl (__real__ Z) * sinl (__imag__ Z);
return Res;
}
|
the_stack_data/131713.c | /*
* Simple zombie tester
*
* Created by mike.merinoff
* 2014
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void infinite_loop(){
for (;;)
asm ("nop");
}
int main () {
pid_t childPid;
childPid = fork();
if (childPid >= 0) { //success forking
if (childPid == 0) //child here
exit (-1);
if (childPid > 0){ //parent here
printf ("child process forked with pid %i\n", childPid);
infinite_loop();
}
}
else {
printf("TERMINATE! TERMINATE!!\n");
}
return 0;
}
|
the_stack_data/116055.c | #include <stdio.h>
char *strdelc(char *s, char ch)
{int i, j;
for(i=j=0; s[i] != '\0'; i++)
if(s[i] != ch)
s[j++] = s[i];
s[j] = '\0';
return s;
}
int main(void)
{long m = 0, n = 0;
char tmp[1000+1];
while(scanf("%ld %ld", &m, &n) == 2 && m != 0 && n != 0)
{long sum = ((m) + (n));
sprintf(tmp, "%ld", sum);
strdelc(tmp, '0');
printf("%s\n", tmp);
}
return 0;
}
|
the_stack_data/402545.c | #include <stdio.h>
int n,m;
int graph[100][100];
int new_graph[100][100];
int stack[100];
int visited_1[100];
int visited_2[100];
int end=0;
int min=10000;
int ways=1;
int cost[100];
void push(int i)
{
stack[end++]=i;
}
int pop()
{
return stack[--end];
}
void fill_stack(int vertex)
{
visited_1[vertex]=1;
//recur for all neighbouring vertices
for(int i=1;i<=n;i++)
{
if(graph[vertex][i]==1 && visited_1[i]==0)
fill_stack(i);
}
//when there are no neighbouring vertices left for the current vertex the control comes here
push(vertex);
}
void transpose()
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(graph[i][j]==1)
{
new_graph[j][i]=1;
}
if(graph[j][j]==1)
{
new_graph[i][j]=1;
}
}
}
}
void dfs(int vertex)
{
visited_2[vertex]=1;
//vertex is in one strongly connected component
//printf("\n %d %d \n",vertex,cost[vertex]);
//printf("%d %d ",min,ways);
if(cost[vertex]<min)
min=cost[vertex];
else if(cost[vertex]==min)
ways++;
//printf("\n %d %d \n",min,ways);
for(int i=1;i<=n;i++)
{
if(visited_2[i]==0 && new_graph[vertex][i]==1)
{
dfs(i);
}
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&cost[i]);
scanf("%d",&m);
for(int i=0;i<m;i++)
{
int a,b;
scanf("%d %d",&a,&b);
graph[a][b]=1;
}
for(int i=1;i<=n;i++)
{
visited_2[i]=0;
visited_1[i]=0;
}
for(int i=1;i<=n;i++)
{
if(visited_1[i]==0) //that vertex not visited
fill_stack(i);
}
transpose();
int ans_ways=1;
int ans_cost=0;
for(int i=end-1;i>=0;i--)
{
int value=pop();
if(visited_2[value]==0)
{
min=10000;
ways=1;
dfs(value);
//printf("%d %d \n",min,ways);
ans_cost=ans_cost+min;
ans_ways=ans_ways*ways;
}
}
printf("%d %d\n",ans_ways,ans_cost);
return 0;
}
|
the_stack_data/83425.c | /* $OpenBSD: hil.c,v 1.1 1997/07/14 08:14:15 downsj Exp $ */
/* $NetBSD: hil.c,v 1.2 1997/04/14 19:00:10 thorpej Exp $ */
/*
* Copyright (c) 1997 Jason R. Thorpe. All rights reserved.
* Copyright (c) 1988 University of Utah.
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* the Systems Programming Group of the University of Utah Computer
* Science Department.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* from: Utah Hdr: hil.c 1.1 89/08/22
*
* @(#)hil.c 8.1 (Berkeley) 6/10/93
*/
/*
* HIL keyboard routines for the standalone ITE.
*/
#if defined(ITECONSOLE) && defined(HIL_KEYBOARD)
#include <sys/param.h>
#include <sys/device.h> /* XXX */
#include <hp300/dev/hilreg.h>
#include <hp300/dev/kbdmap.h>
#include <hp300/dev/itevar.h>
#include "samachdep.h"
#include "kbdvar.h"
#ifndef SMALL
/*
* HIL cooked keyboard keymaps.
* Supports only unshifted, shifted and control keys.
*/
char hil_us_keymap[] = {
NULL, '`', '\\', ESC, NULL, DEL, NULL, NULL,
'\n', '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\n', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, '\b', NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
ESC, '\r', NULL, '\n', '0', '.', ',', '+',
'1', '2', '3', '-', '4', '5', '6', '*',
'7', '8', '9', '/', 'E', '(', ')', '^',
'1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '-', '=', '[', ']', ';', '\'',
',', '.', '/', '\040', 'o', 'p', 'k', 'l',
'q', 'w', 'e', 'r', 't', 'y', 'u', 'i',
'a', 's', 'd', 'f', 'g', 'h', 'j', 'm',
'z', 'x', 'c', 'v', 'b', 'n', NULL, NULL
};
char hil_us_shiftmap[] = {
NULL, '~', '|', DEL, NULL, DEL, NULL, NULL,
'\n', '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\n', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, DEL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
ESC, '\r', NULL, '\n', '0', '.', ',', '+',
'1', '2', '3', '-', '4', '5', '6', '*',
'7', '8', '9', '/', '`', '|', '\\', '~',
'!', '@', '#', '$', '%', '^', '&', '*',
'(', ')', '_', '+', '{', '}', ':', '\"',
'<', '>', '?', '\040', 'O', 'P', 'K', 'L',
'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I',
'A', 'S', 'D', 'F', 'G', 'H', 'J', 'M',
'Z', 'X', 'C', 'V', 'B', 'N', NULL, NULL
};
char hil_us_ctrlmap[] = {
NULL, '`', '\034', ESC, NULL, DEL, NULL, NULL,
'\n', '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\n', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, '\b', NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
ESC, '\r', NULL, '\n', '0', '.', ',', '+',
'1', '2', '3', '-', '4', '5', '6', '*',
'7', '8', '9', '/', 'E', '(', ')', '\036',
'1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '-', '=', '\033', '\035', ';', '\'',
',', '.', '/', '\040', '\017', '\020', '\013', '\014',
'\021', '\027', '\005', '\022', '\024', '\031', '\025', '\011',
'\001', '\023', '\004', '\006', '\007', '\010', '\012', '\015',
'\032', '\030', '\003', '\026', '\002', '\016', NULL, NULL
};
#ifdef UK_KEYBOARD
char hil_uk_keymap[] = {
NULL, '`', '<', ESC, NULL, DEL, NULL, NULL,
'\n', '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\n', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, '\b', NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
ESC, '\r', NULL, '\n', '0', '.', ',', '+',
'1', '2', '3', '-', '4', '5', '6', '*',
'7', '8', '9', '/', 'E', '(', ')', '^',
'1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '+', '\'', '[', ']', '*', '\\',
',', '.', '-', '\040', 'o', 'p', 'k', 'l',
'q', 'w', 'e', 'r', 't', 'y', 'u', 'i',
'a', 's', 'd', 'f', 'g', 'h', 'j', 'm',
'z', 'x', 'c', 'v', 'b', 'n', NULL, NULL
};
char hil_uk_shiftmap[] = {
NULL, '~', '>', DEL, NULL, DEL, NULL, NULL,
'\n', '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\n', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, DEL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
ESC, '\r', NULL, '\n', '0', '.', ',', '+',
'1', '2', '3', '-', '4', '5', '6', '*',
'7', '8', '9', '/', '`', '|', '\\', '~',
'!', '\"', '#', '$', '%', '&', '^', '(',
')', '=', '?', '/', '{', '}', '@', '|',
';', ':', '_', '\040', 'O', 'P', 'K', 'L',
'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I',
'A', 'S', 'D', 'F', 'G', 'H', 'J', 'M',
'Z', 'X', 'C', 'V', 'B', 'N', NULL, NULL
};
char hil_uk_ctrlmap[] = {
NULL, '`', '<', ESC, NULL, DEL, NULL, NULL,
'\n', '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\n', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, '\t', NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, '\b', NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
ESC, '\r', NULL, '\n', '0', '.', ',', '+',
'1', '2', '3', '-', '4', '5', '6', '*',
'7', '8', '9', '/', 'E', '(', ')', '\036',
'1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '+', '\'', '\033', '\035', '*', '\034',
',', '.', '/', '\040', '\017', '\020', '\013', '\014',
'\021', '\027', '\005', '\022', '\024', '\031', '\025', '\011',
'\001', '\023', '\004', '\006', '\007', '\010', '\012', '\015',
'\032', '\030', '\003', '\026', '\002', '\016', NULL, NULL
};
#endif
/*
* The keyboard map table.
* Lookup is by hardware returned language code.
*/
struct kbdmap hilkbd_map[] = {
KBD_US, NULL,
hil_us_keymap, hil_us_shiftmap, hil_us_ctrlmap, NULL, NULL,
#ifdef UK_KEYBOARD
KBD_UK, NULL,
hil_uk_keymap, hil_uk_shiftmap, hil_uk_ctrlmap, NULL, NULL,
#endif
0, NULL,
NULL, NULL, NULL, NULL, NULL,
};
char *hilkbd_keymap = hil_us_keymap;
char *hilkbd_shiftmap = hil_us_shiftmap;
char *hilkbd_ctrlmap = hil_us_ctrlmap;
int
hilkbd_getc()
{
int status, c;
struct hil_dev *hiladdr = HILADDR;
status = hiladdr->hil_stat;
if ((status & HIL_DATA_RDY) == 0)
return(0);
c = hiladdr->hil_data;
switch ((status>>KBD_SSHIFT) & KBD_SMASK) {
case KBD_SHIFT:
c = hilkbd_shiftmap[c & KBD_CHARMASK];
break;
case KBD_CTRL:
c = hilkbd_ctrlmap[c & KBD_CHARMASK];
break;
case KBD_KEY:
c = hilkbd_keymap[c & KBD_CHARMASK];
break;
default:
c = 0;
break;
}
return(c);
}
#endif /* SMALL */
void
hilkbd_nmi()
{
struct hil_dev *hiladdr = HILADDR;
HILWAIT(hiladdr);
hiladdr->hil_cmd = HIL_CNMT;
HILWAIT(hiladdr);
hiladdr->hil_cmd = HIL_CNMT;
HILWAIT(hiladdr);
printf("\nboot interrupted\n");
}
int
hilkbd_init()
{
struct hil_dev *hiladdr = HILADDR;
struct kbdmap *km;
u_char lang;
/*
* Determine the existence of a HIL keyboard.
*/
HILWAIT(hiladdr);
hiladdr->hil_cmd = HIL_READKBDSADR;
HILDATAWAIT(hiladdr);
lang = hiladdr->hil_data;
if (lang == 0)
return (0);
HILWAIT(hiladdr);
hiladdr->hil_cmd = HIL_SETARR;
HILWAIT(hiladdr);
hiladdr->hil_data = ar_format(KBD_ARR);
HILWAIT(hiladdr);
hiladdr->hil_cmd = HIL_READKBDLANG;
HILDATAWAIT(hiladdr);
lang = hiladdr->hil_data;
for (km = hilkbd_map; km->kbd_code; km++) {
if (km->kbd_code == lang) {
hilkbd_keymap = km->kbd_keymap;
hilkbd_shiftmap = km->kbd_shiftmap;
hilkbd_ctrlmap = km->kbd_ctrlmap;
}
}
HILWAIT(hiladdr);
hiladdr->hil_cmd = HIL_INTON;
}
#endif /* ITECONSOLE && HIL_KEYBOARD */
|
the_stack_data/1094872.c | /*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2015 RDK Management
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**********************************************************************
Copyright [2014] [Cisco Systems, Inc.]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include <sys/socket.h>
#include <features.h>
#include <linux/if_packet.h>
#include <netinet/if_ether.h>
#include <linux/if_ether.h>
#include <errno.h>
#include <sys/ioctl.h>
#include<net/if.h>
//#include<net/ethernet.h>
//#include<linux/ip.h>
#include <netinet/ip.h>
#include<netinet/ip6.h>
#include<linux/tcp.h>
#include<arpa/inet.h>
#include<string.h>
#include<sys/time.h>
#include<unistd.h>
#include <netinet/ether.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <ifaddrs.h>
#define HDRLEN 62
#define MAX_IPLEN INET6_ADDRSTRLEN
//starts with "0x0a 0x0d"
unsigned char http_redirect_payload2[] = { \
0x2f,0x48,0x6e,0x61,0x70,0x50,0x63,0x53,0x69,0x74, \
0x65,0x42,0x6c,0x6f,0x63,0x6b,0x65,0x64,0x2e,0x70,0x68,0x70,0x3f,0x75,0x72,0x6c, 0x3d \
}; //ends with "url=", add "www.xxx.com"
const unsigned char http_redirect_payload_bottom[] = { \
0x0d,0x0a, \
0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x74,0x79,0x70,0x65,0x3a,0x20,0x74,0x65, \
0x78,0x74,0x2f,0x68,0x74,0x6d,0x6c,0x0d,0x0a,0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74, \
0x2d,0x4c,0x65,0x6e,0x67,0x74,0x68,0x3a,0x20,0x30,0x0d,0x0a, \
0x44,0x61,0x74,0x65,0x3a,0x20,0x4d,0x6f,0x6e,0x2c,0x20,0x31,0x36,0x20,0x53,0x65, \
0x70,0x20,0x32,0x30,0x31,0x33,0x20,0x30,0x30,0x3a,0x33,0x33,0x3a,0x33,0x35,0x20, \
0x47,0x4d,0x54,0x0d,0x0a, \
0x53,0x65,0x72,0x76, 0x65,0x72,0x3a,0x20,0x6c,0x69,0x67,0x68,0x74,0x74,0x70,0x64, \
0x0d,0x0a,0x0d,0x0a \
};
//assuming max url length is 256
unsigned char http_redirect_payload[HDRLEN+MAX_IPLEN + 2 +sizeof(http_redirect_payload2)+256+sizeof(http_redirect_payload_bottom)] = { \
0x48,0x54,0x54,0x50,0x2f,0x31,0x2e,0x31,0x20,0x33,0x30,0x32,0x20,0x46,0x6f,0x75, \
0x6e,0x64,0x0d,0x0a,0x58,0x2d,0x50,0x6f,0x77,0x65,0x72,0x65,0x64,0x2d,0x42,0x79, \
0x3a,0x20,0x50,0x48,0x50,0x2f,0x35,0x2e,0x33,0x2e,0x32,0x0d,0x0a,0x4c,0x6f,0x63, \
0x61,0x74,0x69,0x6f,0x6e,0x3a,0x20,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f \
}; //ends with http://, add "192.168.0.1"
typedef struct PseudoHeader {
u_int32_t source_ip;
u_int32_t dest_ip;
u_int8_t reserved;
u_int8_t protocol;
u_int16_t tcp_length;
} PseudoHeader;
typedef struct PseudoHeaderv6 {
u_int8_t source_ipv6[16];
u_int8_t dest_ipv6[16];
u_int32_t up_len;
u_int8_t reserved[3];
u_int8_t next_hdr;
} PseudoHeaderv6;
unsigned short tcp_checksum(unsigned short *buffer, int byte_count)
{
register long word_sum;
int word_count;
int i;
word_sum = 0;
word_count = byte_count >> 1;
for(i = 0; i < word_count ; i++) {
word_sum += buffer[i];
}
if( byte_count & 1 ) {
word_sum += *(unsigned char*)&buffer[i];
}
unsigned short carry = (unsigned short) (word_sum >> 16);
while (0 != carry)
{
word_sum = (word_sum & 0xffff) + carry;
carry = (unsigned short) (word_sum >> 16);
}
return (short)(~word_sum);
}
int SendRawPacket(int rawsock, unsigned char *pkt, int pkt_len, char *dstIp, unsigned short dstPort)
{
int sent= 0;
struct sockaddr_in to;
to.sin_family = AF_INET;
to.sin_addr.s_addr = inet_addr(dstIp); // you can also use inet_aton()
to.sin_port = htons(dstPort);
memset(to.sin_zero, '\0', sizeof(to.sin_zero));
if((sent = write(rawsock, pkt, pkt_len)) != pkt_len)
{
/* Error */
printf("Could only send %d bytes of packet of length %d\n", sent, pkt_len);
return 0;
}
return 1;
}
struct ethhdr* CreateEthernetHeader(char *src_mac, char *dst_mac, int protocol)
{
struct ethhdr *ethernet_header;
ethernet_header = (struct ethhdr *)malloc(sizeof(struct ethhdr));
/* copy the Src mac addr */
memcpy(ethernet_header->h_source, (void *)ether_aton(src_mac), 6);
/* copy the Dst mac addr */
memcpy(ethernet_header->h_dest, (void *)ether_aton(dst_mac), 6);
/* copy the protocol */
ethernet_header->h_proto = htons(protocol);
/* done ...send the header back */
return (ethernet_header);
}
/* ComputeChecksum() */
unsigned short ComputeChecksum( void *data, unsigned long length )
{
unsigned short *tempUshort = NULL,
UshortForPadding = 0;
unsigned long checksum = 0;
/*
* retrieve the shortcut pointer
*/
tempUshort = (unsigned short*)data;
/*
* loop to calculate the check sum
*/
while ( length > 1 )
{
checksum += *tempUshort;
tempUshort++;
/*
* if high-order bit set, fold
*/
if ( checksum & 0x80000000 )
{
checksum = ( checksum & 0xFFFF ) + ( checksum >> 16 );
}
/*
* modify length
*/
length -= 2;
}
/*
* take care of left over bytes.
* note: although it's impossible...
*/
if ( length )
{
UshortForPadding = 0;
*(unsigned char*)&UshortForPadding = *(unsigned char*)tempUshort;
checksum += UshortForPadding;
}
/*
* fold the result checksum
*/
while ( checksum >> 16 )
{
checksum = ( checksum & 0xFFFF ) + ( checksum >> 16 );
}
/*
* return complement of checksum
*/
return ~((unsigned short)checksum);
}
void *CreateIPHeader(int family, char *srcIp, char *dstIp, unsigned int dataSize)
{
if(family == AF_INET6){
struct ip6_hdr *ipv6Hdr = malloc(sizeof(struct ip6_hdr));
if(ipv6Hdr == NULL)
return NULL;
memset(ipv6Hdr, 0, sizeof(struct ip6_hdr));
ipv6Hdr->ip6_flow = 0x60000000;/* version = 6; flowlab = 0;triffic class = 0; */
ipv6Hdr->ip6_plen = htons(sizeof(struct tcphdr) + dataSize);
ipv6Hdr->ip6_nxt = IPPROTO_TCP;
ipv6Hdr->ip6_hops = 60;
inet_pton(AF_INET6, srcIp, &(ipv6Hdr->ip6_src));
inet_pton(AF_INET6, dstIp, &(ipv6Hdr->ip6_dst));
return (ipv6Hdr);
}else{
struct iphdr *ip_header;
ip_header = (struct iphdr *)malloc(sizeof(struct iphdr));
ip_header->version = 4;
ip_header->ihl = (sizeof(struct iphdr))/4 ;
ip_header->tos = 0;
ip_header->tot_len = htons(sizeof(struct iphdr) + sizeof(struct tcphdr) + dataSize);
ip_header->id = htons(111);
ip_header->frag_off = 0;
ip_header->ttl = 111;
ip_header->protocol = IPPROTO_TCP;
ip_header->check = 0; /* We will calculate the checksum later */
ip_header->saddr = inet_addr(srcIp);
ip_header->daddr = inet_addr(dstIp);
/* Calculate the IP checksum now :
The IP Checksum is only over the IP header */
ip_header->check = ComputeChecksum((unsigned char *)ip_header, ip_header->ihl*4);
return (ip_header);
}
}
struct tcphdr *CreateTcpHeader(int family, unsigned short sport, unsigned short dport, unsigned long seqNum, unsigned long ackNum, unsigned char fin)
{
struct tcphdr *tcp_header;
/* Check /usr/include/linux/tcp.h for header definiation */
tcp_header = (struct tcphdr *)malloc(sizeof(struct tcphdr));
tcp_header->source = htons(sport);
tcp_header->dest = htons(dport);
tcp_header->seq = htonl(seqNum);
tcp_header->ack_seq = htonl(ackNum);
tcp_header->res1 = 0;
tcp_header->doff = (sizeof(struct tcphdr))/4;
tcp_header->psh = 1;
tcp_header->fin = fin;
tcp_header->ack = 1;
tcp_header->window = htons(14608);
tcp_header->check = 0; /* Will calculate the checksum with pseudo-header later */
tcp_header->urg_ptr = 0;
return (tcp_header);
}
void CreatePseudoHeaderAndComputeTcpChecksum(int family, struct tcphdr *tcp_header, void *ip_header, unsigned char *data, unsigned int dataSize)
{
unsigned char *hdr = NULL;
int pseudo_offset = 0;
int header_len;
/*The TCP Checksum is calculated over the PseudoHeader + TCP header +Data*/
if(family == AF_INET){
struct iphdr *ipv4_header = ip_header;
/* Find the size of the TCP Header + Data */
int segment_len = ntohs(ipv4_header->tot_len) - ipv4_header->ihl*4;
/* Total length over which TCP checksum will be computed */
header_len = sizeof(PseudoHeader) + segment_len;
/* Allocate the memory */
hdr = (unsigned char *)malloc(header_len);
if(hdr == NULL)
return;
pseudo_offset = sizeof(PseudoHeader);
/* Fill in the pseudo header first */
PseudoHeader *pseudo_header = (PseudoHeader *)hdr;
pseudo_header->source_ip = ipv4_header->saddr;
pseudo_header->dest_ip = ipv4_header->daddr;
pseudo_header->reserved = 0;
pseudo_header->protocol = ipv4_header->protocol;
pseudo_header->tcp_length = htons(segment_len);
}else{
struct ip6_hdr *ipv6_header = ip_header;
/* total len = pseudo header length + tcp length */
header_len = sizeof(PseudoHeaderv6) + ntohs(ipv6_header->ip6_plen);
/* Allocate the memory */
hdr = (unsigned char *)malloc(header_len);
if(hdr == NULL)
return;
pseudo_offset = sizeof(PseudoHeaderv6);
PseudoHeaderv6 *pseudo_header = (PseudoHeaderv6 *)hdr;
memcpy(pseudo_header->source_ipv6, &(ipv6_header->ip6_src), 16);
memcpy(pseudo_header->dest_ipv6, &(ipv6_header->ip6_dst), 16);
pseudo_header->up_len = ipv6_header->ip6_plen;
memset(pseudo_header->reserved, 0, 3);
pseudo_header->next_hdr = ipv6_header->ip6_nxt;
}
/* Now copy TCP */
memcpy((hdr + pseudo_offset), (void *)tcp_header, tcp_header->doff*4);
/* Now copy the Data */
memcpy((hdr + pseudo_offset + tcp_header->doff*4), data, dataSize);
/* Calculate the Checksum */
tcp_header->check = tcp_checksum((unsigned short *)hdr, header_len);
/* Free the PseudoHeader */
free(hdr);
return ;
}
unsigned char *CreateData(int family, char *url, char *gwIp)
{
unsigned char *data = http_redirect_payload;
int offset = 0;
if(family == AF_INET){
offset = strlen(gwIp);
memcpy(http_redirect_payload + HDRLEN, gwIp, offset);
}else{
offset = strlen(gwIp);
memcpy(http_redirect_payload + HDRLEN, "[", 1);
memcpy(http_redirect_payload + HDRLEN + 1, gwIp, offset);
memcpy(http_redirect_payload + HDRLEN + offset + 1 , "]",1);
offset += 2;
}
memcpy(http_redirect_payload + HDRLEN + offset, http_redirect_payload2, sizeof(http_redirect_payload2));
memcpy(http_redirect_payload + HDRLEN + offset + sizeof(http_redirect_payload2), url, strlen(url));
memcpy(http_redirect_payload + HDRLEN + offset + sizeof(http_redirect_payload2) + strlen(url), http_redirect_payload_bottom, sizeof(http_redirect_payload_bottom));
return data;
}
void send_tcp_pkt(char *interface,int family, char *srcMac, char *dstMac, char *srcIp, char *dstIp, unsigned short srcPort, unsigned short dstPort, unsigned long seqNum, unsigned long ackNum, char *url, unsigned char rst)
{
int raw;
unsigned char *packet;
struct sockaddr_ll socket_ll;
struct ifreq inf_request;
struct ethhdr* ethernet_header;
void *ip_header;
struct tcphdr *tcp_header;
unsigned char *data;
int pkt_len;
int ip_offset;
unsigned int dataSize;
char gwIp[INET6_ADDRSTRLEN] = {'\0'};
if(family == AF_INET){
FILE *fp = fopen("/var/.gwip", "r");
if(fp != NULL){
fgets(gwIp, sizeof("255.255.255.255"), fp);
fclose(fp);
}
}else{
struct ifaddrs *ifaddr, *ifa;
if (getifaddrs(&ifaddr) == 0 ){
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL)
continue;
if(0 == strcmp(ifa->ifa_name, interface) && \
ifa->ifa_addr->sa_family == AF_INET6){
struct sockaddr_in6 *addr = (struct sockaddr_in6 *)(ifa->ifa_addr);
inet_ntop(AF_INET6, &(addr->sin6_addr), gwIp, INET6_ADDRSTRLEN);
if(strncmp("fe80", gwIp, 4) != 0)
break;
}
}
freeifaddrs(ifaddr);
}
}
if(gwIp[0] == '\0')
return;
dataSize = HDRLEN + strlen(gwIp) + sizeof(http_redirect_payload2) + strlen(url) + sizeof(http_redirect_payload_bottom);
/* Create the raw socket */
raw = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if(-1 == raw)
{
perror("Error creating raw socket: ");
exit(-1);
}
/* Bind raw socket to interface */
bzero(&socket_ll, sizeof(socket_ll));
bzero(&inf_request, sizeof(inf_request));
/* First Get the Interface Index */
/*CID 135235 : BUFFER_SIZE_WARNING */
strncpy((char *)inf_request.ifr_name, interface, sizeof(inf_request.ifr_name)-1);
inf_request.ifr_name[sizeof(inf_request.ifr_name)-1] = '\0';
if(-1 == (ioctl(raw, SIOCGIFINDEX, &inf_request)))
{
printf("Error getting Interface index !\n");
exit(-1);
}
/* Bind our raw socket to this interface */
socket_ll.sll_family = AF_PACKET;
socket_ll.sll_ifindex = inf_request.ifr_ifindex;
socket_ll.sll_protocol = htons(ETH_P_ALL);
if(-1 == (bind(raw, (struct sockaddr *)&socket_ll, sizeof(socket_ll))))
{
perror("Error binding raw socket to interface\n");
exit(-1);
}
/* create Ethernet header */
ethernet_header = CreateEthernetHeader(srcMac, dstMac, family == AF_INET ? ETHERTYPE_IP : ETHERTYPE_IPV6);
/* Create IP Header */
ip_header = CreateIPHeader(family, srcIp, dstIp, dataSize);
/* Create TCP Header */
tcp_header = CreateTcpHeader(family, srcPort, dstPort, seqNum, ackNum, rst);
/* Create Data */
data = CreateData(family, url, gwIp);
/* Create PseudoHeader and compute TCP Checksum */
CreatePseudoHeaderAndComputeTcpChecksum(family, tcp_header, ip_header, data, dataSize);
/* Packet length = ETH + IP header + TCP header + Data*/
if(family == AF_INET){
struct iphdr *ip4_header = ip_header;
pkt_len = sizeof(struct ethhdr) + ntohs(ip4_header->tot_len);
ip_offset = ip4_header->ihl*4;
}else{
struct ip6_hdr *ipv6_header = ip_header;
pkt_len = sizeof(struct ethhdr) + sizeof(struct ip6_hdr) + ntohs(ipv6_header->ip6_plen);
ip_offset = sizeof(struct ip6_hdr);
}
/* Allocate memory */
packet = (unsigned char *)malloc(pkt_len);
/* Copy the Ethernet header first */
memcpy(packet, ethernet_header, sizeof(struct ethhdr));
/* Copy the IP header -- but after the ethernet header */
memcpy((packet + sizeof(struct ethhdr)), ip_header, ip_offset);
/* Copy the TCP header after the IP header */
memcpy((packet + sizeof(struct ethhdr) + ip_offset),tcp_header, tcp_header->doff*4);
/* Copy the Data after the TCP header */
memcpy((packet + sizeof(struct ethhdr) + ip_offset + tcp_header->doff*4), data, dataSize);
/* send the packet on the wire */
if(!SendRawPacket(raw, packet, pkt_len, dstIp, dstPort)) {
perror("Error sending packet");
}
else {
//printf("Packet sent successfully\n");
}
/* Free the headers back to the heavenly heap */
free(ethernet_header);
free(ip_header);
free(tcp_header);
free(packet);
close(raw);
return;
}
#if 0
int main(int argc, char **argv)
{
//void send_tcp_pkt(char *interface,int family, char *srcMac, char *dstMac, char *srcIp, char *dstIp, unsigned short srcPort, unsigned short dstPort, unsigned long seqNum, unsigned long ackNum, char *url, unsigned char rst)
send_tcp_pkt(argv[1], atoi(argv[2]), argv[3], argv[4], argv[5], argv[6],atol(argv[7]), atol(argv[8]), strtoul(argv[9], NULL, 10), strtoul(argv[10], NULL, 10), argv[11], 1);
return 0;
}
#endif
|
the_stack_data/44625.c | /*
============================================================================
Description : 将字符串数组进行排序
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sort(char **array1, int num1,
char(*array2)[30], int num2,
char ***myp3, int *num3) {
if (array1 == NULL || array2 == NULL || myp3 == NULL || num3 == NULL) {
return -1;
}
//char *buf[]
int n = num1 + num2;
char **p = malloc(n * sizeof(char *)); //sizeof(char *)
if (p == NULL) {
return -1;
}
int i = 0;
for (i = 0; i < num1; i++) {
p[i] = malloc(strlen(array1[i]) + 1); //加上字符串结束符字符‘\0’
if (p[i] != NULL) {
strcpy(p[i], array1[i]);
}
}
int j = 0;
for (i = num1, j = 0; i < n; i++, j++) {
p[i] = malloc(strlen(array2[j]) + 1);
if (p[i] != NULL) {
strcpy(p[i], array2[j]);
}
}
//选择法排序,交换的是指针变量的值,即交换的是指针的指向
char *tmp = NULL;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (strcmp(p[i], p[j]) > 0) {
tmp = p[i];
p[i] = p[j];
p[j] = tmp;
}
}
}
//间接赋值
*myp3 = p;
*num3 = n;
return 0;
}
void printBuf(char **p, int n) {
int i = 0;
for (i = 0; i < n; i++) {
printf("%s\n", p[i]);
}
}
void freeBuf(char ***p, int n) {
if (p == NULL) {
return;
}
char **tmp = *p; //还原二级指针
int i = 0;
for (i = 0; i < n; i++) {
if (tmp[i] != NULL) {
free(tmp[i]);
tmp[i] = NULL;
}
}
if (tmp != NULL) {
free(tmp);
*p = NULL;
}
}
int main() {
int ret = 0;
char *p1[] = {"aa", "ccccccc", "bbbbbb"};
char buf2[10][30] = {"111111", "3333333", "222222"};
char **p3 = NULL;
int len1, len2, len3, i = 0;
len1 = sizeof(p1) / sizeof(*p1);
len2 = 3;
//通过形参改变实参的值
ret = sort(p1, len1, buf2, len2, &p3, &len3);
if (ret != 0) {
printf("sort err: %d\n", ret);
return ret;
}
printBuf(p3, len3);
freeBuf(&p3, len3);
printf("\n");
system("pause");
return 0;
} |
the_stack_data/63163.c | #include <stdio.h>
#include <stdlib.h>
extern void min_caml_start(char *, char *);
/* "stderr" is a macro and cannot be referred to in libmincaml.S, so
this "min_caml_stderr" is used (in place of "__iob+32") for better
portability (under SPARC emulators, for example). Thanks to Steven
Shaw for reporting the problem and proposing this solution. */
FILE *min_caml_stderr;
int main() {
char *hp, *sp;
min_caml_stderr = stderr;
sp = alloca(1000000); hp = malloc(4000000);
if (hp == NULL || sp == NULL) {
fprintf(stderr, "malloc or alloca failed\n");
return 1;
}
fprintf(stderr, "sp = %p, hp = %p\n", sp, hp);
min_caml_start(sp, hp);
return 0;
}
|
the_stack_data/1213820.c | /*-
* Copyright (c) 1983 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef lint
char copyright[] =
"@(#) Copyright (c) 1983 The Regents of the University of California.\n\
All rights reserved.\n";
#endif /* not lint */
#ifndef lint
static char sccsid[] = "@(#)tc1.c 5.3 (Berkeley) 4/12/91";
#endif /* not lint */
/*
* tc1 [term]
* dummy program to test termlib.
* gets entry, counts it, and prints it.
*/
#include <stdio.h>
char buf[1024];
char *getenv();
main(argc, argv) char **argv; {
char *p;
int rc;
if (argc < 2)
p = getenv("TERM");
else
p = argv[1];
rc = tgetent(buf,p);
printf("tgetent returns %d, len=%d, text=\n'%s'\n",rc,strlen(buf),buf);
}
|
the_stack_data/34512950.c | #include <stdio.h>
int main (void)
{
int dia, mes, ano;
printf("Insira uma data: ");
scanf("%d %d %d", &dia, &mes, &ano);
if (valida(dia, mes, ano) == 1)
{
printf("Data valida\n");
printf("O ultimo dia deste mes eh: %d\n", ultimo_dia(mes, ano));
if (bissexto(ano)==1)
printf("Este ano eh bissexto!\n");
else
printf("Este ano nao eh bissexto!\n");
exibe_ds(dia, mes, ano);
}
else
{
printf("Data invalida\n");
}
return 0;
}
int valida (int d, int m, int a)
{
if (m==2 && bissexto(a) == 1 && (d>29 || d<1)){
return 0;
}
else if (m==2 && bissexto(a) == 0 && (d>28 || d<1)){
return 0;
}
if ((m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) && (d>31 || d<1))
return 0;
if ((m == 4 || m == 6 || m == 9 || m == 11) && (d>30 || d<1))
return 0;
if(m > 12 || m<1 || a<1){
}
else
return 1;
}
int ultimo_dia(int m,int a)
{
if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12)
return 31;
if (m == 4 || m == 6 || m == 9 || m == 11)
return 30;
if (m == 2 && bissexto(a)==1)
return 29;
if (m == 2 && bissexto(a)==0)
return 28;
}
int bissexto (a)
{
if (a % 400 == 0) {
return 1;
}
else if ((a % 4 == 0) && (a % 100 != 0)) {
return 1;
}
else {
return 0;
}
}
int exibe_ds(int d, int m, int a)
{
if ((m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10) && (d<31)){
d += 1;
printf("O proximo dia eh : %d/%d/%d\n", d, m, a);
return 0;
}
if ((m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10) && (d==31)){
m += 1;
d = 1;
printf("O proximo dia eh : %d/%d/%d\n", d, m, a);
return 0;
}
if ((m == 4 || m == 6 || m == 9 || m == 11) && (d<30)){
d += 1;
printf("O proximo dia eh : %d/%d/%d\n", d, m, a);
return 0;
}
if ((m == 4 || m == 6 || m == 9 || m == 11) && (d==30)){
m += 1;
d = 1;
printf("O proximo dia eh : %d/%d/%d\n", d, m, a);
return 0;
}
if ((m==2 && bissexto(a)==1) &&(d < 29)){
d += 1;
printf("O proximo dia eh : %d/%d/%d\n", d, m, a);
return 0;
}
if ((m==2 && bissexto(a)==1) &&(d== 29)){
m += 1;
d = 1;
printf("O proximo dia eh : %d/%d/%d\n", d, m, a);
return 0;
}
if ((m==2 && bissexto(a)==0) &&(d < 28)){
d += 1;
printf("O proximo dia eh : %d/%d/%d\n", d, m, a);
return 0;
}
if ((m==2 && bissexto(a)==0) &&(d== 28)){
m += 1;
d = 1;
printf("O proximo dia eh : %d/%d/%d\n", d, m, a);
return 0;
}
if ((m==12) &&(d==31)){
m = 1;
d = 1;
a += 1;
printf("O proximo dia eh : %d/%d/%d\n", d, m, a);
return 0;
}
}
|
the_stack_data/152150.c | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
struct sum {int /*<<< orphan*/ rsc; } ;
struct ct_mixer {struct sum** sums; struct amixer** amixers; } ;
struct amixer {TYPE_1__* ops; int /*<<< orphan*/ rsc; } ;
typedef enum CT_AMIXER_CTL { ____Placeholder_CT_AMIXER_CTL } CT_AMIXER_CTL ;
struct TYPE_2__ {int /*<<< orphan*/ (* setup ) (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;} ;
/* Variables and functions */
int AMIXER_LINEIN ;
int AMIXER_LINEIN_C ;
int AMIXER_MASTER_F ;
int AMIXER_MASTER_F_C ;
int AMIXER_MASTER_S ;
int AMIXER_MIC ;
int AMIXER_MIC_C ;
int AMIXER_PCM_F ;
int AMIXER_PCM_F_C ;
int AMIXER_PCM_S ;
int AMIXER_SPDIFI ;
int AMIXER_SPDIFI_C ;
int AMIXER_SPDIFO ;
int AMIXER_WAVE_F ;
int AMIXER_WAVE_S ;
int CHN_NUM ;
int /*<<< orphan*/ INIT_VOL ;
int SUM_IN_F ;
int SUM_IN_F_C ;
int /*<<< orphan*/ stub1 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub10 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub11 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub12 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub13 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub14 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub15 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub16 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub17 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub18 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub19 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub2 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub20 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub21 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub22 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub23 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub24 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub3 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub4 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub5 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub6 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub7 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub8 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
int /*<<< orphan*/ stub9 (struct amixer*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,struct sum*) ;
__attribute__((used)) static int ct_mixer_topology_build(struct ct_mixer *mixer)
{
struct sum *sum;
struct amixer *amix_d, *amix_s;
enum CT_AMIXER_CTL i, j;
/* Build topology from destination to source */
/* Set up Master mixer */
for (i = AMIXER_MASTER_F, j = SUM_IN_F;
i <= AMIXER_MASTER_S; i++, j++) {
amix_d = mixer->amixers[i*CHN_NUM];
sum = mixer->sums[j*CHN_NUM];
amix_d->ops->setup(amix_d, &sum->rsc, INIT_VOL, NULL);
amix_d = mixer->amixers[i*CHN_NUM+1];
sum = mixer->sums[j*CHN_NUM+1];
amix_d->ops->setup(amix_d, &sum->rsc, INIT_VOL, NULL);
}
/* Set up Wave-out mixer */
for (i = AMIXER_WAVE_F, j = AMIXER_MASTER_F;
i <= AMIXER_WAVE_S; i++, j++) {
amix_d = mixer->amixers[i*CHN_NUM];
amix_s = mixer->amixers[j*CHN_NUM];
amix_d->ops->setup(amix_d, &amix_s->rsc, INIT_VOL, NULL);
amix_d = mixer->amixers[i*CHN_NUM+1];
amix_s = mixer->amixers[j*CHN_NUM+1];
amix_d->ops->setup(amix_d, &amix_s->rsc, INIT_VOL, NULL);
}
/* Set up S/PDIF-out mixer */
amix_d = mixer->amixers[AMIXER_SPDIFO*CHN_NUM];
amix_s = mixer->amixers[AMIXER_MASTER_F*CHN_NUM];
amix_d->ops->setup(amix_d, &amix_s->rsc, INIT_VOL, NULL);
amix_d = mixer->amixers[AMIXER_SPDIFO*CHN_NUM+1];
amix_s = mixer->amixers[AMIXER_MASTER_F*CHN_NUM+1];
amix_d->ops->setup(amix_d, &amix_s->rsc, INIT_VOL, NULL);
/* Set up PCM-in mixer */
for (i = AMIXER_PCM_F, j = SUM_IN_F; i <= AMIXER_PCM_S; i++, j++) {
amix_d = mixer->amixers[i*CHN_NUM];
sum = mixer->sums[j*CHN_NUM];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
amix_d = mixer->amixers[i*CHN_NUM+1];
sum = mixer->sums[j*CHN_NUM+1];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
}
/* Set up Line-in mixer */
amix_d = mixer->amixers[AMIXER_LINEIN*CHN_NUM];
sum = mixer->sums[SUM_IN_F*CHN_NUM];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
amix_d = mixer->amixers[AMIXER_LINEIN*CHN_NUM+1];
sum = mixer->sums[SUM_IN_F*CHN_NUM+1];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
/* Set up Mic-in mixer */
amix_d = mixer->amixers[AMIXER_MIC*CHN_NUM];
sum = mixer->sums[SUM_IN_F*CHN_NUM];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
amix_d = mixer->amixers[AMIXER_MIC*CHN_NUM+1];
sum = mixer->sums[SUM_IN_F*CHN_NUM+1];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
/* Set up S/PDIF-in mixer */
amix_d = mixer->amixers[AMIXER_SPDIFI*CHN_NUM];
sum = mixer->sums[SUM_IN_F*CHN_NUM];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
amix_d = mixer->amixers[AMIXER_SPDIFI*CHN_NUM+1];
sum = mixer->sums[SUM_IN_F*CHN_NUM+1];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
/* Set up Master recording mixer */
amix_d = mixer->amixers[AMIXER_MASTER_F_C*CHN_NUM];
sum = mixer->sums[SUM_IN_F_C*CHN_NUM];
amix_d->ops->setup(amix_d, &sum->rsc, INIT_VOL, NULL);
amix_d = mixer->amixers[AMIXER_MASTER_F_C*CHN_NUM+1];
sum = mixer->sums[SUM_IN_F_C*CHN_NUM+1];
amix_d->ops->setup(amix_d, &sum->rsc, INIT_VOL, NULL);
/* Set up PCM-in recording mixer */
amix_d = mixer->amixers[AMIXER_PCM_F_C*CHN_NUM];
sum = mixer->sums[SUM_IN_F_C*CHN_NUM];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
amix_d = mixer->amixers[AMIXER_PCM_F_C*CHN_NUM+1];
sum = mixer->sums[SUM_IN_F_C*CHN_NUM+1];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
/* Set up Line-in recording mixer */
amix_d = mixer->amixers[AMIXER_LINEIN_C*CHN_NUM];
sum = mixer->sums[SUM_IN_F_C*CHN_NUM];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
amix_d = mixer->amixers[AMIXER_LINEIN_C*CHN_NUM+1];
sum = mixer->sums[SUM_IN_F_C*CHN_NUM+1];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
/* Set up Mic-in recording mixer */
amix_d = mixer->amixers[AMIXER_MIC_C*CHN_NUM];
sum = mixer->sums[SUM_IN_F_C*CHN_NUM];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
amix_d = mixer->amixers[AMIXER_MIC_C*CHN_NUM+1];
sum = mixer->sums[SUM_IN_F_C*CHN_NUM+1];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
/* Set up S/PDIF-in recording mixer */
amix_d = mixer->amixers[AMIXER_SPDIFI_C*CHN_NUM];
sum = mixer->sums[SUM_IN_F_C*CHN_NUM];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
amix_d = mixer->amixers[AMIXER_SPDIFI_C*CHN_NUM+1];
sum = mixer->sums[SUM_IN_F_C*CHN_NUM+1];
amix_d->ops->setup(amix_d, NULL, INIT_VOL, sum);
return 0;
} |
the_stack_data/12639059.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
ptr = (int *)calloc(3,sizeof(int));
for (int i = 0; i < 3; i++)
{
printf("enter the value of %d element of the array\n", i+1);
scanf("%d", &ptr[i]);
}
for (int i = 0; i < 3; i++)
{
printf("the value at %d element of array is %d\n", i+1, ptr[i]);
}
free(ptr);
return 0;
} |
the_stack_data/193893165.c | #include<stdio.h>
int gcd(int a,int b)
{
if(b < 0)
return a;
else
return gcd(b,a%b);
}
int main()
{
printf("Sanchay Joshi\n");
int a,b;
printf("Enter values of a and b\n");
scanf("%d%d",&a,&b);
printf("GCD of %d and %d is %d\n",a,b,gcd(a,b));
return 0;
}
|
the_stack_data/54824231.c | /*
* POK header
*
* The following file is a part of the POK project. Any modification should
* made according to the POK licence. You CANNOT use this file or a part of
* this file is this part of a file for your own project
*
* For more information on the POK licence, please see our LICENCE FILE
*
* Please follow the coding guidelines described in doc/CODING_GUIDELINES
*
* Copyright (c) 2007-2009 POK team
*
* Created by julien on Fri Jan 30 13:44:27 2009
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/*
* wrapper sqrt(x)
*/
#ifdef POK_NEEDS_LIBMATH
#include "math_private.h"
#include <libm.h>
double sqrt(double x) /* wrapper sqrt */
{
#ifdef _IEEE_LIBM
return __ieee754_sqrt(x);
#else
double z;
z = __ieee754_sqrt(x);
if (isnan(x)) return z;
if (x < 0.0) {
return -1.0;
} else
return z;
#endif
}
#endif
|
the_stack_data/70451246.c | #include <stdio.h>
int main(void){
int a, b, c;
printf("Digite o valor de a: ");
scanf("%d", &a);
printf("Digite o valor de b: ");
scanf("%d", &b);
printf("Digite o valor de c: ");
scanf("%d", &c);
if (a > b && a > c){
printf("O maior valor eh o de a: %d\n", a);
}else{
if (b > a && b > c){
printf("O maior valor eh o de b: %d\n", b);
}else{
printf("O maior valor eh o de c: %d\n", c);
}
}
return 0;
}
|
the_stack_data/273935.c | // C > Functions > Variadic functions in C
//
//
// https://www.hackerrank.com/challenges/variadic-functions-in-c/problem
//
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MIN_ELEMENT 1
#define MAX_ELEMENT 1000000
// (skeliton_head) ----------------------------------------------------------------------
int sum (int count, ...)
{
va_list ap;
int val = 0;
va_start(ap, count);
for(int i = 0; i < count; i++)
val += va_arg(ap, int);
va_end(ap);
return val;
}
int min(int count, ...)
{
va_list ap;
int val = 0;
va_start(ap, count);
for(int i = 0; i < count; i++)
{
int x = va_arg(ap, int);
if (x < val || i == 0) val = x;
}
va_end(ap);
return val;
}
int max(int count, ...)
{
va_list ap;
int val = 0;
va_start(ap, count);
for(int i = 0; i < count; i++)
{
int x = va_arg(ap, int);
if (x > val || i == 0) val = x;
}
va_end(ap);
return val;
}
// (skeliton_tail) ----------------------------------------------------------------------
int test_implementations_by_sending_three_elements() {
srand(time(NULL));
int elements[3];
elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
fprintf(stderr, "Sending following three elements:\n");
for (int i = 0; i < 3; i++) {
fprintf(stderr, "%d\n", elements[i]);
}
int elements_sum = sum(3, elements[0], elements[1], elements[2]);
int minimum_element = min(3, elements[0], elements[1], elements[2]);
int maximum_element = max(3, elements[0], elements[1], elements[2]);
fprintf(stderr, "Your output is:\n");
fprintf(stderr, "Elements sum is %d\n", elements_sum);
fprintf(stderr, "Minimum element is %d\n", minimum_element);
fprintf(stderr, "Maximum element is %d\n\n", maximum_element);
int expected_elements_sum = 0;
for (int i = 0; i < 3; i++) {
if (elements[i] < minimum_element) {
return 0;
}
if (elements[i] > maximum_element) {
return 0;
}
expected_elements_sum += elements[i];
}
return elements_sum == expected_elements_sum;
}
int test_implementations_by_sending_five_elements() {
srand(time(NULL));
int elements[5];
elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[3] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[4] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
fprintf(stderr, "Sending following five elements:\n");
for (int i = 0; i < 5; i++) {
fprintf(stderr, "%d\n", elements[i]);
}
int elements_sum = sum(5, elements[0], elements[1], elements[2], elements[3], elements[4]);
int minimum_element = min(5, elements[0], elements[1], elements[2], elements[3], elements[4]);
int maximum_element = max(5, elements[0], elements[1], elements[2], elements[3], elements[4]);
fprintf(stderr, "Your output is:\n");
fprintf(stderr, "Elements sum is %d\n", elements_sum);
fprintf(stderr, "Minimum element is %d\n", minimum_element);
fprintf(stderr, "Maximum element is %d\n\n", maximum_element);
int expected_elements_sum = 0;
for (int i = 0; i < 5; i++) {
if (elements[i] < minimum_element) {
return 0;
}
if (elements[i] > maximum_element) {
return 0;
}
expected_elements_sum += elements[i];
}
return elements_sum == expected_elements_sum;
}
int test_implementations_by_sending_ten_elements() {
srand(time(NULL));
int elements[10];
elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[3] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[4] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[5] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[6] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[7] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[8] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[9] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
fprintf(stderr, "Sending following ten elements:\n");
for (int i = 0; i < 10; i++) {
fprintf(stderr, "%d\n", elements[i]);
}
int elements_sum = sum(10, elements[0], elements[1], elements[2], elements[3], elements[4],
elements[5], elements[6], elements[7], elements[8], elements[9]);
int minimum_element = min(10, elements[0], elements[1], elements[2], elements[3], elements[4],
elements[5], elements[6], elements[7], elements[8], elements[9]);
int maximum_element = max(10, elements[0], elements[1], elements[2], elements[3], elements[4],
elements[5], elements[6], elements[7], elements[8], elements[9]);
fprintf(stderr, "Your output is:\n");
fprintf(stderr, "Elements sum is %d\n", elements_sum);
fprintf(stderr, "Minimum element is %d\n", minimum_element);
fprintf(stderr, "Maximum element is %d\n\n", maximum_element);
int expected_elements_sum = 0;
for (int i = 0; i < 10; i++) {
if (elements[i] < minimum_element) {
return 0;
}
if (elements[i] > maximum_element) {
return 0;
}
expected_elements_sum += elements[i];
}
return elements_sum == expected_elements_sum;
}
int main ()
{
int number_of_test_cases;
scanf("%d", &number_of_test_cases);
while (number_of_test_cases--) {
if (test_implementations_by_sending_three_elements()) {
printf("Correct Answer\n");
} else {
printf("Wrong Answer\n");
}
if (test_implementations_by_sending_five_elements()) {
printf("Correct Answer\n");
} else {
printf("Wrong Answer\n");
}
if (test_implementations_by_sending_ten_elements()) {
printf("Correct Answer\n");
} else {
printf("Wrong Answer\n");
}
}
return 0;
}
|
the_stack_data/57951741.c | /*
* C Implementation: Lookaside.c
*
* Description: Implementation of lookaside list
*
*
* Author: Puneet Kaushik <[email protected]>, (C) 2010
*
* Copyright: See COPYRIGHT file that comes with this distribution
*
*/
|
the_stack_data/82949706.c | #include<stdio.h>
int main()
{
int num1, num2, value;
char sign;
printf("Plese enter a number:");
scanf("%d", &num1);
printf("Plese enter another number:");
scanf("%d", &num2);
value=num1+num2;
sign='+';
printf("%d %c %d = %d\n", num1, sign, num2, value);
value=num1-num2;
sign='-';
printf("%d %c %d = %d\n", num1, sign, num2,value);
value=num1*num2;
sign='*';
printf("%d %C %d = %d\n", num1, sign, num2, value);
value=num1/num2;
sign='/';
printf("%d %c %d = %d\n", num1, sign, num2, value);
return 0;
}
|
the_stack_data/1180418.c | #include <stdio.h>
#include <stdlib.h>
int main() {
char CelebrityF[20];
char CelebrityL[20];
printf("Enter a celebrity: ");
scanf("%s%s", CelebrityF, CelebrityL);
printf("I love %s %s", CelebrityF, CelebrityL);
return 0;
} |
the_stack_data/31078.c | /* Test structures passed by value, including to a function with a
variable-length argument lists. All struct members are float
scalars. */
extern void struct_by_value_5a_x (void);
extern void exit (int);
int fails;
int
main ()
{
struct_by_value_5a_x ();
exit (0);
}
|
the_stack_data/863811.c | int main() {
int a = 1;
int b = 10;
int c = 3 - 2;
while (a < b) {
c++;
}
return c;
}
// 1: {a}
// 10: {b}
|
the_stack_data/1229379.c | // Code from https://martin.uy/blog/pthread_cancel-glibc-stack-unwinding/
#include <pthread.h>
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
static pthread_mutex_t mutex;
static pthread_mutex_t* mutex_ptr = NULL;
static pthread_cond_t thread_state_cond;
static pthread_cond_t* thread_state_cond_ptr = NULL;
static int thread_state = 0; // Sync
void thread_cleanup(void* args) {
pthread_mutex_lock(mutex_ptr);
printf("Thread: thread_state = 2.\n");
thread_state = 2;
pthread_cond_broadcast(thread_state_cond_ptr);
pthread_mutex_unlock(mutex_ptr);
}
static void thread_f(void) {
int ret = -1;
pthread_mutex_lock(mutex_ptr);
printf("Thread: thread_state = 1.\n");
thread_state = 1;
pthread_cond_broadcast(thread_state_cond_ptr);
pthread_mutex_unlock(mutex_ptr);
while (1) {
sleep(1000);
}
}
static void* thread_main(void* args) {
pthread_cleanup_push(&thread_cleanup, NULL);
thread_f();
// This should never be executed
pthread_cleanup_pop(0);
return NULL;
}
int main(void) {
int ret = 0;
pthread_t thread;
pthread_attr_t thread_attributes;
pthread_attr_t* thread_attributes_ptr = NULL;
if (pthread_mutex_init(&mutex, NULL) != 0)
goto error;
mutex_ptr = &mutex;
if (pthread_cond_init(&thread_state_cond, NULL) != 0)
goto error;
thread_state_cond_ptr = &thread_state_cond;
if (pthread_attr_init(&thread_attributes) != 0)
goto error;
thread_attributes_ptr = &thread_attributes;
if (pthread_create(&thread, thread_attributes_ptr, &thread_main, NULL) != 0)
goto error;
thread_attributes_ptr = NULL;
if (pthread_attr_destroy(&thread_attributes) != 0)
goto error;
// Wait for thread to go deep into the call stack
pthread_mutex_lock(mutex_ptr);
while (thread_state != 1)
pthread_cond_wait(thread_state_cond_ptr, mutex_ptr);
printf("Main thread: thread_state == 1.\n");
pthread_mutex_unlock(mutex_ptr);
if (pthread_cancel(thread) != 0)
goto error;
// Wait for thread to execute the cleanup function
pthread_mutex_lock(mutex_ptr);
while (thread_state != 2)
pthread_cond_wait(thread_state_cond_ptr, mutex_ptr);
printf("Main thread: thread_state == 2.\n");
pthread_mutex_unlock(mutex_ptr);
thread_state_cond_ptr = NULL;
if (pthread_cond_destroy(&thread_state_cond) != 0)
goto error;
mutex_ptr = NULL;
if (pthread_mutex_destroy(&mutex) != 0)
goto error;
goto cleanup;
error:
ret = -1;
cleanup:
if (thread_attributes_ptr != NULL)
pthread_attr_destroy(thread_attributes_ptr);
if (thread_state_cond_ptr != NULL)
pthread_cond_destroy(thread_state_cond_ptr);
if (mutex_ptr != NULL)
pthread_mutex_destroy(mutex_ptr);
if (ret == -1)
printf("Finished with errors.\n");
else
printf("Finished with no errors.\n");
return ret;
}
|
the_stack_data/95451649.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#define ROWS 30
#define COLS 80
/**
* randomly populates the board with either a 0 or a 1
* @param board a 2D Array of size [ROWS][COLS]
*/
void populateBoard(int board[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLS; j++)
board[i][j] = rand() % 2;
}
/**
* counts the neighbors of a cell
* @param board a 2D Array of size [ROWS][COLS]
* @param x x position of a cell on the board
* @param y y position of a cell on the board
*/
int countNeighbors(int board[ROWS][COLS], int x, int y) {
int sum = 0;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
int row = (x + i + ROWS) % ROWS;
int col = (y + j + COLS) % COLS;
sum += board[row][col];
}
}
sum -= board[x][y];
return sum;
}
/**
* computes the next generation of cells following the game's rules
* @param board a 2D Array of size [ROWS][COLS]
* @param next another 2D Array of size [ROWS][COLS] where we will compute the new values
*/
void computeNewGen(int board[ROWS][COLS], int next[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
int state = board[i][j];
int neighbors = countNeighbors(board, i, j);
if (state == 0 && neighbors == 3) {
next[i][j] = 1;
} else if (state == 1 && (neighbors < 2 || neighbors > 3)) {
next[i][j] = 0;
} else {
next[i][j] = board[i][j];
}
}
}
}
/**
* prints the board using special characters
* @param board a 2D Array of size [ROWS][COLS]
*/
void printBoard(int board[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (board[i][j] == 1) {
printf("█");
} else {
printf("░");
}
}
printf("\n");
}
}
int main() {
srand(time(0));
/**
* * gen 0:
* generating a randomly populated board
*/
int board[ROWS][COLS];
populateBoard(board);
/**
* * gen 0:
* copying board cells to another board (next)
* we will compute the next gen in "next"
*/
int next[ROWS][COLS];
memcpy(next, board, sizeof(board));
/**
* * gen 0:
* creating pointers to the boards (type: ‘int (*)[COLS]’)
* this way we avoid using memcpy later on in the code
*/
int (*pboard)[COLS] = board;
int (*pnext)[COLS] = next;
while (1) {
system("clear");
printBoard(pboard);
// computing the next gen
computeNewGen(pboard, pnext);
/**
* swapping the boards: "board" gets the computed value
* which is "next" and "next" gets the old value of "board".
* We don't really need to assign to "next" those specific values, we could even
* make it point to an empty board. Swapping them avoids allocating more memory.
*/
int (*temp)[COLS] = pboard;
pboard = pnext;
pnext = temp;
usleep(1000000/4); // lowering the frame rate
}
return 0;
} |
the_stack_data/698908.c | /* { dg-do compile } */
/* { dg-options "-O2 -ftree-parallelize-loops=4 -fdump-tree-parloops2-details -fdump-tree-optimized" } */
#include <stdarg.h>
#include <stdlib.h>
#define N 1600
#define DIFF 121
signed char b[N] = {1,2,3,6,8,10,12,14,16,18,20,22,24,26,28,30};
signed char c[N] = {1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
__attribute__ ((noinline))
void main1 (signed char x, signed char max_result, signed char min_result)
{
int i;
signed char diff = 2;
signed char max = x;
signed char min = x;
for (i = 0; i < N; i++) {
diff += (signed char)(b[i] - c[i]);
}
for (i = 0; i < N; i++) {
max = max < c[i] ? c[i] : max;
}
for (i = 0; i < N; i++) {
min = min > c[i] ? c[i] : min;
}
/* check results: */
if (diff != DIFF)
abort ();
if (max != max_result)
abort ();
if (min != min_result)
abort ();
}
void __attribute__((noinline))
__attribute__((optimize ("-ftree-parallelize-loops=0")))
init_arrays ()
{
int i;
for (i=16; i<N; i++)
{
b[i] = 1;
c[i] = 1;
}
}
int main (void)
{
init_arrays();
main1 (100, 100, 1);
main1 (0, 15, 0);
return 0;
}
/* { dg-final { scan-tree-dump-times "Detected reduction" 2 "parloops2" } } */
/* { dg-final { scan-tree-dump-times "Detected reduction" 3 "parloops2" { xfail *-*-* } } } */
/* { dg-final { scan-tree-dump-times "SUCCESS: may be parallelized" 2 "parloops2" } } */
/* { dg-final { scan-tree-dump-times "SUCCESS: may be parallelized" 3 "parloops2" { xfail *-*-* } } } */
|
the_stack_data/1181790.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 21
#define MAX_DIGIT_PLUS_ONE 10
void fill_square(int array[N][N]);
void print_square(int array[N][N]);
void twiddle(int array[N][N]);
int main(void)
{
int square[N][N];
int count;
srand(time(NULL));
fill_square(square);
while(count < N*N*N*N)
{
twiddle(square);
count++;
}
print_square(square);
return(0);
}
void fill_square(int array[N][N])
{
int i, j;
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
array[i][j] = rand()%MAX_DIGIT_PLUS_ONE;
}
}
}
void print_square(int array[N][N])
{
int i, j;
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
printf("%d", array[i][j]);
}
printf("\n");
}
}
int distance_from_centre(int x, int y)
{
int distance;
distance = ((x-(N/2))*(x-(N/2)))+((y-(N/2))*(y-(N/2)));
return(distance);
}
void twiddle(int array[N][N])
{
int x, y, u, v, a, b;
x = rand()%N;
y = rand()%N;
u = rand()%N;
v = rand()%N;
a = array[y][x];
b = array[v][u];
if(distance_from_centre(x, y) < distance_from_centre(u, v))
{
if(a > b)
{
array[y][x] = b;
array[v][u] = a;
}
}
else
{
if(a < b)
{
array[y][x] = b;
array[v][u] = a;
}
}
} |
the_stack_data/138641.c |
static int x = 0;
static int
foo()
{
return x;
}
int
main()
{
return foo();
}
|
the_stack_data/477318.c | #include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
#ifdef _MSC_VER
static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;}
static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;}
static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;}
static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;}
#else
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#endif
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#ifdef _MSC_VER
#define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);}
#define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);}
#else
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#endif
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimagf(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#ifdef _MSC_VER
static _Fcomplex cpow_ui(complex x, integer n) {
complex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i;
for(u = n; ; ) {
if(u & 01) pow.r *= x.r, pow.i *= x.i;
if(u >>= 1) x.r *= x.r, x.i *= x.i;
else break;
}
}
_Fcomplex p={pow.r, pow.i};
return p;
}
#else
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
#ifdef _MSC_VER
static _Dcomplex zpow_ui(_Dcomplex x, integer n) {
_Dcomplex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1];
for(u = n; ; ) {
if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1];
if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1];
else break;
}
}
_Dcomplex p = {pow._Val[0], pow._Val[1]};
return p;
}
#else
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static integer c__1 = 1;
static real c_b9 = 1.f;
static real c_b21 = -1.f;
/* > \brief \b SLARFB_GETT */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download SLARFB_GETT + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/slarfb_
gett.f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/slarfb_
gett.f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/slarfb_
gett.f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE SLARFB_GETT( IDENT, M, N, K, T, LDT, A, LDA, B, LDB, */
/* $ WORK, LDWORK ) */
/* IMPLICIT NONE */
/* CHARACTER IDENT */
/* INTEGER K, LDA, LDB, LDT, LDWORK, M, N */
/* REAL A( LDA, * ), B( LDB, * ), T( LDT, * ), */
/* $ WORK( LDWORK, * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > SLARFB_GETT applies a real Householder block reflector H from the */
/* > left to a real (K+M)-by-N "triangular-pentagonal" matrix */
/* > composed of two block matrices: an upper trapezoidal K-by-N matrix A */
/* > stored in the array A, and a rectangular M-by-(N-K) matrix B, stored */
/* > in the array B. The block reflector H is stored in a compact */
/* > WY-representation, where the elementary reflectors are in the */
/* > arrays A, B and T. See Further Details section. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] IDENT */
/* > \verbatim */
/* > IDENT is CHARACTER*1 */
/* > If IDENT = not 'I', or not 'i', then V1 is unit */
/* > lower-triangular and stored in the left K-by-K block of */
/* > the input matrix A, */
/* > If IDENT = 'I' or 'i', then V1 is an identity matrix and */
/* > not stored. */
/* > See Further Details section. */
/* > \endverbatim */
/* > */
/* > \param[in] M */
/* > \verbatim */
/* > M is INTEGER */
/* > The number of rows of the matrix B. */
/* > M >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of columns of the matrices A and B. */
/* > N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] K */
/* > \verbatim */
/* > K is INTEGER */
/* > The number or rows of the matrix A. */
/* > K is also order of the matrix T, i.e. the number of */
/* > elementary reflectors whose product defines the block */
/* > reflector. 0 <= K <= N. */
/* > \endverbatim */
/* > */
/* > \param[in] T */
/* > \verbatim */
/* > T is REAL array, dimension (LDT,K) */
/* > The upper-triangular K-by-K matrix T in the representation */
/* > of the block reflector. */
/* > \endverbatim */
/* > */
/* > \param[in] LDT */
/* > \verbatim */
/* > LDT is INTEGER */
/* > The leading dimension of the array T. LDT >= K. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is REAL array, dimension (LDA,N) */
/* > */
/* > On entry: */
/* > a) In the K-by-N upper-trapezoidal part A: input matrix A. */
/* > b) In the columns below the diagonal: columns of V1 */
/* > (ones are not stored on the diagonal). */
/* > */
/* > On exit: */
/* > A is overwritten by rectangular K-by-N product H*A. */
/* > */
/* > See Further Details section. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDB is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,K). */
/* > \endverbatim */
/* > */
/* > \param[in,out] B */
/* > \verbatim */
/* > B is REAL array, dimension (LDB,N) */
/* > */
/* > On entry: */
/* > a) In the M-by-(N-K) right block: input matrix B. */
/* > b) In the M-by-N left block: columns of V2. */
/* > */
/* > On exit: */
/* > B is overwritten by rectangular M-by-N product H*B. */
/* > */
/* > See Further Details section. */
/* > \endverbatim */
/* > */
/* > \param[in] LDB */
/* > \verbatim */
/* > LDB is INTEGER */
/* > The leading dimension of the array B. LDB >= f2cmax(1,M). */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is REAL array, */
/* > dimension (LDWORK,f2cmax(K,N-K)) */
/* > \endverbatim */
/* > */
/* > \param[in] LDWORK */
/* > \verbatim */
/* > LDWORK is INTEGER */
/* > The leading dimension of the array WORK. LDWORK>=f2cmax(1,K). */
/* > */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \ingroup singleOTHERauxiliary */
/* > \par Contributors: */
/* ================== */
/* > */
/* > \verbatim */
/* > */
/* > November 2020, Igor Kozachenko, */
/* > Computer Science Division, */
/* > University of California, Berkeley */
/* > */
/* > \endverbatim */
/* > \par Further Details: */
/* ===================== */
/* > */
/* > \verbatim */
/* > */
/* > (1) Description of the Algebraic Operation. */
/* > */
/* > The matrix A is a K-by-N matrix composed of two column block */
/* > matrices, A1, which is K-by-K, and A2, which is K-by-(N-K): */
/* > A = ( A1, A2 ). */
/* > The matrix B is an M-by-N matrix composed of two column block */
/* > matrices, B1, which is M-by-K, and B2, which is M-by-(N-K): */
/* > B = ( B1, B2 ). */
/* > */
/* > Perform the operation: */
/* > */
/* > ( A_out ) := H * ( A_in ) = ( I - V * T * V**T ) * ( A_in ) = */
/* > ( B_out ) ( B_in ) ( B_in ) */
/* > = ( I - ( V1 ) * T * ( V1**T, V2**T ) ) * ( A_in ) */
/* > ( V2 ) ( B_in ) */
/* > On input: */
/* > */
/* > a) ( A_in ) consists of two block columns: */
/* > ( B_in ) */
/* > */
/* > ( A_in ) = (( A1_in ) ( A2_in )) = (( A1_in ) ( A2_in )) */
/* > ( B_in ) (( B1_in ) ( B2_in )) (( 0 ) ( B2_in )), */
/* > */
/* > where the column blocks are: */
/* > */
/* > ( A1_in ) is a K-by-K upper-triangular matrix stored in the */
/* > upper triangular part of the array A(1:K,1:K). */
/* > ( B1_in ) is an M-by-K rectangular ZERO matrix and not stored. */
/* > */
/* > ( A2_in ) is a K-by-(N-K) rectangular matrix stored */
/* > in the array A(1:K,K+1:N). */
/* > ( B2_in ) is an M-by-(N-K) rectangular matrix stored */
/* > in the array B(1:M,K+1:N). */
/* > */
/* > b) V = ( V1 ) */
/* > ( V2 ) */
/* > */
/* > where: */
/* > 1) if IDENT == 'I',V1 is a K-by-K identity matrix, not stored; */
/* > 2) if IDENT != 'I',V1 is a K-by-K unit lower-triangular matrix, */
/* > stored in the lower-triangular part of the array */
/* > A(1:K,1:K) (ones are not stored), */
/* > and V2 is an M-by-K rectangular stored the array B(1:M,1:K), */
/* > (because on input B1_in is a rectangular zero */
/* > matrix that is not stored and the space is */
/* > used to store V2). */
/* > */
/* > c) T is a K-by-K upper-triangular matrix stored */
/* > in the array T(1:K,1:K). */
/* > */
/* > On output: */
/* > */
/* > a) ( A_out ) consists of two block columns: */
/* > ( B_out ) */
/* > */
/* > ( A_out ) = (( A1_out ) ( A2_out )) */
/* > ( B_out ) (( B1_out ) ( B2_out )), */
/* > */
/* > where the column blocks are: */
/* > */
/* > ( A1_out ) is a K-by-K square matrix, or a K-by-K */
/* > upper-triangular matrix, if V1 is an */
/* > identity matrix. AiOut is stored in */
/* > the array A(1:K,1:K). */
/* > ( B1_out ) is an M-by-K rectangular matrix stored */
/* > in the array B(1:M,K:N). */
/* > */
/* > ( A2_out ) is a K-by-(N-K) rectangular matrix stored */
/* > in the array A(1:K,K+1:N). */
/* > ( B2_out ) is an M-by-(N-K) rectangular matrix stored */
/* > in the array B(1:M,K+1:N). */
/* > */
/* > */
/* > The operation above can be represented as the same operation */
/* > on each block column: */
/* > */
/* > ( A1_out ) := H * ( A1_in ) = ( I - V * T * V**T ) * ( A1_in ) */
/* > ( B1_out ) ( 0 ) ( 0 ) */
/* > */
/* > ( A2_out ) := H * ( A2_in ) = ( I - V * T * V**T ) * ( A2_in ) */
/* > ( B2_out ) ( B2_in ) ( B2_in ) */
/* > */
/* > If IDENT != 'I': */
/* > */
/* > The computation for column block 1: */
/* > */
/* > A1_out: = A1_in - V1*T*(V1**T)*A1_in */
/* > */
/* > B1_out: = - V2*T*(V1**T)*A1_in */
/* > */
/* > The computation for column block 2, which exists if N > K: */
/* > */
/* > A2_out: = A2_in - V1*T*( (V1**T)*A2_in + (V2**T)*B2_in ) */
/* > */
/* > B2_out: = B2_in - V2*T*( (V1**T)*A2_in + (V2**T)*B2_in ) */
/* > */
/* > If IDENT == 'I': */
/* > */
/* > The operation for column block 1: */
/* > */
/* > A1_out: = A1_in - V1*T**A1_in */
/* > */
/* > B1_out: = - V2*T**A1_in */
/* > */
/* > The computation for column block 2, which exists if N > K: */
/* > */
/* > A2_out: = A2_in - T*( A2_in + (V2**T)*B2_in ) */
/* > */
/* > B2_out: = B2_in - V2*T*( A2_in + (V2**T)*B2_in ) */
/* > */
/* > (2) Description of the Algorithmic Computation. */
/* > */
/* > In the first step, we compute column block 2, i.e. A2 and B2. */
/* > Here, we need to use the K-by-(N-K) rectangular workspace */
/* > matrix W2 that is of the same size as the matrix A2. */
/* > W2 is stored in the array WORK(1:K,1:(N-K)). */
/* > */
/* > In the second step, we compute column block 1, i.e. A1 and B1. */
/* > Here, we need to use the K-by-K square workspace matrix W1 */
/* > that is of the same size as the as the matrix A1. */
/* > W1 is stored in the array WORK(1:K,1:K). */
/* > */
/* > NOTE: Hence, in this routine, we need the workspace array WORK */
/* > only of size WORK(1:K,1:f2cmax(K,N-K)) so it can hold both W2 from */
/* > the first step and W1 from the second step. */
/* > */
/* > Case (A), when V1 is unit lower-triangular, i.e. IDENT != 'I', */
/* > more computations than in the Case (B). */
/* > */
/* > if( IDENT != 'I' ) then */
/* > if ( N > K ) then */
/* > (First Step - column block 2) */
/* > col2_(1) W2: = A2 */
/* > col2_(2) W2: = (V1**T) * W2 = (unit_lower_tr_of_(A1)**T) * W2 */
/* > col2_(3) W2: = W2 + (V2**T) * B2 = W2 + (B1**T) * B2 */
/* > col2_(4) W2: = T * W2 */
/* > col2_(5) B2: = B2 - V2 * W2 = B2 - B1 * W2 */
/* > col2_(6) W2: = V1 * W2 = unit_lower_tr_of_(A1) * W2 */
/* > col2_(7) A2: = A2 - W2 */
/* > else */
/* > (Second Step - column block 1) */
/* > col1_(1) W1: = A1 */
/* > col1_(2) W1: = (V1**T) * W1 = (unit_lower_tr_of_(A1)**T) * W1 */
/* > col1_(3) W1: = T * W1 */
/* > col1_(4) B1: = - V2 * W1 = - B1 * W1 */
/* > col1_(5) square W1: = V1 * W1 = unit_lower_tr_of_(A1) * W1 */
/* > col1_(6) square A1: = A1 - W1 */
/* > end if */
/* > end if */
/* > */
/* > Case (B), when V1 is an identity matrix, i.e. IDENT == 'I', */
/* > less computations than in the Case (A) */
/* > */
/* > if( IDENT == 'I' ) then */
/* > if ( N > K ) then */
/* > (First Step - column block 2) */
/* > col2_(1) W2: = A2 */
/* > col2_(3) W2: = W2 + (V2**T) * B2 = W2 + (B1**T) * B2 */
/* > col2_(4) W2: = T * W2 */
/* > col2_(5) B2: = B2 - V2 * W2 = B2 - B1 * W2 */
/* > col2_(7) A2: = A2 - W2 */
/* > else */
/* > (Second Step - column block 1) */
/* > col1_(1) W1: = A1 */
/* > col1_(3) W1: = T * W1 */
/* > col1_(4) B1: = - V2 * W1 = - B1 * W1 */
/* > col1_(6) upper-triangular_of_(A1): = A1 - W1 */
/* > end if */
/* > end if */
/* > */
/* > Combine these cases (A) and (B) together, this is the resulting */
/* > algorithm: */
/* > */
/* > if ( N > K ) then */
/* > */
/* > (First Step - column block 2) */
/* > */
/* > col2_(1) W2: = A2 */
/* > if( IDENT != 'I' ) then */
/* > col2_(2) W2: = (V1**T) * W2 */
/* > = (unit_lower_tr_of_(A1)**T) * W2 */
/* > end if */
/* > col2_(3) W2: = W2 + (V2**T) * B2 = W2 + (B1**T) * B2] */
/* > col2_(4) W2: = T * W2 */
/* > col2_(5) B2: = B2 - V2 * W2 = B2 - B1 * W2 */
/* > if( IDENT != 'I' ) then */
/* > col2_(6) W2: = V1 * W2 = unit_lower_tr_of_(A1) * W2 */
/* > end if */
/* > col2_(7) A2: = A2 - W2 */
/* > */
/* > else */
/* > */
/* > (Second Step - column block 1) */
/* > */
/* > col1_(1) W1: = A1 */
/* > if( IDENT != 'I' ) then */
/* > col1_(2) W1: = (V1**T) * W1 */
/* > = (unit_lower_tr_of_(A1)**T) * W1 */
/* > end if */
/* > col1_(3) W1: = T * W1 */
/* > col1_(4) B1: = - V2 * W1 = - B1 * W1 */
/* > if( IDENT != 'I' ) then */
/* > col1_(5) square W1: = V1 * W1 = unit_lower_tr_of_(A1) * W1 */
/* > col1_(6_a) below_diag_of_(A1): = - below_diag_of_(W1) */
/* > end if */
/* > col1_(6_b) up_tr_of_(A1): = up_tr_of_(A1) - up_tr_of_(W1) */
/* > */
/* > end if */
/* > */
/* > \endverbatim */
/* > */
/* ===================================================================== */
/* Subroutine */ int slarfb_gett_(char *ident, integer *m, integer *n,
integer *k, real *t, integer *ldt, real *a, integer *lda, real *b,
integer *ldb, real *work, integer *ldwork)
{
/* System generated locals */
integer a_dim1, a_offset, b_dim1, b_offset, t_dim1, t_offset, work_dim1,
work_offset, i__1, i__2;
/* Local variables */
integer i__, j;
extern logical lsame_(char *, char *);
extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *,
integer *, real *, real *, integer *, real *, integer *, real *,
real *, integer *), scopy_(integer *, real *,
integer *, real *, integer *), strmm_(char *, char *, char *,
char *, integer *, integer *, real *, real *, integer *, real *,
integer *);
logical lnotident;
/* -- LAPACK auxiliary routine -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* ===================================================================== */
/* Quick return if possible */
/* Parameter adjustments */
t_dim1 = *ldt;
t_offset = 1 + t_dim1 * 1;
t -= t_offset;
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
b_dim1 = *ldb;
b_offset = 1 + b_dim1 * 1;
b -= b_offset;
work_dim1 = *ldwork;
work_offset = 1 + work_dim1 * 1;
work -= work_offset;
/* Function Body */
if (*m < 0 || *n <= 0 || *k == 0 || *k > *n) {
return 0;
}
lnotident = ! lsame_(ident, "I");
/* ------------------------------------------------------------------ */
/* First Step. Computation of the Column Block 2: */
/* ( A2 ) := H * ( A2 ) */
/* ( B2 ) ( B2 ) */
/* ------------------------------------------------------------------ */
if (*n > *k) {
/* col2_(1) Compute W2: = A2. Therefore, copy A2 = A(1:K, K+1:N) */
/* into W2=WORK(1:K, 1:N-K) column-by-column. */
i__1 = *n - *k;
for (j = 1; j <= i__1; ++j) {
scopy_(k, &a[(*k + j) * a_dim1 + 1], &c__1, &work[j * work_dim1 +
1], &c__1);
}
if (lnotident) {
/* col2_(2) Compute W2: = (V1**T) * W2 = (A1**T) * W2, */
/* V1 is not an identy matrix, but unit lower-triangular */
/* V1 stored in A1 (diagonal ones are not stored). */
i__1 = *n - *k;
strmm_("L", "L", "T", "U", k, &i__1, &c_b9, &a[a_offset], lda, &
work[work_offset], ldwork);
}
/* col2_(3) Compute W2: = W2 + (V2**T) * B2 = W2 + (B1**T) * B2 */
/* V2 stored in B1. */
if (*m > 0) {
i__1 = *n - *k;
sgemm_("T", "N", k, &i__1, m, &c_b9, &b[b_offset], ldb, &b[(*k +
1) * b_dim1 + 1], ldb, &c_b9, &work[work_offset], ldwork);
}
/* col2_(4) Compute W2: = T * W2, */
/* T is upper-triangular. */
i__1 = *n - *k;
strmm_("L", "U", "N", "N", k, &i__1, &c_b9, &t[t_offset], ldt, &work[
work_offset], ldwork);
/* col2_(5) Compute B2: = B2 - V2 * W2 = B2 - B1 * W2, */
/* V2 stored in B1. */
if (*m > 0) {
i__1 = *n - *k;
sgemm_("N", "N", m, &i__1, k, &c_b21, &b[b_offset], ldb, &work[
work_offset], ldwork, &c_b9, &b[(*k + 1) * b_dim1 + 1],
ldb);
}
if (lnotident) {
/* col2_(6) Compute W2: = V1 * W2 = A1 * W2, */
/* V1 is not an identity matrix, but unit lower-triangular, */
/* V1 stored in A1 (diagonal ones are not stored). */
i__1 = *n - *k;
strmm_("L", "L", "N", "U", k, &i__1, &c_b9, &a[a_offset], lda, &
work[work_offset], ldwork);
}
/* col2_(7) Compute A2: = A2 - W2 = */
/* = A(1:K, K+1:N-K) - WORK(1:K, 1:N-K), */
/* column-by-column. */
i__1 = *n - *k;
for (j = 1; j <= i__1; ++j) {
i__2 = *k;
for (i__ = 1; i__ <= i__2; ++i__) {
a[i__ + (*k + j) * a_dim1] -= work[i__ + j * work_dim1];
}
}
}
/* ------------------------------------------------------------------ */
/* Second Step. Computation of the Column Block 1: */
/* ( A1 ) := H * ( A1 ) */
/* ( B1 ) ( 0 ) */
/* ------------------------------------------------------------------ */
/* col1_(1) Compute W1: = A1. Copy the upper-triangular */
/* A1 = A(1:K, 1:K) into the upper-triangular */
/* W1 = WORK(1:K, 1:K) column-by-column. */
i__1 = *k;
for (j = 1; j <= i__1; ++j) {
scopy_(&j, &a[j * a_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1)
;
}
/* Set the subdiagonal elements of W1 to zero column-by-column. */
i__1 = *k - 1;
for (j = 1; j <= i__1; ++j) {
i__2 = *k;
for (i__ = j + 1; i__ <= i__2; ++i__) {
work[i__ + j * work_dim1] = 0.f;
}
}
if (lnotident) {
/* col1_(2) Compute W1: = (V1**T) * W1 = (A1**T) * W1, */
/* V1 is not an identity matrix, but unit lower-triangular */
/* V1 stored in A1 (diagonal ones are not stored), */
/* W1 is upper-triangular with zeroes below the diagonal. */
strmm_("L", "L", "T", "U", k, k, &c_b9, &a[a_offset], lda, &work[
work_offset], ldwork);
}
/* col1_(3) Compute W1: = T * W1, */
/* T is upper-triangular, */
/* W1 is upper-triangular with zeroes below the diagonal. */
strmm_("L", "U", "N", "N", k, k, &c_b9, &t[t_offset], ldt, &work[
work_offset], ldwork);
/* col1_(4) Compute B1: = - V2 * W1 = - B1 * W1, */
/* V2 = B1, W1 is upper-triangular with zeroes below the diagonal. */
if (*m > 0) {
strmm_("R", "U", "N", "N", m, k, &c_b21, &work[work_offset], ldwork, &
b[b_offset], ldb);
}
if (lnotident) {
/* col1_(5) Compute W1: = V1 * W1 = A1 * W1, */
/* V1 is not an identity matrix, but unit lower-triangular */
/* V1 stored in A1 (diagonal ones are not stored), */
/* W1 is upper-triangular on input with zeroes below the diagonal, */
/* and square on output. */
strmm_("L", "L", "N", "U", k, k, &c_b9, &a[a_offset], lda, &work[
work_offset], ldwork);
/* col1_(6) Compute A1: = A1 - W1 = A(1:K, 1:K) - WORK(1:K, 1:K) */
/* column-by-column. A1 is upper-triangular on input. */
/* If IDENT, A1 is square on output, and W1 is square, */
/* if NOT IDENT, A1 is upper-triangular on output, */
/* W1 is upper-triangular. */
/* col1_(6)_a Compute elements of A1 below the diagonal. */
i__1 = *k - 1;
for (j = 1; j <= i__1; ++j) {
i__2 = *k;
for (i__ = j + 1; i__ <= i__2; ++i__) {
a[i__ + j * a_dim1] = -work[i__ + j * work_dim1];
}
}
}
/* col1_(6)_b Compute elements of A1 on and above the diagonal. */
i__1 = *k;
for (j = 1; j <= i__1; ++j) {
i__2 = j;
for (i__ = 1; i__ <= i__2; ++i__) {
a[i__ + j * a_dim1] -= work[i__ + j * work_dim1];
}
}
return 0;
/* End of SLARFB_GETT */
} /* slarfb_gett__ */
|
the_stack_data/145453620.c | /*
* FIPS-46-3 compliant Triple-DES implementation
*
* Copyright The Mbed TLS Contributors
* 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.
*/
/*
* DES, on which TDES is based, was originally designed by Horst Feistel
* at IBM in 1974, and was adopted as a standard by NIST (formerly NBS).
*
* http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf
*/
//#include "common.h"
#if defined(MBEDTLS_DES_C)
#include "des.h"
//#include "platform_util.h"
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#if !defined(MBEDTLS_DES_ALT)
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_UINT32_BE
#define GET_UINT32_BE(n,b,i) \
{ \
(n) = ( (uint32_t) (b)[(i) ] << 24 ) \
| ( (uint32_t) (b)[(i) + 1] << 16 ) \
| ( (uint32_t) (b)[(i) + 2] << 8 ) \
| ( (uint32_t) (b)[(i) + 3] ); \
}
#endif
#ifndef PUT_UINT32_BE
#define PUT_UINT32_BE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 3] = (unsigned char) ( (n) ); \
}
#endif
/*
* Expanded DES S-boxes
*/
static const uint32_t SB1[64] =
{
0x01010400, 0x00000000, 0x00010000, 0x01010404,
0x01010004, 0x00010404, 0x00000004, 0x00010000,
0x00000400, 0x01010400, 0x01010404, 0x00000400,
0x01000404, 0x01010004, 0x01000000, 0x00000004,
0x00000404, 0x01000400, 0x01000400, 0x00010400,
0x00010400, 0x01010000, 0x01010000, 0x01000404,
0x00010004, 0x01000004, 0x01000004, 0x00010004,
0x00000000, 0x00000404, 0x00010404, 0x01000000,
0x00010000, 0x01010404, 0x00000004, 0x01010000,
0x01010400, 0x01000000, 0x01000000, 0x00000400,
0x01010004, 0x00010000, 0x00010400, 0x01000004,
0x00000400, 0x00000004, 0x01000404, 0x00010404,
0x01010404, 0x00010004, 0x01010000, 0x01000404,
0x01000004, 0x00000404, 0x00010404, 0x01010400,
0x00000404, 0x01000400, 0x01000400, 0x00000000,
0x00010004, 0x00010400, 0x00000000, 0x01010004
};
static const uint32_t SB2[64] =
{
0x80108020, 0x80008000, 0x00008000, 0x00108020,
0x00100000, 0x00000020, 0x80100020, 0x80008020,
0x80000020, 0x80108020, 0x80108000, 0x80000000,
0x80008000, 0x00100000, 0x00000020, 0x80100020,
0x00108000, 0x00100020, 0x80008020, 0x00000000,
0x80000000, 0x00008000, 0x00108020, 0x80100000,
0x00100020, 0x80000020, 0x00000000, 0x00108000,
0x00008020, 0x80108000, 0x80100000, 0x00008020,
0x00000000, 0x00108020, 0x80100020, 0x00100000,
0x80008020, 0x80100000, 0x80108000, 0x00008000,
0x80100000, 0x80008000, 0x00000020, 0x80108020,
0x00108020, 0x00000020, 0x00008000, 0x80000000,
0x00008020, 0x80108000, 0x00100000, 0x80000020,
0x00100020, 0x80008020, 0x80000020, 0x00100020,
0x00108000, 0x00000000, 0x80008000, 0x00008020,
0x80000000, 0x80100020, 0x80108020, 0x00108000
};
static const uint32_t SB3[64] =
{
0x00000208, 0x08020200, 0x00000000, 0x08020008,
0x08000200, 0x00000000, 0x00020208, 0x08000200,
0x00020008, 0x08000008, 0x08000008, 0x00020000,
0x08020208, 0x00020008, 0x08020000, 0x00000208,
0x08000000, 0x00000008, 0x08020200, 0x00000200,
0x00020200, 0x08020000, 0x08020008, 0x00020208,
0x08000208, 0x00020200, 0x00020000, 0x08000208,
0x00000008, 0x08020208, 0x00000200, 0x08000000,
0x08020200, 0x08000000, 0x00020008, 0x00000208,
0x00020000, 0x08020200, 0x08000200, 0x00000000,
0x00000200, 0x00020008, 0x08020208, 0x08000200,
0x08000008, 0x00000200, 0x00000000, 0x08020008,
0x08000208, 0x00020000, 0x08000000, 0x08020208,
0x00000008, 0x00020208, 0x00020200, 0x08000008,
0x08020000, 0x08000208, 0x00000208, 0x08020000,
0x00020208, 0x00000008, 0x08020008, 0x00020200
};
static const uint32_t SB4[64] =
{
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802080, 0x00800081, 0x00800001, 0x00002001,
0x00000000, 0x00802000, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00800080, 0x00800001,
0x00000001, 0x00002000, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002001, 0x00002080,
0x00800081, 0x00000001, 0x00002080, 0x00800080,
0x00002000, 0x00802080, 0x00802081, 0x00000081,
0x00800080, 0x00800001, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00000000, 0x00802000,
0x00002080, 0x00800080, 0x00800081, 0x00000001,
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802081, 0x00000081, 0x00000001, 0x00002000,
0x00800001, 0x00002001, 0x00802080, 0x00800081,
0x00002001, 0x00002080, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002000, 0x00802080
};
static const uint32_t SB5[64] =
{
0x00000100, 0x02080100, 0x02080000, 0x42000100,
0x00080000, 0x00000100, 0x40000000, 0x02080000,
0x40080100, 0x00080000, 0x02000100, 0x40080100,
0x42000100, 0x42080000, 0x00080100, 0x40000000,
0x02000000, 0x40080000, 0x40080000, 0x00000000,
0x40000100, 0x42080100, 0x42080100, 0x02000100,
0x42080000, 0x40000100, 0x00000000, 0x42000000,
0x02080100, 0x02000000, 0x42000000, 0x00080100,
0x00080000, 0x42000100, 0x00000100, 0x02000000,
0x40000000, 0x02080000, 0x42000100, 0x40080100,
0x02000100, 0x40000000, 0x42080000, 0x02080100,
0x40080100, 0x00000100, 0x02000000, 0x42080000,
0x42080100, 0x00080100, 0x42000000, 0x42080100,
0x02080000, 0x00000000, 0x40080000, 0x42000000,
0x00080100, 0x02000100, 0x40000100, 0x00080000,
0x00000000, 0x40080000, 0x02080100, 0x40000100
};
static const uint32_t SB6[64] =
{
0x20000010, 0x20400000, 0x00004000, 0x20404010,
0x20400000, 0x00000010, 0x20404010, 0x00400000,
0x20004000, 0x00404010, 0x00400000, 0x20000010,
0x00400010, 0x20004000, 0x20000000, 0x00004010,
0x00000000, 0x00400010, 0x20004010, 0x00004000,
0x00404000, 0x20004010, 0x00000010, 0x20400010,
0x20400010, 0x00000000, 0x00404010, 0x20404000,
0x00004010, 0x00404000, 0x20404000, 0x20000000,
0x20004000, 0x00000010, 0x20400010, 0x00404000,
0x20404010, 0x00400000, 0x00004010, 0x20000010,
0x00400000, 0x20004000, 0x20000000, 0x00004010,
0x20000010, 0x20404010, 0x00404000, 0x20400000,
0x00404010, 0x20404000, 0x00000000, 0x20400010,
0x00000010, 0x00004000, 0x20400000, 0x00404010,
0x00004000, 0x00400010, 0x20004010, 0x00000000,
0x20404000, 0x20000000, 0x00400010, 0x20004010
};
static const uint32_t SB7[64] =
{
0x00200000, 0x04200002, 0x04000802, 0x00000000,
0x00000800, 0x04000802, 0x00200802, 0x04200800,
0x04200802, 0x00200000, 0x00000000, 0x04000002,
0x00000002, 0x04000000, 0x04200002, 0x00000802,
0x04000800, 0x00200802, 0x00200002, 0x04000800,
0x04000002, 0x04200000, 0x04200800, 0x00200002,
0x04200000, 0x00000800, 0x00000802, 0x04200802,
0x00200800, 0x00000002, 0x04000000, 0x00200800,
0x04000000, 0x00200800, 0x00200000, 0x04000802,
0x04000802, 0x04200002, 0x04200002, 0x00000002,
0x00200002, 0x04000000, 0x04000800, 0x00200000,
0x04200800, 0x00000802, 0x00200802, 0x04200800,
0x00000802, 0x04000002, 0x04200802, 0x04200000,
0x00200800, 0x00000000, 0x00000002, 0x04200802,
0x00000000, 0x00200802, 0x04200000, 0x00000800,
0x04000002, 0x04000800, 0x00000800, 0x00200002
};
static const uint32_t SB8[64] =
{
0x10001040, 0x00001000, 0x00040000, 0x10041040,
0x10000000, 0x10001040, 0x00000040, 0x10000000,
0x00040040, 0x10040000, 0x10041040, 0x00041000,
0x10041000, 0x00041040, 0x00001000, 0x00000040,
0x10040000, 0x10000040, 0x10001000, 0x00001040,
0x00041000, 0x00040040, 0x10040040, 0x10041000,
0x00001040, 0x00000000, 0x00000000, 0x10040040,
0x10000040, 0x10001000, 0x00041040, 0x00040000,
0x00041040, 0x00040000, 0x10041000, 0x00001000,
0x00000040, 0x10040040, 0x00001000, 0x00041040,
0x10001000, 0x00000040, 0x10000040, 0x10040000,
0x10040040, 0x10000000, 0x00040000, 0x10001040,
0x00000000, 0x10041040, 0x00040040, 0x10000040,
0x10040000, 0x10001000, 0x10001040, 0x00000000,
0x10041040, 0x00041000, 0x00041000, 0x00001040,
0x00001040, 0x00040040, 0x10000000, 0x10041000
};
/*
* PC1: left and right halves bit-swap
*/
static const uint32_t LHs[16] =
{
0x00000000, 0x00000001, 0x00000100, 0x00000101,
0x00010000, 0x00010001, 0x00010100, 0x00010101,
0x01000000, 0x01000001, 0x01000100, 0x01000101,
0x01010000, 0x01010001, 0x01010100, 0x01010101
};
static const uint32_t RHs[16] =
{
0x00000000, 0x01000000, 0x00010000, 0x01010000,
0x00000100, 0x01000100, 0x00010100, 0x01010100,
0x00000001, 0x01000001, 0x00010001, 0x01010001,
0x00000101, 0x01000101, 0x00010101, 0x01010101,
};
/*
* Initial Permutation macro
*/
#define DES_IP(X,Y) \
do \
{ \
T = (((X) >> 4) ^ (Y)) & 0x0F0F0F0F; (Y) ^= T; (X) ^= (T << 4); \
T = (((X) >> 16) ^ (Y)) & 0x0000FFFF; (Y) ^= T; (X) ^= (T << 16); \
T = (((Y) >> 2) ^ (X)) & 0x33333333; (X) ^= T; (Y) ^= (T << 2); \
T = (((Y) >> 8) ^ (X)) & 0x00FF00FF; (X) ^= T; (Y) ^= (T << 8); \
(Y) = (((Y) << 1) | ((Y) >> 31)) & 0xFFFFFFFF; \
T = ((X) ^ (Y)) & 0xAAAAAAAA; (Y) ^= T; (X) ^= T; \
(X) = (((X) << 1) | ((X) >> 31)) & 0xFFFFFFFF; \
} while( 0 )
/*
* Final Permutation macro
*/
#define DES_FP(X,Y) \
do \
{ \
(X) = (((X) << 31) | ((X) >> 1)) & 0xFFFFFFFF; \
T = ((X) ^ (Y)) & 0xAAAAAAAA; (X) ^= T; (Y) ^= T; \
(Y) = (((Y) << 31) | ((Y) >> 1)) & 0xFFFFFFFF; \
T = (((Y) >> 8) ^ (X)) & 0x00FF00FF; (X) ^= T; (Y) ^= (T << 8); \
T = (((Y) >> 2) ^ (X)) & 0x33333333; (X) ^= T; (Y) ^= (T << 2); \
T = (((X) >> 16) ^ (Y)) & 0x0000FFFF; (Y) ^= T; (X) ^= (T << 16); \
T = (((X) >> 4) ^ (Y)) & 0x0F0F0F0F; (Y) ^= T; (X) ^= (T << 4); \
} while( 0 )
/*
* DES round macro
*/
#define DES_ROUND(X,Y) \
do \
{ \
T = *SK++ ^ (X); \
(Y) ^= SB8[ (T ) & 0x3F ] ^ \
SB6[ (T >> 8) & 0x3F ] ^ \
SB4[ (T >> 16) & 0x3F ] ^ \
SB2[ (T >> 24) & 0x3F ]; \
\
T = *SK++ ^ (((X) << 28) | ((X) >> 4)); \
(Y) ^= SB7[ (T ) & 0x3F ] ^ \
SB5[ (T >> 8) & 0x3F ] ^ \
SB3[ (T >> 16) & 0x3F ] ^ \
SB1[ (T >> 24) & 0x3F ]; \
} while( 0 )
#define SWAP(a,b) \
do \
{ \
uint32_t t = (a); (a) = (b); (b) = t; t = 0; \
} while( 0 )
void mbedtls_des_init( mbedtls_des_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_des_context ) );
}
void mbedtls_des_free( mbedtls_des_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_des_context ) );
}
void mbedtls_des3_init( mbedtls_des3_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_des3_context ) );
}
void mbedtls_des3_free( mbedtls_des3_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_des3_context ) );
}
static const unsigned char odd_parity_table[128] = { 1, 2, 4, 7, 8,
11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44,
47, 49, 50, 52, 55, 56, 59, 61, 62, 64, 67, 69, 70, 73, 74, 76, 79, 81,
82, 84, 87, 88, 91, 93, 94, 97, 98, 100, 103, 104, 107, 109, 110, 112,
115, 117, 118, 121, 122, 124, 127, 128, 131, 133, 134, 137, 138, 140,
143, 145, 146, 148, 151, 152, 155, 157, 158, 161, 162, 164, 167, 168,
171, 173, 174, 176, 179, 181, 182, 185, 186, 188, 191, 193, 194, 196,
199, 200, 203, 205, 206, 208, 211, 213, 214, 217, 218, 220, 223, 224,
227, 229, 230, 233, 234, 236, 239, 241, 242, 244, 247, 248, 251, 253,
254 };
void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
int i;
for( i = 0; i < MBEDTLS_DES_KEY_SIZE; i++ )
key[i] = odd_parity_table[key[i] / 2];
}
/*
* Check the given key's parity, returns 1 on failure, 0 on SUCCESS
*/
int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
int i;
for( i = 0; i < MBEDTLS_DES_KEY_SIZE; i++ )
if( key[i] != odd_parity_table[key[i] / 2] )
return( 1 );
return( 0 );
}
/*
* Table of weak and semi-weak keys
*
* Source: http://en.wikipedia.org/wiki/Weak_key
*
* Weak:
* Alternating ones + zeros (0x0101010101010101)
* Alternating 'F' + 'E' (0xFEFEFEFEFEFEFEFE)
* '0xE0E0E0E0F1F1F1F1'
* '0x1F1F1F1F0E0E0E0E'
*
* Semi-weak:
* 0x011F011F010E010E and 0x1F011F010E010E01
* 0x01E001E001F101F1 and 0xE001E001F101F101
* 0x01FE01FE01FE01FE and 0xFE01FE01FE01FE01
* 0x1FE01FE00EF10EF1 and 0xE01FE01FF10EF10E
* 0x1FFE1FFE0EFE0EFE and 0xFE1FFE1FFE0EFE0E
* 0xE0FEE0FEF1FEF1FE and 0xFEE0FEE0FEF1FEF1
*
*/
#define WEAK_KEY_COUNT 16
static const unsigned char weak_key_table[WEAK_KEY_COUNT][MBEDTLS_DES_KEY_SIZE] =
{
{ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
{ 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE },
{ 0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E },
{ 0xE0, 0xE0, 0xE0, 0xE0, 0xF1, 0xF1, 0xF1, 0xF1 },
{ 0x01, 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E },
{ 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E, 0x01 },
{ 0x01, 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1 },
{ 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1, 0x01 },
{ 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE },
{ 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01 },
{ 0x1F, 0xE0, 0x1F, 0xE0, 0x0E, 0xF1, 0x0E, 0xF1 },
{ 0xE0, 0x1F, 0xE0, 0x1F, 0xF1, 0x0E, 0xF1, 0x0E },
{ 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E, 0xFE },
{ 0xFE, 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E },
{ 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE },
{ 0xFE, 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1 }
};
int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
int i;
for( i = 0; i < WEAK_KEY_COUNT; i++ )
if( memcmp( weak_key_table[i], key, MBEDTLS_DES_KEY_SIZE) == 0 )
return( 1 );
return( 0 );
}
#if !defined(MBEDTLS_DES_SETKEY_ALT)
void mbedtls_des_setkey( uint32_t SK[32], const unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
int i;
uint32_t X, Y, T;
GET_UINT32_BE( X, key, 0 );
GET_UINT32_BE( Y, key, 4 );
/*
* Permuted Choice 1
*/
T = ((Y >> 4) ^ X) & 0x0F0F0F0F; X ^= T; Y ^= (T << 4);
T = ((Y ) ^ X) & 0x10101010; X ^= T; Y ^= (T );
X = (LHs[ (X ) & 0xF] << 3) | (LHs[ (X >> 8) & 0xF ] << 2)
| (LHs[ (X >> 16) & 0xF] << 1) | (LHs[ (X >> 24) & 0xF ] )
| (LHs[ (X >> 5) & 0xF] << 7) | (LHs[ (X >> 13) & 0xF ] << 6)
| (LHs[ (X >> 21) & 0xF] << 5) | (LHs[ (X >> 29) & 0xF ] << 4);
Y = (RHs[ (Y >> 1) & 0xF] << 3) | (RHs[ (Y >> 9) & 0xF ] << 2)
| (RHs[ (Y >> 17) & 0xF] << 1) | (RHs[ (Y >> 25) & 0xF ] )
| (RHs[ (Y >> 4) & 0xF] << 7) | (RHs[ (Y >> 12) & 0xF ] << 6)
| (RHs[ (Y >> 20) & 0xF] << 5) | (RHs[ (Y >> 28) & 0xF ] << 4);
X &= 0x0FFFFFFF;
Y &= 0x0FFFFFFF;
/*
* calculate subkeys
*/
for( i = 0; i < 16; i++ )
{
if( i < 2 || i == 8 || i == 15 )
{
X = ((X << 1) | (X >> 27)) & 0x0FFFFFFF;
Y = ((Y << 1) | (Y >> 27)) & 0x0FFFFFFF;
}
else
{
X = ((X << 2) | (X >> 26)) & 0x0FFFFFFF;
Y = ((Y << 2) | (Y >> 26)) & 0x0FFFFFFF;
}
*SK++ = ((X << 4) & 0x24000000) | ((X << 28) & 0x10000000)
| ((X << 14) & 0x08000000) | ((X << 18) & 0x02080000)
| ((X << 6) & 0x01000000) | ((X << 9) & 0x00200000)
| ((X >> 1) & 0x00100000) | ((X << 10) & 0x00040000)
| ((X << 2) & 0x00020000) | ((X >> 10) & 0x00010000)
| ((Y >> 13) & 0x00002000) | ((Y >> 4) & 0x00001000)
| ((Y << 6) & 0x00000800) | ((Y >> 1) & 0x00000400)
| ((Y >> 14) & 0x00000200) | ((Y ) & 0x00000100)
| ((Y >> 5) & 0x00000020) | ((Y >> 10) & 0x00000010)
| ((Y >> 3) & 0x00000008) | ((Y >> 18) & 0x00000004)
| ((Y >> 26) & 0x00000002) | ((Y >> 24) & 0x00000001);
*SK++ = ((X << 15) & 0x20000000) | ((X << 17) & 0x10000000)
| ((X << 10) & 0x08000000) | ((X << 22) & 0x04000000)
| ((X >> 2) & 0x02000000) | ((X << 1) & 0x01000000)
| ((X << 16) & 0x00200000) | ((X << 11) & 0x00100000)
| ((X << 3) & 0x00080000) | ((X >> 6) & 0x00040000)
| ((X << 15) & 0x00020000) | ((X >> 4) & 0x00010000)
| ((Y >> 2) & 0x00002000) | ((Y << 8) & 0x00001000)
| ((Y >> 14) & 0x00000808) | ((Y >> 9) & 0x00000400)
| ((Y ) & 0x00000200) | ((Y << 7) & 0x00000100)
| ((Y >> 7) & 0x00000020) | ((Y >> 3) & 0x00000011)
| ((Y << 2) & 0x00000004) | ((Y >> 21) & 0x00000002);
}
}
#endif /* !MBEDTLS_DES_SETKEY_ALT */
/*
* DES key schedule (56-bit, encryption)
*/
int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
mbedtls_des_setkey( ctx->sk, key );
return( 0 );
}
/*
* DES key schedule (56-bit, decryption)
*/
int mbedtls_des_setkey_dec( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
int i;
mbedtls_des_setkey( ctx->sk, key );
for( i = 0; i < 16; i += 2 )
{
SWAP( ctx->sk[i ], ctx->sk[30 - i] );
SWAP( ctx->sk[i + 1], ctx->sk[31 - i] );
}
return( 0 );
}
static void des3_set2key( uint32_t esk[96],
uint32_t dsk[96],
const unsigned char key[MBEDTLS_DES_KEY_SIZE*2] )
{
int i;
mbedtls_des_setkey( esk, key );
mbedtls_des_setkey( dsk + 32, key + 8 );
for( i = 0; i < 32; i += 2 )
{
dsk[i ] = esk[30 - i];
dsk[i + 1] = esk[31 - i];
esk[i + 32] = dsk[62 - i];
esk[i + 33] = dsk[63 - i];
esk[i + 64] = esk[i ];
esk[i + 65] = esk[i + 1];
dsk[i + 64] = dsk[i ];
dsk[i + 65] = dsk[i + 1];
}
}
/*
* Triple-DES key schedule (112-bit, encryption)
*/
int mbedtls_des3_set2key_enc( mbedtls_des3_context *ctx,
const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] )
{
uint32_t sk[96];
des3_set2key( ctx->sk, sk, key );
mbedtls_platform_zeroize( sk, sizeof( sk ) );
return( 0 );
}
/*
* Triple-DES key schedule (112-bit, decryption)
*/
int mbedtls_des3_set2key_dec( mbedtls_des3_context *ctx,
const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] )
{
uint32_t sk[96];
des3_set2key( sk, ctx->sk, key );
mbedtls_platform_zeroize( sk, sizeof( sk ) );
return( 0 );
}
static void des3_set3key( uint32_t esk[96],
uint32_t dsk[96],
const unsigned char key[24] )
{
int i;
mbedtls_des_setkey( esk, key );
mbedtls_des_setkey( dsk + 32, key + 8 );
mbedtls_des_setkey( esk + 64, key + 16 );
for( i = 0; i < 32; i += 2 )
{
dsk[i ] = esk[94 - i];
dsk[i + 1] = esk[95 - i];
esk[i + 32] = dsk[62 - i];
esk[i + 33] = dsk[63 - i];
dsk[i + 64] = esk[30 - i];
dsk[i + 65] = esk[31 - i];
}
}
/*
* Triple-DES key schedule (168-bit, encryption)
*/
int mbedtls_des3_set3key_enc( mbedtls_des3_context *ctx,
const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] )
{
uint32_t sk[96];
des3_set3key( ctx->sk, sk, key );
mbedtls_platform_zeroize( sk, sizeof( sk ) );
return( 0 );
}
/*
* Triple-DES key schedule (168-bit, decryption)
*/
int mbedtls_des3_set3key_dec( mbedtls_des3_context *ctx,
const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] )
{
uint32_t sk[96];
des3_set3key( sk, ctx->sk, key );
mbedtls_platform_zeroize( sk, sizeof( sk ) );
return( 0 );
}
/*
* DES-ECB block encryption/decryption
*/
#if !defined(MBEDTLS_DES_CRYPT_ECB_ALT)
int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx,
const unsigned char input[8],
unsigned char output[8] )
{
int i;
uint32_t X, Y, T, *SK;
SK = ctx->sk;
GET_UINT32_BE( X, input, 0 );
GET_UINT32_BE( Y, input, 4 );
DES_IP( X, Y );
for( i = 0; i < 8; i++ )
{
DES_ROUND( Y, X );
DES_ROUND( X, Y );
}
DES_FP( Y, X );
PUT_UINT32_BE( Y, output, 0 );
PUT_UINT32_BE( X, output, 4 );
return( 0 );
}
#endif /* !MBEDTLS_DES_CRYPT_ECB_ALT */
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/*
* DES-CBC buffer encryption/decryption
*/
int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx,
int mode,
size_t length,
unsigned char iv[8],
const unsigned char *input,
unsigned char *output )
{
int i;
unsigned char temp[8];
if( length % 8 )
return( MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH );
if( mode == MBEDTLS_DES_ENCRYPT )
{
while( length > 0 )
{
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( input[i] ^ iv[i] );
mbedtls_des_crypt_ecb( ctx, output, output );
memcpy( iv, output, 8 );
input += 8;
output += 8;
length -= 8;
}
}
else /* MBEDTLS_DES_DECRYPT */
{
while( length > 0 )
{
memcpy( temp, input, 8 );
mbedtls_des_crypt_ecb( ctx, input, output );
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, 8 );
input += 8;
output += 8;
length -= 8;
}
}
return( 0 );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
/*
* 3DES-ECB block encryption/decryption
*/
#if !defined(MBEDTLS_DES3_CRYPT_ECB_ALT)
int mbedtls_des3_crypt_ecb( mbedtls_des3_context *ctx,
const unsigned char input[8],
unsigned char output[8] )
{
int i;
uint32_t X, Y, T, *SK;
SK = ctx->sk;
GET_UINT32_BE( X, input, 0 );
GET_UINT32_BE( Y, input, 4 );
DES_IP( X, Y );
for( i = 0; i < 8; i++ )
{
DES_ROUND( Y, X );
DES_ROUND( X, Y );
}
for( i = 0; i < 8; i++ )
{
DES_ROUND( X, Y );
DES_ROUND( Y, X );
}
for( i = 0; i < 8; i++ )
{
DES_ROUND( Y, X );
DES_ROUND( X, Y );
}
DES_FP( Y, X );
PUT_UINT32_BE( Y, output, 0 );
PUT_UINT32_BE( X, output, 4 );
return( 0 );
}
#endif /* !MBEDTLS_DES3_CRYPT_ECB_ALT */
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/*
* 3DES-CBC buffer encryption/decryption
*/
int mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx,
int mode,
size_t length,
unsigned char iv[8],
const unsigned char *input,
unsigned char *output )
{
int i;
unsigned char temp[8];
if( length % 8 )
return( MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH );
if( mode == MBEDTLS_DES_ENCRYPT )
{
while( length > 0 )
{
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( input[i] ^ iv[i] );
mbedtls_des3_crypt_ecb( ctx, output, output );
memcpy( iv, output, 8 );
input += 8;
output += 8;
length -= 8;
}
}
else /* MBEDTLS_DES_DECRYPT */
{
while( length > 0 )
{
memcpy( temp, input, 8 );
mbedtls_des3_crypt_ecb( ctx, input, output );
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, 8 );
input += 8;
output += 8;
length -= 8;
}
}
return( 0 );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* !MBEDTLS_DES_ALT */
#if defined(MBEDTLS_SELF_TEST)
/*
* DES and 3DES test vectors from:
*
* http://csrc.nist.gov/groups/STM/cavp/documents/des/tripledes-vectors.zip
*/
static const unsigned char des3_test_keys[24] =
{
0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF,
0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01,
0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23
};
static const unsigned char des3_test_buf[8] =
{
0x4E, 0x6F, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74
};
static const unsigned char des3_test_ecb_dec[3][8] =
{
{ 0x37, 0x2B, 0x98, 0xBF, 0x52, 0x65, 0xB0, 0x59 },
{ 0xC2, 0x10, 0x19, 0x9C, 0x38, 0x5A, 0x65, 0xA1 },
{ 0xA2, 0x70, 0x56, 0x68, 0x69, 0xE5, 0x15, 0x1D }
};
static const unsigned char des3_test_ecb_enc[3][8] =
{
{ 0x1C, 0xD5, 0x97, 0xEA, 0x84, 0x26, 0x73, 0xFB },
{ 0xB3, 0x92, 0x4D, 0xF3, 0xC5, 0xB5, 0x42, 0x93 },
{ 0xDA, 0x37, 0x64, 0x41, 0xBA, 0x6F, 0x62, 0x6F }
};
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static const unsigned char des3_test_iv[8] =
{
0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF,
};
static const unsigned char des3_test_cbc_dec[3][8] =
{
{ 0x58, 0xD9, 0x48, 0xEF, 0x85, 0x14, 0x65, 0x9A },
{ 0x5F, 0xC8, 0x78, 0xD4, 0xD7, 0x92, 0xD9, 0x54 },
{ 0x25, 0xF9, 0x75, 0x85, 0xA8, 0x1E, 0x48, 0xBF }
};
static const unsigned char des3_test_cbc_enc[3][8] =
{
{ 0x91, 0x1C, 0x6D, 0xCF, 0x48, 0xA7, 0xC3, 0x4D },
{ 0x60, 0x1A, 0x76, 0x8F, 0xA1, 0xF9, 0x66, 0xF1 },
{ 0xA1, 0x50, 0x0F, 0x99, 0xB2, 0xCD, 0x64, 0x76 }
};
#endif /* MBEDTLS_CIPHER_MODE_CBC */
/*
* Checkup routine
*/
int mbedtls_des_self_test( int verbose )
{
int i, j, u, v, ret = 0;
mbedtls_des_context ctx;
mbedtls_des3_context ctx3;
unsigned char buf[8];
#if defined(MBEDTLS_CIPHER_MODE_CBC)
unsigned char prv[8];
unsigned char iv[8];
#endif
mbedtls_des_init( &ctx );
mbedtls_des3_init( &ctx3 );
/*
* ECB mode
*/
for( i = 0; i < 6; i++ )
{
u = i >> 1;
v = i & 1;
if( verbose != 0 )
mbedtls_printf( " DES%c-ECB-%3d (%s): ",
( u == 0 ) ? ' ' : '3', 56 + u * 56,
( v == MBEDTLS_DES_DECRYPT ) ? "dec" : "enc" );
memcpy( buf, des3_test_buf, 8 );
switch( i )
{
case 0:
mbedtls_des_setkey_dec( &ctx, des3_test_keys );
break;
case 1:
mbedtls_des_setkey_enc( &ctx, des3_test_keys );
break;
case 2:
mbedtls_des3_set2key_dec( &ctx3, des3_test_keys );
break;
case 3:
mbedtls_des3_set2key_enc( &ctx3, des3_test_keys );
break;
case 4:
mbedtls_des3_set3key_dec( &ctx3, des3_test_keys );
break;
case 5:
mbedtls_des3_set3key_enc( &ctx3, des3_test_keys );
break;
default:
return( 1 );
}
for( j = 0; j < 100; j++ )
{
if( u == 0 )
mbedtls_des_crypt_ecb( &ctx, buf, buf );
else
mbedtls_des3_crypt_ecb( &ctx3, buf, buf );
}
if( ( v == MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_ecb_dec[u], 8 ) != 0 ) ||
( v != MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_ecb_enc[u], 8 ) != 0 ) )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
goto exit;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/*
* CBC mode
*/
for( i = 0; i < 6; i++ )
{
u = i >> 1;
v = i & 1;
if( verbose != 0 )
mbedtls_printf( " DES%c-CBC-%3d (%s): ",
( u == 0 ) ? ' ' : '3', 56 + u * 56,
( v == MBEDTLS_DES_DECRYPT ) ? "dec" : "enc" );
memcpy( iv, des3_test_iv, 8 );
memcpy( prv, des3_test_iv, 8 );
memcpy( buf, des3_test_buf, 8 );
switch( i )
{
case 0:
mbedtls_des_setkey_dec( &ctx, des3_test_keys );
break;
case 1:
mbedtls_des_setkey_enc( &ctx, des3_test_keys );
break;
case 2:
mbedtls_des3_set2key_dec( &ctx3, des3_test_keys );
break;
case 3:
mbedtls_des3_set2key_enc( &ctx3, des3_test_keys );
break;
case 4:
mbedtls_des3_set3key_dec( &ctx3, des3_test_keys );
break;
case 5:
mbedtls_des3_set3key_enc( &ctx3, des3_test_keys );
break;
default:
return( 1 );
}
if( v == MBEDTLS_DES_DECRYPT )
{
for( j = 0; j < 100; j++ )
{
if( u == 0 )
mbedtls_des_crypt_cbc( &ctx, v, 8, iv, buf, buf );
else
mbedtls_des3_crypt_cbc( &ctx3, v, 8, iv, buf, buf );
}
}
else
{
for( j = 0; j < 100; j++ )
{
unsigned char tmp[8];
if( u == 0 )
mbedtls_des_crypt_cbc( &ctx, v, 8, iv, buf, buf );
else
mbedtls_des3_crypt_cbc( &ctx3, v, 8, iv, buf, buf );
memcpy( tmp, prv, 8 );
memcpy( prv, buf, 8 );
memcpy( buf, tmp, 8 );
}
memcpy( buf, prv, 8 );
}
if( ( v == MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_cbc_dec[u], 8 ) != 0 ) ||
( v != MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_cbc_enc[u], 8 ) != 0 ) )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
goto exit;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
if( verbose != 0 )
mbedtls_printf( "\n" );
exit:
mbedtls_des_free( &ctx );
mbedtls_des3_free( &ctx3 );
return( ret );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_DES_C */
|
the_stack_data/122015974.c | // INFO: trying to register non-static key in usbtouch_open
// https://syzkaller.appspot.com/bug?id=19bb4d1c56f91465a4a9f5396f0607d487947838
// status:dup
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <linux/usb/ch9.h>
unsigned long long procid;
static void sleep_ms(uint64_t ms)
{
usleep(ms * 1000);
}
#define USB_DEBUG 0
#define USB_MAX_EP_NUM 32
struct usb_device_index {
struct usb_device_descriptor* dev;
struct usb_config_descriptor* config;
unsigned config_length;
struct usb_interface_descriptor* iface;
struct usb_endpoint_descriptor* eps[USB_MAX_EP_NUM];
unsigned eps_num;
};
static bool parse_usb_descriptor(char* buffer, size_t length,
struct usb_device_index* index)
{
if (length <
sizeof(*index->dev) + sizeof(*index->config) + sizeof(*index->iface))
return false;
index->dev = (struct usb_device_descriptor*)buffer;
index->config = (struct usb_config_descriptor*)(buffer + sizeof(*index->dev));
index->config_length = length - sizeof(*index->dev);
index->iface =
(struct usb_interface_descriptor*)(buffer + sizeof(*index->dev) +
sizeof(*index->config));
index->eps_num = 0;
size_t offset = 0;
while (true) {
if (offset + 1 >= length)
break;
uint8_t desc_length = buffer[offset];
uint8_t desc_type = buffer[offset + 1];
if (desc_length <= 2)
break;
if (offset + desc_length > length)
break;
if (desc_type == USB_DT_ENDPOINT) {
index->eps[index->eps_num] =
(struct usb_endpoint_descriptor*)(buffer + offset);
index->eps_num++;
}
if (index->eps_num == USB_MAX_EP_NUM)
break;
offset += desc_length;
}
return true;
}
enum usb_fuzzer_event_type {
USB_FUZZER_EVENT_INVALID,
USB_FUZZER_EVENT_CONNECT,
USB_FUZZER_EVENT_DISCONNECT,
USB_FUZZER_EVENT_SUSPEND,
USB_FUZZER_EVENT_RESUME,
USB_FUZZER_EVENT_CONTROL,
};
struct usb_fuzzer_event {
uint32_t type;
uint32_t length;
char data[0];
};
struct usb_fuzzer_init {
uint64_t speed;
const char* driver_name;
const char* device_name;
};
struct usb_fuzzer_ep_io {
uint16_t ep;
uint16_t flags;
uint32_t length;
char data[0];
};
#define USB_FUZZER_IOCTL_INIT _IOW('U', 0, struct usb_fuzzer_init)
#define USB_FUZZER_IOCTL_RUN _IO('U', 1)
#define USB_FUZZER_IOCTL_EVENT_FETCH _IOR('U', 2, struct usb_fuzzer_event)
#define USB_FUZZER_IOCTL_EP0_WRITE _IOW('U', 3, struct usb_fuzzer_ep_io)
#define USB_FUZZER_IOCTL_EP0_READ _IOWR('U', 4, struct usb_fuzzer_ep_io)
#define USB_FUZZER_IOCTL_EP_ENABLE _IOW('U', 5, struct usb_endpoint_descriptor)
#define USB_FUZZER_IOCTL_EP_WRITE _IOW('U', 7, struct usb_fuzzer_ep_io)
#define USB_FUZZER_IOCTL_EP_READ _IOWR('U', 8, struct usb_fuzzer_ep_io)
#define USB_FUZZER_IOCTL_CONFIGURE _IO('U', 9)
#define USB_FUZZER_IOCTL_VBUS_DRAW _IOW('U', 10, uint32_t)
int usb_fuzzer_open()
{
return open("/sys/kernel/debug/usb-fuzzer", O_RDWR);
}
int usb_fuzzer_init(int fd, uint32_t speed, const char* driver,
const char* device)
{
struct usb_fuzzer_init arg;
arg.speed = speed;
arg.driver_name = driver;
arg.device_name = device;
return ioctl(fd, USB_FUZZER_IOCTL_INIT, &arg);
}
int usb_fuzzer_run(int fd)
{
return ioctl(fd, USB_FUZZER_IOCTL_RUN, 0);
}
int usb_fuzzer_event_fetch(int fd, struct usb_fuzzer_event* event)
{
return ioctl(fd, USB_FUZZER_IOCTL_EVENT_FETCH, event);
}
int usb_fuzzer_ep0_write(int fd, struct usb_fuzzer_ep_io* io)
{
return ioctl(fd, USB_FUZZER_IOCTL_EP0_WRITE, io);
}
int usb_fuzzer_ep0_read(int fd, struct usb_fuzzer_ep_io* io)
{
return ioctl(fd, USB_FUZZER_IOCTL_EP0_READ, io);
}
int usb_fuzzer_ep_write(int fd, struct usb_fuzzer_ep_io* io)
{
return ioctl(fd, USB_FUZZER_IOCTL_EP_WRITE, io);
}
int usb_fuzzer_ep_read(int fd, struct usb_fuzzer_ep_io* io)
{
return ioctl(fd, USB_FUZZER_IOCTL_EP_READ, io);
}
int usb_fuzzer_ep_enable(int fd, struct usb_endpoint_descriptor* desc)
{
return ioctl(fd, USB_FUZZER_IOCTL_EP_ENABLE, desc);
}
int usb_fuzzer_configure(int fd)
{
return ioctl(fd, USB_FUZZER_IOCTL_CONFIGURE, 0);
}
int usb_fuzzer_vbus_draw(int fd, uint32_t power)
{
return ioctl(fd, USB_FUZZER_IOCTL_VBUS_DRAW, power);
}
#define USB_MAX_PACKET_SIZE 1024
struct usb_fuzzer_control_event {
struct usb_fuzzer_event inner;
struct usb_ctrlrequest ctrl;
char data[USB_MAX_PACKET_SIZE];
};
struct usb_fuzzer_ep_io_data {
struct usb_fuzzer_ep_io inner;
char data[USB_MAX_PACKET_SIZE];
};
struct vusb_connect_string_descriptor {
uint32_t len;
char* str;
} __attribute__((packed));
struct vusb_connect_descriptors {
uint32_t qual_len;
char* qual;
uint32_t bos_len;
char* bos;
uint32_t strs_len;
struct vusb_connect_string_descriptor strs[0];
} __attribute__((packed));
static const char* default_string = "syzkaller";
static bool lookup_connect_response(struct vusb_connect_descriptors* descs,
struct usb_device_index* index,
struct usb_ctrlrequest* ctrl,
char** response_data,
uint32_t* response_length)
{
uint8_t str_idx;
switch (ctrl->bRequestType & USB_TYPE_MASK) {
case USB_TYPE_STANDARD:
switch (ctrl->bRequest) {
case USB_REQ_GET_DESCRIPTOR:
switch (ctrl->wValue >> 8) {
case USB_DT_DEVICE:
*response_data = (char*)index->dev;
*response_length = sizeof(*index->dev);
return true;
case USB_DT_CONFIG:
*response_data = (char*)index->config;
*response_length = index->config_length;
return true;
case USB_DT_STRING:
str_idx = (uint8_t)ctrl->wValue;
if (str_idx >= descs->strs_len) {
*response_data = (char*)default_string;
*response_length = strlen(default_string);
} else {
*response_data = descs->strs[str_idx].str;
*response_length = descs->strs[str_idx].len;
}
return true;
case USB_DT_BOS:
*response_data = descs->bos;
*response_length = descs->bos_len;
return true;
case USB_DT_DEVICE_QUALIFIER:
*response_data = descs->qual;
*response_length = descs->qual_len;
return true;
default:
exit(1);
return false;
}
break;
default:
exit(1);
return false;
}
break;
default:
exit(1);
return false;
}
return false;
}
static volatile long syz_usb_connect(volatile long a0, volatile long a1,
volatile long a2, volatile long a3)
{
uint64_t speed = a0;
uint64_t dev_len = a1;
char* dev = (char*)a2;
struct vusb_connect_descriptors* descs = (struct vusb_connect_descriptors*)a3;
if (!dev) {
return -1;
}
struct usb_device_index index;
memset(&index, 0, sizeof(index));
int rv = 0;
rv = parse_usb_descriptor(dev, dev_len, &index);
if (!rv) {
return rv;
}
int fd = usb_fuzzer_open();
if (fd < 0) {
return fd;
}
char device[32];
sprintf(&device[0], "dummy_udc.%llu", procid);
rv = usb_fuzzer_init(fd, speed, "dummy_udc", &device[0]);
if (rv < 0) {
return rv;
}
rv = usb_fuzzer_run(fd);
if (rv < 0) {
return rv;
}
bool done = false;
while (!done) {
struct usb_fuzzer_control_event event;
event.inner.type = 0;
event.inner.length = sizeof(event.ctrl);
rv = usb_fuzzer_event_fetch(fd, (struct usb_fuzzer_event*)&event);
if (rv < 0) {
return rv;
}
if (event.inner.type != USB_FUZZER_EVENT_CONTROL)
continue;
bool response_found = false;
char* response_data = NULL;
uint32_t response_length = 0;
if (event.ctrl.bRequestType & USB_DIR_IN) {
response_found = lookup_connect_response(
descs, &index, &event.ctrl, &response_data, &response_length);
if (!response_found) {
return -1;
}
} else {
if ((event.ctrl.bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD ||
event.ctrl.bRequest != USB_REQ_SET_CONFIGURATION) {
exit(1);
return -1;
}
done = true;
}
if (done) {
rv = usb_fuzzer_vbus_draw(fd, index.config->bMaxPower);
if (rv < 0) {
return rv;
}
rv = usb_fuzzer_configure(fd);
if (rv < 0) {
return rv;
}
unsigned ep;
for (ep = 0; ep < index.eps_num; ep++) {
rv = usb_fuzzer_ep_enable(fd, index.eps[ep]);
if (rv < 0) {
} else {
}
}
}
struct usb_fuzzer_ep_io_data response;
response.inner.ep = 0;
response.inner.flags = 0;
if (response_length > sizeof(response.data))
response_length = 0;
if (event.ctrl.wLength < response_length)
response_length = event.ctrl.wLength;
response.inner.length = response_length;
if (response_data)
memcpy(&response.data[0], response_data, response_length);
else
memset(&response.data[0], 0, response_length);
if (event.ctrl.bRequestType & USB_DIR_IN)
rv = usb_fuzzer_ep0_write(fd, (struct usb_fuzzer_ep_io*)&response);
else
rv = usb_fuzzer_ep0_read(fd, (struct usb_fuzzer_ep_io*)&response);
if (rv < 0) {
return rv;
}
}
sleep_ms(200);
return fd;
}
static long syz_open_dev(volatile long a0, volatile long a1, volatile long a2)
{
if (a0 == 0xc || a0 == 0xb) {
char buf[128];
sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1,
(uint8_t)a2);
return open(buf, O_RDWR, 0);
} else {
char buf[1024];
char* hash;
strncpy(buf, (char*)a0, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
while ((hash = strchr(buf, '#'))) {
*hash = '0' + (char)(a1 % 10);
a1 /= 10;
}
return open(buf, a2, 0);
}
}
int main(void)
{
syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0);
*(uint8_t*)0x20000000 = 0x12;
*(uint8_t*)0x20000001 = 1;
*(uint16_t*)0x20000002 = 0;
*(uint8_t*)0x20000004 = 0xac;
*(uint8_t*)0x20000005 = 0xb8;
*(uint8_t*)0x20000006 = 0x3e;
*(uint8_t*)0x20000007 = 8;
*(uint16_t*)0x20000008 = 0x4e7;
*(uint16_t*)0x2000000a = 0x20;
*(uint16_t*)0x2000000c = 0x4e81;
*(uint8_t*)0x2000000e = 0;
*(uint8_t*)0x2000000f = 0;
*(uint8_t*)0x20000010 = 0;
*(uint8_t*)0x20000011 = 1;
*(uint8_t*)0x20000012 = 9;
*(uint8_t*)0x20000013 = 2;
*(uint16_t*)0x20000014 = 0x1b;
*(uint8_t*)0x20000016 = 1;
*(uint8_t*)0x20000017 = 0;
*(uint8_t*)0x20000018 = 0;
*(uint8_t*)0x20000019 = 0;
*(uint8_t*)0x2000001a = 0;
*(uint8_t*)0x2000001b = 9;
*(uint8_t*)0x2000001c = 4;
*(uint8_t*)0x2000001d = 0xae;
*(uint8_t*)0x2000001e = 0;
*(uint8_t*)0x2000001f = 1;
*(uint8_t*)0x20000020 = 0xba;
*(uint8_t*)0x20000021 = 0xca;
*(uint8_t*)0x20000022 = 0x3b;
*(uint8_t*)0x20000023 = 0;
*(uint8_t*)0x20000024 = 7;
*(uint8_t*)0x20000025 = 5;
*(uint8_t*)0x20000026 = 0x81;
*(uint8_t*)0x20000027 = 0;
*(uint16_t*)0x20000028 = 0;
*(uint8_t*)0x2000002a = 0;
*(uint8_t*)0x2000002b = 0;
*(uint8_t*)0x2000002c = 0;
syz_usb_connect(0, 0x2d, 0x20000000, 0);
memcpy((void*)0x20000000, "/dev/input/event#\000", 18);
syz_open_dev(0x20000000, 4, 2);
return 0;
}
|
the_stack_data/1096521.c | #include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define UNCONN_DGRAM_PATH "/tmp/unconn_dgram.sock"
static void
test_send_unconn_dgram(void)
{
struct sockaddr_un un;
int s, n;
s = socket(AF_LOCAL, SOCK_DGRAM, 0);
if (s < 0)
err(1, "send socket failed");
memset(&un, 0, sizeof(un));
un.sun_family = AF_LOCAL;
strlcpy(un.sun_path, UNCONN_DGRAM_PATH, sizeof(un.sun_path));
n = sendto(s, UNCONN_DGRAM_PATH, sizeof(UNCONN_DGRAM_PATH), 0,
(const struct sockaddr *)&un, sizeof(un));
if (n < 0)
err(1, "sendto failed");
else if (n != sizeof(UNCONN_DGRAM_PATH))
err(1, "sendto size mismatch");
}
int
main(void)
{
struct sockaddr_un un;
char buf[64];
pid_t pid;
int s, n, status;
s = socket(AF_LOCAL, SOCK_DGRAM, 0);
if (s < 0)
err(1, "socket failed");
memset(&un, 0, sizeof(un));
un.sun_family = AF_LOCAL;
strlcpy(un.sun_path, UNCONN_DGRAM_PATH, sizeof(un.sun_path));
unlink(un.sun_path);
if (bind(s, (const struct sockaddr *)&un, sizeof(un)) < 0)
err(1, "bind failed");
pid = fork();
if (pid < 0) {
err(1, "fork failed");
} else if (pid == 0) {
close(s);
test_send_unconn_dgram();
exit(0);
}
waitpid(pid, &status, 0);
if (!WIFEXITED(status))
err(1, "child did not exit");
if (WEXITSTATUS(status) != 0)
err(WEXITSTATUS(status), "child failed");
n = read(s, buf, sizeof(buf));
if (n < 0) {
err(1, "read failed");
} else if (n != sizeof(UNCONN_DGRAM_PATH)) {
warnx("dgram size mismatch");
abort();
}
fprintf(stderr, "%s\n", buf);
exit(0);
}
|
the_stack_data/341191.c | #include <stdio.h>
#include <stdlib.h>
struct NODE
{
int key;
struct NODE *next;
};
struct NODE *createNewNode(int key)
{
struct NODE *newNode = (struct NODE *)malloc(sizeof(struct NODE));
newNode->key = key;
newNode->next = NULL;
return newNode;
}
struct NODE *buildingOneTwoThree()
{
struct NODE *first = NULL;
struct NODE *second = NULL;
struct NODE *third = NULL;
first = (struct NODE *)malloc(sizeof(struct NODE));
second = (struct NODE *)malloc(sizeof(struct NODE));
third = (struct NODE *)malloc(sizeof(struct NODE));
first->key = 1;
first->next = second;
second->key = 250;
second->next = third;
third->key = 3;
third->next = NULL;
return first;
}
int Length(struct NODE *head)
{
struct NODE *ptr = head;
int count = 0;
while (ptr != NULL)
{
count++;
ptr = ptr->next;
}
return count;
}
int searchKey(struct NODE *list_head, int searchKey)
{
struct NODE *ptr = list_head;
while (ptr != NULL)
{
if (ptr->key != searchKey)
ptr = ptr->next;
else
return 1;
}
return 0;
}
void searchTest()
{
struct NODE *myList = buildingOneTwoThree();
int found = searchKey(myList, 250);
if (found)
printf("Search key found\n");
else
printf("Search key not found\n");
}
int main()
{
searchTest();
} |
the_stack_data/242329515.c | /*
* Exercise 1.13
* Write a program to print a histogram of the lengths of words in its input.
* Vertical Version
*/
#include <stdio.h>
#define MAX_LENGTH 31 // max length of the word
/* prints histogram for the length of words
* vertical ver.
*/
int main (void)
{
int words[MAX_LENGTH];
int length, print, c, i, j;
length = 0;
print = 1;
for (i = 0; i < MAX_LENGTH; i++)
words[i] = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\t' || c == '\n') {
words[length]++;
length = 0;
} else {
length++;
}
}
for (i = 1; i < MAX_LENGTH; i++)
printf("%2d ", i);
printf("\n");
for (j = 0; print != 0; j++) {
print = 0;
for (i = 1; i < MAX_LENGTH; i++) {
if (words[i] > j) {
printf("## ");
print++;
} else {
printf(" ");
}
}
printf("\n");
}
}
|
the_stack_data/190768351.c | #include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
puts("pipe1 running");
printf("PARENT: pid=%d\n", getpid());
int pipefd[2];
pipe(pipefd);
puts("PARENT: fork");
pid_t pid = fork();
if (pid == 0) {
printf("CHILD: pid=%d; ppid=%d\n", getpid(), getppid());
close(pipefd[0]); // fechar a ponta que não vai usar
write(pipefd[1], "Hello, parent!", 15);
} else {
printf("PARENT: pid=%d; child=%d\n", getpid(), pid);
close(pipefd[1]); // fechar a ponta que não vai usar
char msg[15];
read(pipefd[0], msg, 15);
printf("PARENT: message from child is \"%s\"\n", msg);
int res;
waitpid(pid, &res, 0);
printf("PARENT: child process %d terminated with %d\n", pid, res);
if (WIFEXITED(res)) {
printf("PARENT: child returned %d\n", WEXITSTATUS(res));
} else {
printf("PARENT: child terminated abnormally\n");
}
}
return 0;
}
|
the_stack_data/126485.c | #include <stdio.h>
#include <stdlib.h>
#define NUM 100
int comp(const void *, const void *);
int main(void)
{
int ar[NUM];
int i = 0;
for (; i < NUM; i++)
{
ar[i] = i;
}
for (i = 0; i < NUM; i++)
{
printf("%3d ", ar[i]);
if (i % 20 == 19)
putchar('\n');
}
putchar('\n');
putchar('\n');
qsort(ar, NUM, sizeof(int), comp);
for (i = 0; i < NUM; i++)
{
printf("%3d ", ar[i]);
if (i % 20 == 19)
putchar('\n');
}
putchar('\n');
return 0;
}
int comp(const void * p1, const void * p2)
{
const int * a1 = (const int *) p1;
const int * a2 = (const int *) p2;
if (*a1 > *a2)
return -1;
else if (*a1 == *a2)
return 0;
else return 1;
} |
the_stack_data/148578052.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int citatel,jmenovatel;
}ZLOMEK;
void menu(){
printf("Konec ....................... 0\n");
printf("Soucet zlomku ............... 1\n");
printf("Rozdil zlomku ............... 2\n");
printf("Soucin zlomku ............... 3\n");
printf("Podil zlomku ............... 4\n");
printf("Zkraceni prvniho zlomku .... 5\n");
printf("Zkraceni druheho zlomku .... 6\n");
printf("Novy prvni zlomek ........... 7\n");
printf("Novy druhy zlomek ........... 8\n");
}
int nsd(int a, int b){
int pom;
while(b != 0){
pom=a % b;
a = b;
b = pom;
}
return (a);
}
ZLOMEK zkraceniZlomku(ZLOMEK z){
printf("%d/%d = ",z.citatel,z.jmenovatel);
//tady doplňte kód, který zkrátí aktuální zlomek z
//využijte funkci nsd, kterou jsem vám napsala, znaménka neřešte
int x = nsd(z.citatel, z.jmenovatel);
z.citatel/=x;
z.jmenovatel/=x;
printf("%d/%d\n",z.citatel,z.jmenovatel);
return z;
}
void soucet(ZLOMEK z1, ZLOMEK z2){
ZLOMEK pom;
pom.jmenovatel = z1.jmenovatel*z2.jmenovatel;
pom.citatel = z2.jmenovatel*z1.citatel + z1.jmenovatel*z2.citatel;
printf("%d/%d + %d/%d = %d/%d\n",z1.citatel, z1.jmenovatel, z2. citatel, z2.jmenovatel, pom.citatel, pom.jmenovatel);
}
void rozdil(ZLOMEK z1, ZLOMEK z2){
ZLOMEK pom;
pom.jmenovatel = z1.jmenovatel*z2.jmenovatel;
pom.citatel = z2.jmenovatel*z1.citatel - z1.jmenovatel*z2.citatel;
printf("%d/%d – %d/%d = %d/%d\n",z1.citatel, z1.jmenovatel, z2. citatel, z2.jmenovatel, pom.citatel, pom.jmenovatel);
}
void soucin(ZLOMEK z1, ZLOMEK z2){
ZLOMEK pom;
pom.jmenovatel = z1.jmenovatel*z2.jmenovatel;
pom.citatel = z1.citatel*z2.citatel;
printf("%d/%d * %d/%d = %d/%d\n",z1.citatel, z1.jmenovatel, z2. citatel, z2.jmenovatel, pom.citatel, pom.jmenovatel);
}
void podil(ZLOMEK z1, ZLOMEK z2){
ZLOMEK pom;
pom.jmenovatel = z1.jmenovatel*z2.citatel;
pom.citatel = z1.citatel*z2.jmenovatel;
printf("%d/%d / %d/%d = %d/%d\n",z1.citatel, z1.jmenovatel, z2. citatel, z2.jmenovatel, pom.citatel, pom.jmenovatel);
}
ZLOMEK novy(){
ZLOMEK novy;
printf("Zadej citatel: ");
scanf("%d",&novy.citatel);
do{
printf("Zadej jmenovatel ruzny od nuly: ");
scanf("%d",&novy.jmenovatel);
}while(novy.jmenovatel==0);
printf("Novy zlomek: %d/%d\n",novy.citatel,novy.jmenovatel);
return novy;
}
int main(void) {
//budeme pracovat se dvěma zlomky
ZLOMEK z1 ={5,25};
ZLOMEK z2 ={1,3};
int volba=1;
while (volba!=0){
menu();
scanf("%d",&volba);
switch (volba){
case 1: soucet(z1,z2);
break;
case 2: rozdil(z1,z2);
break;
case 3: soucin(z1,z2);
break;
case 4: podil(z1,z2);
break;
case 5: z1=zkraceniZlomku(z1);
break;
case 6: z2=zkraceniZlomku(z2);
break;
case 7: z1=novy();
break;
case 8: z2=novy();
break;
default: printf("Tato volba je neplatna.\n");break;
}
}
printf("\nKonec");
return 0;
}
|
the_stack_data/81976.c | /* $XConsortium: AuDispose.c,v 1.5 95/07/10 21:18:07 gildea Exp $ */
/*
Copyright (c) 1988 X Consortium
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
X CONSORTIUM 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.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
*/
#include <X11/Xauth.h>
void
XauDisposeAuth (auth)
Xauth *auth;
{
if (auth) {
if (auth->address) (void) free (auth->address);
if (auth->number) (void) free (auth->number);
if (auth->name) (void) free (auth->name);
if (auth->data) {
(void) bzero (auth->data, auth->data_length);
(void) free (auth->data);
}
free ((char *) auth);
}
return;
}
|
the_stack_data/815097.c | /**
******************************************************************************
* @file stm32g0xx_ll_usart.c
* @author MCD Application Team
* @brief USART LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2018 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32g0xx_ll_usart.h"
#include "stm32g0xx_ll_rcc.h"
#include "stm32g0xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G0xx_LL_Driver
* @{
*/
#if defined (USART1) || defined (USART2) || defined (USART3) || defined (USART4) || defined (USART5) || defined (USART6)
/** @addtogroup USART_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup USART_LL_Private_Macros
* @{
*/
#define IS_LL_USART_PRESCALER(__VALUE__) (((__VALUE__) == LL_USART_PRESCALER_DIV1) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV2) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV4) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV6) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV8) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV10) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV12) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV16) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV32) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV64) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV128) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV256))
/* __BAUDRATE__ The maximum Baud Rate is derived from the maximum clock available
* divided by the smallest oversampling used on the USART (i.e. 8) */
#define IS_LL_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) <= 8000000U)
/* __VALUE__ In case of oversampling by 16 and 8, BRR content must be greater than or equal to 16d. */
#define IS_LL_USART_BRR_MIN(__VALUE__) ((__VALUE__) >= 16U)
#define IS_LL_USART_DIRECTION(__VALUE__) (((__VALUE__) == LL_USART_DIRECTION_NONE) \
|| ((__VALUE__) == LL_USART_DIRECTION_RX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX_RX))
#define IS_LL_USART_PARITY(__VALUE__) (((__VALUE__) == LL_USART_PARITY_NONE) \
|| ((__VALUE__) == LL_USART_PARITY_EVEN) \
|| ((__VALUE__) == LL_USART_PARITY_ODD))
#define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_7B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_8B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_9B))
#define IS_LL_USART_OVERSAMPLING(__VALUE__) (((__VALUE__) == LL_USART_OVERSAMPLING_16) \
|| ((__VALUE__) == LL_USART_OVERSAMPLING_8))
#define IS_LL_USART_LASTBITCLKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_LASTCLKPULSE_NO_OUTPUT) \
|| ((__VALUE__) == LL_USART_LASTCLKPULSE_OUTPUT))
#define IS_LL_USART_CLOCKPHASE(__VALUE__) (((__VALUE__) == LL_USART_PHASE_1EDGE) \
|| ((__VALUE__) == LL_USART_PHASE_2EDGE))
#define IS_LL_USART_CLOCKPOLARITY(__VALUE__) (((__VALUE__) == LL_USART_POLARITY_LOW) \
|| ((__VALUE__) == LL_USART_POLARITY_HIGH))
#define IS_LL_USART_CLOCKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_CLOCK_DISABLE) \
|| ((__VALUE__) == LL_USART_CLOCK_ENABLE))
#define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_0_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_1) \
|| ((__VALUE__) == LL_USART_STOPBITS_1_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_2))
#define IS_LL_USART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_USART_HWCONTROL_NONE) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_CTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS_CTS))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup USART_LL_Exported_Functions
* @{
*/
/** @addtogroup USART_LL_EF_Init
* @{
*/
/**
* @brief De-initialize USART registers (Registers restored to their default values).
* @param USARTx USART Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are de-initialized
* - ERROR: USART registers are not de-initialized
*/
ErrorStatus LL_USART_DeInit(USART_TypeDef *USARTx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
if (USARTx == USART1)
{
/* Force reset of USART clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_USART1);
/* Release reset of USART clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_USART1);
}
else if (USARTx == USART2)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART2);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART2);
}
#if defined(USART3)
else if (USARTx == USART3)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART3);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART3);
}
#endif /* USART3 */
#if defined(USART4)
else if (USARTx == USART4)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART4);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART4);
}
#endif /* USART4 */
#if defined(USART5)
else if (USARTx == USART5)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART5);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART5);
}
#endif /* USART5 */
#if defined(USART6)
else if (USARTx == USART6)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART6);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART6);
}
#endif /* USART6 */
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Initialize USART registers according to the specified
* parameters in USART_InitStruct.
* @note As some bits in USART configuration registers can only be written when
* the USART is disabled (USART_CR1_UE bit =0), USART Peripheral should be in disabled state prior calling
* this function. Otherwise, ERROR result will be returned.
* @note Baud rate value stored in USART_InitStruct BaudRate field, should be valid (different from 0).
* @param USARTx USART Instance
* @param USART_InitStruct pointer to a LL_USART_InitTypeDef structure
* that contains the configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are initialized according to USART_InitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, LL_USART_InitTypeDef *USART_InitStruct)
{
ErrorStatus status = ERROR;
uint32_t periphclk = LL_RCC_PERIPH_FREQUENCY_NO;
#if !defined(RCC_CCIPR_USART3SEL)&&!defined(RCC_CCIPR_USART4SEL)||(!defined(RCC_CCIPR_USART2SEL))||!defined(RCC_CCIPR_USART5SEL)||!defined(RCC_CCIPR_USART6SEL)
LL_RCC_ClocksTypeDef RCC_Clocks;
#endif
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_PRESCALER(USART_InitStruct->PrescalerValue));
assert_param(IS_LL_USART_BAUDRATE(USART_InitStruct->BaudRate));
assert_param(IS_LL_USART_DATAWIDTH(USART_InitStruct->DataWidth));
assert_param(IS_LL_USART_STOPBITS(USART_InitStruct->StopBits));
assert_param(IS_LL_USART_PARITY(USART_InitStruct->Parity));
assert_param(IS_LL_USART_DIRECTION(USART_InitStruct->TransferDirection));
assert_param(IS_LL_USART_HWCONTROL(USART_InitStruct->HardwareFlowControl));
assert_param(IS_LL_USART_OVERSAMPLING(USART_InitStruct->OverSampling));
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/*---------------------------- USART CR1 Configuration ---------------------
* Configure USARTx CR1 (USART Word Length, Parity, Mode and Oversampling bits) with parameters:
* - DataWidth: USART_CR1_M bits according to USART_InitStruct->DataWidth value
* - Parity: USART_CR1_PCE, USART_CR1_PS bits according to USART_InitStruct->Parity value
* - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to USART_InitStruct->TransferDirection value
* - Oversampling: USART_CR1_OVER8 bit according to USART_InitStruct->OverSampling value.
*/
MODIFY_REG(USARTx->CR1,
(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS |
USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8),
(USART_InitStruct->DataWidth | USART_InitStruct->Parity |
USART_InitStruct->TransferDirection | USART_InitStruct->OverSampling));
/*---------------------------- USART CR2 Configuration ---------------------
* Configure USARTx CR2 (Stop bits) with parameters:
* - Stop Bits: USART_CR2_STOP bits according to USART_InitStruct->StopBits value.
* - CLKEN, CPOL, CPHA and LBCL bits are to be configured using LL_USART_ClockInit().
*/
LL_USART_SetStopBitsLength(USARTx, USART_InitStruct->StopBits);
/*---------------------------- USART CR3 Configuration ---------------------
* Configure USARTx CR3 (Hardware Flow Control) with parameters:
* - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according to
* USART_InitStruct->HardwareFlowControl value.
*/
LL_USART_SetHWFlowCtrl(USARTx, USART_InitStruct->HardwareFlowControl);
/*---------------------------- USART BRR Configuration ---------------------
* Retrieve Clock frequency used for USART Peripheral
*/
if (USARTx == USART1)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART1_CLKSOURCE);
}
else if (USARTx == USART2)
{
#if defined(RCC_CCIPR_USART2SEL)
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART2_CLKSOURCE);
#else
/* USART2 clock is PCLK */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
#endif
}
#if defined(USART3)
else if (USARTx == USART3)
{
#if defined(RCC_CCIPR_USART3SEL)
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART3_CLKSOURCE);
#else
/* USART3 clock is PCLK */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
#endif
}
#endif /* USART3 */
#if defined(USART4)
else if (USARTx == USART4)
{
#if defined(RCC_CCIPR_USART4SEL)
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART4_CLKSOURCE);
#else
/* USART4 clock is PCLK1 */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
#endif /* RCC_CCIPR_USART4SEL */
}
#endif /* USART4 */
#if defined(USART5)
else if (USARTx == USART5)
{
/* USART5 clock is PCLK1 */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
}
#endif /* USART5 */
#if defined(USART6)
else if (USARTx == USART6)
{
/* USART6 clock is PCLK1 */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
}
#endif /* USART6 */
else
{
/* Nothing to do, as error code is already assigned to ERROR value */
}
/* Configure the USART Baud Rate :
- prescaler value is required
- valid baud rate value (different from 0) is required
- Peripheral clock as returned by RCC service, should be valid (different from 0).
*/
if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO)
&& (USART_InitStruct->BaudRate != 0U))
{
status = SUCCESS;
LL_USART_SetBaudRate(USARTx,
periphclk,
USART_InitStruct->PrescalerValue,
USART_InitStruct->OverSampling,
USART_InitStruct->BaudRate);
/* Check BRR is greater than or equal to 16d */
assert_param(IS_LL_USART_BRR_MIN(USARTx->BRR));
}
/*---------------------------- USART PRESC Configuration -----------------------
* Configure USARTx PRESC (Prescaler) with parameters:
* - PrescalerValue: USART_PRESC_PRESCALER bits according to USART_InitStruct->PrescalerValue value.
*/
LL_USART_SetPrescaler(USARTx, USART_InitStruct->PrescalerValue);
}
/* Endif (=> USART not in Disabled state => return ERROR) */
return (status);
}
/**
* @brief Set each @ref LL_USART_InitTypeDef field to default value.
* @param USART_InitStruct pointer to a @ref LL_USART_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_StructInit(LL_USART_InitTypeDef *USART_InitStruct)
{
/* Set USART_InitStruct fields to default values */
USART_InitStruct->PrescalerValue = LL_USART_PRESCALER_DIV1;
USART_InitStruct->BaudRate = 9600U;
USART_InitStruct->DataWidth = LL_USART_DATAWIDTH_8B;
USART_InitStruct->StopBits = LL_USART_STOPBITS_1;
USART_InitStruct->Parity = LL_USART_PARITY_NONE ;
USART_InitStruct->TransferDirection = LL_USART_DIRECTION_TX_RX;
USART_InitStruct->HardwareFlowControl = LL_USART_HWCONTROL_NONE;
USART_InitStruct->OverSampling = LL_USART_OVERSAMPLING_16;
}
/**
* @brief Initialize USART Clock related settings according to the
* specified parameters in the USART_ClockInitStruct.
* @note As some bits in USART configuration registers can only be written when
* the USART is disabled (USART_CR1_UE bit =0), USART Peripheral should be in disabled state prior calling
* this function. Otherwise, ERROR result will be returned.
* @param USARTx USART Instance
* @param USART_ClockInitStruct pointer to a @ref LL_USART_ClockInitTypeDef structure
* that contains the Clock configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers related to Clock settings are initialized according
* to USART_ClockInitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_ClockInit(USART_TypeDef *USARTx, LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
ErrorStatus status = SUCCESS;
/* Check USART Instance and Clock signal output parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_CLOCKOUTPUT(USART_ClockInitStruct->ClockOutput));
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/* Ensure USART instance is USART capable */
assert_param(IS_USART_INSTANCE(USARTx));
/* Check clock related parameters */
assert_param(IS_LL_USART_CLOCKPOLARITY(USART_ClockInitStruct->ClockPolarity));
assert_param(IS_LL_USART_CLOCKPHASE(USART_ClockInitStruct->ClockPhase));
assert_param(IS_LL_USART_LASTBITCLKOUTPUT(USART_ClockInitStruct->LastBitClockPulse));
/*---------------------------- USART CR2 Configuration -----------------------
* Configure USARTx CR2 (Clock signal related bits) with parameters:
* - Clock Output: USART_CR2_CLKEN bit according to USART_ClockInitStruct->ClockOutput value
* - Clock Polarity: USART_CR2_CPOL bit according to USART_ClockInitStruct->ClockPolarity value
* - Clock Phase: USART_CR2_CPHA bit according to USART_ClockInitStruct->ClockPhase value
* - Last Bit Clock Pulse Output: USART_CR2_LBCL bit according to USART_ClockInitStruct->LastBitClockPulse value.
*/
MODIFY_REG(USARTx->CR2,
USART_CR2_CLKEN | USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_LBCL,
USART_ClockInitStruct->ClockOutput | USART_ClockInitStruct->ClockPolarity |
USART_ClockInitStruct->ClockPhase | USART_ClockInitStruct->LastBitClockPulse);
}
/* Else (USART not in Disabled state => return ERROR */
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Set each field of a @ref LL_USART_ClockInitTypeDef type structure to default value.
* @param USART_ClockInitStruct pointer to a @ref LL_USART_ClockInitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
/* Set LL_USART_ClockInitStruct fields with default values */
USART_ClockInitStruct->ClockOutput = LL_USART_CLOCK_DISABLE;
USART_ClockInitStruct->ClockPolarity = LL_USART_POLARITY_LOW; /* Not relevant when ClockOutput =
LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->ClockPhase = LL_USART_PHASE_1EDGE; /* Not relevant when ClockOutput =
LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->LastBitClockPulse = LL_USART_LASTCLKPULSE_NO_OUTPUT; /* Not relevant when ClockOutput =
LL_USART_CLOCK_DISABLE */
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* USART1 || USART2 || USART3 || USART4 || USART5 || USART6 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/628006.c | #include <stdio.h>
int main(){
int valorInicial = 10, valorFinal = 20, posicaoVetor, numero = 0;
int tamanhoVetor = 11, vetorNumeros[tamanhoVetor];
numero = valorInicial;
for(posicaoVetor = 0 ; posicaoVetor < tamanhoVetor; posicaoVetor++){
vetorNumeros[posicaoVetor] = numero;
numero++;
}
printf("Os valores pares que vão do número 20 ao 10 são: \n");
for(posicaoVetor = tamanhoVetor - 1 ; posicaoVetor >= 0; posicaoVetor--){
if(vetorNumeros[posicaoVetor] % 2 == 0){
printf("%d\n", vetorNumeros[posicaoVetor]);
}
}
printf("\n\n");
printf("Elementos ímpares: \n");
for(posicaoVetor = tamanhoVetor - 1 ; posicaoVetor >= 0; posicaoVetor--){
if(vetorNumeros[posicaoVetor] % 2 != 0){
printf("%d\n", vetorNumeros[posicaoVetor]);
}
}
return 0;
} |
the_stack_data/386391.c | /* getopt_long and getopt_long_only entry points for GNU getopt.
Copyright (C) 1987, 88, 89, 90, 91, 92, 1993, 1994
Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "getopt.h"
#if !defined (__STDC__) || !__STDC__
/* This is a separate conditional since some stdc systems
reject `defined (const)'. */
#ifndef const
#define const
#endif
#endif
#include <stdio.h>
/* Comment out all this code if we are using the GNU C Library, and are not
actually compiling the library itself. This code is part of the GNU C
Library, but also included in many other GNU distributions. Compiling
and linking in this code is a waste when using the GNU C library
(especially if it is a shared library). Rather than having every GNU
program understand `configure --with-gnu-libc' and omit the object files,
it is simpler to just do this in the source for each such file. */
#if defined (_LIBC) || !defined (__GNU_LIBRARY__)
/* This needs to come after some library #include
to get __GNU_LIBRARY__ defined. */
#ifdef __GNU_LIBRARY__
#include <stdlib.h>
#else
char *getenv ();
#endif
#ifndef NULL
#define NULL 0
#endif
int
getopt_long (argc, argv, options, long_options, opt_index)
int argc;
char *const *argv;
const char *options;
const struct option *long_options;
int *opt_index;
{
return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
}
/* Like getopt_long, but '-' as well as '--' can indicate a long option.
If an option that starts with '-' (not '--') doesn't match a long option,
but does match a short option, it is parsed as a short option
instead. */
int
getopt_long_only (argc, argv, options, long_options, opt_index)
int argc;
char *const *argv;
const char *options;
const struct option *long_options;
int *opt_index;
{
return _getopt_internal (argc, argv, options, long_options, opt_index, 1);
}
#endif /* _LIBC or not __GNU_LIBRARY__. */
#ifdef TEST
#include <stdio.h>
int
main (argc, argv)
int argc;
char **argv;
{
int c;
int digit_optind = 0;
while (1)
{
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] =
{
{"add", 1, 0, 0},
{"append", 0, 0, 0},
{"delete", 1, 0, 0},
{"verbose", 0, 0, 0},
{"create", 0, 0, 0},
{"file", 1, 0, 0},
{0, 0, 0, 0}
};
c = getopt_long (argc, argv, "abc:d:0123456789",
long_options, &option_index);
if (c == EOF)
break;
switch (c)
{
case 0:
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf ("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf ("option %c\n", c);
break;
case 'a':
printf ("option a\n");
break;
case 'b':
printf ("option b\n");
break;
case 'c':
printf ("option c with value `%s'\n", optarg);
break;
case 'd':
printf ("option d with value `%s'\n", optarg);
break;
case '?':
break;
default:
printf ("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
printf ("\n");
}
exit (0);
}
#endif /* TEST */
|
the_stack_data/100140485.c | #include <stdio.h>
#include <string.h>
#include <dlfcn.h>
#include <stdlib.h>
/* Author: https://github.com/Hackerl/
* https://github.com/Hackerl/Wine_Appimage/issues/11#issuecomment-447834456
* sudo apt-get -y install gcc-multilib
* gcc -shared -fPIC -ldl libhookexecv.c -o libhookexecv.so
* for i386: gcc -shared -fPIC -m32 -ldl libhookexecv.c -o libhookexecv.so
*
* hook wine execv syscall. use special ld.so
gcc -shared -fPIC -m32 -ldl libhookexecv32.c -o libhookexecv32.so
* */
typedef int(*EXECV)(const char*, char**);
static inline int strendswith( const char* str, const char* end )
{
size_t len = strlen( str );
size_t tail = strlen( end );
return len >= tail && !strcmp( str + len - tail, end );
}
int execv(char *path, char ** argv)
{
static void *handle = NULL;
static EXECV old_execv = NULL;
char **last_arg = argv;
if( !handle )
{
handle = dlopen("libc.so.6", RTLD_LAZY);
old_execv = (EXECV)dlsym(handle, "execv");
}
char * wineloader = getenv("WINELDLIBRARY");
if (wineloader == NULL)
{
return old_execv(path, argv);
}
while (*last_arg) last_arg++;
char ** new_argv = (char **) malloc( (last_arg - argv + 2) * sizeof(*argv) );
memcpy( new_argv + 1, argv, (last_arg - argv + 1) * sizeof(*argv) );
char * pathname = NULL;
char hookpath[256];
memset(hookpath, 0, 256);
if (strendswith(path, "wine-preloader"))
{
strcat(hookpath, path);
strcat(hookpath, "_hook");
wineloader = hookpath;
}
new_argv[0] = wineloader;
int res = old_execv(wineloader, new_argv);
free( new_argv );
return res;
}
|
the_stack_data/468254.c | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define dprintf(...) do{}while(0)
int main( int argc, char *argv[])
{
int uport = 10001;
int cuport = 0;
char *cli = "127.0.0.1";
char *srv = 0;
int port = 12346;
int n, ss, s;
struct sockaddr_in sa, usa;
int arg = 1;
if (arg < argc)
{
sscanf( argv[arg++], "%d", &uport);
if (arg < argc)
{
srv = argv[arg++];
if (arg < argc)
{
sscanf( argv[arg++], "%d", &port);
if (arg < argc)
{
sscanf( argv[arg++], "%d", &cuport);
if (arg < argc)
{
cli = argv[arg++];
}
}
}
}
}
if (!srv)
{
printf( "Usage: %s <UDP_port> <TCP_srv> <TCP_port> [UDP_port_cli [UDP_cli]]\n", argv[0]);
exit( 1);
}
s = socket( PF_INET, SOCK_STREAM, 0);
memset( &sa, 0, sizeof( sa));
sa.sin_family = AF_INET;
sa.sin_port = htons( port);
sa.sin_addr.s_addr = inet_addr( srv);
printf( "connecting to TCP %s:%d..\n", srv, port);
n = connect( s, (struct sockaddr *)&sa, sizeof( sa));
if (n == -1)
{
perror( "connect");
exit( 1);
}
ss = socket( PF_INET, SOCK_DGRAM, 0);
memset( &usa, 0, sizeof( usa));
usa.sin_family = AF_INET;
usa.sin_port = htons( uport);
usa.sin_addr.s_addr = INADDR_ANY;
n = bind( ss, (struct sockaddr *)&usa, sizeof( usa));
if (n == -1)
{
perror( "bind");
exit( 1);
}
printf( "bound to listen on UDP port %d..\n", uport);
if (cuport)
{
printf( "forcing UDP client ip %s port %d\n", cli, cuport);
memset( &usa, 0, sizeof( usa));
usa.sin_family = AF_INET;
usa.sin_port = htons( cuport);
usa.sin_addr.s_addr = inet_addr( cli);
}
while (1)
{
socklen_t ssa = sizeof( usa);
char buf[1600];
fd_set rfds;
int max = -1;
FD_ZERO( &rfds);
if (s != -1)
{
FD_SET( s, &rfds);
if (s > max)
max = s;
}
if (ss != -1)
{
FD_SET( ss, &rfds);
if (ss > max)
max = ss;
}
n = select( max + 1, &rfds, 0, 0, 0);
if (n == -1)
{
perror( "accept");
exit( 3);
}
if ((ss != -1) && FD_ISSET( ss, &rfds))
{
memset( buf, 0, sizeof( buf));
n = recvfrom( ss, buf, sizeof( buf) - 1, 0, (struct sockaddr *)&usa, &ssa);
if (n == -1)
{
perror( "recvfrom");
exit( 1);
}
else if (n == 0)
{
printf( "hangup\n");
exit( 2);
}
dprintf( "recvfrom returned %d from %s\n", n, inet_ntoa( usa.sin_addr));
uint32_t size = n;
uint32_t nsize = htonl( size);
n = write( s, &nsize, sizeof( nsize));
n = write( s, buf, size);
}
if ((s != -1) && FD_ISSET( s, &rfds))
{
uint32_t nsize = 0, size;
n = read( s, &nsize, sizeof( nsize));
dprintf( "read returned %d\n", n);
if (n == 0)
{
printf( "hangup\n");
close( s);
break;
}
size = ntohl( nsize);
n = read( s, buf, size);
n = sendto( ss, buf, size, 0, (struct sockaddr *)&usa, ssa);
}
}
return 0;
}
|
the_stack_data/340219.c | #include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <pthread.h>
struct thread_info {
int maxitr;
double exec_time;
};
typedef struct thread_info thread_info_t;
void *func(void *arg)
{
struct timespec time_1, time_2;
double exec_time;
thread_info_t *info;
int i, maxitr;
volatile double a, b, c;
info = (thread_info_t *)arg;
maxitr = info->maxitr;
b = 2.3; c = 4.5;
exec_time = 0.0;
clock_gettime(CLOCK_REALTIME, &time_1);
for (i = 0; i < maxitr ; i++) {
a = b*b + b*c + c*c;
}
clock_gettime(CLOCK_REALTIME, &time_2);
exec_time = (time_2.tv_sec - time_1.tv_sec);
exec_time = exec_time + (time_2.tv_nsec - time_1.tv_nsec)/1.0e9;
info->exec_time = exec_time;
pthread_exit(NULL);
}
int main(void)
{
pthread_t thread1;
thread_info_t info1;
double maxitr;
maxitr = 5.0e8;
info1.maxitr = (int)maxitr;
if (pthread_create(&thread1, NULL, &func, &info1) != 0) {
printf("Error in creating thread 1\n");
exit(1);
}
pthread_join(thread1, NULL);
printf("Exec time for thread1 = %lf sec\n", info1.exec_time);
pthread_exit(NULL);
}
|
the_stack_data/781827.c | #ifndef _R__IO_H
#define _R__IO_H
#include<stdio.h>
char getch();
void clrscr();
char getch()
{
getchar();
return getchar();
}
void clrscr()
{
system("clear");
}
#endif
|
the_stack_data/22012820.c | void fence() { asm("sync"); }
void lwfence() { asm("lwsync"); }
void isync() { asm("isync"); }
int __unbuffered_cnt=0;
int __unbuffered_p3_EAX=0;
int a=0;
int x=0;
int y=0;
int z=0;
void * P0(void * arg) {
a = 1;
x = 1;
// Instrumentation for CPROVER
fence();
__unbuffered_cnt++;
}
void * P1(void * arg) {
x = 2;
y = 1;
// Instrumentation for CPROVER
fence();
__unbuffered_cnt++;
}
void * P2(void * arg) {
y = 2;
z = 1;
// Instrumentation for CPROVER
fence();
__unbuffered_cnt++;
}
void * P3(void * arg) {
z = 2;
__unbuffered_p3_EAX = a;
// Instrumentation for CPROVER
fence();
__unbuffered_cnt++;
}
int main() {
__CPROVER_ASYNC_0: P0(0);
__CPROVER_ASYNC_1: P1(0);
__CPROVER_ASYNC_2: P2(0);
__CPROVER_ASYNC_3: P3(0);
__CPROVER_assume(__unbuffered_cnt==4);
fence();
// EXPECT:exists
__CPROVER_assert(!(x==2 && y==2 && z==2 && __unbuffered_p3_EAX==0), "Program proven to be relaxed for X86, model checker says YES.");
return 0;
}
|
the_stack_data/440504.c | #include <stdio.h>
int main()
{
}
|
the_stack_data/7951657.c | #include <stdio.h>
int main(){
int n;
scanf("%d",&n);
printf("%d\n",1-(((n>>31)&1)<<1)-(!n));
}
|
the_stack_data/1170004.c | /* Copyright (c) 2007-2009, UNINETT AS
* Copyright (c) 2010-2011,2015-2016, NORDUnet A/S */
/* See LICENSE for licensing information. */
#if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#ifdef SYS_SOLARIS9
#include <fcntl.h>
#endif
#include <sys/time.h>
#include <sys/types.h>
#include <sys/select.h>
#include <ctype.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <regex.h>
#include <libgen.h>
#include <pthread.h>
#include <openssl/ssl.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/md5.h>
#include <openssl/x509v3.h>
#include "debug.h"
#include "hash.h"
#include "util.h"
#include "hostport.h"
#include "radsecproxy.h"
static struct hash *tlsconfs = NULL;
static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
int pwdlen = strlen(userdata);
if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
return 0;
memcpy(buf, userdata, pwdlen);
return pwdlen;
}
static int verify_cb(int ok, X509_STORE_CTX *ctx) {
char *buf = NULL;
X509 *err_cert;
int err, depth;
err_cert = X509_STORE_CTX_get_current_cert(ctx);
err = X509_STORE_CTX_get_error(ctx);
depth = X509_STORE_CTX_get_error_depth(ctx);
if (depth > MAX_CERT_DEPTH) {
ok = 0;
err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
X509_STORE_CTX_set_error(ctx, err);
}
if (!ok) {
if (err_cert)
buf = X509_NAME_oneline(X509_get_subject_name(err_cert), NULL, 0);
debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf ? buf : "");
free(buf);
buf = NULL;
switch (err) {
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
if (err_cert) {
buf = X509_NAME_oneline(X509_get_issuer_name(err_cert), NULL, 0);
if (buf) {
debug(DBG_WARN, "\tIssuer=%s", buf);
free(buf);
buf = NULL;
}
}
break;
case X509_V_ERR_CERT_NOT_YET_VALID:
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
debug(DBG_WARN, "\tCertificate not yet valid");
break;
case X509_V_ERR_CERT_HAS_EXPIRED:
debug(DBG_WARN, "Certificate has expired");
break;
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
break;
case X509_V_ERR_NO_EXPLICIT_POLICY:
debug(DBG_WARN, "No Explicit Certificate Policy");
break;
}
}
#ifdef DEBUG
printf("certificate verify returns %d\n", ok);
#endif
return ok;
}
#ifdef DEBUG
static void ssl_info_callback(const SSL *ssl, int where, int ret) {
const char *s;
int w;
w = where & ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT)
s = "SSL_connect";
else if (w & SSL_ST_ACCEPT)
s = "SSL_accept";
else
s = "undefined";
if (where & SSL_CB_LOOP)
debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
else if (where & SSL_CB_ALERT) {
s = (where & SSL_CB_READ) ? "read" : "write";
debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
}
else if (where & SSL_CB_EXIT) {
if (ret == 0)
debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
else if (ret < 0)
debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
}
}
#endif
static X509_VERIFY_PARAM *createverifyparams(char **poids) {
X509_VERIFY_PARAM *pm;
ASN1_OBJECT *pobject;
int i;
pm = X509_VERIFY_PARAM_new();
if (!pm)
return NULL;
for (i = 0; poids[i]; i++) {
pobject = OBJ_txt2obj(poids[i], 0);
if (!pobject) {
X509_VERIFY_PARAM_free(pm);
return NULL;
}
X509_VERIFY_PARAM_add0_policy(pm, pobject);
}
X509_VERIFY_PARAM_set_flags(pm, X509_V_FLAG_POLICY_CHECK | X509_V_FLAG_EXPLICIT_POLICY);
return pm;
}
static int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
STACK_OF(X509_NAME) *calist;
X509_STORE *x509_s;
unsigned long error;
SSL_CTX_set_cert_store(ctx, X509_STORE_new());
if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
while ((error = ERR_get_error()))
debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
return 0;
}
calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
if (!conf->cacertfile || calist) {
if (conf->cacertpath) {
if (!calist)
calist = sk_X509_NAME_new_null();
if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
sk_X509_NAME_free(calist);
calist = NULL;
}
}
}
if (!calist) {
while ((error = ERR_get_error()))
debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
return 0;
}
ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
SSL_CTX_set_client_CA_list(ctx, calist);
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
if (conf->crlcheck || conf->vpm) {
x509_s = SSL_CTX_get_cert_store(ctx);
if (conf->crlcheck)
X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
if (conf->vpm)
X509_STORE_set1_param(x509_s, conf->vpm);
}
debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
return 1;
}
static SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
SSL_CTX *ctx = NULL;
unsigned long error;
long sslversion = SSLeay();
switch (type) {
#ifdef RADPROT_TLS
case RAD_TLS:
#if OPENSSL_VERSION_NUMBER >= 0x10100000
/* TLS_method() was introduced in OpenSSL 1.1.0. */
ctx = SSL_CTX_new(TLS_method());
#else
/* No TLS_method(), use SSLv23_method() and disable SSLv2 and SSLv3. */
ctx = SSL_CTX_new(SSLv23_method());
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
#endif
#ifdef DEBUG
SSL_CTX_set_info_callback(ctx, ssl_info_callback);
#endif
break;
#endif
#ifdef RADPROT_DTLS
case RAD_DTLS:
#if OPENSSL_VERSION_NUMBER >= 0x10002000
/* DTLS_method() seems to have been introduced in OpenSSL 1.0.2. */
ctx = SSL_CTX_new(DTLS_method());
#else
ctx = SSL_CTX_new(DTLSv1_method());
#endif
#ifdef DEBUG
SSL_CTX_set_info_callback(ctx, ssl_info_callback);
#endif
SSL_CTX_set_read_ahead(ctx, 1);
break;
#endif
}
if (!ctx) {
debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
return NULL;
}
if (sslversion < 0x00908100L ||
(sslversion >= 0x10000000L && sslversion < 0x10000020L)) {
debug(DBG_WARN, "%s: %s seems to be of a version with a "
"certain security critical bug (fixed in OpenSSL 0.9.8p and "
"1.0.0b). Disabling OpenSSL session caching for context %p.",
__func__, SSLeay_version(SSLEAY_VERSION), ctx);
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
}
if (conf->certkeypwd) {
SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
}
if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
!SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
!SSL_CTX_check_private_key(ctx)) {
while ((error = ERR_get_error()))
debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
SSL_CTX_free(ctx);
return NULL;
}
if (conf->policyoids) {
if (!conf->vpm) {
conf->vpm = createverifyparams(conf->policyoids);
if (!conf->vpm) {
debug(DBG_ERR, "tlscreatectx: Failed to add policyOIDs in TLS context %s", conf->name);
SSL_CTX_free(ctx);
return NULL;
}
}
}
if (!tlsaddcacrl(ctx, conf)) {
if (conf->vpm) {
X509_VERIFY_PARAM_free(conf->vpm);
conf->vpm = NULL;
}
SSL_CTX_free(ctx);
return NULL;
}
debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
return ctx;
}
struct tls *tlsgettls(char *alt1, char *alt2) {
struct tls *t;
t = hash_read(tlsconfs, alt1, strlen(alt1));
if (!t)
t = hash_read(tlsconfs, alt2, strlen(alt2));
return t;
}
SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
struct timeval now;
if (!t)
return NULL;
gettimeofday(&now, NULL);
switch (type) {
#ifdef RADPROT_TLS
case RAD_TLS:
if (t->tlsexpiry && t->tlsctx) {
if (t->tlsexpiry < now.tv_sec) {
t->tlsexpiry = now.tv_sec + t->cacheexpiry;
tlsaddcacrl(t->tlsctx, t);
}
}
if (!t->tlsctx) {
t->tlsctx = tlscreatectx(RAD_TLS, t);
if (t->cacheexpiry)
t->tlsexpiry = now.tv_sec + t->cacheexpiry;
}
return t->tlsctx;
#endif
#ifdef RADPROT_DTLS
case RAD_DTLS:
if (t->dtlsexpiry && t->dtlsctx) {
if (t->dtlsexpiry < now.tv_sec) {
t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
tlsaddcacrl(t->dtlsctx, t);
}
}
if (!t->dtlsctx) {
t->dtlsctx = tlscreatectx(RAD_DTLS, t);
if (t->cacheexpiry)
t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
}
return t->dtlsctx;
#endif
}
return NULL;
}
void tlsreloadcrls() {
struct tls *conf;
struct hash_entry *entry;
struct timeval now;
gettimeofday(&now, NULL);
for (entry = hash_first(tlsconfs); entry; entry = hash_next(entry)) {
conf = (struct tls *)entry->data;
#ifdef RADPROT_TLS
if (conf->tlsctx) {
if (conf->tlsexpiry)
conf->tlsexpiry = now.tv_sec + conf->cacheexpiry;
tlsaddcacrl(conf->tlsctx, conf);
}
#endif
#ifdef RADPROT_DTLS
if (conf->dtlsctx) {
if (conf->dtlsexpiry)
conf->dtlsexpiry = now.tv_sec + conf->cacheexpiry;
tlsaddcacrl(conf->dtlsctx, conf);
}
#endif
}
}
X509 *verifytlscert(SSL *ssl) {
X509 *cert;
unsigned long error;
if (SSL_get_verify_result(ssl) != X509_V_OK) {
debug(DBG_ERR, "verifytlscert: basic validation failed");
while ((error = ERR_get_error()))
debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
return NULL;
}
cert = SSL_get_peer_certificate(ssl);
if (!cert)
debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
return cert;
}
static int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
int loc, i, l, n, r = 0;
char *v;
X509_EXTENSION *ex;
STACK_OF(GENERAL_NAME) *alt;
GENERAL_NAME *gn;
debug(DBG_DBG, "subjectaltnameaddr");
loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
if (loc < 0)
return r;
ex = X509_get_ext(cert, loc);
alt = X509V3_EXT_d2i(ex);
if (!alt)
return r;
n = sk_GENERAL_NAME_num(alt);
for (i = 0; i < n; i++) {
gn = sk_GENERAL_NAME_value(alt, i);
if (gn->type != GEN_IPADD)
continue;
r = -1;
v = (char *)ASN1_STRING_get0_data(gn->d.ia5);
l = ASN1_STRING_length(gn->d.ia5);
if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
&& !memcmp(v, &addr, l)) {
r = 1;
break;
}
}
GENERAL_NAMES_free(alt);
return r;
}
static int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
int loc, i, l, n, r = 0;
char *s, *v;
X509_EXTENSION *ex;
STACK_OF(GENERAL_NAME) *alt;
GENERAL_NAME *gn;
debug(DBG_DBG, "subjectaltnameregexp");
loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
if (loc < 0)
return r;
ex = X509_get_ext(cert, loc);
alt = X509V3_EXT_d2i(ex);
if (!alt)
return r;
n = sk_GENERAL_NAME_num(alt);
for (i = 0; i < n; i++) {
gn = sk_GENERAL_NAME_value(alt, i);
if (gn->type != type)
continue;
r = -1;
v = (char *)ASN1_STRING_get0_data(gn->d.ia5);
l = ASN1_STRING_length(gn->d.ia5);
if (l <= 0)
continue;
#ifdef DEBUG
printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, (uint8_t *) v, l);
#endif
if (exact) {
if (memcmp(v, exact, l))
continue;
} else {
s = stringcopy((char *)v, l);
if (!s) {
debug(DBG_ERR, "malloc failed");
continue;
}
if (regexec(regex, s, 0, NULL, 0)) {
free(s);
continue;
}
free(s);
}
r = 1;
break;
}
GENERAL_NAMES_free(alt);
return r;
}
static int cnregexp(X509 *cert, char *exact, regex_t *regex) {
int loc, l;
char *v, *s;
X509_NAME *nm;
X509_NAME_ENTRY *e;
ASN1_STRING *t;
nm = X509_get_subject_name(cert);
loc = -1;
for (;;) {
loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
if (loc == -1)
break;
e = X509_NAME_get_entry(nm, loc);
t = X509_NAME_ENTRY_get_data(e);
v = (char *) ASN1_STRING_get0_data(t);
l = ASN1_STRING_length(t);
if (l < 0)
continue;
if (exact) {
if (l == strlen(exact) && !strncasecmp(exact, v, l))
return 1;
} else {
s = stringcopy((char *)v, l);
if (!s) {
debug(DBG_ERR, "malloc failed");
continue;
}
if (regexec(regex, s, 0, NULL, 0)) {
free(s);
continue;
}
free(s);
return 1;
}
}
return 0;
}
/* this is a bit sloppy, should not always accept match to any */
int certnamecheck(X509 *cert, struct list *hostports) {
struct list_node *entry;
struct hostportres *hp;
int r;
uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
struct in6_addr addr;
for (entry = list_first(hostports); entry; entry = list_next(entry)) {
hp = (struct hostportres *)entry->data;
if (hp->prefixlen != 255) {
/* we disable the check for prefixes */
return 1;
}
if (inet_pton(AF_INET, hp->host, &addr))
type = AF_INET;
else if (inet_pton(AF_INET6, hp->host, &addr))
type = AF_INET6;
else
type = 0;
r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, hp->host, NULL);
if (r) {
if (r > 0) {
debug(DBG_DBG, "certnamecheck: Found subjectaltname matching %s %s", type ? "address" : "host", hp->host);
return 1;
}
debug(DBG_WARN, "certnamecheck: No subjectaltname matching %s %s", type ? "address" : "host", hp->host);
} else {
if (cnregexp(cert, hp->host, NULL)) {
debug(DBG_DBG, "certnamecheck: Found cn matching host %s", hp->host);
return 1;
}
debug(DBG_WARN, "certnamecheck: cn not matching host %s", hp->host);
}
}
return 0;
}
int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
if (conf->certnamecheck) {
if (!certnamecheck(cert, conf->hostports)) {
debug(DBG_WARN, "verifyconfcert: certificate name check failed");
return 0;
}
debug(DBG_WARN, "verifyconfcert: certificate name check ok");
}
if (conf->certcnregex) {
if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
debug(DBG_WARN, "verifyconfcert: CN not matching regex");
return 0;
}
debug(DBG_DBG, "verifyconfcert: CN matching regex");
}
if (conf->certuriregex) {
if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
return 0;
}
debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
}
return 1;
}
int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
struct tls *conf;
long int expiry = LONG_MIN;
debug(DBG_DBG, "conftls_cb called for %s", block);
conf = malloc(sizeof(struct tls));
if (!conf) {
debug(DBG_ERR, "conftls_cb: malloc failed");
return 0;
}
memset(conf, 0, sizeof(struct tls));
if (!getgenericconfig(cf, block,
"CACertificateFile", CONF_STR, &conf->cacertfile,
"CACertificatePath", CONF_STR, &conf->cacertpath,
"CertificateFile", CONF_STR, &conf->certfile,
"CertificateKeyFile", CONF_STR, &conf->certkeyfile,
"CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
"CacheExpiry", CONF_LINT, &expiry,
"CRLCheck", CONF_BLN, &conf->crlcheck,
"PolicyOID", CONF_MSTR, &conf->policyoids,
NULL
)) {
debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
goto errexit;
}
if (!conf->certfile || !conf->certkeyfile) {
debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
goto errexit;
}
if (!conf->cacertfile && !conf->cacertpath) {
debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
goto errexit;
}
if (expiry != LONG_MIN) {
if (expiry < 0) {
debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
goto errexit;
}
conf->cacheexpiry = expiry;
}
conf->name = stringcopy(val, 0);
if (!conf->name) {
debug(DBG_ERR, "conftls_cb: malloc failed");
goto errexit;
}
if (!tlsconfs)
tlsconfs = hash_create();
if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
debug(DBG_ERR, "conftls_cb: malloc failed");
goto errexit;
}
if (!tlsgetctx(RAD_TLS, conf))
debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
return 1;
errexit:
free(conf->cacertfile);
free(conf->cacertpath);
free(conf->certfile);
free(conf->certkeyfile);
free(conf->certkeypwd);
freegconfmstr(conf->policyoids);
free(conf);
return 0;
}
int addmatchcertattr(struct clsrvconf *conf) {
char *v;
regex_t **r;
if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
r = &conf->certcnregex;
v = conf->matchcertattr + 4;
} else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
r = &conf->certuriregex;
v = conf->matchcertattr + 20;
} else
return 0;
if (!*v)
return 0;
/* regexp, remove optional trailing / if present */
if (v[strlen(v) - 1] == '/')
v[strlen(v) - 1] = '\0';
if (!*v)
return 0;
*r = malloc(sizeof(regex_t));
if (!*r) {
debug(DBG_ERR, "malloc failed");
return 0;
}
if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
free(*r);
*r = NULL;
debug(DBG_ERR, "failed to compile regular expression %s", v);
return 0;
}
return 1;
}
#else
/* Just to makes file non-empty, should rather avoid compiling this file when not needed */
static void tlsdummy() {
}
#endif
/* Local Variables: */
/* c-file-style: "stroustrup" */
/* End: */
|
the_stack_data/167329877.c | /*
Thread Niggas
Proof that q1.c works, this file does the same thing except it doesn't use threads
Created by nmf2
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 11 // number of files
#define P 11 //tipos de produtos
int tipos_produtos = 0, total_produtos = 0; //quantidade de tipos de produtos diferentes existentes.
FILE *files[N];
int produtos[P] = { 0 };
void treatFile(int arg){
int i = (int) arg;
char file_name[7] = {'\0'};
char problem[4] = {'\0'}; //problem type
sprintf(file_name, "%d.in", i); //print file name in file_name
files[i] = fopen(file_name, "r"); //open file
{//file opened
while(fgets(problem, 4, files[i]), !feof(files[i])){ //
int prob_num = atoi(problem); //convert string to number...
printf("file: %d, atoi: %d\n", i, prob_num);
produtos[prob_num]++;
total_produtos++;
}
}//file to be closed
fclose(files[i]);
}
int main (){
int i = 1;
for (; i < N; i++){
treatFile(i);
}
for (i = 1; i < P; i++){
printf("Produtos do tipo %d:\n\t\tQtde: %d, %%%f\n", i, produtos[i], ((float) produtos[i])*(100)/total_produtos);
}
printf("Total de produtos: %d\n", total_produtos);
return 0;
}
|
the_stack_data/148577044.c | #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
double get_canvas_size(double canvasDimension, double imageDimension)
{
return canvasDimension - imageDimension;
}
double update_axis(double axis, double velocity, double dimension)
{
axis += velocity;
if (axis > dimension)
{
axis = dimension;
}
else if (axis < 0)
{
axis = 0;
}
return axis;
}
int get_selection(int selection, double axis, double velocity)
{
int newSelection = selection;
if (0 > velocity)
newSelection++;
if (selection > 2)
newSelection = 0;
return newSelection;
}
double change_direction(double axis, double velocity, double boundary)
{
if ((axis >= boundary && velocity > 0) || (axis <= 0 && velocity < 0))
return velocity * -1;
return velocity;
}
double get_resize_ratio(double imgWidth, double imgHeight, double canvasWidth, double canvasHeight)
{
double resizeRatio = 2;
if (imgHeight / canvasHeight > 0.25 || imgWidth / canvasWidth > 0.25)
{
resizeRatio = (imgHeight / canvasHeight > imgWidth / canvasWidth) ? 1 - imgHeight / canvasHeight : 1 - imgWidth / canvasWidth;
if (resizeRatio < 0.25)
{
resizeRatio = 0.25;
}
}
return resizeRatio;
} |
the_stack_data/21122.c | //reverse String using stack
#include<stdio.h>
#include<stdio.h>
#include<string.h>
struct node{
char data;
struct node *link;
};
struct node *top=NULL;
void main(){
int i,n;
char str[100];
gets(str);
n=strlen(str);
for(i=0;i<n;i++)
{
push(str[i]);
}
for(i=0;i<n;i++)
{
pop(str[i]);
}
return 0;
}
void push(char a){
struct node *ptr;
ptr=(struct node*)malloc(sizeof(struct node));
ptr->data=a;
ptr->link=NULL;
if(top==NULL){
top=ptr;
}
else{
ptr->link=top;
top=ptr;
}
}
void pop(){
struct node *ptr;
if(top==NULL){
printf("Stack is empty\n");
}
else {
ptr=top;
printf("%c",ptr->data);
top=top->link;
free(ptr);
}
}
|
the_stack_data/129493.c | int main()
{
int a = 2, b = 3;
int d[2] = {4, 2};
float m[2] = {2.6, 1.3};
float k;
assert(d[0] == 4, "d[0] must be 4");
assert(d[1] == 2, "d[1] must be 2");
assert(m[0] == 2.6, "m[0] must be 2.6");
assert(m[1] == 1.3, "m[1] must be 1.3");
a /= b;
assert(a == 0, "a must be 0");
d[0] /= d[1];
b = d[0];
assert(b == 2, "b must be 2");
m[0] /= d[1];
k = m[0];
assert(k == 1.300000, "k must be 1.300000");
m[0] /= m[1];
k = m[0];
assert(k == 1.000000, "k must be 1.000000");
return 0;
}
|
the_stack_data/190767347.c | /*
* fputc.c - print an unsigned character
*/
/* $Header$ */
#include <stdio.h>
int
fputc(int c, FILE *stream)
{
return putc(c, stream);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.