filename
stringlengths 3
9
| code
stringlengths 6
1.09M
|
---|---|
721307.c | #include <linux/mali/mali_utgard.h>
#include <linux/platform_device.h>
#include <linux/version.h>
#include <linux/regulator/consumer.h>
#include <linux/clk.h>
#include <linux/clk/sunxi_name.h>
#include <linux/clk-private.h>
#include <linux/pm_runtime.h>
#include <linux/dma-mapping.h>
#include <linux/delay.h>
#include <mach/irqs.h>
#include <mach/sys_config.h>
#include <mach/platform.h>
#if defined(CONFIG_CPU_BUDGET_THERMAL)
#include <linux/cpu_budget_cooling.h>
static int cur_mode = 0;
#elif defined(CONFIG_SW_POWERNOW)
#include <mach/powernow.h>
#endif
#ifdef CONFIG_HAS_EARLYSUSPEND
#include <linux/earlysuspend.h>
#endif /* CONFIG_HAS_EARLYSUSPEND */
static struct clk *mali_clk = NULL;
static struct clk *gpu_pll = NULL;
extern unsigned long totalram_pages;
struct __fb_addr_para
{
unsigned int fb_paddr;
unsigned int fb_size;
};
extern void sunxi_get_fb_addr_para(struct __fb_addr_para *fb_addr_para);
#ifdef CONFIG_HAS_EARLYSUSPEND
static void mali_driver_early_suspend_scheduler(struct early_suspend *h);
static void mali_driver_late_resume_scheduler(struct early_suspend *h);
#endif /* CONFIG_HAS_EARLYSUSPEND */
static unsigned int freq_table[4] =
{
128, /* for early suspend */
252, /* for play video mode */
384, /* for normal mode */
384, /* for extreme mode */
};
#ifdef CONFIG_HAS_EARLYSUSPEND
static struct early_suspend mali_early_suspend_handler =
{
.level = EARLY_SUSPEND_LEVEL_DISABLE_FB + 100,
.suspend = mali_driver_early_suspend_scheduler,
.resume = mali_driver_late_resume_scheduler,
};
#endif /* CONFIG_HAS_EARLYSUSPEND */
static struct mali_gpu_device_data mali_gpu_data;
#if defined(CONFIG_ARCH_SUN8IW3P1) || defined(CONFIG_ARCH_SUN8IW5P1) || defined(CONFIG_ARCH_SUN8IW9P1)
static struct resource mali_gpu_resources[]=
{
MALI_GPU_RESOURCES_MALI400_MP2_PMU(SUNXI_GPU_PBASE, SUNXI_IRQ_GPUGP, SUNXI_IRQ_GPUGPMMU, \
SUNXI_IRQ_GPUPP0, SUNXI_IRQ_GPUPPMMU0, SUNXI_IRQ_GPUPP1, SUNXI_IRQ_GPUPPMMU1)
};
#elif defined(CONFIG_ARCH_SUN8IW7P1)
static struct resource mali_gpu_resources[]=
{
MALI_GPU_RESOURCES_MALI400_MP2_PMU(SUNXI_GPU_PBASE, SUNXI_IRQ_GPU_GP, SUNXI_IRQ_GPU_GPMMU, \
SUNXI_IRQ_GPU_PP0, SUNXI_IRQ_GPU_PPMMU0, SUNXI_IRQ_GPU_PP1, SUNXI_IRQ_GPU_PPMMU1)
};
#endif
static struct platform_device mali_gpu_device =
{
.name = MALI_GPU_NAME_UTGARD,
.id = 0,
.dev.coherent_dma_mask = DMA_BIT_MASK(32),
};
/*
***************************************************************
@Function :get_gpu_clk
@Description:Get gpu related clocks
@Input :None
@Return :Zero or error code
***************************************************************
*/
static int get_gpu_clk(void)
{
#if defined(CONFIG_ARCH_SUN8IW3P1)
gpu_pll = clk_get(NULL, PLL8_CLK);
#elif defined(CONFIG_ARCH_SUN8IW5P1) || defined(CONFIG_ARCH_SUN8IW7P1) || defined(CONFIG_ARCH_SUN8IW9P1)
gpu_pll = clk_get(NULL, PLL_GPU_CLK);
#endif
if(!gpu_pll || IS_ERR(gpu_pll))
{
printk(KERN_ERR "Failed to get gpu pll clock!\n");
return -1;
}
mali_clk = clk_get(NULL, GPU_CLK);
if(!mali_clk || IS_ERR(mali_clk))
{
printk(KERN_ERR "Failed to get mali clock!\n");
return -1;
}
return 0;
}
/*
***************************************************************
@Function :set_freq
@Description:Set the frequency of gpu related clocks
@Input :Frequency value
@Return :Zero or error code
***************************************************************
*/
static int set_freq(int freq /* MHz */)
{
if(clk_set_rate(gpu_pll, freq*1000*1000))
{
printk(KERN_ERR "Failed to set gpu pll clock!\n");
return -1;
}
if(clk_set_rate(mali_clk, freq*1000*1000))
{
printk(KERN_ERR "Failed to set mali clock!\n");
return -1;
}
return 0;
}
#if defined(CONFIG_CPU_BUDGET_THERMAL) || defined(CONFIG_SW_POWERNOW) || defined(CONFIG_HAS_EARLYSUSPEND)
/*
***************************************************************
@Function :mali_set_freq
@Description:Set the frequency of gpu related clocks with mali dvfs function
@Input :Frequency value
@Return :Zero or error code
***************************************************************
*/
static int mali_set_freq(int freq /* MHz */)
{
int err;
mali_dev_pause();
err = set_freq(freq);
mali_dev_resume();
return err;
}
#endif /* defined(CONFIG_CPU_BUDGET_THERMAL) || defined(CONFIG_SW_POWERNOW) || defined(CONFIG_HAS_EARLYSUSPEND) */
/*
***************************************************************
@Function :enable_gpu_clk
@Description:Enable gpu related clocks
@Input :None
@Return :None
***************************************************************
*/
void enable_gpu_clk(void)
{
if(mali_clk->enable_count == 0)
{
if(clk_prepare_enable(gpu_pll))
{
printk(KERN_ERR "Failed to enable gpu pll!\n");
}
if(clk_prepare_enable(mali_clk))
{
printk(KERN_ERR "Failed to enable mali clock!\n");
}
}
}
/*
***************************************************************
@Function :disable_gpu_clk
@Description:Disable gpu related clocks
@Input :None
@Return :None
***************************************************************
*/
void disable_gpu_clk(void)
{
if(mali_clk->enable_count == 1)
{
clk_disable_unprepare(mali_clk);
clk_disable_unprepare(gpu_pll);
}
}
#if defined(CONFIG_CPU_BUDGET_THERMAL)
/*
***************************************************************
@Function :mali_throttle_notifier_call
@Description:The callback function of throttle notifier
@Input :nfb, mode, cmd
@Return :retval
***************************************************************
*/
static int mali_throttle_notifier_call(struct notifier_block *nfb, unsigned long mode, void *cmd)
{
int retval = NOTIFY_DONE;
if(mode == BUDGET_GPU_THROTTLE && cur_mode == 1)
{
mali_set_freq(freq_table[2]);
cur_mode = 0;
}
else
{
if(cmd && (*(int *)cmd) == 1 && cur_mode != 1)
{
mali_set_freq(freq_table[3]);
cur_mode = 1;
}
else if(cmd && (*(int *)cmd) == 0 && cur_mode != 0)
{
mali_set_freq(freq_table[2]);
cur_mode = 0;
}
else if(cmd && (*(int *)cmd) == 2 && cur_mode != 2)
{
mali_set_freq(freq_table[1]);
cur_mode = 2;
}
}
return retval;
}
static struct notifier_block mali_throttle_notifier = {
.notifier_call = mali_throttle_notifier_call,
};
#elif defined(CONFIG_SW_POWERNOW)
/*
***************************************************************
@Function :mali_powernow_notifier_call
@Description:The callback function of powernow notifier
@Input :this, mode, cmd
@Return :Zero
***************************************************************
*/
static int mali_powernow_notifier_call(struct notifier_block *this, unsigned long mode, void *cmd)
{
if(mode == 0 && cur_mode != 0)
{
mali_set_freq(freq_table[3]);
cur_mode = 1;
}
else if(mode == 1 && cur_mode != 1)
{
mali_set_freq(freq_table[2]);
cur_mode = 0;
}
return 0;
}
static struct notifier_block mali_powernow_notifier = {
.notifier_call = mali_powernow_notifier_call,
};
#endif
/*
***************************************************************
@Function :parse_fex
@Description:Parse fex file data of gpu
@Input :None
@Return :None
***************************************************************
*/
static void parse_fex(void)
{
script_item_u mali_used, mali_max_freq, mali_clk_freq;
#if defined(CONFIG_ARCH_SUN8IW7P1)
if(SCIRPT_ITEM_VALUE_TYPE_INT == script_get_item("clock", "pll_gpu", &mali_clk_freq))
#else
if(SCIRPT_ITEM_VALUE_TYPE_INT == script_get_item("clock", "pll8", &mali_clk_freq))
#endif
{
if(mali_clk_freq.val > 0)
{
freq_table[2] = mali_clk_freq.val;
}
}
else
{
goto err_out;
}
if(SCIRPT_ITEM_VALUE_TYPE_INT == script_get_item("mali_para", "mali_used", &mali_used))
{
if(mali_used.val == 1)
{
if(SCIRPT_ITEM_VALUE_TYPE_INT == script_get_item("mali_para", "mali_extreme_freq", &mali_max_freq))
{
if (mali_max_freq.val >= mali_clk_freq.val)
{
freq_table[3] = mali_max_freq.val;
}
else
{
freq_table[3] = mali_clk_freq.val;
}
}
else
{
goto err_out;
}
}
}
else
{
goto err_out;
}
printk(KERN_INFO "Get mali parameter successfully\n");
return;
err_out:
printk(KERN_ERR "Failed to get mali parameter!\n");
return;
}
/*
***************************************************************
@Function :mali_platform_init
@Description:Init the power and clocks of gpu
@Input :None
@Return :Zero or error code
***************************************************************
*/
static int mali_platform_init(void)
{
parse_fex();
if(get_gpu_clk())
{
goto err_out;
}
if(set_freq(freq_table[2]))
{
goto err_out;
}
enable_gpu_clk();
#if defined(CONFIG_CPU_BUDGET_THERMAL)
register_budget_cooling_notifier(&mali_throttle_notifier);
#elif defined(CONFIG_SW_POWERNOW)
register_sw_powernow_notifier(&mali_powernow_notifier);
#endif
#ifdef CONFIG_HAS_EARLYSUSPEND
register_early_suspend(&mali_early_suspend_handler);
#endif /* CONFIG_HAS_EARLYSUSPEND */
printk(KERN_INFO "Init Mali gpu successfully\n");
return 0;
err_out:
printk(KERN_ERR "Failed to init Mali gpu!\n");
return -1;
}
/*
***************************************************************
@Function :mali_platform_device_unregister
@Description:Unregister mali platform device
@Input :None
@Return :Zero
***************************************************************
*/
static int mali_platform_device_unregister(void)
{
platform_device_unregister(&mali_gpu_device);
#if defined(CONFIG_SW_POWERNOW)
unregister_sw_powernow_notifier(&mali_powernow_notifier);
#endif /* CONFIG_SW_POWERNOW */
#ifdef CONFIG_HAS_EARLYSUSPEND
unregister_early_suspend(&mali_early_suspend_handler);
#endif /* CONFIG_HAS_EARLYSUSPEND */
disable_gpu_clk();
return 0;
}
/*
***************************************************************
@Function :sun8i_mali_platform_device_register
@Description:Register mali platform device
@Input :None
@Return :Zero or error code
***************************************************************
*/
int sun8i_mali_platform_device_register(void)
{
int err;
struct __fb_addr_para fb_addr_para = {0};
sunxi_get_fb_addr_para(&fb_addr_para);
err = platform_device_add_resources(&mali_gpu_device, mali_gpu_resources, sizeof(mali_gpu_resources) / sizeof(mali_gpu_resources[0]));
if (0 == err)
{
mali_gpu_data.fb_start = fb_addr_para.fb_paddr;
mali_gpu_data.fb_size = fb_addr_para.fb_size;
mali_gpu_data.shared_mem_size = totalram_pages * PAGE_SIZE; /* B */
err = platform_device_add_data(&mali_gpu_device, &mali_gpu_data, sizeof(mali_gpu_data));
if(0 == err)
{
err = platform_device_register(&mali_gpu_device);
if (0 == err)
{
if(0 != mali_platform_init())
{
return -1;
}
#if defined(CONFIG_PM_RUNTIME)
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,37))
pm_runtime_set_autosuspend_delay(&(mali_gpu_device.dev), 1000);
pm_runtime_use_autosuspend(&(mali_gpu_device.dev));
#endif
pm_runtime_enable(&(mali_gpu_device.dev));
#endif /* CONFIG_PM_RUNTIME */
return 0;
}
}
mali_platform_device_unregister();
}
return err;
}
#ifdef CONFIG_HAS_EARLYSUSPEND
/*
***************************************************************
@Function :mali_driver_early_suspend_scheduler
@Description:The callback function of early suspend
@Input :h
@Return :None
***************************************************************
*/
static void mali_driver_early_suspend_scheduler(struct early_suspend *h)
{
mali_set_freq(freq_table[0]);
}
/*
***************************************************************
@Function :mali_driver_late_resume_scheduler
@Description:The callback function of early suspend
@Input :h
@Return :None
***************************************************************
*/
static void mali_driver_late_resume_scheduler(struct early_suspend *h)
{
mali_set_freq(freq_table[2]);
}
#endif /* CONFIG_HAS_EARLYSUSPEND */
|
706441.c | /* main.c: The main program for bc. */
/* This file is part of bc written for MINIX.
Copyright (C) 1991, 1992 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 of the License , or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
You may contact the author by:
e-mail: [email protected]
us-mail: Philip A. Nelson
Computer Science Department, 9062
Western Washington University
Bellingham, WA 98226-9062
*************************************************************************/
#include "bcdefs.h"
#include <signal.h>
#include "global.h"
#include "proto.h"
/* Variables for processing multiple files. */
char first_file;
extern FILE *yyin;
/* The main program for bc. */
int
main (int argc, char **argv)
{
int ch;
/* Initialize many variables. */
compile_only = FALSE;
use_math = FALSE;
warn_not_std = FALSE;
std_only = FALSE;
if (isatty(0) && isatty(1))
interactive = TRUE;
else
interactive = FALSE;
/* Parse the command line */
ch = getopt (argc, argv, "lcisvw");
while (ch != EOF)
{
switch (ch)
{
case 'c': /* compile only */
compile_only = TRUE;
break;
case 'l': /* math lib */
use_math = TRUE;
break;
case 'i': /* force interactive */
interactive = TRUE;
break;
case 'w': /* Non standard features give warnings. */
warn_not_std = TRUE;
break;
case 's': /* Non standard features give errors. */
std_only = TRUE;
break;
case 'v': /* Print the version. */
printf ("%s\n", BC_VERSION);
break;
}
ch = getopt (argc, argv, "lcisvw");
}
/* Initialize the machine. */
init_storage();
init_load();
/* Set up interrupts to print a message. */
if (interactive)
signal (SIGINT, use_quit);
/* Initialize the front end. */
init_tree();
init_gen ();
g_argv = /* XXX argv */ NULL;
g_argc = /* XXX argc */ 0;
is_std_in = FALSE;
first_file = TRUE;
if (!open_new_file ())
exit (1);
/* Do the parse. */
yyparse ();
/* End the compile only output with a newline. */
if (compile_only)
printf ("\n");
#ifdef PLUS_STATS
PrintDerefStats(stderr);
PrintHeapSize(stderr);
#endif /* PLUS_STATS */
exit (0);
}
/* This is the function that opens all the files.
It returns TRUE if the file was opened, otherwise
it returns FALSE. */
int
open_new_file (void)
{
FILE *new_file;
/* Set the line number. */
line_no = 1;
/* Check to see if we are done. */
if (is_std_in) return (FALSE);
/* Open the other files. */
if (use_math && first_file)
{
#ifdef BC_MATH_FILE
/* Make the first file be the math library. */
new_file = fopen (BC_MATH_FILE, "r");
use_math = FALSE;
if (new_file != NULL)
{
new_yy_file (new_file);
return TRUE;
}
else
{
fprintf (stderr, "Math Library unavailable.\n");
exit (1);
}
#else
/* Load the code from a precompiled version of the math libarary. */
extern char libmath[];
char tmp;
/* These MUST be in the order of first mention of each function.
That is why "a" comes before "c" even though "a" is defined after
after "c". "a" is used in "s"! */
tmp = lookup ("e", FUNCT);
tmp = lookup ("l", FUNCT);
tmp = lookup ("s", FUNCT);
tmp = lookup ("a", FUNCT);
tmp = lookup ("c", FUNCT);
tmp = lookup ("j", FUNCT);
load_code (libmath);
#endif
}
/* One of the argv values. */
while (optind < g_argc)
{
new_file = fopen (g_argv[optind], "r");
if (new_file != NULL)
{
new_yy_file (new_file);
optind++;
return TRUE;
}
fprintf (stderr, "File %s is unavailable.\n", g_argv[optind++]);
exit (1);
}
/* If we fall through to here, we should return stdin. */
new_yy_file (stdin);
is_std_in = TRUE;
return TRUE;
}
/* Set yyin to the new file. */
void
new_yy_file (FILE *file)
{
if (!first_file) fclose (yyin);
yyin = file;
first_file = FALSE;
}
/* Message to use quit. */
void
use_quit (int sig)
{
printf ("\n(interrupt) use quit to exit.\n");
signal (SIGINT, use_quit);
}
|
640930.c | const unsigned char gImage_demo[15000] = { /* 0X00,0X01,0X8F,0X01,0X2C,0X01, */
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,
0X01,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XF8,0X00,0X00,
0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XF0,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,0X3F,0XFF,0XFE,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X00,0X00,0X03,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,0X1F,0XFF,
0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X1F,0XFF,0X80,0X00,0X00,0X00,0X00,
0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,
0X07,0XF8,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0X00,0X00,0X00,
0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,
0X00,0X00,0X03,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X0C,0X00,
0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X01,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X01,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X03,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X0F,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XF0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X7F,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XF0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X7F,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X0F,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X03,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XF0,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,
0XF8,0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X0F,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X01,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,
0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,
0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X0F,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFC,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,
0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,
0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,
0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,
0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0X01,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X01,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X00,
0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFB,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XBF,0XFF,0XFF,0XFF,0XF8,
0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,
0XEF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0XFF,0XFF,0XFF,
0XFF,0XF8,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X1F,
0XFF,0XFF,0XBF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFB,0XFF,
0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,
0X00,0X3F,0XFF,0XFF,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XF7,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,
0X00,0X00,0X00,0X3F,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XEF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,
0X00,0X00,0X00,0X00,0X00,0X7F,0XFF,0XFD,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XDF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X03,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFB,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XBF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X03,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XF7,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,
0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XE7,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,
0XC0,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XEF,
0XFF,0XE0,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFE,0X07,0XFF,
0XFF,0XFF,0XC0,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X03,0XFF,
0XFF,0XCF,0XFF,0X80,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFD,0XFF,0XF8,
0X01,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,
0X03,0XFF,0XFF,0XDF,0XFF,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFD,
0XFF,0XF0,0X00,0X7F,0XFF,0XFF,0XE0,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,
0X00,0X00,0X03,0XFF,0XFF,0X9F,0XFE,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFB,0XFF,0XE0,0X00,0X3E,0XFF,0XFF,0XF0,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XBF,0XFC,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFB,0XFF,0XC0,0X00,0X3F,0XFF,0XFF,0XF0,0X00,0X00,0X03,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XBF,0XF8,0X00,0X01,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFB,0XFF,0X80,0X00,0X1F,0XFF,0XFF,0XF0,0X00,0X00,0X03,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,0X3F,0XF8,0X00,0X00,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XFF,0X80,0X00,0X0F,0XFF,0XFF,0XF8,0X00,
0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,0X7F,0XF0,0X00,
0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XFF,0X00,0X00,0X0F,0XFF,0XFF,
0XF8,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,0X7F,
0XF0,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XFF,0X00,0X00,0X07,
0XBF,0XFF,0XF8,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X0F,0XFF,
0XFF,0X7F,0XE0,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFE,0X00,
0X00,0X07,0XBF,0XFF,0XF8,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,
0X0F,0XFF,0XFE,0X7F,0XE0,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,
0XFE,0X00,0X00,0X07,0XFF,0XFF,0XFC,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,
0X00,0X00,0X1F,0XFF,0XFE,0XFF,0XE0,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XEF,0XFE,0X00,0X00,0X03,0XDF,0XFF,0XFC,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0X00,0X00,0X00,0X00,0X1F,0XFF,0XFE,0XFF,0XC0,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XEF,0XFC,0X00,0X00,0X03,0XDF,0XFF,0XFC,0X00,0X00,0X07,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0X00,0X00,0X00,0X00,0X1F,0XFF,0XFE,0XFF,0XC0,0X00,0X00,0X3F,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,0XFC,0X00,0X00,0X03,0XDF,0XFF,0XFC,0X00,0X00,0X0F,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,0X1F,0XFF,0XFE,0XFF,0XC0,0X00,0X00,0X3F,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,0XFC,0X00,0X00,0X03,0XDF,0XFF,0XFC,0X00,
0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,0X1F,0XFF,0XFE,0XFF,0XC0,0X00,
0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,0XFC,0X00,0X00,0X03,0XFF,0XFF,
0XFC,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X1F,0XFF,0XFE,0XFF,
0XC0,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,0XFC,0X00,0X00,0X03,
0XFF,0XFF,0XFC,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X1F,0XFF,
0XFE,0XFF,0XC0,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,0XFC,0X00,
0X00,0X03,0XEF,0XFF,0XFC,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,
0X1F,0XFF,0XFE,0XFF,0XC0,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,
0XFC,0X00,0X00,0X03,0XEF,0XFF,0XFC,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,
0X00,0X00,0X1F,0XFF,0XFE,0XFF,0XC0,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XEF,0XFC,0X00,0X00,0X03,0XEF,0XFF,0XFC,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XC0,0X00,0X00,0X00,0X1F,0XFF,0XFE,0XFF,0XC0,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XEF,0XFC,0X00,0X00,0X03,0XEF,0XFF,0XFC,0X00,0X00,0X1F,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XC0,0X00,0X00,0X00,0X1F,0XFF,0XFE,0XFF,0XC0,0X00,0X00,0X3F,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,0XFC,0X00,0X00,0X03,0XEF,0XFF,0XFC,0X00,0X00,0X1F,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0X1F,0XFF,0XFE,0XFF,0XC0,0X00,0X00,0X3F,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,0XFC,0X00,0X00,0X03,0XEF,0XFF,0XFC,0X00,
0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0X1F,0XFF,0XFE,0XFF,0XE0,0X00,
0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,0XFC,0X00,0X00,0X03,0XDF,0XFF,
0XFC,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X1F,0XFF,0XFE,0XFF,
0XE0,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,0XFE,0X00,0X00,0X07,
0XDF,0XFF,0XFC,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X0F,0XFF,
0XFF,0X7F,0XE0,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XFE,0X00,
0X00,0X07,0XDF,0XFF,0XFC,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,
0X0F,0XFF,0XFF,0X7F,0XF0,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,
0XFE,0X00,0X00,0X07,0XDF,0XFF,0XF8,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,
0X00,0X00,0X0F,0XFF,0XFF,0X7F,0XF0,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XF7,0XFF,0X00,0X00,0X0F,0XDF,0XFF,0XF8,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,
0X00,0X00,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XF7,0XFF,0X00,0X00,0X0F,0XDF,0XFF,0XF8,0X00,0X00,0X00,0X00,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XF0,0X00,0X00,0X00,0X0F,0XFF,0XFF,0XBF,0XF8,0X00,0X01,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFB,0XFF,0X80,0X00,0X1F,0X9F,0XFF,0XF8,0X00,0X00,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,0X0F,0XFF,0XFF,0XBF,0XFC,0X00,0X01,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFB,0XFF,0XC0,0X00,0X1F,0XBF,0XFF,0XF8,0X00,
0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,0X07,0XFF,0XFF,0XDF,0XFE,0X00,
0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X3F,0XBF,0XFF,
0XF8,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X07,0XFF,0XFF,0XDF,
0XFF,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFD,0XFF,0XE0,0X00,0X7F,
0X3F,0XFF,0XF0,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X07,0XFF,
0XFF,0XFF,0XFF,0X80,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,
0X00,0XFF,0X7F,0XFF,0XF0,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,
0X07,0XFF,0XFF,0XEF,0XFF,0XC0,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFC,0X03,0XFE,0X7F,0XFF,0XF0,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,
0X00,0X00,0X03,0XFF,0XFF,0XF7,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XE0,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X00,0X00,0X00,0X03,0XFF,0XFF,0XF7,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0X7F,0XFF,0XFF,0XFC,0XFF,0XFF,0XE0,0X00,0X07,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XC0,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFB,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XBF,0XFF,0XFF,0XFD,0XFF,0XFF,0XE0,0X00,0X00,0X00,
0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XF8,0X00,0X00,0XFF,0X80,0X00,0X00,0X01,0XFF,0XFF,0XFD,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFF,0XFF,0XDF,0XFF,0XFF,0XF9,0XFF,0XFF,0XC0,0X00,
0X0F,0XE0,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X80,0X7F,0XFF,0XFF,0X80,0X00,0X00,0X01,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,
0XC0,0X00,0X1F,0XFF,0XFF,0XE0,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0XFF,0XFF,0XFF,
0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,
0XFF,0XFF,0XC0,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XC7,0XFF,0XFF,0X80,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,
0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X7F,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X8F,0XFF,0XFF,0X80,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,
0X00,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X7F,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X1F,0XFF,0XFF,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XF0,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,
0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X7F,0XFF,0XFF,0X00,0X00,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X80,0XFF,0XFF,0XFF,0XFF,0XFF,0XEF,0XF1,0XFF,0XFF,0XFE,0X00,0X01,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XC0,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X07,0XFF,0XFF,0XFC,0X00,0X01,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XE3,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,
0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X0F,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XF8,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X07,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XF0,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,
0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XC0,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XE0,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XCF,0XFF,0XF9,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XC7,0XFF,0XF1,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X01,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X1F,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XC7,0XFF,0XF1,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,
0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X0F,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE3,0XFF,0XE1,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XF8,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,
0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE1,0XFF,0XC3,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XF0,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,
0X00,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0XFF,0X87,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XE0,0X00,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X1C,0X0F,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,
0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X01,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X07,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X7F,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X0F,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,
0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,
0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,
0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XE0,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFE,0X00,0X00,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XF0,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,
0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0X00,0X00,0X1F,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X83,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X0F,0X87,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X0F,0XC1,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X0F,
0XC0,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFC,0X07,0X8E,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFE,0X00,0X1F,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X1F,0X87,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XE0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X1F,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XC0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X06,0X00,0X3F,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X7E,0X00,0X03,0XE0,0X00,0X00,0X1F,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X00,0X3F,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X7F,0XE0,0X7F,0XE0,0X00,0X00,0X0F,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,
0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X3F,0XFF,0XFF,0XC0,0X00,
0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X1F,0XFF,0XFF,
0X80,0X3F,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,0X0F,
0XFF,0X7F,0X00,0XFF,0XC0,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X00,
0X00,0X0F,0XFF,0X7F,0X01,0XFF,0XE0,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,
0X00,0X00,0X00,0X07,0XFF,0XFE,0X03,0XDE,0XF0,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XE0,0X00,0X00,0X00,0X03,0XFA,0XFC,0X07,0XFF,0XB8,0X00,0X7F,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X03,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X00,0X03,0XFE,0XF8,0X07,0XDE,0XF8,0X00,0X3F,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X01,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X00,0X01,0XFF,0X78,0X0E,0XC0,0XDC,0X00,
0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X00,
0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0XFF,0X70,0X0F,0XC0,
0X7C,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XE0,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0XFF,0X60,
0X0F,0XC0,0X7C,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XF0,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,
0X7F,0X60,0X0F,0XC0,0X7C,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,
0X00,0X00,0X3F,0X40,0X0E,0XE0,0XFC,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,
0X00,0X00,0X00,0X00,0X3F,0X00,0X06,0XF3,0XDC,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,
0XFE,0X00,0X00,0X00,0X00,0X00,0X1F,0X00,0X07,0X63,0XB8,0X00,0X07,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X0F,0XFF,0XFF,
0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X0E,0X00,0X07,0XB3,0X78,0X00,0X07,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X07,
0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X0C,0X00,0X03,0XC0,0XF0,0X00,
0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,
0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X00,0X00,0X00,0X00,0X06,0X00,0X01,0XFF,
0XE0,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XC0,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X7F,0X80,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XC0,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X1E,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFC,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X00,0X0F,0XFF,0XFF,0XFF,0XF0,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X00,0X03,0XFF,0XFF,0XFF,
0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X01,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,0X00,0X7F,
0XFF,0XFC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X01,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X00,0X00,
0X00,0X07,0XFF,0XC0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X0F,0XC0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X1F,0X80,0X00,0X07,0XE0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0XFF,0X80,
0X7F,0X87,0XFF,0XFF,0X00,0X7F,0XF0,0X00,0X00,0XFF,0X01,0XF8,0X07,0XF8,0XFF,0XFF,
0XF0,0X00,0X00,0XFF,0XE0,0X00,0X1F,0XFC,0X00,0X7F,0XFC,0X00,0X07,0XFF,0XFF,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,
0X7F,0X80,0X7F,0X87,0XFF,0XFF,0X00,0XFF,0XFC,0X00,0X00,0XFF,0X01,0XFC,0X07,0XF8,
0XFF,0XFF,0XF0,0X00,0X01,0XFF,0XF8,0X00,0X7F,0XFE,0X00,0X7F,0XFF,0X80,0X07,0XFF,
0XFF,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X80,0X7F,0X80,0XFF,0X87,0XFF,0XFF,0X01,0XFF,0XFE,0X00,0X00,0XFF,0X01,0XFC,
0X0F,0XF0,0XFF,0XFF,0XF0,0X00,0X03,0XFF,0XFC,0X00,0XFF,0XFF,0X00,0X7F,0XFF,0XE0,
0X07,0XFF,0XFF,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X80,0X7F,0XC0,0XFF,0X87,0XFF,0XFF,0X03,0XFF,0XFF,0X00,0X00,0XFF,
0X01,0XFC,0X0F,0XF0,0XFF,0XFF,0XF0,0X00,0X07,0XFF,0XFE,0X00,0XFF,0XFF,0X80,0X7F,
0XFF,0XF0,0X07,0XFF,0XFF,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X7F,0XC0,0XFF,0X07,0XFF,0XFF,0X07,0XFF,0XFF,0X00,
0X00,0XFF,0X01,0XFC,0X0F,0XF0,0XFF,0XFF,0XF0,0X00,0X07,0XFF,0XFE,0X01,0XFF,0XFF,
0XC0,0X7F,0XFF,0XF8,0X07,0XFF,0XFF,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X3F,0XC0,0XFF,0X07,0XFF,0XFF,0X07,0XFF,
0XFF,0X80,0X00,0XFF,0X03,0XFC,0X0F,0XF0,0XFF,0XFF,0XF0,0X00,0X0F,0XFF,0XFF,0X03,
0XFF,0XFF,0XC0,0X7F,0XFF,0XF8,0X07,0XFF,0XFF,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X3F,0XC0,0XFF,0X07,0XFF,0XFF,
0X07,0XFF,0XFF,0X80,0X00,0X7F,0X03,0XFC,0X0F,0XF0,0XFF,0XFF,0XF0,0X00,0X0F,0XFF,
0XFF,0X03,0XFF,0XFF,0XE0,0X7F,0XFF,0XFC,0X07,0XFF,0XFF,0X00,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X3F,0XC1,0XFF,0X07,
0XFF,0XFF,0X0F,0XF8,0XFF,0X80,0X00,0X7F,0X83,0XFC,0X0F,0XF0,0XFF,0XFF,0XF0,0X00,
0X1F,0XFF,0XFF,0X83,0XFF,0X7F,0XE0,0X7F,0XFF,0XFC,0X07,0XFF,0XFF,0X00,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X3F,0XE1,
0XFE,0X07,0XFF,0XFF,0X0F,0XF8,0X7F,0XC0,0X00,0X7F,0X83,0XFC,0X0F,0XF0,0XFF,0XFF,
0XE0,0X00,0X1F,0XF0,0XFF,0X83,0XFC,0X3F,0XE0,0X7F,0X9F,0XFC,0X07,0XFF,0XFF,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,
0X1F,0XE1,0XFE,0X07,0XF8,0X00,0X0F,0XF0,0X7F,0XC0,0X00,0X7F,0X83,0XFE,0X0F,0XF0,
0XFF,0X80,0X00,0X00,0X1F,0XF0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X87,0XFE,0X07,0XF8,
0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X80,0X1F,0XE1,0XFE,0X07,0XF8,0X00,0X0F,0XF0,0X7F,0XC0,0X00,0X7F,0X83,0XFE,
0X0F,0XE0,0XFF,0X80,0X00,0X00,0X1F,0XF0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X83,0XFE,
0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X80,0X1F,0XE3,0XFE,0X07,0XF8,0X00,0X0F,0XF0,0X3F,0XC0,0X00,0X7F,
0X83,0XFE,0X1F,0XE0,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,
0X83,0XFE,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X1F,0XF3,0XFC,0X07,0XF8,0X00,0X0F,0XF0,0X3F,0XC0,
0X00,0X7F,0X83,0XFE,0X1F,0XE0,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X7F,0X87,0XFC,0X1F,
0XE0,0X7F,0X83,0XFE,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X0F,0XF3,0XFC,0X07,0XF8,0X00,0X0F,0XF0,
0X3F,0XC0,0X00,0X3F,0X87,0XFE,0X1F,0XE0,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X7F,0X87,
0XFC,0X1F,0XE0,0X7F,0X81,0XFE,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X0F,0XF3,0XFC,0X07,0XF8,0X00,
0X0F,0XF0,0X3F,0X00,0X00,0X3F,0X87,0XFE,0X1F,0XE0,0XFF,0X80,0X00,0X00,0X1F,0XE0,
0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X81,0XFE,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X0F,0XF7,0XF8,0X07,
0XF8,0X00,0X0F,0XF8,0X00,0X00,0X00,0X3F,0X87,0XFE,0X1F,0XE0,0XFF,0X80,0X00,0X00,
0X1F,0XE0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XF8,0X00,0X00,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X0F,0XFF,
0XF8,0X07,0XF8,0X00,0X0F,0XF8,0X00,0X00,0X00,0X3F,0XC7,0XFE,0X1F,0XE0,0XFF,0X80,
0X00,0X00,0X1F,0XE0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XF8,0X00,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,
0X07,0XFF,0XF8,0X07,0XF8,0X00,0X0F,0XF8,0X00,0X00,0X00,0X3F,0XC7,0XFF,0X1F,0XC0,
0XFF,0X80,0X00,0X00,0X1F,0XE0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XF8,
0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X80,0X07,0XFF,0XF8,0X07,0XF8,0X00,0X07,0XFC,0X00,0X00,0X00,0X3F,0XC7,0XFF,
0X1F,0XC0,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,
0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X80,0X07,0XFF,0XF0,0X07,0XF8,0X00,0X07,0XFE,0X00,0X00,0X00,0X3F,
0XC7,0XFF,0X1F,0XC0,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X00,0X07,0XFC,0X1F,0XE0,0X7F,
0X81,0XFF,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X07,0XFF,0XF0,0X07,0XF8,0X00,0X07,0XFE,0X00,0X00,
0X00,0X3F,0XC7,0XFF,0X3F,0XC0,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X00,0X07,0XFC,0X1F,
0XE0,0X7F,0X81,0XFF,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X03,0XFF,0XF0,0X07,0XF8,0X00,0X03,0XFF,
0X00,0X00,0X00,0X1F,0XCF,0XFF,0X3F,0XC0,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X00,0X07,
0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X03,0XFF,0XF0,0X07,0XF8,0X00,
0X03,0XFF,0X80,0X00,0X00,0X1F,0XCF,0XFF,0X3F,0XC0,0XFF,0X80,0X00,0X00,0X1F,0XE0,
0X00,0X07,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X03,0XFF,0XE0,0X07,
0XFF,0XF8,0X01,0XFF,0X80,0X00,0X00,0X1F,0XCF,0XFF,0X3F,0XC0,0XFF,0XFF,0X80,0X00,
0X1F,0XE0,0X00,0X07,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XFF,0XF8,0X00,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X01,0XFF,
0XE0,0X07,0XFF,0XF8,0X00,0XFF,0XC0,0X00,0X00,0X1F,0XCF,0XFF,0X3F,0X80,0XFF,0XFF,
0X80,0X00,0X1F,0XE0,0X00,0X07,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XFF,0XF8,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,
0X01,0XFF,0XE0,0X07,0XFF,0XF8,0X00,0XFF,0XE0,0X00,0X00,0X1F,0XEF,0XFF,0XBF,0X80,
0XFF,0XFF,0X80,0X00,0X1F,0XE0,0X00,0X07,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XFF,
0XF8,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X80,0X01,0XFF,0XE0,0X07,0XFF,0XF8,0X00,0X7F,0XE0,0X00,0X00,0X1F,0XEF,0XFF,
0XBF,0X80,0XFF,0XFF,0X80,0X00,0X1F,0XE0,0X00,0X07,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,
0X07,0XFF,0XF8,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X80,0X01,0XFF,0XC0,0X07,0XFF,0XF8,0X00,0X7F,0XF0,0X00,0X00,0X1F,
0XEF,0XFF,0XBF,0X80,0XFF,0XFF,0X80,0X00,0X1F,0XE0,0X00,0X07,0XFC,0X1F,0XE0,0X7F,
0X81,0XFF,0X07,0XFF,0XF8,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0XC0,0X07,0XFF,0XF8,0X00,0X3F,0XF8,0X00,
0X00,0X0F,0XEF,0XDF,0XBF,0X80,0XFF,0XFF,0X80,0X00,0X1F,0XE0,0X00,0X07,0XFC,0X1F,
0XE0,0X7F,0X81,0XFF,0X07,0XFF,0XF8,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0XC0,0X07,0XFF,0XF8,0X00,0X1F,
0XF8,0X00,0X00,0X0F,0XFF,0XDF,0XFF,0X80,0XFF,0XFF,0X80,0X00,0X1F,0XE0,0X00,0X07,
0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XFF,0XF8,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0XC0,0X07,0XFF,0XF8,
0X00,0X1F,0XFC,0X00,0X00,0X0F,0XFF,0XDF,0XFF,0X80,0XFF,0XFF,0X80,0X00,0X1F,0XE0,
0X00,0X07,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XFF,0XF8,0X00,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,
0XFF,0XF8,0X00,0X0F,0XFE,0X00,0X00,0X0F,0XFF,0XDF,0XFF,0X80,0XFF,0XFF,0X80,0X00,
0X1F,0XE0,0X00,0X07,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XFF,0XF8,0X00,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,
0X80,0X07,0XF8,0X00,0X00,0X07,0XFE,0X00,0X00,0X0F,0XFF,0X9F,0XFF,0X00,0XFF,0X80,
0X00,0X00,0X1F,0XE0,0X00,0X07,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XFC,0X00,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,
0X00,0XFF,0X80,0X07,0XF8,0X00,0X00,0X03,0XFF,0X00,0X00,0X0F,0XFF,0X9F,0XFF,0X00,
0XFF,0X80,0X00,0X00,0X1F,0XE0,0X00,0X07,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XF8,
0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X80,0X00,0XFF,0X80,0X07,0XF8,0X00,0X00,0X03,0XFF,0X00,0X00,0X0F,0XFF,0X9F,
0XFF,0X00,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X00,0X07,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,
0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XF8,0X00,0X00,0X01,0XFF,0X80,0X00,0X07,
0XFF,0X8F,0XFF,0X00,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X00,0X07,0XFC,0X1F,0XE0,0X7F,
0X81,0XFF,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XF8,0X00,0X00,0X01,0XFF,0X80,
0X00,0X07,0XFF,0X8F,0XFF,0X00,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X7F,0X87,0XFC,0X1F,
0XE0,0X7F,0X81,0XFF,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XF8,0X00,0X00,0X00,
0XFF,0X80,0X00,0X07,0XFF,0X8F,0XFF,0X00,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X7F,0X87,
0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XF8,0X00,
0X00,0X00,0X7F,0XC0,0X00,0X07,0XFF,0X8F,0XFF,0X00,0XFF,0X80,0X00,0X00,0X1F,0XE0,
0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,
0XF8,0X00,0X01,0XE0,0X7F,0XC0,0X00,0X07,0XFF,0X0F,0XFE,0X00,0XFF,0X80,0X00,0X00,
0X1F,0XE0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XF8,0X00,0X00,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,
0X80,0X07,0XF8,0X00,0X3F,0XE0,0X7F,0XC0,0X00,0X07,0XFF,0X0F,0XFE,0X00,0XFF,0X80,
0X00,0X00,0X1F,0XE0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X81,0XFF,0X07,0XF8,0X00,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,
0X00,0XFF,0X80,0X07,0XF8,0X00,0X3F,0XE0,0X3F,0XC0,0X00,0X07,0XFF,0X0F,0XFE,0X00,
0XFF,0X80,0X00,0X00,0X1F,0XE0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X81,0XFE,0X07,0XF8,
0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X80,0X00,0XFF,0X80,0X07,0XF8,0X00,0X3F,0XE0,0X3F,0XC0,0X00,0X07,0XFF,0X07,
0XFE,0X00,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X83,0XFE,
0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XF8,0X00,0X1F,0XE0,0X3F,0XC0,0X00,0X03,
0XFF,0X07,0XFE,0X00,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X7F,0X87,0XFC,0X1F,0XE0,0X7F,
0X83,0XFE,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XF8,0X00,0X1F,0XE0,0X3F,0XC0,
0X00,0X03,0XFF,0X07,0XFE,0X00,0XFF,0X80,0X00,0X00,0X1F,0XE0,0X7F,0X87,0XFC,0X1F,
0XE0,0X7F,0X83,0XFE,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XF8,0X00,0X1F,0XE0,
0X7F,0XC0,0X00,0X03,0XFF,0X07,0XFE,0X00,0XFF,0X80,0X00,0X00,0X1F,0XF0,0X7F,0X87,
0XFC,0X1F,0XE0,0X7F,0X83,0XFE,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XF8,0X00,
0X1F,0XF0,0X7F,0XC0,0X00,0X03,0XFE,0X07,0XFE,0X00,0XFF,0X80,0X00,0X00,0X1F,0XF0,
0X7F,0X87,0XFC,0X1F,0XE0,0X7F,0X87,0XFE,0X07,0XF8,0X00,0X00,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,
0XFF,0XFF,0X1F,0XF0,0X7F,0XC0,0X00,0X03,0XFE,0X07,0XFC,0X00,0XFF,0XFF,0XF0,0X00,
0X1F,0XF0,0XFF,0X83,0XFE,0X3F,0XE0,0X7F,0XFF,0XFC,0X07,0XFF,0XFF,0X00,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,
0X80,0X07,0XFF,0XFF,0X1F,0XFD,0XFF,0X80,0X00,0X03,0XFE,0X07,0XFC,0X00,0XFF,0XFF,
0XF0,0X00,0X1F,0XFF,0XFF,0X03,0XFF,0XFF,0XE0,0X7F,0XFF,0XFC,0X07,0XFF,0XFF,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,
0X00,0XFF,0X80,0X07,0XFF,0XFF,0X0F,0XFF,0XFF,0X80,0X00,0X03,0XFE,0X03,0XFC,0X00,
0XFF,0XFF,0XF0,0X00,0X0F,0XFF,0XFF,0X03,0XFF,0XFF,0XC0,0X7F,0XFF,0XFC,0X07,0XFF,
0XFF,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X80,0X00,0XFF,0X80,0X07,0XFF,0XFF,0X0F,0XFF,0XFF,0X80,0X00,0X01,0XFE,0X03,
0XFC,0X00,0XFF,0XFF,0XF0,0X00,0X0F,0XFF,0XFF,0X01,0XFF,0XFF,0XC0,0X7F,0XFF,0XF8,
0X07,0XFF,0XFF,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XFF,0XFF,0X0F,0XFF,0XFF,0X00,0X00,0X01,
0XFE,0X03,0XFC,0X00,0XFF,0XFF,0XF0,0X00,0X07,0XFF,0XFE,0X01,0XFF,0XFF,0XC0,0X7F,
0XFF,0XF0,0X07,0XFF,0XFF,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XFF,0XFF,0X07,0XFF,0XFF,0X00,
0X00,0X01,0XFC,0X03,0XFC,0X00,0XFF,0XFF,0XF0,0X00,0X07,0XFF,0XFE,0X00,0XFF,0XFF,
0X80,0X7F,0XFF,0XF0,0X07,0XFF,0XFF,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XFF,0XFF,0X03,0XFF,
0XFE,0X00,0X00,0X01,0XFC,0X03,0XFC,0X00,0XFF,0XFF,0XF0,0X00,0X03,0XFF,0XFC,0X00,
0XFF,0XFF,0X00,0X7F,0XFF,0XC0,0X07,0XFF,0XFF,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,0XFF,0XFF,
0X01,0XFF,0XFC,0X00,0X00,0X01,0XFC,0X03,0XF8,0X00,0XFF,0XFF,0XF0,0X00,0X01,0XFF,
0XF8,0X00,0X3F,0XFE,0X00,0X7F,0XFF,0X80,0X07,0XFF,0XFF,0X00,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0XFF,0X80,0X07,
0XFF,0XFF,0X00,0X7F,0XF0,0X00,0X00,0X01,0XFC,0X03,0XF8,0X00,0XFF,0XFF,0XF0,0X00,
0X00,0X7F,0XE0,0X00,0X1F,0XF8,0X00,0X7F,0XF8,0X00,0X07,0XFF,0XFF,0X00,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X07,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X0F,0X00,0X00,0X01,0XC0,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,};
|
488466.c | /*
* @brief LPC17xx/40xx IOCON driver
*
* Copyright(C) NXP Semiconductors, 2014
* All rights reserved.
*
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* LPC products. This software is supplied "AS IS" without any warranties of
* any kind, and NXP Semiconductors and its licensor disclaim any and
* all warranties, express or implied, including all implied warranties of
* merchantability, fitness for a particular purpose and non-infringement of
* intellectual property rights. NXP Semiconductors assumes no responsibility
* or liability for the use of the software, conveys no license or rights under any
* patent, copyright, mask work right, or any other intellectual property rights in
* or to any products. NXP Semiconductors reserves the right to make changes
* in the software without notification. NXP Semiconductors also makes no
* representation or warranty that such application will be suitable for the
* specified use without further testing or modification.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation is hereby granted, under NXP Semiconductors' and its
* licensor's relevant copyrights in the software, without fee, provided that it
* is used in conjunction with NXP Semiconductors microcontrollers. This
* copyright, permission, and disclaimer notice must appear in all copies of
* this code.
*/
#include "chip.h"
/*****************************************************************************
* Private types/enumerations/variables
****************************************************************************/
/*****************************************************************************
* Public types/enumerations/variables
****************************************************************************/
/*****************************************************************************
* Private functions
****************************************************************************/
/*****************************************************************************
* Public functions
****************************************************************************/
#if defined(CHIP_LPC175X_6X)
/* Sets I/O Control pin mux */
void Chip_IOCON_PinMuxSet(LPC_IOCON_T *pIOCON, uint8_t port, uint8_t pin, uint32_t modefunc)
{
Chip_IOCON_PinMux(pIOCON, port, pin,
/* mode is in bits 3:2 */
modefunc >> 2,
/* func is in bits 1:0 */
modefunc & 3 );
}
/* Setup pin modes and function */
void Chip_IOCON_PinMux(LPC_IOCON_T *pIOCON, uint8_t port, uint8_t pin, uint32_t mode, uint8_t func)
{
uint8_t reg, bitPos;
uint32_t temp;
bitPos = IOCON_BIT_INDEX(pin);
reg = IOCON_REG_INDEX(port,pin);
temp = pIOCON->PINSEL[reg] & ~(0x03UL << bitPos);
pIOCON->PINSEL[reg] = temp | (func << bitPos);
temp = pIOCON->PINMODE[reg] & ~(0x03UL << bitPos);
pIOCON->PINMODE[reg] = temp | (mode << bitPos);
}
#endif /* defined(CHIP_LPC175X_6X) */
/* Set all I/O Control pin muxing */
void Chip_IOCON_SetPinMuxing(LPC_IOCON_T *pIOCON, const PINMUX_GRP_T* pinArray, uint32_t arrayLength)
{
uint32_t ix;
for (ix = 0; ix < arrayLength; ix++ ) {
Chip_IOCON_PinMuxSet(pIOCON, pinArray[ix].pingrp, pinArray[ix].pinnum, pinArray[ix].modefunc);
}
}
/* Set all I/O Control pin muxing */
void Chip_IOCON_SetPinMuxing2(LPC_IOCON_T *pIOCON, const PINMUX_GRP_T2* pinArray, uint32_t arrayLength)
{
uint32_t ix;
for (ix = 0; ix < arrayLength; ix++ ) {
const PINMUX_GRP_T2* pin = &(pinArray[ix]);
Chip_IOCON_PinMuxSet(pIOCON, pin->pingrp, pin->pinnum, pin->modefunc);
if (IOCON_ISGPIO(pin)) {
Chip_GPIO_WriteDirBit(LPC_GPIO, pin->pingrp, pin->pinnum, pin->output );
if ( pin->output ) {
if (pin->opendrain) {
Chip_IOCON_EnableOD(pIOCON, pin->pingrp, pin->pinnum);
} else {
Chip_IOCON_DisableOD(pIOCON, pin->pingrp, pin->pinnum);
}
Chip_GPIO_SetPinState(LPC_GPIO,pin->pingrp, pin->pinnum, pin->initval);
}
}
}
}
|
581413.c | /*
* MultiByteToWideChar implementation
*
* Copyright 2000 Alexandre Julliard
*
* This 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.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <string.h>
#include "wine/unicode.h"
extern unsigned int wine_decompose( WCHAR ch, WCHAR *dst, unsigned int dstlen ) DECLSPEC_HIDDEN;
/* check the code whether it is in Unicode Private Use Area (PUA). */
/* MB_ERR_INVALID_CHARS raises an error converting from 1-byte character to PUA. */
static inline int is_private_use_area_char(WCHAR code)
{
return (code >= 0xe000 && code <= 0xf8ff);
}
/* check src string for invalid chars; return non-zero if invalid char found */
static inline int check_invalid_chars_sbcs( const struct sbcs_table *table, int flags,
const unsigned char *src, unsigned int srclen )
{
const WCHAR * const cp2uni = (flags & MB_USEGLYPHCHARS) ? table->cp2uni_glyphs : table->cp2uni;
const WCHAR def_unicode_char = table->info.def_unicode_char;
const unsigned char def_char = table->uni2cp_low[table->uni2cp_high[def_unicode_char >> 8]
+ (def_unicode_char & 0xff)];
while (srclen)
{
if ((cp2uni[*src] == def_unicode_char && *src != def_char) ||
is_private_use_area_char(cp2uni[*src])) break;
src++;
srclen--;
}
return srclen;
}
/* mbstowcs for single-byte code page */
/* all lengths are in characters, not bytes */
static inline int mbstowcs_sbcs( const struct sbcs_table *table, int flags,
const unsigned char *src, unsigned int srclen,
WCHAR *dst, unsigned int dstlen )
{
const WCHAR * const cp2uni = (flags & MB_USEGLYPHCHARS) ? table->cp2uni_glyphs : table->cp2uni;
int ret = srclen;
if (dstlen < srclen)
{
/* buffer too small: fill it up to dstlen and return error */
srclen = dstlen;
ret = -1;
}
while (srclen >= 16)
{
dst[0] = cp2uni[src[0]];
dst[1] = cp2uni[src[1]];
dst[2] = cp2uni[src[2]];
dst[3] = cp2uni[src[3]];
dst[4] = cp2uni[src[4]];
dst[5] = cp2uni[src[5]];
dst[6] = cp2uni[src[6]];
dst[7] = cp2uni[src[7]];
dst[8] = cp2uni[src[8]];
dst[9] = cp2uni[src[9]];
dst[10] = cp2uni[src[10]];
dst[11] = cp2uni[src[11]];
dst[12] = cp2uni[src[12]];
dst[13] = cp2uni[src[13]];
dst[14] = cp2uni[src[14]];
dst[15] = cp2uni[src[15]];
src += 16;
dst += 16;
srclen -= 16;
}
/* now handle the remaining characters */
src += srclen;
dst += srclen;
switch (srclen)
{
case 15: dst[-15] = cp2uni[src[-15]];
case 14: dst[-14] = cp2uni[src[-14]];
case 13: dst[-13] = cp2uni[src[-13]];
case 12: dst[-12] = cp2uni[src[-12]];
case 11: dst[-11] = cp2uni[src[-11]];
case 10: dst[-10] = cp2uni[src[-10]];
case 9: dst[-9] = cp2uni[src[-9]];
case 8: dst[-8] = cp2uni[src[-8]];
case 7: dst[-7] = cp2uni[src[-7]];
case 6: dst[-6] = cp2uni[src[-6]];
case 5: dst[-5] = cp2uni[src[-5]];
case 4: dst[-4] = cp2uni[src[-4]];
case 3: dst[-3] = cp2uni[src[-3]];
case 2: dst[-2] = cp2uni[src[-2]];
case 1: dst[-1] = cp2uni[src[-1]];
case 0: break;
}
return ret;
}
/* mbstowcs for single-byte code page with char decomposition */
static int mbstowcs_sbcs_decompose( const struct sbcs_table *table, int flags,
const unsigned char *src, unsigned int srclen,
WCHAR *dst, unsigned int dstlen )
{
const WCHAR * const cp2uni = (flags & MB_USEGLYPHCHARS) ? table->cp2uni_glyphs : table->cp2uni;
unsigned int len;
if (!dstlen) /* compute length */
{
WCHAR dummy[4]; /* no decomposition is larger than 4 chars */
for (len = 0; srclen; srclen--, src++)
len += wine_decompose( cp2uni[*src], dummy, 4 );
return len;
}
for (len = dstlen; srclen && len; srclen--, src++)
{
unsigned int res = wine_decompose( cp2uni[*src], dst, len );
if (!res) break;
len -= res;
dst += res;
}
if (srclen) return -1; /* overflow */
return dstlen - len;
}
/* query necessary dst length for src string */
static inline int get_length_dbcs( const struct dbcs_table *table,
const unsigned char *src, unsigned int srclen )
{
const unsigned char * const cp2uni_lb = table->cp2uni_leadbytes;
int len;
for (len = 0; srclen; srclen--, src++, len++)
{
if (cp2uni_lb[*src] && srclen > 1 && src[1])
{
src++;
srclen--;
}
}
return len;
}
/* check src string for invalid chars; return non-zero if invalid char found */
static inline int check_invalid_chars_dbcs( const struct dbcs_table *table,
const unsigned char *src, unsigned int srclen )
{
const WCHAR * const cp2uni = table->cp2uni;
const unsigned char * const cp2uni_lb = table->cp2uni_leadbytes;
const WCHAR def_unicode_char = table->info.def_unicode_char;
const unsigned short def_char = table->uni2cp_low[table->uni2cp_high[def_unicode_char >> 8]
+ (def_unicode_char & 0xff)];
while (srclen)
{
unsigned char off = cp2uni_lb[*src];
if (off) /* multi-byte char */
{
if (srclen == 1) break; /* partial char, error */
if (cp2uni[(off << 8) + src[1]] == def_unicode_char &&
((src[0] << 8) | src[1]) != def_char) break;
src++;
srclen--;
}
else if ((cp2uni[*src] == def_unicode_char && *src != def_char) ||
is_private_use_area_char(cp2uni[*src])) break;
src++;
srclen--;
}
return srclen;
}
/* mbstowcs for double-byte code page */
/* all lengths are in characters, not bytes */
static inline int mbstowcs_dbcs( const struct dbcs_table *table,
const unsigned char *src, unsigned int srclen,
WCHAR *dst, unsigned int dstlen )
{
const WCHAR * const cp2uni = table->cp2uni;
const unsigned char * const cp2uni_lb = table->cp2uni_leadbytes;
unsigned int len;
if (!dstlen) return get_length_dbcs( table, src, srclen );
for (len = dstlen; srclen && len; len--, srclen--, src++, dst++)
{
unsigned char off = cp2uni_lb[*src];
if (off && srclen > 1 && src[1])
{
src++;
srclen--;
*dst = cp2uni[(off << 8) + *src];
}
else *dst = cp2uni[*src];
}
if (srclen) return -1; /* overflow */
return dstlen - len;
}
/* mbstowcs for double-byte code page with character decomposition */
static int mbstowcs_dbcs_decompose( const struct dbcs_table *table,
const unsigned char *src, unsigned int srclen,
WCHAR *dst, unsigned int dstlen )
{
const WCHAR * const cp2uni = table->cp2uni;
const unsigned char * const cp2uni_lb = table->cp2uni_leadbytes;
unsigned int len, res;
WCHAR ch;
if (!dstlen) /* compute length */
{
WCHAR dummy[4]; /* no decomposition is larger than 4 chars */
for (len = 0; srclen; srclen--, src++)
{
unsigned char off = cp2uni_lb[*src];
if (off && srclen > 1 && src[1])
{
src++;
srclen--;
ch = cp2uni[(off << 8) + *src];
}
else ch = cp2uni[*src];
len += wine_decompose( ch, dummy, 4 );
}
return len;
}
for (len = dstlen; srclen && len; srclen--, src++)
{
unsigned char off = cp2uni_lb[*src];
if (off && srclen > 1 && src[1])
{
src++;
srclen--;
ch = cp2uni[(off << 8) + *src];
}
else ch = cp2uni[*src];
if (!(res = wine_decompose( ch, dst, len ))) break;
dst += res;
len -= res;
}
if (srclen) return -1; /* overflow */
return dstlen - len;
}
/* return -1 on dst buffer overflow, -2 on invalid input char */
int wine_cp_mbstowcs( const union cptable *table, int flags,
const char *s, int srclen,
WCHAR *dst, int dstlen )
{
const unsigned char *src = (const unsigned char*) s;
if (table->info.char_size == 1)
{
if (flags & MB_ERR_INVALID_CHARS)
{
if (check_invalid_chars_sbcs( &table->sbcs, flags, src, srclen )) return -2;
}
if (!(flags & MB_COMPOSITE))
{
if (!dstlen) return srclen;
return mbstowcs_sbcs( &table->sbcs, flags, src, srclen, dst, dstlen );
}
return mbstowcs_sbcs_decompose( &table->sbcs, flags, src, srclen, dst, dstlen );
}
else /* mbcs */
{
if (flags & MB_ERR_INVALID_CHARS)
{
if (check_invalid_chars_dbcs( &table->dbcs, src, srclen )) return -2;
}
if (!(flags & MB_COMPOSITE))
return mbstowcs_dbcs( &table->dbcs, src, srclen, dst, dstlen );
else
return mbstowcs_dbcs_decompose( &table->dbcs, src, srclen, dst, dstlen );
}
}
|
248290.c | // This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/*
* Code to handle tags and the tag stack
*/
#include <assert.h>
#include <inttypes.h>
#include <stdbool.h>
#include <string.h>
#include "nvim/ascii.h"
#include "nvim/buffer.h"
#include "nvim/charset.h"
#include "nvim/cursor.h"
#include "nvim/edit.h"
#include "nvim/eval.h"
#include "nvim/ex_cmds.h"
#include "nvim/ex_cmds2.h"
#include "nvim/ex_docmd.h"
#include "nvim/ex_getln.h"
#include "nvim/file_search.h"
#include "nvim/fileio.h"
#include "nvim/fold.h"
#include "nvim/garray.h"
#include "nvim/if_cscope.h"
#include "nvim/mark.h"
#include "nvim/mbyte.h"
#include "nvim/memory.h"
#include "nvim/message.h"
#include "nvim/misc1.h"
#include "nvim/move.h"
#include "nvim/option.h"
#include "nvim/os/input.h"
#include "nvim/os/os.h"
#include "nvim/os/time.h"
#include "nvim/os_unix.h"
#include "nvim/path.h"
#include "nvim/quickfix.h"
#include "nvim/regexp.h"
#include "nvim/screen.h"
#include "nvim/search.h"
#include "nvim/strings.h"
#include "nvim/tag.h"
#include "nvim/ui.h"
#include "nvim/vim.h"
#include "nvim/window.h"
/*
* Structure to hold pointers to various items in a tag line.
*/
typedef struct tag_pointers {
// filled in by parse_tag_line():
char_u *tagname; // start of tag name (skip "file:")
char_u *tagname_end; // char after tag name
char_u *fname; // first char of file name
char_u *fname_end; // char after file name
char_u *command; // first char of command
// filled in by parse_match():
char_u *command_end; // first char after command
char_u *tag_fname; // file name of the tags file. This is used
// when 'tr' is set.
char_u *tagkind; // "kind:" value
char_u *tagkind_end; // end of tagkind
char_u *user_data; // user_data string
char_u *user_data_end; // end of user_data
linenr_T tagline; // "line:" value
} tagptrs_T;
/*
* Structure to hold info about the tag pattern being used.
*/
typedef struct {
char_u *pat; // the pattern
int len; // length of pat[]
char_u *head; // start of pattern head
int headlen; // length of head[]
regmatch_T regmatch; // regexp program, may be NULL
} pat_T;
// The matching tags are first stored in one of the hash tables. In
// which one depends on the priority of the match.
// ht_match[] is used to find duplicates, ga_match[] to keep them in sequence.
// At the end, the matches from ga_match[] are concatenated, to make a list
// sorted on priority.
#define MT_ST_CUR 0 // static match in current file
#define MT_GL_CUR 1 // global match in current file
#define MT_GL_OTH 2 // global match in other file
#define MT_ST_OTH 3 // static match in other file
#define MT_IC_OFF 4 // add for icase match
#define MT_RE_OFF 8 // add for regexp match
#define MT_MASK 7 // mask for printing priority
#define MT_COUNT 16
static char *mt_names[MT_COUNT/2] =
{ "FSC", "F C", "F ", "FS ", " SC", " C", " ", " S " };
#define NOTAGFILE 99 // return value for jumpto_tag
static char_u *nofile_fname = NULL; // fname for NOTAGFILE error
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "tag.c.generated.h"
#endif
static char_u *bottommsg = (char_u *)N_("E555: at bottom of tag stack");
static char_u *topmsg = (char_u *)N_("E556: at top of tag stack");
static char_u *recurmsg
= (char_u *)N_("E986: cannot modify the tag stack within tagfunc");
static char_u *tfu_inv_ret_msg
= (char_u *)N_("E987: invalid return value from tagfunc");
static char_u *tagmatchname = NULL; // name of last used tag
/*
* Tag for preview window is remembered separately, to avoid messing up the
* normal tagstack.
*/
static taggy_T ptag_entry = { NULL, { { 0, 0, 0 }, 0, 0, NULL }, 0, 0, NULL };
static int tfu_in_use = false; // disallow recursive call of tagfunc
// Used instead of NUL to separate tag fields in the growarrays.
#define TAG_SEP 0x02
/// Jump to tag; handling of tag commands and tag stack
///
/// *tag != NUL: ":tag {tag}", jump to new tag, add to tag stack
///
/// type == DT_TAG: ":tag [tag]", jump to newer position or same tag again
/// type == DT_HELP: like DT_TAG, but don't use regexp.
/// type == DT_POP: ":pop" or CTRL-T, jump to old position
/// type == DT_NEXT: jump to next match of same tag
/// type == DT_PREV: jump to previous match of same tag
/// type == DT_FIRST: jump to first match of same tag
/// type == DT_LAST: jump to last match of same tag
/// type == DT_SELECT: ":tselect [tag]", select tag from a list of all matches
/// type == DT_JUMP: ":tjump [tag]", jump to tag or select tag from a list
/// type == DT_CSCOPE: use cscope to find the tag
/// type == DT_LTAG: use location list for displaying tag matches
/// type == DT_FREE: free cached matches
///
/// for cscope, returns TRUE if we jumped to tag or aborted, FALSE otherwise
///
/// @param tag tag (pattern) to jump to
/// @param forceit :ta with !
/// @param verbose print "tag not found" message
int do_tag(char_u *tag, int type, int count, int forceit, int verbose)
{
taggy_T *tagstack = curwin->w_tagstack;
int tagstackidx = curwin->w_tagstackidx;
int tagstacklen = curwin->w_tagstacklen;
int cur_match = 0;
int cur_fnum = curbuf->b_fnum;
int oldtagstackidx = tagstackidx;
int prevtagstackidx = tagstackidx;
int prev_num_matches;
int new_tag = false;
int i;
int ic;
int no_regexp = false;
int error_cur_match = 0;
int save_pos = false;
fmark_T saved_fmark;
int jumped_to_tag = false;
int new_num_matches;
char_u **new_matches;
int use_tagstack;
int skip_msg = false;
char_u *buf_ffname = curbuf->b_ffname; // name for priority computation
int use_tfu = 1;
// remember the matches for the last used tag
static int num_matches = 0;
static int max_num_matches = 0; // limit used for match search
static char_u **matches = NULL;
static int flags;
if (tfu_in_use) {
EMSG(_(recurmsg));
return false;
}
#ifdef EXITFREE
if (type == DT_FREE) {
// remove the list of matches
FreeWild(num_matches, matches);
cs_free_tags();
num_matches = 0;
return false;
}
#endif
if (type == DT_HELP) {
type = DT_TAG;
no_regexp = true;
use_tfu = 0;
}
prev_num_matches = num_matches;
free_string_option(nofile_fname);
nofile_fname = NULL;
clearpos(&saved_fmark.mark); // shutup gcc 4.0
saved_fmark.fnum = 0;
// Don't add a tag to the tagstack if 'tagstack' has been reset.
assert(tag != NULL);
if (!p_tgst && *tag != NUL) { // -V522
use_tagstack = false;
new_tag = true;
if (g_do_tagpreview != 0) {
tagstack_clear_entry(&ptag_entry);
ptag_entry.tagname = vim_strsave(tag);
}
} else {
if (g_do_tagpreview != 0) {
use_tagstack = false;
} else {
use_tagstack = true;
}
// new pattern, add to the tag stack
if (*tag != NUL
&& (type == DT_TAG || type == DT_SELECT || type == DT_JUMP
|| type == DT_LTAG
|| type == DT_CSCOPE
)) {
if (g_do_tagpreview != 0) {
if (ptag_entry.tagname != NULL
&& STRCMP(ptag_entry.tagname, tag) == 0) {
// Jumping to same tag: keep the current match, so that
// the CursorHold autocommand example works.
cur_match = ptag_entry.cur_match;
cur_fnum = ptag_entry.cur_fnum;
} else {
tagstack_clear_entry(&ptag_entry);
ptag_entry.tagname = vim_strsave(tag);
}
} else {
/*
* If the last used entry is not at the top, delete all tag
* stack entries above it.
*/
while (tagstackidx < tagstacklen) {
tagstack_clear_entry(&tagstack[--tagstacklen]);
}
// if the tagstack is full: remove oldest entry
if (++tagstacklen > TAGSTACKSIZE) {
tagstacklen = TAGSTACKSIZE;
tagstack_clear_entry(&tagstack[0]);
for (i = 1; i < tagstacklen; i++) {
tagstack[i - 1] = tagstack[i];
}
tagstackidx--;
}
// put the tag name in the tag stack
tagstack[tagstackidx].tagname = vim_strsave(tag);
curwin->w_tagstacklen = tagstacklen;
save_pos = true; // save the cursor position below
}
new_tag = true;
} else {
if (
g_do_tagpreview != 0 ? ptag_entry.tagname == NULL :
tagstacklen == 0) {
// empty stack
EMSG(_(e_tagstack));
goto end_do_tag;
}
if (type == DT_POP) { // go to older position
const bool old_KeyTyped = KeyTyped;
if ((tagstackidx -= count) < 0) {
EMSG(_(bottommsg));
if (tagstackidx + count == 0) {
// We did [num]^T from the bottom of the stack
tagstackidx = 0;
goto end_do_tag;
}
// We weren't at the bottom of the stack, so jump all the
// way to the bottom now.
tagstackidx = 0;
} else if (tagstackidx >= tagstacklen) { // count == 0?
EMSG(_(topmsg));
goto end_do_tag;
}
// Make a copy of the fmark, autocommands may invalidate the
// tagstack before it's used.
saved_fmark = tagstack[tagstackidx].fmark;
if (saved_fmark.fnum != curbuf->b_fnum) {
/*
* Jump to other file. If this fails (e.g. because the
* file was changed) keep original position in tag stack.
*/
if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum,
GETF_SETMARK, forceit) == FAIL) {
tagstackidx = oldtagstackidx; // back to old posn
goto end_do_tag;
}
// A BufReadPost autocommand may jump to the '" mark, but
// we don't what that here.
curwin->w_cursor.lnum = saved_fmark.mark.lnum;
} else {
setpcmark();
curwin->w_cursor.lnum = saved_fmark.mark.lnum;
}
curwin->w_cursor.col = saved_fmark.mark.col;
curwin->w_set_curswant = true;
check_cursor();
if ((fdo_flags & FDO_TAG) && old_KeyTyped) {
foldOpenCursor();
}
// remove the old list of matches
FreeWild(num_matches, matches);
cs_free_tags();
num_matches = 0;
tag_freematch();
goto end_do_tag;
}
if (type == DT_TAG
|| type == DT_LTAG) {
if (g_do_tagpreview != 0) {
cur_match = ptag_entry.cur_match;
cur_fnum = ptag_entry.cur_fnum;
} else {
// ":tag" (no argument): go to newer pattern
save_pos = true; // save the cursor position below
if ((tagstackidx += count - 1) >= tagstacklen) {
/*
* Beyond the last one, just give an error message and
* go to the last one. Don't store the cursor
* position.
*/
tagstackidx = tagstacklen - 1;
EMSG(_(topmsg));
save_pos = false;
} else if (tagstackidx < 0) { // must have been count == 0
EMSG(_(bottommsg));
tagstackidx = 0;
goto end_do_tag;
}
cur_match = tagstack[tagstackidx].cur_match;
cur_fnum = tagstack[tagstackidx].cur_fnum;
}
new_tag = true;
} else { // go to other matching tag
// Save index for when selection is cancelled.
prevtagstackidx = tagstackidx;
if (g_do_tagpreview != 0) {
cur_match = ptag_entry.cur_match;
cur_fnum = ptag_entry.cur_fnum;
} else {
if (--tagstackidx < 0) {
tagstackidx = 0;
}
cur_match = tagstack[tagstackidx].cur_match;
cur_fnum = tagstack[tagstackidx].cur_fnum;
}
switch (type) {
case DT_FIRST:
cur_match = count - 1; break;
case DT_SELECT:
case DT_JUMP:
case DT_CSCOPE:
case DT_LAST:
cur_match = MAXCOL - 1; break;
case DT_NEXT:
cur_match += count; break;
case DT_PREV:
cur_match -= count; break;
}
if (cur_match >= MAXCOL) {
cur_match = MAXCOL - 1;
} else if (cur_match < 0) {
EMSG(_("E425: Cannot go before first matching tag"));
skip_msg = true;
cur_match = 0;
cur_fnum = curbuf->b_fnum;
}
}
}
if (g_do_tagpreview != 0) {
if (type != DT_SELECT && type != DT_JUMP) {
ptag_entry.cur_match = cur_match;
ptag_entry.cur_fnum = cur_fnum;
}
} else {
/*
* For ":tag [arg]" or ":tselect" remember position before the jump.
*/
saved_fmark = tagstack[tagstackidx].fmark;
if (save_pos) {
tagstack[tagstackidx].fmark.mark = curwin->w_cursor;
tagstack[tagstackidx].fmark.fnum = curbuf->b_fnum;
}
// Curwin will change in the call to jumpto_tag() if ":stag" was
// used or an autocommand jumps to another window; store value of
// tagstackidx now.
curwin->w_tagstackidx = tagstackidx;
if (type != DT_SELECT && type != DT_JUMP) {
curwin->w_tagstack[tagstackidx].cur_match = cur_match;
curwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum;
}
}
}
// When not using the current buffer get the name of buffer "cur_fnum".
// Makes sure that the tag order doesn't change when using a remembered
// position for "cur_match".
if (cur_fnum != curbuf->b_fnum) {
buf_T *buf = buflist_findnr(cur_fnum);
if (buf != NULL) {
buf_ffname = buf->b_ffname;
}
}
/*
* Repeat searching for tags, when a file has not been found.
*/
for (;; ) {
int other_name;
char_u *name;
// When desired match not found yet, try to find it (and others).
if (use_tagstack) {
name = tagstack[tagstackidx].tagname;
} else if (g_do_tagpreview != 0) {
name = ptag_entry.tagname;
} else {
name = tag;
}
other_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0);
if (new_tag
|| (cur_match >= num_matches && max_num_matches != MAXCOL)
|| other_name) {
if (other_name) {
xfree(tagmatchname);
tagmatchname = vim_strsave(name);
}
if (type == DT_SELECT || type == DT_JUMP
|| type == DT_LTAG) {
cur_match = MAXCOL - 1;
}
if (type == DT_TAG) {
max_num_matches = MAXCOL;
} else {
max_num_matches = cur_match + 1;
}
// when the argument starts with '/', use it as a regexp
if (!no_regexp && *name == '/') {
flags = TAG_REGEXP;
++name;
} else {
flags = TAG_NOIC;
}
if (type == DT_CSCOPE) {
flags = TAG_CSCOPE;
}
if (verbose) {
flags |= TAG_VERBOSE;
}
if (!use_tfu) {
flags |= TAG_NO_TAGFUNC;
}
if (find_tags(name, &new_num_matches, &new_matches, flags,
max_num_matches, buf_ffname) == OK
&& new_num_matches < max_num_matches) {
max_num_matches = MAXCOL; // If less than max_num_matches
// found: all matches found.
}
// If there already were some matches for the same name, move them
// to the start. Avoids that the order changes when using
// ":tnext" and jumping to another file.
if (!new_tag && !other_name) {
int j, k;
int idx = 0;
tagptrs_T tagp, tagp2;
// Find the position of each old match in the new list. Need
// to use parse_match() to find the tag line.
for (j = 0; j < num_matches; j++) {
parse_match(matches[j], &tagp);
for (i = idx; i < new_num_matches; ++i) {
parse_match(new_matches[i], &tagp2);
if (STRCMP(tagp.tagname, tagp2.tagname) == 0) {
char_u *p = new_matches[i];
for (k = i; k > idx; k--) {
new_matches[k] = new_matches[k - 1];
}
new_matches[idx++] = p;
break;
}
}
}
}
FreeWild(num_matches, matches);
num_matches = new_num_matches;
matches = new_matches;
}
if (num_matches <= 0) {
if (verbose) {
EMSG2(_("E426: tag not found: %s"), name);
}
g_do_tagpreview = 0;
} else {
bool ask_for_selection = false;
if (type == DT_CSCOPE && num_matches > 1) {
cs_print_tags();
ask_for_selection = true;
} else if (type == DT_TAG && *tag != NUL) {
// If a count is supplied to the ":tag <name>" command, then
// jump to count'th matching tag.
cur_match = count > 0 ? count - 1 : 0;
} else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1)) {
print_tag_list(new_tag, use_tagstack, num_matches, matches);
ask_for_selection = true;
} else if (type == DT_LTAG) {
if (add_llist_tags(tag, num_matches, matches) == FAIL) {
goto end_do_tag;
}
cur_match = 0; // Jump to the first tag
}
if (ask_for_selection) {
// Ask to select a tag from the list.
i = prompt_for_number(NULL);
if (i <= 0 || i > num_matches || got_int) {
// no valid choice: don't change anything
if (use_tagstack) {
tagstack[tagstackidx].fmark = saved_fmark;
tagstackidx = prevtagstackidx;
}
cs_free_tags();
jumped_to_tag = true;
break;
}
cur_match = i - 1;
}
if (cur_match >= num_matches) {
// Avoid giving this error when a file wasn't found and we're
// looking for a match in another file, which wasn't found.
// There will be an EMSG("file doesn't exist") below then.
if ((type == DT_NEXT || type == DT_FIRST)
&& nofile_fname == NULL) {
if (num_matches == 1) {
EMSG(_("E427: There is only one matching tag"));
} else {
EMSG(_("E428: Cannot go beyond last matching tag"));
}
skip_msg = true;
}
cur_match = num_matches - 1;
}
if (use_tagstack) {
tagptrs_T tagp2;
tagstack[tagstackidx].cur_match = cur_match;
tagstack[tagstackidx].cur_fnum = cur_fnum;
// store user-provided data originating from tagfunc
if (use_tfu && parse_match(matches[cur_match], &tagp2) == OK
&& tagp2.user_data) {
XFREE_CLEAR(tagstack[tagstackidx].user_data);
tagstack[tagstackidx].user_data = vim_strnsave(tagp2.user_data,
tagp2.user_data_end - tagp2.user_data);
}
tagstackidx++;
} else if (g_do_tagpreview != 0) {
ptag_entry.cur_match = cur_match;
ptag_entry.cur_fnum = cur_fnum;
}
/*
* Only when going to try the next match, report that the previous
* file didn't exist. Otherwise an EMSG() is given below.
*/
if (nofile_fname != NULL && error_cur_match != cur_match) {
smsg(_("File \"%s\" does not exist"), nofile_fname);
}
ic = (matches[cur_match][0] & MT_IC_OFF);
if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP
&& type != DT_CSCOPE
&& (num_matches > 1 || ic)
&& !skip_msg) {
// Give an indication of the number of matching tags
snprintf((char *)IObuff, sizeof(IObuff), _("tag %d of %d%s"),
cur_match + 1,
num_matches,
max_num_matches != MAXCOL ? _(" or more") : "");
if (ic) {
STRCAT(IObuff, _(" Using tag with different case!"));
}
if ((num_matches > prev_num_matches || new_tag)
&& num_matches > 1) {
if (ic) {
msg_attr((const char *)IObuff, HL_ATTR(HLF_W));
} else {
msg(IObuff);
}
msg_scroll = true; // Don't overwrite this message.
} else {
give_warning(IObuff, ic);
}
if (ic && !msg_scrolled && msg_silent == 0) {
ui_flush();
os_delay(1007L, true);
}
}
// Let the SwapExists event know what tag we are jumping to.
vim_snprintf((char *)IObuff, IOSIZE, ":ta %s\r", name);
set_vim_var_string(VV_SWAPCOMMAND, (char *)IObuff, -1);
/*
* Jump to the desired match.
*/
i = jumpto_tag(matches[cur_match], forceit, type != DT_CSCOPE);
set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
if (i == NOTAGFILE) {
// File not found: try again with another matching tag
if ((type == DT_PREV && cur_match > 0)
|| ((type == DT_TAG || type == DT_NEXT
|| type == DT_FIRST)
&& (max_num_matches != MAXCOL
|| cur_match < num_matches - 1))) {
error_cur_match = cur_match;
if (use_tagstack) {
--tagstackidx;
}
if (type == DT_PREV) {
--cur_match;
} else {
type = DT_NEXT;
++cur_match;
}
continue;
}
EMSG2(_("E429: File \"%s\" does not exist"), nofile_fname);
} else {
// We may have jumped to another window, check that
// tagstackidx is still valid.
if (use_tagstack && tagstackidx > curwin->w_tagstacklen) {
tagstackidx = curwin->w_tagstackidx;
}
jumped_to_tag = true;
}
}
break;
}
end_do_tag:
// Only store the new index when using the tagstack and it's valid.
if (use_tagstack && tagstackidx <= curwin->w_tagstacklen) {
curwin->w_tagstackidx = tagstackidx;
}
postponed_split = 0; // don't split next time
g_do_tagpreview = 0; // don't do tag preview next time
return jumped_to_tag;
}
//
// List all the matching tags.
//
static void print_tag_list(int new_tag, int use_tagstack, int num_matches, char_u **matches)
{
taggy_T *tagstack = curwin->w_tagstack;
int tagstackidx = curwin->w_tagstackidx;
int i;
char_u *p;
char_u *command_end;
tagptrs_T tagp;
int taglen;
int attr;
// Assume that the first match indicates how long the tags can
// be, and align the file names to that.
parse_match(matches[0], &tagp);
taglen = (int)(tagp.tagname_end - tagp.tagname + 2);
if (taglen < 18) {
taglen = 18;
}
if (taglen > Columns - 25) {
taglen = MAXCOL;
}
if (msg_col == 0) {
msg_didout = false; // overwrite previous message
}
msg_start();
msg_puts_attr(_(" # pri kind tag"), HL_ATTR(HLF_T));
msg_clr_eos();
taglen_advance(taglen);
msg_puts_attr(_("file\n"), HL_ATTR(HLF_T));
for (i = 0; i < num_matches && !got_int; i++) {
parse_match(matches[i], &tagp);
if (!new_tag && (
(g_do_tagpreview != 0
&& i == ptag_entry.cur_match)
|| (use_tagstack
&& i == tagstack[tagstackidx].cur_match))) {
*IObuff = '>';
} else {
*IObuff = ' ';
}
vim_snprintf((char *)IObuff + 1, IOSIZE - 1,
"%2d %s ", i + 1,
mt_names[matches[i][0] & MT_MASK]);
msg_puts((char *)IObuff);
if (tagp.tagkind != NULL) {
msg_outtrans_len(tagp.tagkind,
(int)(tagp.tagkind_end - tagp.tagkind));
}
msg_advance(13);
msg_outtrans_len_attr(tagp.tagname,
(int)(tagp.tagname_end - tagp.tagname),
HL_ATTR(HLF_T));
msg_putchar(' ');
taglen_advance(taglen);
// Find out the actual file name. If it is long, truncate
// it and put "..." in the middle
p = tag_full_fname(&tagp);
if (p != NULL) {
msg_outtrans_attr(p, HL_ATTR(HLF_D));
XFREE_CLEAR(p);
}
if (msg_col > 0) {
msg_putchar('\n');
}
if (got_int) {
break;
}
msg_advance(15);
// print any extra fields
command_end = tagp.command_end;
if (command_end != NULL) {
p = command_end + 3;
while (*p && *p != '\r' && *p != '\n') {
while (*p == TAB) {
p++;
}
// skip "file:" without a value (static tag)
if (STRNCMP(p, "file:", 5) == 0 && ascii_isspace(p[5])) {
p += 5;
continue;
}
// skip "kind:<kind>" and "<kind>"
if (p == tagp.tagkind
|| (p + 5 == tagp.tagkind
&& STRNCMP(p, "kind:", 5) == 0)) {
p = tagp.tagkind_end;
continue;
}
// print all other extra fields
attr = HL_ATTR(HLF_CM);
while (*p && *p != '\r' && *p != '\n') {
if (msg_col + ptr2cells(p) >= Columns) {
msg_putchar('\n');
if (got_int) {
break;
}
msg_advance(15);
}
p = msg_outtrans_one(p, attr);
if (*p == TAB) {
msg_puts_attr(" ", attr);
break;
}
if (*p == ':') {
attr = 0;
}
}
}
if (msg_col > 15) {
msg_putchar('\n');
if (got_int) {
break;
}
msg_advance(15);
}
} else {
for (p = tagp.command;
*p && *p != '\r' && *p != '\n';
p++) {
}
command_end = p;
}
// Put the info (in several lines) at column 15.
// Don't display "/^" and "?^".
p = tagp.command;
if (*p == '/' || *p == '?') {
p++;
if (*p == '^') {
p++;
}
}
// Remove leading whitespace from pattern
while (p != command_end && ascii_isspace(*p)) {
p++;
}
while (p != command_end) {
if (msg_col + (*p == TAB ? 1 : ptr2cells(p)) > Columns) {
msg_putchar('\n');
}
if (got_int) {
break;
}
msg_advance(15);
// skip backslash used for escaping a command char or
// a backslash
if (*p == '\\' && (*(p + 1) == *tagp.command
|| *(p + 1) == '\\')) {
p++;
}
if (*p == TAB) {
msg_putchar(' ');
p++;
} else {
p = msg_outtrans_one(p, 0);
}
// don't display the "$/;\"" and "$?;\""
if (p == command_end - 2 && *p == '$'
&& *(p + 1) == *tagp.command) {
break;
}
// don't display matching '/' or '?'
if (p == command_end - 1 && *p == *tagp.command
&& (*p == '/' || *p == '?')) {
break;
}
}
if (msg_col) {
msg_putchar('\n');
}
os_breakcheck();
}
if (got_int) {
got_int = false; // only stop the listing
}
}
//
// Add the matching tags to the location list for the current
// window.
//
static int add_llist_tags(char_u *tag, int num_matches, char_u **matches)
{
list_T *list;
char_u tag_name[128 + 1];
char_u *fname;
char_u *cmd;
int i;
char_u *p;
tagptrs_T tagp;
fname = xmalloc(MAXPATHL + 1);
cmd = xmalloc(CMDBUFFSIZE + 1);
list = tv_list_alloc(0);
for (i = 0; i < num_matches; i++) {
int len, cmd_len;
long lnum;
dict_T *dict;
parse_match(matches[i], &tagp);
// Save the tag name
len = (int)(tagp.tagname_end - tagp.tagname);
if (len > 128) {
len = 128;
}
STRLCPY(tag_name, tagp.tagname, len + 1);
tag_name[len] = NUL;
// Save the tag file name
p = tag_full_fname(&tagp);
if (p == NULL) {
continue;
}
STRLCPY(fname, p, MAXPATHL);
XFREE_CLEAR(p);
// Get the line number or the search pattern used to locate
// the tag.
lnum = 0;
if (isdigit(*tagp.command)) {
// Line number is used to locate the tag
lnum = atol((char *)tagp.command);
} else {
char_u *cmd_start, *cmd_end;
// Search pattern is used to locate the tag
// Locate the end of the command
cmd_start = tagp.command;
cmd_end = tagp.command_end;
if (cmd_end == NULL) {
for (p = tagp.command;
*p && *p != '\r' && *p != '\n'; p++) {
}
cmd_end = p;
}
// Now, cmd_end points to the character after the
// command. Adjust it to point to the last
// character of the command.
cmd_end--;
// Skip the '/' and '?' characters at the
// beginning and end of the search pattern.
if (*cmd_start == '/' || *cmd_start == '?') {
cmd_start++;
}
if (*cmd_end == '/' || *cmd_end == '?') {
cmd_end--;
}
len = 0;
cmd[0] = NUL;
// If "^" is present in the tag search pattern, then
// copy it first.
if (*cmd_start == '^') {
STRCPY(cmd, "^");
cmd_start++;
len++;
}
// Precede the tag pattern with \V to make it very
// nomagic.
STRCAT(cmd, "\\V");
len += 2;
cmd_len = (int)(cmd_end - cmd_start + 1);
if (cmd_len > (CMDBUFFSIZE - 5)) {
cmd_len = CMDBUFFSIZE - 5;
}
snprintf((char *)cmd + len, CMDBUFFSIZE + 1 - len,
"%.*s", cmd_len, cmd_start);
len += cmd_len;
if (cmd[len - 1] == '$') {
// Replace '$' at the end of the search pattern
// with '\$'
cmd[len - 1] = '\\';
cmd[len] = '$';
len++;
}
cmd[len] = NUL;
}
dict = tv_dict_alloc();
tv_list_append_dict(list, dict);
tv_dict_add_str(dict, S_LEN("text"), (const char *)tag_name);
tv_dict_add_str(dict, S_LEN("filename"), (const char *)fname);
tv_dict_add_nr(dict, S_LEN("lnum"), lnum);
if (lnum == 0) {
tv_dict_add_str(dict, S_LEN("pattern"), (const char *)cmd);
}
}
vim_snprintf((char *)IObuff, IOSIZE, "ltag %s", tag);
set_errorlist(curwin, list, ' ', IObuff, NULL);
tv_list_free(list);
XFREE_CLEAR(fname);
XFREE_CLEAR(cmd);
return OK;
}
/*
* Free cached tags.
*/
void tag_freematch(void)
{
XFREE_CLEAR(tagmatchname);
}
static void taglen_advance(int l)
{
if (l == MAXCOL) {
msg_putchar('\n');
msg_advance(24);
} else {
msg_advance(13 + l);
}
}
/*
* Print the tag stack
*/
void do_tags(exarg_T *eap)
{
int i;
char_u *name;
taggy_T *tagstack = curwin->w_tagstack;
int tagstackidx = curwin->w_tagstackidx;
int tagstacklen = curwin->w_tagstacklen;
// Highlight title
MSG_PUTS_TITLE(_("\n # TO tag FROM line in file/text"));
for (i = 0; i < tagstacklen; ++i) {
if (tagstack[i].tagname != NULL) {
name = fm_getname(&(tagstack[i].fmark), 30);
if (name == NULL) { // file name not available
continue;
}
msg_putchar('\n');
vim_snprintf((char *)IObuff, IOSIZE, "%c%2d %2d %-15s %5ld ",
i == tagstackidx ? '>' : ' ',
i + 1,
tagstack[i].cur_match + 1,
tagstack[i].tagname,
tagstack[i].fmark.mark.lnum);
msg_outtrans(IObuff);
msg_outtrans_attr(name, tagstack[i].fmark.fnum == curbuf->b_fnum
? HL_ATTR(HLF_D) : 0);
xfree(name);
}
ui_flush(); // show one line at a time
}
if (tagstackidx == tagstacklen) { // idx at top of stack
MSG_PUTS("\n>");
}
}
/*
* Compare two strings, for length "len", ignoring case the ASCII way.
* return 0 for match, < 0 for smaller, > 0 for bigger
* Make sure case is folded to uppercase in comparison (like for 'sort -f')
*/
static int tag_strnicmp(char_u *s1, char_u *s2, size_t len)
{
int i;
while (len > 0) {
i = TOUPPER_ASC(*s1) - TOUPPER_ASC(*s2);
if (i != 0) {
return i; // this character different
}
if (*s1 == NUL) {
break; // strings match until NUL
}
++s1;
++s2;
--len;
}
return 0; // strings match
}
/*
* Extract info from the tag search pattern "pats->pat".
*/
static void prepare_pats(pat_T *pats, int has_re)
{
pats->head = pats->pat;
pats->headlen = pats->len;
if (has_re) {
// When the pattern starts with '^' or "\\<", binary searching can be
// used (much faster).
if (pats->pat[0] == '^') {
pats->head = pats->pat + 1;
} else if (pats->pat[0] == '\\' && pats->pat[1] == '<') {
pats->head = pats->pat + 2;
}
if (pats->head == pats->pat) {
pats->headlen = 0;
} else {
for (pats->headlen = 0; pats->head[pats->headlen] != NUL;
++pats->headlen) {
if (vim_strchr((char_u *)(p_magic ? ".[~*\\$" : "\\$"),
pats->head[pats->headlen]) != NULL) {
break;
}
}
}
if (p_tl != 0 && pats->headlen > p_tl) { // adjust for 'taglength'
pats->headlen = p_tl;
}
}
if (has_re) {
pats->regmatch.regprog = vim_regcomp(pats->pat, p_magic ? RE_MAGIC : 0);
} else {
pats->regmatch.regprog = NULL;
}
}
/// Call the user-defined function to generate a list of tags used by
/// find_tags().
///
/// Return OK if at least 1 tag has been successfully found,
/// NOTDONE if the function returns v:null, and FAIL otherwise.
///
/// @param pat pattern supplied to the user-defined function
/// @param ga the tags will be placed here
/// @param match_count here the number of tags found will be placed
/// @param flags flags from find_tags (TAG_*)
/// @param buf_ffname name of buffer for priority
static int find_tagfunc_tags(char_u *pat, garray_T *ga, int *match_count, int flags,
char_u *buf_ffname)
{
pos_T save_pos;
list_T *taglist;
int ntags = 0;
int result = FAIL;
typval_T args[4];
typval_T rettv;
char_u flagString[4];
taggy_T *tag = &curwin->w_tagstack[curwin->w_tagstackidx];
if (*curbuf->b_p_tfu == NUL) {
return FAIL;
}
args[0].v_type = VAR_STRING;
args[0].vval.v_string = pat;
args[1].v_type = VAR_STRING;
args[1].vval.v_string = flagString;
// create 'info' dict argument
dict_T *const d = tv_dict_alloc_lock(VAR_FIXED);
if (tag->user_data != NULL) {
tv_dict_add_str(d, S_LEN("user_data"), (const char *)tag->user_data);
}
if (buf_ffname != NULL) {
tv_dict_add_str(d, S_LEN("buf_ffname"), (const char *)buf_ffname);
}
d->dv_refcount++;
args[2].v_type = VAR_DICT;
args[2].vval.v_dict = d;
args[3].v_type = VAR_UNKNOWN;
vim_snprintf((char *)flagString, sizeof(flagString),
"%s%s%s",
g_tag_at_cursor ? "c": "",
flags & TAG_INS_COMP ? "i": "",
flags & TAG_REGEXP ? "r": "");
save_pos = curwin->w_cursor;
result = call_vim_function(curbuf->b_p_tfu, 3, args, &rettv);
curwin->w_cursor = save_pos; // restore the cursor position
d->dv_refcount--;
if (result == FAIL) {
return FAIL;
}
if (rettv.v_type == VAR_SPECIAL && rettv.vval.v_special == kSpecialVarNull) {
tv_clear(&rettv);
return NOTDONE;
}
if (rettv.v_type != VAR_LIST || !rettv.vval.v_list) {
tv_clear(&rettv);
EMSG(_(tfu_inv_ret_msg));
return FAIL;
}
taglist = rettv.vval.v_list;
TV_LIST_ITER_CONST(taglist, li, {
char_u *res_name;
char_u *res_fname;
char_u *res_cmd;
char_u *res_kind;
int has_extra = 0;
int name_only = flags & TAG_NAMES;
if (TV_LIST_ITEM_TV(li)->v_type != VAR_DICT) {
EMSG(_(tfu_inv_ret_msg));
break;
}
size_t len = 2;
res_name = NULL;
res_fname = NULL;
res_cmd = NULL;
res_kind = NULL;
TV_DICT_ITER(TV_LIST_ITEM_TV(li)->vval.v_dict, di, {
const char_u *dict_key = di->di_key;
typval_T *tv = &di->di_tv;
if (tv->v_type != VAR_STRING || tv->vval.v_string == NULL) {
continue;
}
len += STRLEN(tv->vval.v_string) + 1; // Space for "\tVALUE"
if (!STRCMP(dict_key, "name")) {
res_name = tv->vval.v_string;
continue;
}
if (!STRCMP(dict_key, "filename")) {
res_fname = tv->vval.v_string;
continue;
}
if (!STRCMP(dict_key, "cmd")) {
res_cmd = tv->vval.v_string;
continue;
}
has_extra = 1;
if (!STRCMP(dict_key, "kind")) {
res_kind = tv->vval.v_string;
continue;
}
// Other elements will be stored as "\tKEY:VALUE"
// Allocate space for the key and the colon
len += STRLEN(dict_key) + 1;
});
if (has_extra) {
len += 2; // need space for ;"
}
if (!res_name || !res_fname || !res_cmd) {
EMSG(_(tfu_inv_ret_msg));
break;
}
char_u *const mfp = name_only ? vim_strsave(res_name) : xmalloc(len + 2);
if (!name_only) {
char_u *p = mfp;
*p++ = MT_GL_OTH + 1; // mtt
*p++ = TAG_SEP; // no tag file name
STRCPY(p, res_name);
p += STRLEN(p);
*p++ = TAB;
STRCPY(p, res_fname);
p += STRLEN(p);
*p++ = TAB;
STRCPY(p, res_cmd);
p += STRLEN(p);
if (has_extra) {
STRCPY(p, ";\"");
p += STRLEN(p);
if (res_kind) {
*p++ = TAB;
STRCPY(p, res_kind);
p += STRLEN(p);
}
TV_DICT_ITER(TV_LIST_ITEM_TV(li)->vval.v_dict, di, {
const char_u *dict_key = di->di_key;
typval_T *tv = &di->di_tv;
if (tv->v_type != VAR_STRING || tv->vval.v_string == NULL) {
continue;
}
if (!STRCMP(dict_key, "name")) {
continue;
}
if (!STRCMP(dict_key, "filename")) {
continue;
}
if (!STRCMP(dict_key, "cmd")) {
continue;
}
if (!STRCMP(dict_key, "kind")) {
continue;
}
*p++ = TAB;
STRCPY(p, dict_key);
p += STRLEN(p);
STRCPY(p, ":");
p += STRLEN(p);
STRCPY(p, tv->vval.v_string);
p += STRLEN(p);
});
}
}
// Add all matches because tagfunc should do filtering.
ga_grow(ga, 1);
((char_u **)(ga->ga_data))[ga->ga_len++] = mfp;
ntags++;
result = OK;
});
tv_clear(&rettv);
*match_count = ntags;
return result;
}
/// find_tags() - search for tags in tags files
///
/// Return FAIL if search completely failed (*num_matches will be 0, *matchesp
/// will be NULL), OK otherwise.
///
/// There is a priority in which type of tag is recognized.
///
/// 6. A static or global tag with a full matching tag for the current file.
/// 5. A global tag with a full matching tag for another file.
/// 4. A static tag with a full matching tag for another file.
/// 3. A static or global tag with an ignore-case matching tag for the
/// current file.
/// 2. A global tag with an ignore-case matching tag for another file.
/// 1. A static tag with an ignore-case matching tag for another file.
///
/// Tags in an emacs-style tags file are always global.
///
/// flags:
/// TAG_HELP only search for help tags
/// TAG_NAMES only return name of tag
/// TAG_REGEXP use "pat" as a regexp
/// TAG_NOIC don't always ignore case
/// TAG_KEEP_LANG keep language
/// TAG_CSCOPE use cscope results for tags
/// TAG_NO_TAGFUNC do not call the 'tagfunc' function
///
/// @param pat pattern to search for
/// @param num_matches return: number of matches found
/// @param matchesp return: array of matches found
/// @param mincount MAXCOL: find all matches other: minimal number of matches */
/// @param buf_ffname name of buffer for priority
int find_tags(char_u *pat, int *num_matches, char_u ***matchesp, int flags, int mincount,
char_u *buf_ffname)
{
FILE *fp;
char_u *lbuf; // line buffer
int lbuf_size = LSIZE; // length of lbuf
char_u *tag_fname; // name of tag file
tagname_T tn; // info for get_tagfname()
int first_file; // trying first tag file
tagptrs_T tagp;
bool did_open = false; // did open a tag file
bool stop_searching = false; // stop when match found or error
int retval = FAIL; // return value
int is_static; // current tag line is static
int is_current; // file name matches
bool eof = false; // found end-of-file
char_u *p;
char_u *s;
int i;
int tag_file_sorted = NUL; // !_TAG_FILE_SORTED value
struct tag_search_info { // Binary search file offsets
off_T low_offset; // offset for first char of first line that
// could match
off_T high_offset; // offset of char after last line that could
// match
off_T curr_offset; // Current file offset in search range
off_T curr_offset_used; // curr_offset used when skipping back
off_T match_offset; // Where the binary search found a tag
int low_char; // first char at low_offset
int high_char; // first char at high_offset
} search_info;
int tagcmp;
off_T offset;
int round;
enum {
TS_START, // at start of file
TS_LINEAR, // linear searching forward, till EOF
TS_BINARY, // binary searching
TS_SKIP_BACK, // skipping backwards
TS_STEP_FORWARD, // stepping forwards
} state; // Current search state
int cmplen;
int match; // matches
int match_no_ic = 0; // matches with rm_ic == FALSE
int match_re; // match with regexp
int matchoff = 0;
int save_emsg_off;
char_u *mfp;
garray_T ga_match[MT_COUNT]; // stores matches in sequence
hashtab_T ht_match[MT_COUNT]; // stores matches by key
hash_T hash = 0;
int match_count = 0; // number of matches found
char_u **matches;
int mtt;
int help_save;
int help_pri = 0;
char_u *help_lang_find = NULL; // lang to be found
char_u help_lang[3]; // lang of current tags file
char_u *saved_pat = NULL; // copy of pat[]
bool is_txt = false;
pat_T orgpat; // holds unconverted pattern info
vimconv_T vimconv;
int findall = (mincount == MAXCOL || mincount == TAG_MANY);
// find all matching tags
bool sort_error = false; // tags file not sorted
int linear; // do a linear search
bool sortic = false; // tag file sorted in nocase
bool line_error = false; // syntax error
int has_re = (flags & TAG_REGEXP); // regexp used
int help_only = (flags & TAG_HELP);
int name_only = (flags & TAG_NAMES);
int noic = (flags & TAG_NOIC);
int get_it_again = FALSE;
int use_cscope = (flags & TAG_CSCOPE);
int verbose = (flags & TAG_VERBOSE);
int use_tfu = ((flags & TAG_NO_TAGFUNC) == 0);
int save_p_ic = p_ic;
// Change the value of 'ignorecase' according to 'tagcase' for the
// duration of this function.
switch (curbuf->b_tc_flags ? curbuf->b_tc_flags : tc_flags) {
case TC_FOLLOWIC:
break;
case TC_IGNORE:
p_ic = true;
break;
case TC_MATCH:
p_ic = false;
break;
case TC_FOLLOWSCS:
p_ic = ignorecase(pat);
break;
case TC_SMART:
p_ic = ignorecase_opt(pat, true, true);
break;
default:
abort();
}
help_save = curbuf->b_help;
orgpat.pat = pat;
orgpat.regmatch.regprog = NULL;
vimconv.vc_type = CONV_NONE;
/*
* Allocate memory for the buffers that are used
*/
lbuf = xmalloc(lbuf_size);
tag_fname = xmalloc(MAXPATHL + 1);
for (mtt = 0; mtt < MT_COUNT; mtt++) {
ga_init(&ga_match[mtt], sizeof(char_u *), 100);
hash_init(&ht_match[mtt]);
}
STRCPY(tag_fname, "from cscope"); // for error messages
/*
* Initialize a few variables
*/
if (help_only) { // want tags from help file
curbuf->b_help = true; // will be restored later
} else if (use_cscope) {
// Make sure we don't mix help and cscope, confuses Coverity.
help_only = false;
curbuf->b_help = false;
}
orgpat.len = (int)STRLEN(pat);
if (curbuf->b_help) {
// When "@ab" is specified use only the "ab" language, otherwise
// search all languages.
if (orgpat.len > 3 && pat[orgpat.len - 3] == '@'
&& ASCII_ISALPHA(pat[orgpat.len - 2])
&& ASCII_ISALPHA(pat[orgpat.len - 1])) {
saved_pat = vim_strnsave(pat, orgpat.len - 3);
help_lang_find = &pat[orgpat.len - 2];
orgpat.pat = saved_pat;
orgpat.len -= 3;
}
}
if (p_tl != 0 && orgpat.len > p_tl) { // adjust for 'taglength'
orgpat.len = p_tl;
}
save_emsg_off = emsg_off;
emsg_off = TRUE; // don't want error for invalid RE here
prepare_pats(&orgpat, has_re);
emsg_off = save_emsg_off;
if (has_re && orgpat.regmatch.regprog == NULL) {
goto findtag_end;
}
// This is only to avoid a compiler warning for using search_info
// uninitialised.
memset(&search_info, 0, 1); // -V512
if (*curbuf->b_p_tfu != NUL && use_tfu && !tfu_in_use) {
tfu_in_use = true;
retval = find_tagfunc_tags(pat, &ga_match[0], &match_count,
flags, buf_ffname);
tfu_in_use = false;
if (retval != NOTDONE) {
goto findtag_end;
}
}
/*
* When finding a specified number of matches, first try with matching
* case, so binary search can be used, and try ignore-case matches in a
* second loop.
* When finding all matches, 'tagbsearch' is off, or there is no fixed
* string to look for, ignore case right away to avoid going though the
* tags files twice.
* When the tag file is case-fold sorted, it is either one or the other.
* Only ignore case when TAG_NOIC not used or 'ignorecase' set.
*/
// Set a flag if the file extension is .txt
if ((flags & TAG_KEEP_LANG)
&& help_lang_find == NULL
&& curbuf->b_fname != NULL
&& (i = (int)STRLEN(curbuf->b_fname)) > 4
&& STRICMP(curbuf->b_fname + i - 4, ".txt") == 0) {
is_txt = true;
}
orgpat.regmatch.rm_ic = ((p_ic || !noic)
&& (findall || orgpat.headlen == 0 || !p_tbs));
for (round = 1; round <= 2; ++round) {
linear = (orgpat.headlen == 0 || !p_tbs || round == 2);
// Try tag file names from tags option one by one.
for (first_file = true;
use_cscope || get_tagfname(&tn, first_file, tag_fname) == OK;
first_file = false) {
// A file that doesn't exist is silently ignored. Only when not a
// single file is found, an error message is given (further on).
if (use_cscope) {
fp = NULL; // avoid GCC warning
} else {
if (curbuf->b_help) {
// Keep en if the file extension is .txt
if (is_txt) {
STRCPY(help_lang, "en");
} else {
// Prefer help tags according to 'helplang'. Put the
// two-letter language name in help_lang[].
i = (int)STRLEN(tag_fname);
if (i > 3 && tag_fname[i - 3] == '-') {
STRCPY(help_lang, tag_fname + i - 2);
} else {
STRCPY(help_lang, "en");
}
}
// When searching for a specific language skip tags files
// for other languages.
if (help_lang_find != NULL
&& STRICMP(help_lang, help_lang_find) != 0) {
continue;
}
// For CTRL-] in a help file prefer a match with the same
// language.
if ((flags & TAG_KEEP_LANG)
&& help_lang_find == NULL
&& curbuf->b_fname != NULL
&& (i = (int)STRLEN(curbuf->b_fname)) > 4
&& curbuf->b_fname[i - 1] == 'x'
&& curbuf->b_fname[i - 4] == '.'
&& STRNICMP(curbuf->b_fname + i - 3, help_lang, 2) == 0) {
help_pri = 0;
} else {
help_pri = 1;
for (s = p_hlg; *s != NUL; ++s) {
if (STRNICMP(s, help_lang, 2) == 0) {
break;
}
++help_pri;
if ((s = vim_strchr(s, ',')) == NULL) {
break;
}
}
if (s == NULL || *s == NUL) {
// Language not in 'helplang': use last, prefer English,
// unless found already.
help_pri++;
if (STRICMP(help_lang, "en") != 0) {
++help_pri;
}
}
}
}
if ((fp = os_fopen((char *)tag_fname, "r")) == NULL) {
continue;
}
if (p_verbose >= 5) {
verbose_enter();
smsg(_("Searching tags file %s"), tag_fname);
verbose_leave();
}
}
did_open = true; // remember that we found at least one file
state = TS_START; // we're at the start of the file
/*
* Read and parse the lines in the file one by one
*/
for (;; ) {
// check for CTRL-C typed, more often when jumping around
if (state == TS_BINARY || state == TS_SKIP_BACK) {
line_breakcheck();
} else {
fast_breakcheck();
}
if ((flags & TAG_INS_COMP)) { // Double brackets for gcc
ins_compl_check_keys(30, false);
}
if (got_int || compl_interrupted) {
stop_searching = true;
break;
}
// When mincount is TAG_MANY, stop when enough matches have been
// found (for completion).
if (mincount == TAG_MANY && match_count >= TAG_MANY) {
stop_searching = true;
retval = OK;
break;
}
if (get_it_again) {
goto line_read_in;
}
/*
* For binary search: compute the next offset to use.
*/
if (state == TS_BINARY) {
offset = search_info.low_offset + ((search_info.high_offset
- search_info.low_offset) / 2);
if (offset == search_info.curr_offset) {
break; // End the binary search without a match.
} else {
search_info.curr_offset = offset;
}
} else if (state == TS_SKIP_BACK) {
// Skipping back (after a match during binary search).
search_info.curr_offset -= lbuf_size * 2;
if (search_info.curr_offset < 0) {
search_info.curr_offset = 0;
rewind(fp);
state = TS_STEP_FORWARD;
}
}
/*
* When jumping around in the file, first read a line to find the
* start of the next line.
*/
if (state == TS_BINARY || state == TS_SKIP_BACK) {
// Adjust the search file offset to the correct position
search_info.curr_offset_used = search_info.curr_offset;
vim_fseek(fp, search_info.curr_offset, SEEK_SET);
eof = vim_fgets(lbuf, lbuf_size, fp);
if (!eof && search_info.curr_offset != 0) {
// The explicit cast is to work around a bug in gcc 3.4.2
// (repeated below).
search_info.curr_offset = vim_ftell(fp);
if (search_info.curr_offset == search_info.high_offset) {
// oops, gone a bit too far; try from low offset
vim_fseek(fp, search_info.low_offset, SEEK_SET);
search_info.curr_offset = search_info.low_offset;
}
eof = vim_fgets(lbuf, lbuf_size, fp);
}
// skip empty and blank lines
while (!eof && vim_isblankline(lbuf)) {
search_info.curr_offset = vim_ftell(fp);
eof = vim_fgets(lbuf, lbuf_size, fp);
}
if (eof) {
// Hit end of file. Skip backwards.
state = TS_SKIP_BACK;
search_info.match_offset = vim_ftell(fp);
search_info.curr_offset = search_info.curr_offset_used;
continue;
}
}
/*
* Not jumping around in the file: Read the next line.
*/
else {
// skip empty and blank lines
do {
eof = use_cscope
? cs_fgets(lbuf, lbuf_size)
: vim_fgets(lbuf, lbuf_size, fp);
} while (!eof && vim_isblankline(lbuf));
if (eof) {
break; // end of file
}
}
line_read_in:
if (vimconv.vc_type != CONV_NONE) {
char_u *conv_line;
int len;
// Convert every line. Converting the pattern from 'enc' to
// the tags file encoding doesn't work, because characters are
// not recognized.
conv_line = string_convert(&vimconv, lbuf, NULL);
if (conv_line != NULL) {
// Copy or swap lbuf and conv_line.
len = (int)STRLEN(conv_line) + 1;
if (len > lbuf_size) {
xfree(lbuf);
lbuf = conv_line;
lbuf_size = len;
} else {
STRCPY(lbuf, conv_line);
xfree(conv_line);
}
}
}
/*
* When still at the start of the file, check for Emacs tags file
* format, and for "not sorted" flag.
*/
if (state == TS_START) {
// The header ends when the line sorts below "!_TAG_". When
// case is folded lower case letters sort before "_".
if (STRNCMP(lbuf, "!_TAG_", 6) <= 0
|| (lbuf[0] == '!' && ASCII_ISLOWER(lbuf[1]))) {
if (STRNCMP(lbuf, "!_TAG_", 6) != 0) {
// Non-header item before the header, e.g. "!" itself.
goto parse_line;
}
/*
* Read header line.
*/
if (STRNCMP(lbuf, "!_TAG_FILE_SORTED\t", 18) == 0) {
tag_file_sorted = lbuf[18];
}
if (STRNCMP(lbuf, "!_TAG_FILE_ENCODING\t", 20) == 0) {
// Prepare to convert every line from the specified
// encoding to 'encoding'.
for (p = lbuf + 20; *p > ' ' && *p < 127; p++) {
}
*p = NUL;
convert_setup(&vimconv, lbuf + 20, p_enc);
}
// Read the next line. Unrecognized flags are ignored.
continue;
}
// Headers ends.
/*
* When there is no tag head, or ignoring case, need to do a
* linear search.
* When no "!_TAG_" is found, default to binary search. If
* the tag file isn't sorted, the second loop will find it.
* When "!_TAG_FILE_SORTED" found: start binary search if
* flag set.
* For cscope, it's always linear.
*/
if (linear || use_cscope) {
state = TS_LINEAR;
} else if (tag_file_sorted == NUL) {
state = TS_BINARY;
} else if (tag_file_sorted == '1') {
state = TS_BINARY;
} else if (tag_file_sorted == '2') {
state = TS_BINARY;
sortic = true;
orgpat.regmatch.rm_ic = (p_ic || !noic);
} else {
state = TS_LINEAR;
}
if (state == TS_BINARY && orgpat.regmatch.rm_ic && !sortic) {
// Binary search won't work for ignoring case, use linear
// search.
linear = true;
state = TS_LINEAR;
}
// When starting a binary search, get the size of the file and
// compute the first offset.
if (state == TS_BINARY) {
if (vim_fseek(fp, 0, SEEK_END) != 0) {
// can't seek, don't use binary search
state = TS_LINEAR;
} else {
// Get the tag file size.
// Don't use lseek(), it doesn't work
// properly on MacOS Catalina.
const off_T filesize = vim_ftell(fp);
vim_fseek(fp, 0, SEEK_SET);
// Calculate the first read offset in the file. Start
// the search in the middle of the file.
search_info.low_offset = 0;
search_info.low_char = 0;
search_info.high_offset = filesize;
search_info.curr_offset = 0;
search_info.high_char = 0xff;
}
continue;
}
}
parse_line:
// When the line is too long the NUL will not be in the
// last-but-one byte (see vim_fgets()).
// Has been reported for Mozilla JS with extremely long names.
// In that case we need to increase lbuf_size.
if (lbuf[lbuf_size - 2] != NUL && !use_cscope) {
lbuf_size *= 2;
xfree(lbuf);
lbuf = xmalloc(lbuf_size);
// this will try the same thing again, make sure the offset is
// different
search_info.curr_offset = 0;
continue;
}
// Figure out where the different strings are in this line.
// For "normal" tags: Do a quick check if the tag matches.
// This speeds up tag searching a lot!
if (orgpat.headlen) {
tagp.tagname = lbuf;
tagp.tagname_end = vim_strchr(lbuf, TAB);
if (tagp.tagname_end == NULL) {
// Corrupted tag line.
line_error = true;
break;
}
/*
* Skip this line if the length of the tag is different and
* there is no regexp, or the tag is too short.
*/
cmplen = (int)(tagp.tagname_end - tagp.tagname);
if (p_tl != 0 && cmplen > p_tl) { // adjust for 'taglength'
cmplen = p_tl;
}
if (has_re && orgpat.headlen < cmplen) {
cmplen = orgpat.headlen;
} else if (state == TS_LINEAR && orgpat.headlen != cmplen) {
continue;
}
if (state == TS_BINARY) {
/*
* Simplistic check for unsorted tags file.
*/
i = (int)tagp.tagname[0];
if (sortic) {
i = TOUPPER_ASC(tagp.tagname[0]);
}
if (i < search_info.low_char || i > search_info.high_char) {
sort_error = true;
}
/*
* Compare the current tag with the searched tag.
*/
if (sortic) {
tagcmp = tag_strnicmp(tagp.tagname, orgpat.head,
(size_t)cmplen);
} else {
tagcmp = STRNCMP(tagp.tagname, orgpat.head, cmplen);
}
/*
* A match with a shorter tag means to search forward.
* A match with a longer tag means to search backward.
*/
if (tagcmp == 0) {
if (cmplen < orgpat.headlen) {
tagcmp = -1;
} else if (cmplen > orgpat.headlen) {
tagcmp = 1;
}
}
if (tagcmp == 0) {
// We've located the tag, now skip back and search
// forward until the first matching tag is found.
state = TS_SKIP_BACK;
search_info.match_offset = search_info.curr_offset;
continue;
}
if (tagcmp < 0) {
search_info.curr_offset = vim_ftell(fp);
if (search_info.curr_offset < search_info.high_offset) {
search_info.low_offset = search_info.curr_offset;
if (sortic) {
search_info.low_char =
TOUPPER_ASC(tagp.tagname[0]);
} else {
search_info.low_char = tagp.tagname[0];
}
continue;
}
}
if (tagcmp > 0
&& search_info.curr_offset != search_info.high_offset) {
search_info.high_offset = search_info.curr_offset;
if (sortic) {
search_info.high_char =
TOUPPER_ASC(tagp.tagname[0]);
} else {
search_info.high_char = tagp.tagname[0];
}
continue;
}
// No match yet and are at the end of the binary search.
break;
} else if (state == TS_SKIP_BACK) {
assert(cmplen >= 0);
if (mb_strnicmp(tagp.tagname, orgpat.head, (size_t)cmplen) != 0) {
state = TS_STEP_FORWARD;
} else {
// Have to skip back more. Restore the curr_offset
// used, otherwise we get stuck at a long line.
search_info.curr_offset = search_info.curr_offset_used;
}
continue;
} else if (state == TS_STEP_FORWARD) {
assert(cmplen >= 0);
if (mb_strnicmp(tagp.tagname, orgpat.head, (size_t)cmplen) != 0) {
if ((off_T)vim_ftell(fp) > search_info.match_offset) {
break; // past last match
} else {
continue; // before first match
}
}
} else {
// skip this match if it can't match
assert(cmplen >= 0);
}
if (mb_strnicmp(tagp.tagname, orgpat.head, (size_t)cmplen) != 0) {
continue;
}
// Can be a matching tag, isolate the file name and command.
tagp.fname = tagp.tagname_end + 1;
tagp.fname_end = vim_strchr(tagp.fname, TAB);
tagp.command = tagp.fname_end + 1;
if (tagp.fname_end == NULL) {
i = FAIL;
} else {
i = OK;
}
} else {
i = parse_tag_line(lbuf,
&tagp);
}
if (i == FAIL) {
line_error = true;
break;
}
/*
* First try matching with the pattern literally (also when it is
* a regexp).
*/
cmplen = (int)(tagp.tagname_end - tagp.tagname);
if (p_tl != 0 && cmplen > p_tl) { // adjust for 'taglength'
cmplen = p_tl;
}
// if tag length does not match, don't try comparing
if (orgpat.len != cmplen) {
match = FALSE;
} else {
if (orgpat.regmatch.rm_ic) {
assert(cmplen >= 0);
match = mb_strnicmp(tagp.tagname, orgpat.pat, (size_t)cmplen) == 0;
if (match) {
match_no_ic = (STRNCMP(tagp.tagname, orgpat.pat,
cmplen) == 0);
}
} else {
match = (STRNCMP(tagp.tagname, orgpat.pat, cmplen) == 0);
}
}
/*
* Has a regexp: Also find tags matching regexp.
*/
match_re = FALSE;
if (!match && orgpat.regmatch.regprog != NULL) {
int cc;
cc = *tagp.tagname_end;
*tagp.tagname_end = NUL;
match = vim_regexec(&orgpat.regmatch, tagp.tagname, (colnr_T)0);
if (match) {
matchoff = (int)(orgpat.regmatch.startp[0] - tagp.tagname);
if (orgpat.regmatch.rm_ic) {
orgpat.regmatch.rm_ic = FALSE;
match_no_ic = vim_regexec(&orgpat.regmatch, tagp.tagname,
(colnr_T)0);
orgpat.regmatch.rm_ic = TRUE;
}
}
*tagp.tagname_end = cc;
match_re = TRUE;
}
// If a match is found, add it to ht_match[] and ga_match[].
if (match) {
int len = 0;
if (use_cscope) {
// Don't change the ordering, always use the same table.
mtt = MT_GL_OTH;
} else {
// Decide in which array to store this match.
is_current = test_for_current(tagp.fname, tagp.fname_end, tag_fname,
buf_ffname);
is_static = test_for_static(&tagp);
// Decide in which of the sixteen tables to store this match.
if (is_static) {
if (is_current) {
mtt = MT_ST_CUR;
} else {
mtt = MT_ST_OTH;
}
} else {
if (is_current) {
mtt = MT_GL_CUR;
} else {
mtt = MT_GL_OTH;
}
}
if (orgpat.regmatch.rm_ic && !match_no_ic) {
mtt += MT_IC_OFF;
}
if (match_re) {
mtt += MT_RE_OFF;
}
}
// Add the found match in ht_match[mtt] and ga_match[mtt].
// Store the info we need later, which depends on the kind of
// tags we are dealing with.
if (help_only) {
#define ML_EXTRA 3
// Append the help-heuristic number after the tagname, for
// sorting it later. The heuristic is ignored for
// detecting duplicates.
// The format is {tagname}@{lang}NUL{heuristic}NUL
*tagp.tagname_end = NUL;
len = (int)(tagp.tagname_end - tagp.tagname);
mfp = xmalloc(sizeof(char_u) + len + 10 + ML_EXTRA + 1);
p = mfp;
STRCPY(p, tagp.tagname);
p[len] = '@';
STRCPY(p + len + 1, help_lang);
snprintf((char *)p + len + 1 + ML_EXTRA, 10, "%06d",
help_heuristic(tagp.tagname,
match_re ? matchoff : 0, !match_no_ic)
+ help_pri);
*tagp.tagname_end = TAB;
} else if (name_only) {
if (get_it_again) {
char_u *temp_end = tagp.command;
if (*temp_end == '/') {
while (*temp_end && *temp_end != '\r'
&& *temp_end != '\n'
&& *temp_end != '$') {
temp_end++;
}
}
if (tagp.command + 2 < temp_end) {
len = (int)(temp_end - tagp.command - 2);
mfp = xmalloc(len + 2);
STRLCPY(mfp, tagp.command + 2, len + 1);
} else {
mfp = NULL;
}
get_it_again = false;
} else {
len = (int)(tagp.tagname_end - tagp.tagname);
mfp = xmalloc(sizeof(char_u) + len + 1);
STRLCPY(mfp, tagp.tagname, len + 1);
// if wanted, re-read line to get long form too
if (State & INSERT) {
get_it_again = p_sft;
}
}
} else {
size_t tag_fname_len = STRLEN(tag_fname);
// Save the tag in a buffer.
// Use 0x02 to separate fields (Can't use NUL, because the
// hash key is terminated by NUL).
// Emacs tag: <mtt><tag_fname><0x02><ebuf><0x02><lbuf><NUL>
// other tag: <mtt><tag_fname><0x02><0x02><lbuf><NUL>
// without Emacs tags: <mtt><tag_fname><0x02><lbuf><NUL>
// Here <mtt> is the "mtt" value plus 1 to avoid NUL.
len = (int)tag_fname_len + (int)STRLEN(lbuf) + 3;
mfp = xmalloc(sizeof(char_u) + len + 1);
p = mfp;
p[0] = mtt + 1;
STRCPY(p + 1, tag_fname);
#ifdef BACKSLASH_IN_FILENAME
// Ignore differences in slashes, avoid adding
// both path/file and path\file.
slash_adjust(p + 1);
#endif
p[tag_fname_len + 1] = TAG_SEP;
s = p + 1 + tag_fname_len + 1;
STRCPY(s, lbuf);
}
if (mfp != NULL) {
hashitem_T *hi;
// Don't add identical matches.
// Add all cscope tags, because they are all listed.
// "mfp" is used as a hash key, there is a NUL byte to end
// the part that matters for comparing, more bytes may
// follow after it. E.g. help tags store the priority
// after the NUL.
if (use_cscope) {
hash++;
} else {
hash = hash_hash(mfp);
}
hi = hash_lookup(&ht_match[mtt], (const char *)mfp,
STRLEN(mfp), hash);
if (HASHITEM_EMPTY(hi)) {
hash_add_item(&ht_match[mtt], hi, mfp, hash);
ga_grow(&ga_match[mtt], 1);
((char_u **)(ga_match[mtt].ga_data))
[ga_match[mtt].ga_len++] = mfp;
match_count++;
} else {
// duplicate tag, drop it
xfree(mfp);
}
}
}
if (use_cscope && eof) {
break;
}
} // forever
if (line_error) {
EMSG2(_("E431: Format error in tags file \"%s\""), tag_fname);
if (!use_cscope) {
EMSGN(_("Before byte %" PRId64), vim_ftell(fp));
}
stop_searching = true;
line_error = false;
}
if (!use_cscope) {
fclose(fp);
}
if (vimconv.vc_type != CONV_NONE) {
convert_setup(&vimconv, NULL, NULL);
}
tag_file_sorted = NUL;
if (sort_error) {
EMSG2(_("E432: Tags file not sorted: %s"), tag_fname);
sort_error = false;
}
/*
* Stop searching if sufficient tags have been found.
*/
if (match_count >= mincount) {
retval = OK;
stop_searching = true;
}
if (stop_searching || use_cscope) {
break;
}
} // end of for-each-file loop
if (!use_cscope) {
tagname_free(&tn);
}
// stop searching when already did a linear search, or when TAG_NOIC
// used, and 'ignorecase' not set or already did case-ignore search
if (stop_searching || linear || (!p_ic && noic) || orgpat.regmatch.rm_ic) {
break;
}
if (use_cscope) {
break;
}
orgpat.regmatch.rm_ic = TRUE; // try another time while ignoring case
}
if (!stop_searching) {
if (!did_open && verbose) { // never opened any tags file
EMSG(_("E433: No tags file"));
}
retval = OK; // It's OK even when no tag found
}
findtag_end:
xfree(lbuf);
vim_regfree(orgpat.regmatch.regprog);
xfree(tag_fname);
/*
* Move the matches from the ga_match[] arrays into one list of
* matches. When retval == FAIL, free the matches.
*/
if (retval == FAIL) {
match_count = 0;
}
if (match_count > 0) {
matches = xmalloc(match_count * sizeof(char_u *));
} else {
matches = NULL;
}
match_count = 0;
for (mtt = 0; mtt < MT_COUNT; mtt++) {
for (i = 0; i < ga_match[mtt].ga_len; i++) {
mfp = ((char_u **)(ga_match[mtt].ga_data))[i];
if (matches == NULL) {
xfree(mfp);
} else {
if (!name_only) {
// Change mtt back to zero-based.
*mfp = *mfp - 1;
// change the TAG_SEP back to NUL
for (p = mfp + 1; *p != NUL; p++) {
if (*p == TAG_SEP) {
*p = NUL;
}
}
}
matches[match_count++] = mfp;
}
}
ga_clear(&ga_match[mtt]);
hash_clear(&ht_match[mtt]);
}
*matchesp = matches;
*num_matches = match_count;
curbuf->b_help = help_save;
xfree(saved_pat);
p_ic = save_p_ic;
return retval;
}
static garray_T tag_fnames = GA_EMPTY_INIT_VALUE;
/*
* Callback function for finding all "tags" and "tags-??" files in
* 'runtimepath' doc directories.
*/
static void found_tagfile_cb(char_u *fname, void *cookie)
{
char_u *const tag_fname = vim_strsave(fname);
#ifdef BACKSLASH_IN_FILENAME
slash_adjust(tag_fname);
#endif
simplify_filename(tag_fname);
GA_APPEND(char_u *, &tag_fnames, tag_fname);
}
#if defined(EXITFREE)
void free_tag_stuff(void)
{
ga_clear_strings(&tag_fnames);
do_tag(NULL, DT_FREE, 0, 0, 0);
tag_freematch();
tagstack_clear_entry(&ptag_entry);
}
#endif
/// Get the next name of a tag file from the tag file list.
/// For help files, use "tags" file only.
///
/// @param tnp holds status info
/// @param first TRUE when first file name is wanted
/// @param buf pointer to buffer of MAXPATHL chars
///
/// @return FAIL if no more tag file names, OK otherwise.
int get_tagfname(tagname_T *tnp, int first, char_u *buf)
{
char_u *fname = NULL;
char_u *r_ptr;
if (first) {
memset(tnp, 0, sizeof(tagname_T));
}
if (curbuf->b_help) {
/*
* For help files it's done in a completely different way:
* Find "doc/tags" and "doc/tags-??" in all directories in
* 'runtimepath'.
*/
if (first) {
ga_clear_strings(&tag_fnames);
ga_init(&tag_fnames, (int)sizeof(char_u *), 10);
do_in_runtimepath((char_u *)"doc/tags doc/tags-??", DIP_ALL,
found_tagfile_cb, NULL);
}
if (tnp->tn_hf_idx >= tag_fnames.ga_len) {
// Not found in 'runtimepath', use 'helpfile', if it exists and
// wasn't used yet, replacing "help.txt" with "tags".
if (tnp->tn_hf_idx > tag_fnames.ga_len || *p_hf == NUL) {
return FAIL;
}
++tnp->tn_hf_idx;
STRCPY(buf, p_hf);
STRCPY(path_tail(buf), "tags");
#ifdef BACKSLASH_IN_FILENAME
slash_adjust(buf);
#endif
simplify_filename(buf);
for (int i = 0; i < tag_fnames.ga_len; i++) {
if (STRCMP(buf, ((char_u **)(tag_fnames.ga_data))[i]) == 0) {
return FAIL; // avoid duplicate file names
}
}
} else {
STRLCPY(buf, ((char_u **)(tag_fnames.ga_data))[tnp->tn_hf_idx++],
MAXPATHL);
}
return OK;
}
if (first) {
// Init. We make a copy of 'tags', because autocommands may change
// the value without notifying us.
tnp->tn_tags = vim_strsave((*curbuf->b_p_tags != NUL)
? curbuf->b_p_tags : p_tags);
tnp->tn_np = tnp->tn_tags;
}
/*
* Loop until we have found a file name that can be used.
* There are two states:
* tnp->tn_did_filefind_init == FALSE: setup for next part in 'tags'.
* tnp->tn_did_filefind_init == TRUE: find next file in this part.
*/
for (;; ) {
if (tnp->tn_did_filefind_init) {
fname = vim_findfile(tnp->tn_search_ctx);
if (fname != NULL) {
break;
}
tnp->tn_did_filefind_init = FALSE;
} else {
char_u *filename = NULL;
// Stop when used all parts of 'tags'.
if (*tnp->tn_np == NUL) {
vim_findfile_cleanup(tnp->tn_search_ctx);
tnp->tn_search_ctx = NULL;
return FAIL;
}
/*
* Copy next file name into buf.
*/
buf[0] = NUL;
(void)copy_option_part(&tnp->tn_np, buf, MAXPATHL - 1, " ,");
r_ptr = vim_findfile_stopdir(buf);
// move the filename one char forward and truncate the
// filepath with a NUL
filename = path_tail(buf);
STRMOVE(filename + 1, filename);
*filename++ = NUL;
tnp->tn_search_ctx = vim_findfile_init(buf, filename,
r_ptr, 100,
FALSE, // don't free visited list
FINDFILE_FILE, // we search for a file
tnp->tn_search_ctx, TRUE, curbuf->b_ffname);
if (tnp->tn_search_ctx != NULL) {
tnp->tn_did_filefind_init = TRUE;
}
}
}
STRCPY(buf, fname);
xfree(fname);
return OK;
}
/*
* Free the contents of a tagname_T that was filled by get_tagfname().
*/
void tagname_free(tagname_T *tnp)
{
xfree(tnp->tn_tags);
vim_findfile_cleanup(tnp->tn_search_ctx);
tnp->tn_search_ctx = NULL;
ga_clear_strings(&tag_fnames);
}
/// Parse one line from the tags file. Find start/end of tag name, start/end of
/// file name and start of search pattern.
///
/// If is_etag is TRUE, tagp->fname and tagp->fname_end are not set.
///
/// @param lbuf line to be parsed
///
/// @return FAIL if there is a format error in this line, OK otherwise.
static int parse_tag_line(char_u *lbuf, tagptrs_T *tagp)
{
char_u *p;
// Isolate the tagname, from lbuf up to the first white
tagp->tagname = lbuf;
p = vim_strchr(lbuf, TAB);
if (p == NULL) {
return FAIL;
}
tagp->tagname_end = p;
// Isolate file name, from first to second white space
if (*p != NUL) {
++p;
}
tagp->fname = p;
p = vim_strchr(p, TAB);
if (p == NULL) {
return FAIL;
}
tagp->fname_end = p;
// find start of search command, after second white space
if (*p != NUL) {
++p;
}
if (*p == NUL) {
return FAIL;
}
tagp->command = p;
return OK;
}
/*
* Check if tagname is a static tag
*
* Static tags produced by the older ctags program have the format:
* 'file:tag file /pattern'.
* This is only recognized when both occurrence of 'file' are the same, to
* avoid recognizing "string::string" or ":exit".
*
* Static tags produced by the new ctags program have the format:
* 'tag file /pattern/;"<Tab>file:' "
*
* Return TRUE if it is a static tag and adjust *tagname to the real tag.
* Return FALSE if it is not a static tag.
*/
static bool test_for_static(tagptrs_T *tagp)
{
char_u *p;
// Check for new style static tag ":...<Tab>file:[<Tab>...]"
p = tagp->command;
while ((p = vim_strchr(p, '\t')) != NULL) {
++p;
if (STRNCMP(p, "file:", 5) == 0) {
return TRUE;
}
}
return FALSE;
}
// Returns the length of a matching tag line.
static size_t matching_line_len(const char_u *const lbuf)
{
const char_u *p = lbuf + 1;
// does the same thing as parse_match()
p += STRLEN(p) + 1;
return (p - lbuf) + STRLEN(p);
}
/// Parse a line from a matching tag. Does not change the line itself.
///
/// The line that we get looks like this:
/// Emacs tag: <mtt><tag_fname><NUL><ebuf><NUL><lbuf>
/// other tag: <mtt><tag_fname><NUL><NUL><lbuf>
/// without Emacs tags: <mtt><tag_fname><NUL><lbuf>
///
/// @param lbuf input: matching line
/// @param tagp output: pointers into the line
///
/// @return OK or FAIL.
static int parse_match(char_u *lbuf, tagptrs_T *tagp)
{
int retval;
char_u *p;
char_u *pc, *pt;
tagp->tag_fname = lbuf + 1;
lbuf += STRLEN(tagp->tag_fname) + 2;
// Find search pattern and the file name for non-etags.
retval = parse_tag_line(lbuf,
tagp);
tagp->tagkind = NULL;
tagp->user_data = NULL;
tagp->tagline = 0;
tagp->command_end = NULL;
if (retval == OK) {
// Try to find a kind field: "kind:<kind>" or just "<kind>"
p = tagp->command;
if (find_extra(&p) == OK) {
tagp->command_end = p;
if (p > tagp->command && p[-1] == '|') {
tagp->command_end = p - 1; // drop trailing bar
}
p += 2; // skip ";\""
if (*p++ == TAB) {
// Accept ASCII alphabetic kind characters and any multi-byte
// character.
while (ASCII_ISALPHA(*p) || utfc_ptr2len(p) > 1) {
if (STRNCMP(p, "kind:", 5) == 0) {
tagp->tagkind = p + 5;
} else if (STRNCMP(p, "user_data:", 10) == 0) {
tagp->user_data = p + 10;
} else if (STRNCMP(p, "line:", 5) == 0) {
tagp->tagline = atoi((char *)p + 5);
}
if (tagp->tagkind != NULL && tagp->user_data != NULL) {
break;
}
pc = vim_strchr(p, ':');
pt = vim_strchr(p, '\t');
if (pc == NULL || (pt != NULL && pc > pt)) {
tagp->tagkind = p;
}
if (pt == NULL) {
break;
}
p = pt;
MB_PTR_ADV(p);
}
}
}
if (tagp->tagkind != NULL) {
for (p = tagp->tagkind;
*p && *p != '\t' && *p != '\r' && *p != '\n';
MB_PTR_ADV(p)) {
}
tagp->tagkind_end = p;
}
if (tagp->user_data != NULL) {
for (p = tagp->user_data;
*p && *p != '\t' && *p != '\r' && *p != '\n';
MB_PTR_ADV(p)) {
}
tagp->user_data_end = p;
}
}
return retval;
}
/*
* Find out the actual file name of a tag. Concatenate the tags file name
* with the matching tag file name.
* Returns an allocated string.
*/
static char_u *tag_full_fname(tagptrs_T *tagp)
{
int c = *tagp->fname_end;
*tagp->fname_end = NUL;
char_u *fullname = expand_tag_fname(tagp->fname, tagp->tag_fname, false);
*tagp->fname_end = c;
return fullname;
}
/// Jump to a tag that has been found in one of the tag files
///
/// @param lbuf_arg line from the tags file for this tag
/// @param forceit :ta with !
/// @param keep_help keep help flag (FALSE for cscope)
///
/// @return OK for success, NOTAGFILE when file not found, FAIL otherwise.
static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
{
int save_magic;
bool save_p_ws;
int save_p_scs, save_p_ic;
linenr_T save_lnum;
char_u *str;
char_u *pbuf; // search pattern buffer
char_u *pbuf_end;
char_u *tofree_fname = NULL;
char_u *fname;
tagptrs_T tagp;
int retval = FAIL;
int getfile_result = GETFILE_UNUSED;
int search_options;
win_T *curwin_save = NULL;
char_u *full_fname = NULL;
const bool old_KeyTyped = KeyTyped; // getting the file may reset it
const int l_g_do_tagpreview = g_do_tagpreview;
const size_t len = matching_line_len(lbuf_arg) + 1;
char_u *lbuf = xmalloc(len);
memmove(lbuf, lbuf_arg, len);
pbuf = xmalloc(LSIZE);
// parse the match line into the tagp structure
if (parse_match(lbuf, &tagp) == FAIL) {
tagp.fname_end = NULL;
goto erret;
}
// truncate the file name, so it can be used as a string
*tagp.fname_end = NUL;
fname = tagp.fname;
// copy the command to pbuf[], remove trailing CR/NL
str = tagp.command;
for (pbuf_end = pbuf; *str && *str != '\n' && *str != '\r'; ) {
*pbuf_end++ = *str++;
if (pbuf_end - pbuf + 1 >= LSIZE) {
break;
}
}
*pbuf_end = NUL;
{
/*
* Remove the "<Tab>fieldname:value" stuff; we don't need it here.
*/
str = pbuf;
if (find_extra(&str) == OK) {
pbuf_end = str;
*pbuf_end = NUL;
}
}
/*
* Expand file name, when needed (for environment variables).
* If 'tagrelative' option set, may change file name.
*/
fname = expand_tag_fname(fname, tagp.tag_fname, true);
tofree_fname = fname; // free() it later
/*
* Check if the file with the tag exists before abandoning the current
* file. Also accept a file name for which there is a matching BufReadCmd
* autocommand event (e.g., http://sys/file).
*/
if (!os_path_exists(fname)
&& !has_autocmd(EVENT_BUFREADCMD, fname,
NULL)) {
retval = NOTAGFILE;
xfree(nofile_fname);
nofile_fname = vim_strsave(fname);
goto erret;
}
++RedrawingDisabled;
if (l_g_do_tagpreview != 0) {
postponed_split = 0; // don't split again below
curwin_save = curwin; // Save current window
/*
* If we are reusing a window, we may change dir when
* entering it (autocommands) so turn the tag filename
* into a fullpath
*/
if (!curwin->w_p_pvw) {
full_fname = (char_u *)FullName_save((char *)fname, FALSE);
fname = full_fname;
/*
* Make the preview window the current window.
* Open a preview window when needed.
*/
prepare_tagpreview(true);
}
}
// If it was a CTRL-W CTRL-] command split window now. For ":tab tag"
// open a new tab page.
if (postponed_split && (swb_flags & (SWB_USEOPEN | SWB_USETAB))) {
buf_T *const existing_buf = buflist_findname_exp(fname);
if (existing_buf != NULL) {
const win_T *wp = NULL;
if (swb_flags & SWB_USEOPEN) {
wp = buf_jump_open_win(existing_buf);
}
// If 'switchbuf' contains "usetab": jump to first window in any tab
// page containing "existing_buf" if one exists
if (wp == NULL && (swb_flags & SWB_USETAB)) {
wp = buf_jump_open_tab(existing_buf);
}
// We've switched to the buffer, the usual loading of the file must
// be skipped.
if (wp != NULL) {
getfile_result = GETFILE_SAME_FILE;
}
}
}
if (getfile_result == GETFILE_UNUSED
&& (postponed_split || cmdmod.tab != 0)) {
if (win_split(postponed_split > 0 ? postponed_split : 0,
postponed_split_flags) == FAIL) {
RedrawingDisabled--;
goto erret;
}
RESET_BINDING(curwin);
}
if (keep_help) {
// A :ta from a help file will keep the b_help flag set. For ":ptag"
// we need to use the flag from the window where we came from.
if (l_g_do_tagpreview != 0) {
keep_help_flag = curwin_save->w_buffer->b_help;
} else {
keep_help_flag = curbuf->b_help;
}
}
if (getfile_result == GETFILE_UNUSED) {
// Careful: getfile() may trigger autocommands and call jumpto_tag()
// recursively.
getfile_result = getfile(0, fname, NULL, true, (linenr_T)0, forceit);
}
keep_help_flag = false;
if (GETFILE_SUCCESS(getfile_result)) { // got to the right file
curwin->w_set_curswant = true;
postponed_split = 0;
save_magic = p_magic;
p_magic = false; // always execute with 'nomagic'
// Save value of no_hlsearch, jumping to a tag is not a real search
const bool save_no_hlsearch = no_hlsearch;
/*
* If 'cpoptions' contains 't', store the search pattern for the "n"
* command. If 'cpoptions' does not contain 't', the search pattern
* is not stored.
*/
if (vim_strchr(p_cpo, CPO_TAGPAT) != NULL) {
search_options = 0;
} else {
search_options = SEARCH_KEEP;
}
/*
* If the command is a search, try here.
*
* Reset 'smartcase' for the search, since the search pattern was not
* typed by the user.
* Only use do_search() when there is a full search command, without
* anything following.
*/
str = pbuf;
if (pbuf[0] == '/' || pbuf[0] == '?') {
str = skip_regexp(pbuf + 1, pbuf[0], FALSE, NULL) + 1;
}
if (str > pbuf_end - 1) { // search command with nothing following
save_p_ws = p_ws;
save_p_ic = p_ic;
save_p_scs = p_scs;
p_ws = true; // need 'wrapscan' for backward searches
p_ic = FALSE; // don't ignore case now
p_scs = FALSE;
save_lnum = curwin->w_cursor.lnum;
if (tagp.tagline > 0) {
// start search before line from "line:" field
curwin->w_cursor.lnum = tagp.tagline - 1;
} else {
// start search before first line
curwin->w_cursor.lnum = 0;
}
if (do_search(NULL, pbuf[0], pbuf[0], pbuf + 1, (long)1,
search_options, NULL)) {
retval = OK;
} else {
int found = 1;
int cc;
/*
* try again, ignore case now
*/
p_ic = true;
if (!do_search(NULL, pbuf[0], pbuf[0], pbuf + 1, (long)1,
search_options, NULL)) {
// Failed to find pattern, take a guess: "^func ("
found = 2;
(void)test_for_static(&tagp);
cc = *tagp.tagname_end;
*tagp.tagname_end = NUL;
snprintf((char *)pbuf, LSIZE, "^%s\\s\\*(", tagp.tagname);
if (!do_search(NULL, '/', '/', pbuf, (long)1, search_options, NULL)) {
// Guess again: "^char * \<func ("
snprintf((char *)pbuf, LSIZE, "^\\[#a-zA-Z_]\\.\\*\\<%s\\s\\*(",
tagp.tagname);
if (!do_search(NULL, '/', '/', pbuf, (long)1,
search_options, NULL)) {
found = 0;
}
}
*tagp.tagname_end = cc;
}
if (found == 0) {
EMSG(_("E434: Can't find tag pattern"));
curwin->w_cursor.lnum = save_lnum;
} else {
/*
* Only give a message when really guessed, not when 'ic'
* is set and match found while ignoring case.
*/
if (found == 2 || !save_p_ic) {
MSG(_("E435: Couldn't find tag, just guessing!"));
if (!msg_scrolled && msg_silent == 0) {
ui_flush();
os_delay(1010L, true);
}
}
retval = OK;
}
}
p_ws = save_p_ws;
p_ic = save_p_ic; // -V519
p_scs = save_p_scs;
// A search command may have positioned the cursor beyond the end
// of the line. May need to correct that here.
check_cursor();
} else {
const int save_secure = secure;
// Setup the sandbox for executing the command from the tags file.
secure = 1;
sandbox++;
curwin->w_cursor.lnum = 1; // start command in line 1
do_cmdline_cmd((char *)pbuf);
retval = OK;
// When the command has done something that is not allowed make sure
// the error message can be seen.
if (secure == 2) {
wait_return(true);
}
secure = save_secure;
sandbox--;
}
p_magic = save_magic;
// restore no_hlsearch when keeping the old search pattern
if (search_options) {
set_no_hlsearch(save_no_hlsearch);
}
// Return OK if jumped to another file (at least we found the file!).
if (getfile_result == GETFILE_OPEN_OTHER) {
retval = OK;
}
if (retval == OK) {
/*
* For a help buffer: Put the cursor line at the top of the window,
* the help subject will be below it.
*/
if (curbuf->b_help) {
set_topline(curwin, curwin->w_cursor.lnum);
}
if ((fdo_flags & FDO_TAG) && old_KeyTyped) {
foldOpenCursor();
}
}
if (l_g_do_tagpreview != 0
&& curwin != curwin_save && win_valid(curwin_save)) {
// Return cursor to where we were
validate_cursor();
redraw_later(curwin, VALID);
win_enter(curwin_save, true);
}
RedrawingDisabled--;
} else {
RedrawingDisabled--;
if (postponed_split) { // close the window
win_close(curwin, false);
postponed_split = 0;
}
}
erret:
g_do_tagpreview = 0; // For next time
xfree(lbuf);
xfree(pbuf);
xfree(tofree_fname);
xfree(full_fname);
return retval;
}
// If "expand" is true, expand wildcards in fname.
// If 'tagrelative' option set, change fname (name of file containing tag)
// according to tag_fname (name of tag file containing fname).
// Returns a pointer to allocated memory.
static char_u *expand_tag_fname(char_u *fname, char_u *const tag_fname, const bool expand)
{
char_u *p;
char_u *expanded_fname = NULL;
expand_T xpc;
/*
* Expand file name (for environment variables) when needed.
*/
if (expand && path_has_wildcard(fname)) {
ExpandInit(&xpc);
xpc.xp_context = EXPAND_FILES;
expanded_fname = ExpandOne(&xpc, fname, NULL,
WILD_LIST_NOTFOUND|WILD_SILENT, WILD_EXPAND_FREE);
if (expanded_fname != NULL) {
fname = expanded_fname;
}
}
char_u *retval;
if ((p_tr || curbuf->b_help)
&& !vim_isAbsName(fname)
&& (p = path_tail(tag_fname)) != tag_fname) {
retval = xmalloc(MAXPATHL);
STRCPY(retval, tag_fname);
STRLCPY(retval + (p - tag_fname), fname,
MAXPATHL - (p - tag_fname));
/*
* Translate names like "src/a/../b/file.c" into "src/b/file.c".
*/
simplify_filename(retval);
} else {
retval = vim_strsave(fname);
}
xfree(expanded_fname);
return retval;
}
/*
* Check if we have a tag for the buffer with name "buf_ffname".
* This is a bit slow, because of the full path compare in path_full_compare().
* Return TRUE if tag for file "fname" if tag file "tag_fname" is for current
* file.
*/
static int test_for_current(char_u *fname, char_u *fname_end, char_u *tag_fname, char_u *buf_ffname)
{
int c;
int retval = FALSE;
char_u *fullname;
if (buf_ffname != NULL) { // if the buffer has a name
{
c = *fname_end;
*fname_end = NUL;
}
fullname = expand_tag_fname(fname, tag_fname, true);
retval = (path_full_compare(fullname, buf_ffname, true, true)
& kEqualFiles);
xfree(fullname);
*fname_end = c;
}
return retval;
}
/*
* Find the end of the tagaddress.
* Return OK if ";\"" is following, FAIL otherwise.
*/
static int find_extra(char_u **pp)
{
char_u *str = *pp;
char_u first_char = **pp;
// Repeat for addresses separated with ';'
for (;; ) {
if (ascii_isdigit(*str)) {
str = skipdigits(str + 1);
} else if (*str == '/' || *str == '?') {
str = skip_regexp(str + 1, *str, false, NULL);
if (*str != first_char) {
str = NULL;
} else {
str++;
}
} else {
// not a line number or search string, look for terminator.
str = (char_u *)strstr((char *)str, "|;\"");
if (str != NULL) {
str++;
break;
}
}
if (str == NULL || *str != ';'
|| !(ascii_isdigit(str[1]) || str[1] == '/' || str[1] == '?')) {
break;
}
str++; // skip ';'
first_char = *str;
}
if (str != NULL && STRNCMP(str, ";\"", 2) == 0) {
*pp = str;
return OK;
}
return FAIL;
}
//
// Free a single entry in a tag stack
//
static void tagstack_clear_entry(taggy_T *item)
{
XFREE_CLEAR(item->tagname);
XFREE_CLEAR(item->user_data);
}
/// @param tagnames expand tag names
int expand_tags(int tagnames, char_u *pat, int *num_file, char_u ***file)
{
int i;
int extra_flag;
char_u *name_buf;
size_t name_buf_size = 100;
tagptrs_T t_p;
int ret;
name_buf = xmalloc(name_buf_size);
if (tagnames) {
extra_flag = TAG_NAMES;
} else {
extra_flag = 0;
}
if (pat[0] == '/') {
ret = find_tags(pat + 1, num_file, file,
TAG_REGEXP | extra_flag | TAG_VERBOSE | TAG_NO_TAGFUNC,
TAG_MANY, curbuf->b_ffname);
} else {
ret = find_tags(pat, num_file, file,
TAG_REGEXP | extra_flag | TAG_VERBOSE | TAG_NO_TAGFUNC | TAG_NOIC,
TAG_MANY, curbuf->b_ffname);
}
if (ret == OK && !tagnames) {
// Reorganize the tags for display and matching as strings of:
// "<tagname>\0<kind>\0<filename>\0"
for (i = 0; i < *num_file; i++) {
size_t len;
parse_match((*file)[i], &t_p);
len = t_p.tagname_end - t_p.tagname;
if (len > name_buf_size - 3) {
char_u *buf;
name_buf_size = len + 3;
buf = xrealloc(name_buf, name_buf_size);
name_buf = buf;
}
memmove(name_buf, t_p.tagname, len);
name_buf[len++] = 0;
name_buf[len++] = (t_p.tagkind != NULL && *t_p.tagkind)
? *t_p.tagkind : 'f';
name_buf[len++] = 0;
memmove((*file)[i] + len, t_p.fname, t_p.fname_end - t_p.fname);
(*file)[i][len + (t_p.fname_end - t_p.fname)] = 0;
memmove((*file)[i], name_buf, len);
}
}
xfree(name_buf);
return ret;
}
/// Add a tag field to the dictionary "dict".
/// Return OK or FAIL.
///
/// @param start start of the value
/// @param end after the value; can be NULL
static int add_tag_field(dict_T *dict, const char *field_name, const char_u *start,
const char_u *end)
FUNC_ATTR_NONNULL_ARG(1, 2)
{
int len = 0;
int retval;
// Check that the field name doesn't exist yet.
if (tv_dict_find(dict, field_name, -1) != NULL) {
if (p_verbose > 0) {
verbose_enter();
smsg(_("Duplicate field name: %s"), field_name);
verbose_leave();
}
return FAIL;
}
char_u *buf = xmalloc(MAXPATHL);
if (start != NULL) {
if (end == NULL) {
end = start + STRLEN(start);
while (end > start && (end[-1] == '\r' || end[-1] == '\n')) {
--end;
}
}
len = (int)(end - start);
if (len > MAXPATHL - 1) {
len = MAXPATHL - 1;
}
STRLCPY(buf, start, len + 1);
}
buf[len] = NUL;
retval = tv_dict_add_str(dict, field_name, STRLEN(field_name),
(const char *)buf);
xfree(buf);
return retval;
}
/// Add the tags matching the specified pattern "pat" to the list "list"
/// as a dictionary. Use "buf_fname" for priority, unless NULL.
int get_tags(list_T *list, char_u *pat, char_u *buf_fname)
{
int num_matches, i, ret;
char_u **matches;
char_u *full_fname;
dict_T *dict;
tagptrs_T tp;
bool is_static;
ret = find_tags(pat, &num_matches, &matches,
TAG_REGEXP | TAG_NOIC, MAXCOL, buf_fname);
if (ret == OK && num_matches > 0) {
for (i = 0; i < num_matches; ++i) {
int parse_result = parse_match(matches[i], &tp);
// Avoid an unused variable warning in release builds.
(void)parse_result;
assert(parse_result == OK);
is_static = test_for_static(&tp);
// Skip pseudo-tag lines.
if (STRNCMP(tp.tagname, "!_TAG_", 6) == 0) {
xfree(matches[i]);
continue;
}
dict = tv_dict_alloc();
tv_list_append_dict(list, dict);
full_fname = tag_full_fname(&tp);
if (add_tag_field(dict, "name", tp.tagname, tp.tagname_end) == FAIL
|| add_tag_field(dict, "filename", full_fname, NULL) == FAIL
|| add_tag_field(dict, "cmd", tp.command, tp.command_end) == FAIL
|| add_tag_field(dict, "kind", tp.tagkind,
tp.tagkind ? tp.tagkind_end : NULL) == FAIL
|| tv_dict_add_nr(dict, S_LEN("static"), is_static) == FAIL) {
ret = FAIL;
}
xfree(full_fname);
if (tp.command_end != NULL) {
for (char_u *p = tp.command_end + 3;
*p != NUL && *p != '\n' && *p != '\r';
MB_PTR_ADV(p)) {
if (p == tp.tagkind
|| (p + 5 == tp.tagkind && STRNCMP(p, "kind:", 5) == 0)) {
// skip "kind:<kind>" and "<kind>"
p = tp.tagkind_end - 1;
} else if (STRNCMP(p, "file:", 5) == 0) {
// skip "file:" (static tag)
p += 4;
} else if (!ascii_iswhite(*p)) {
char_u *s, *n;
int len;
// Add extra field as a dict entry. Fields are
// separated by Tabs.
n = p;
while (*p != NUL && *p >= ' ' && *p < 127 && *p != ':') {
++p;
}
len = (int)(p - n);
if (*p == ':' && len > 0) {
s = ++p;
while (*p != NUL && *p >= ' ') {
++p;
}
n[len] = NUL;
if (add_tag_field(dict, (char *)n, s, p) == FAIL) {
ret = FAIL;
}
n[len] = ':';
} else {
// Skip field without colon.
while (*p != NUL && *p >= ' ') {
++p;
}
}
if (*p == NUL) {
break;
}
}
}
}
xfree(matches[i]);
}
xfree(matches);
}
return ret;
}
// Return information about 'tag' in dict 'retdict'.
static void get_tag_details(taggy_T *tag, dict_T *retdict)
{
list_T *pos;
fmark_T *fmark;
tv_dict_add_str(retdict, S_LEN("tagname"), (const char *)tag->tagname);
tv_dict_add_nr(retdict, S_LEN("matchnr"), tag->cur_match + 1);
tv_dict_add_nr(retdict, S_LEN("bufnr"), tag->cur_fnum);
if (tag->user_data) {
tv_dict_add_str(retdict, S_LEN("user_data"), (const char *)tag->user_data);
}
pos = tv_list_alloc(4);
tv_dict_add_list(retdict, S_LEN("from"), pos);
fmark = &tag->fmark;
tv_list_append_number(pos,
(varnumber_T)(fmark->fnum != -1 ? fmark->fnum : 0));
tv_list_append_number(pos, (varnumber_T)fmark->mark.lnum);
tv_list_append_number(pos, (varnumber_T)(fmark->mark.col == MAXCOL
? MAXCOL : fmark->mark.col + 1));
tv_list_append_number(pos, (varnumber_T)fmark->mark.coladd);
}
// Return the tag stack entries of the specified window 'wp' in dictionary
// 'retdict'.
void get_tagstack(win_T *wp, dict_T *retdict)
{
list_T *l;
int i;
dict_T *d;
tv_dict_add_nr(retdict, S_LEN("length"), wp->w_tagstacklen);
tv_dict_add_nr(retdict, S_LEN("curidx"), wp->w_tagstackidx + 1);
l = tv_list_alloc(2);
tv_dict_add_list(retdict, S_LEN("items"), l);
for (i = 0; i < wp->w_tagstacklen; i++) {
d = tv_dict_alloc();
tv_list_append_dict(l, d);
get_tag_details(&wp->w_tagstack[i], d);
}
}
// Free all the entries in the tag stack of the specified window
static void tagstack_clear(win_T *wp)
{
// Free the current tag stack
for (int i = 0; i < wp->w_tagstacklen; i++) {
tagstack_clear_entry(&wp->w_tagstack[i]);
}
wp->w_tagstacklen = 0;
wp->w_tagstackidx = 0;
}
// Remove the oldest entry from the tag stack and shift the rest of
// the entries to free up the top of the stack.
static void tagstack_shift(win_T *wp)
{
taggy_T *tagstack = wp->w_tagstack;
tagstack_clear_entry(&tagstack[0]);
for (int i = 1; i < wp->w_tagstacklen; i++) {
tagstack[i - 1] = tagstack[i];
}
wp->w_tagstacklen--;
}
// Push a new item to the tag stack
static void tagstack_push_item(win_T *wp, char_u *tagname, int cur_fnum, int cur_match, pos_T mark,
int fnum, char_u *user_data)
{
taggy_T *tagstack = wp->w_tagstack;
int idx = wp->w_tagstacklen; // top of the stack
// if the tagstack is full: remove the oldest entry
if (idx >= TAGSTACKSIZE) {
tagstack_shift(wp);
idx = TAGSTACKSIZE - 1;
}
wp->w_tagstacklen++;
tagstack[idx].tagname = tagname;
tagstack[idx].cur_fnum = cur_fnum;
tagstack[idx].cur_match = cur_match;
if (tagstack[idx].cur_match < 0) {
tagstack[idx].cur_match = 0;
}
tagstack[idx].fmark.mark = mark;
tagstack[idx].fmark.fnum = fnum;
tagstack[idx].user_data = user_data;
}
// Add a list of items to the tag stack in the specified window
static void tagstack_push_items(win_T *wp, list_T *l)
{
listitem_T *li;
dictitem_T *di;
dict_T *itemdict;
char_u *tagname;
pos_T mark;
int fnum;
// Add one entry at a time to the tag stack
for (li = tv_list_first(l); li != NULL; li = TV_LIST_ITEM_NEXT(l, li)) {
if (TV_LIST_ITEM_TV(li)->v_type != VAR_DICT
|| TV_LIST_ITEM_TV(li)->vval.v_dict == NULL) {
continue; // Skip non-dict items
}
itemdict = TV_LIST_ITEM_TV(li)->vval.v_dict;
// parse 'from' for the cursor position before the tag jump
if ((di = tv_dict_find(itemdict, "from", -1)) == NULL) {
continue;
}
if (list2fpos(&di->di_tv, &mark, &fnum, NULL) != OK) {
continue;
}
if ((tagname = (char_u *)tv_dict_get_string(itemdict, "tagname", true))
== NULL) {
continue;
}
if (mark.col > 0) {
mark.col--;
}
tagstack_push_item(wp,
tagname,
(int)tv_dict_get_number(itemdict, "bufnr"),
(int)tv_dict_get_number(itemdict, "matchnr") - 1,
mark, fnum,
(char_u *)tv_dict_get_string(itemdict, "user_data", true));
}
}
// Set the current index in the tag stack. Valid values are between 0
// and the stack length (inclusive).
static void tagstack_set_curidx(win_T *wp, int curidx)
{
wp->w_tagstackidx = curidx;
if (wp->w_tagstackidx < 0) { // sanity check
wp->w_tagstackidx = 0;
}
if (wp->w_tagstackidx > wp->w_tagstacklen) {
wp->w_tagstackidx = wp->w_tagstacklen;
}
}
// Set the tag stack entries of the specified window.
// 'action' is set to one of:
// 'a' for append
// 'r' for replace
// 't' for truncate
int set_tagstack(win_T *wp, const dict_T *d, int action)
FUNC_ATTR_NONNULL_ARG(1)
{
dictitem_T *di;
list_T *l = NULL;
// not allowed to alter the tag stack entries from inside tagfunc
if (tfu_in_use) {
EMSG(_(recurmsg));
return FAIL;
}
if ((di = tv_dict_find(d, "items", -1)) != NULL) {
if (di->di_tv.v_type != VAR_LIST) {
EMSG(_(e_listreq));
return FAIL;
}
l = di->di_tv.vval.v_list;
}
if ((di = tv_dict_find(d, "curidx", -1)) != NULL) {
tagstack_set_curidx(wp, (int)tv_get_number(&di->di_tv) - 1);
}
if (action == 't') { // truncate the stack
taggy_T *const tagstack = wp->w_tagstack;
const int tagstackidx = wp->w_tagstackidx;
int tagstacklen = wp->w_tagstacklen;
// delete all the tag stack entries above the current entry
while (tagstackidx < tagstacklen) {
tagstack_clear_entry(&tagstack[--tagstacklen]);
}
wp->w_tagstacklen = tagstacklen;
}
if (l != NULL) {
if (action == 'r') { // replace the stack
tagstack_clear(wp);
}
tagstack_push_items(wp, l);
// set the current index after the last entry
wp->w_tagstackidx = wp->w_tagstacklen;
}
return OK;
}
|
749945.c | /* Configuration file parsing and CONFIG GET/SET commands implementation.
*
* Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "server.h"
#include "cluster.h"
#include <fcntl.h>
#include <sys/stat.h>
/*-----------------------------------------------------------------------------
* Config file name-value maps.
*----------------------------------------------------------------------------*/
typedef struct configEnum {
const char *name;
const int val;
} configEnum;
configEnum maxmemory_policy_enum[] = {
{"volatile-lru", MAXMEMORY_VOLATILE_LRU},
{"volatile-lfu", MAXMEMORY_VOLATILE_LFU},
{"volatile-random",MAXMEMORY_VOLATILE_RANDOM},
{"volatile-ttl",MAXMEMORY_VOLATILE_TTL},
{"allkeys-lru",MAXMEMORY_ALLKEYS_LRU},
{"allkeys-lfu",MAXMEMORY_ALLKEYS_LFU},
{"allkeys-random",MAXMEMORY_ALLKEYS_RANDOM},
{"noeviction",MAXMEMORY_NO_EVICTION},
{NULL, 0}
};
configEnum syslog_facility_enum[] = {
{"user", LOG_USER},
{"local0", LOG_LOCAL0},
{"local1", LOG_LOCAL1},
{"local2", LOG_LOCAL2},
{"local3", LOG_LOCAL3},
{"local4", LOG_LOCAL4},
{"local5", LOG_LOCAL5},
{"local6", LOG_LOCAL6},
{"local7", LOG_LOCAL7},
{NULL, 0}
};
configEnum loglevel_enum[] = {
{"debug", LL_DEBUG},
{"verbose", LL_VERBOSE},
{"notice", LL_NOTICE},
{"warning", LL_WARNING},
{NULL,0}
};
configEnum supervised_mode_enum[] = {
{"upstart", SUPERVISED_UPSTART},
{"systemd", SUPERVISED_SYSTEMD},
{"auto", SUPERVISED_AUTODETECT},
{"no", SUPERVISED_NONE},
{NULL, 0}
};
configEnum aof_fsync_enum[] = {
{"everysec", AOF_FSYNC_EVERYSEC},
{"always", AOF_FSYNC_ALWAYS},
{"no", AOF_FSYNC_NO},
{NULL, 0}
};
/* Output buffer limits presets. */
clientBufferLimitsConfig clientBufferLimitsDefaults[CLIENT_TYPE_OBUF_COUNT] = {
{0, 0, 0}, /* normal */
{1024*1024*256, 1024*1024*64, 60}, /* slave */
{1024*1024*32, 1024*1024*8, 60} /* pubsub */
};
/*-----------------------------------------------------------------------------
* Enum access functions
*----------------------------------------------------------------------------*/
/* Get enum value from name. If there is no match INT_MIN is returned. */
int configEnumGetValue(configEnum *ce, char *name) {
while(ce->name != NULL) {
if (!strcasecmp(ce->name,name)) return ce->val;
ce++;
}
return INT_MIN;
}
/* Get enum name from value. If no match is found NULL is returned. */
const char *configEnumGetName(configEnum *ce, int val) {
while(ce->name != NULL) {
if (ce->val == val) return ce->name;
ce++;
}
return NULL;
}
/* Wrapper for configEnumGetName() returning "unknown" instead of NULL if
* there is no match. */
const char *configEnumGetNameOrUnknown(configEnum *ce, int val) {
const char *name = configEnumGetName(ce,val);
return name ? name : "unknown";
}
/* Used for INFO generation. */
const char *evictPolicyToString(void) {
return configEnumGetNameOrUnknown(maxmemory_policy_enum,server.maxmemory_policy);
}
/*-----------------------------------------------------------------------------
* Config file parsing
*----------------------------------------------------------------------------*/
int yesnotoi(char *s) {
if (!strcasecmp(s,"yes")) return 1;
else if (!strcasecmp(s,"no")) return 0;
else return -1;
}
void appendServerSaveParams(time_t seconds, int changes) {
server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
server.saveparams[server.saveparamslen].seconds = seconds;
server.saveparams[server.saveparamslen].changes = changes;
server.saveparamslen++;
}
void resetServerSaveParams(void) {
zfree(server.saveparams);
server.saveparams = NULL;
server.saveparamslen = 0;
}
void queueLoadModule(sds path, sds *argv, int argc) {
int i;
struct moduleLoadQueueEntry *loadmod;
loadmod = zmalloc(sizeof(struct moduleLoadQueueEntry));
loadmod->argv = zmalloc(sizeof(robj*)*argc);
loadmod->path = sdsnew(path);
loadmod->argc = argc;
for (i = 0; i < argc; i++) {
loadmod->argv[i] = createRawStringObject(argv[i],sdslen(argv[i]));
}
listAddNodeTail(server.loadmodule_queue,loadmod);
}
void loadServerConfigFromString(char *config) {
char *err = NULL;
int linenum = 0, totlines, i;
int slaveof_linenum = 0;
sds *lines;
lines = sdssplitlen(config,strlen(config),"\n",1,&totlines);
for (i = 0; i < totlines; i++) {
sds *argv;
int argc;
linenum = i+1;
lines[i] = sdstrim(lines[i]," \t\r\n");
/* Skip comments and blank lines */
if (lines[i][0] == '#' || lines[i][0] == '\0') continue;
/* Split into arguments */
argv = sdssplitargs(lines[i],&argc);
if (argv == NULL) {
err = "Unbalanced quotes in configuration line";
goto loaderr;
}
/* Skip this line if the resulting command vector is empty. */
if (argc == 0) {
sdsfreesplitres(argv,argc);
continue;
}
sdstolower(argv[0]);
/* Execute config directives */
if (!strcasecmp(argv[0],"timeout") && argc == 2) {
server.maxidletime = atoi(argv[1]);
if (server.maxidletime < 0) {
err = "Invalid timeout value"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"tcp-keepalive") && argc == 2) {
server.tcpkeepalive = atoi(argv[1]);
if (server.tcpkeepalive < 0) {
err = "Invalid tcp-keepalive value"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"protected-mode") && argc == 2) {
if ((server.protected_mode = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"port") && argc == 2) {
server.port = atoi(argv[1]);
if (server.port < 0 || server.port > 65535) {
err = "Invalid port"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"tcp-backlog") && argc == 2) {
server.tcp_backlog = atoi(argv[1]);
if (server.tcp_backlog < 0) {
err = "Invalid backlog value"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"bind") && argc >= 2) {
int j, addresses = argc-1;
if (addresses > CONFIG_BINDADDR_MAX) {
err = "Too many bind addresses specified"; goto loaderr;
}
for (j = 0; j < addresses; j++)
server.bindaddr[j] = zstrdup(argv[j+1]);
server.bindaddr_count = addresses;
} else if (!strcasecmp(argv[0],"unixsocket") && argc == 2) {
server.unixsocket = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"unixsocketperm") && argc == 2) {
errno = 0;
server.unixsocketperm = (mode_t)strtol(argv[1], NULL, 8);
if (errno || server.unixsocketperm > 0777) {
err = "Invalid socket file permissions"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"save")) {
if (argc == 3) {
int seconds = atoi(argv[1]);
int changes = atoi(argv[2]);
if (seconds < 1 || changes < 0) {
err = "Invalid save parameters"; goto loaderr;
}
appendServerSaveParams(seconds,changes);
} else if (argc == 2 && !strcasecmp(argv[1],"")) {
resetServerSaveParams();
}
} else if (!strcasecmp(argv[0],"dir") && argc == 2) {
if (chdir(argv[1]) == -1) {
serverLog(LL_WARNING,"Can't chdir to '%s': %s",
argv[1], strerror(errno));
exit(1);
}
} else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
server.verbosity = configEnumGetValue(loglevel_enum,argv[1]);
if (server.verbosity == INT_MIN) {
err = "Invalid log level. "
"Must be one of debug, verbose, notice, warning";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
FILE *logfp;
zfree(server.logfile);
server.logfile = zstrdup(argv[1]);
if (server.logfile[0] != '\0') {
/* Test if we are able to open the file. The server will not
* be able to abort just for this problem later... */
logfp = fopen(server.logfile,"a");
if (logfp == NULL) {
err = sdscatprintf(sdsempty(),
"Can't open the log file: %s", strerror(errno));
goto loaderr;
}
fclose(logfp);
}
} else if (!strcasecmp(argv[0],"aclfile") && argc == 2) {
zfree(server.acl_filename);
server.acl_filename = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"always-show-logo") && argc == 2) {
if ((server.always_show_logo = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"syslog-enabled") && argc == 2) {
if ((server.syslog_enabled = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"syslog-ident") && argc == 2) {
if (server.syslog_ident) zfree(server.syslog_ident);
server.syslog_ident = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"syslog-facility") && argc == 2) {
server.syslog_facility =
configEnumGetValue(syslog_facility_enum,argv[1]);
if (server.syslog_facility == INT_MIN) {
err = "Invalid log facility. Must be one of USER or between LOCAL0-LOCAL7";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"databases") && argc == 2) {
server.dbnum = atoi(argv[1]);
if (server.dbnum < 1) {
err = "Invalid number of databases"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"include") && argc == 2) {
loadServerConfig(argv[1],NULL);
} else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
server.maxclients = atoi(argv[1]);
if (server.maxclients < 1) {
err = "Invalid max clients limit"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
server.maxmemory = memtoll(argv[1],NULL);
} else if (!strcasecmp(argv[0],"maxmemory-policy") && argc == 2) {
server.maxmemory_policy =
configEnumGetValue(maxmemory_policy_enum,argv[1]);
if (server.maxmemory_policy == INT_MIN) {
err = "Invalid maxmemory policy";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"maxmemory-samples") && argc == 2) {
server.maxmemory_samples = atoi(argv[1]);
if (server.maxmemory_samples <= 0) {
err = "maxmemory-samples must be 1 or greater";
goto loaderr;
}
} else if ((!strcasecmp(argv[0],"proto-max-bulk-len")) && argc == 2) {
server.proto_max_bulk_len = memtoll(argv[1],NULL);
} else if ((!strcasecmp(argv[0],"client-query-buffer-limit")) && argc == 2) {
server.client_max_querybuf_len = memtoll(argv[1],NULL);
} else if (!strcasecmp(argv[0],"lfu-log-factor") && argc == 2) {
server.lfu_log_factor = atoi(argv[1]);
if (server.lfu_log_factor < 0) {
err = "lfu-log-factor must be 0 or greater";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"lfu-decay-time") && argc == 2) {
server.lfu_decay_time = atoi(argv[1]);
if (server.lfu_decay_time < 0) {
err = "lfu-decay-time must be 0 or greater";
goto loaderr;
}
} else if ((!strcasecmp(argv[0],"slaveof") ||
!strcasecmp(argv[0],"replicaof")) && argc == 3) {
slaveof_linenum = linenum;
server.masterhost = sdsnew(argv[1]);
server.masterport = atoi(argv[2]);
server.repl_state = REPL_STATE_CONNECT;
} else if ((!strcasecmp(argv[0],"repl-ping-slave-period") ||
!strcasecmp(argv[0],"repl-ping-replica-period")) &&
argc == 2)
{
server.repl_ping_slave_period = atoi(argv[1]);
if (server.repl_ping_slave_period <= 0) {
err = "repl-ping-replica-period must be 1 or greater";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"repl-timeout") && argc == 2) {
server.repl_timeout = atoi(argv[1]);
if (server.repl_timeout <= 0) {
err = "repl-timeout must be 1 or greater";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"repl-disable-tcp-nodelay") && argc==2) {
if ((server.repl_disable_tcp_nodelay = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"repl-diskless-sync") && argc==2) {
if ((server.repl_diskless_sync = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"repl-diskless-sync-delay") && argc==2) {
server.repl_diskless_sync_delay = atoi(argv[1]);
if (server.repl_diskless_sync_delay < 0) {
err = "repl-diskless-sync-delay can't be negative";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"repl-backlog-size") && argc == 2) {
long long size = memtoll(argv[1],NULL);
if (size <= 0) {
err = "repl-backlog-size must be 1 or greater.";
goto loaderr;
}
resizeReplicationBacklog(size);
} else if (!strcasecmp(argv[0],"repl-backlog-ttl") && argc == 2) {
server.repl_backlog_time_limit = atoi(argv[1]);
if (server.repl_backlog_time_limit < 0) {
err = "repl-backlog-ttl can't be negative ";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"masteruser") && argc == 2) {
zfree(server.masteruser);
server.masteruser = argv[1][0] ? zstrdup(argv[1]) : NULL;
} else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
zfree(server.masterauth);
server.masterauth = argv[1][0] ? zstrdup(argv[1]) : NULL;
} else if ((!strcasecmp(argv[0],"slave-serve-stale-data") ||
!strcasecmp(argv[0],"replica-serve-stale-data"))
&& argc == 2)
{
if ((server.repl_serve_stale_data = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if ((!strcasecmp(argv[0],"slave-read-only") ||
!strcasecmp(argv[0],"replica-read-only"))
&& argc == 2)
{
if ((server.repl_slave_ro = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if ((!strcasecmp(argv[0],"slave-ignore-maxmemory") ||
!strcasecmp(argv[0],"replica-ignore-maxmemory"))
&& argc == 2)
{
if ((server.repl_slave_ignore_maxmemory = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
if ((server.rdb_compression = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"rdbchecksum") && argc == 2) {
if ((server.rdb_checksum = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"lazyfree-lazy-eviction") && argc == 2) {
if ((server.lazyfree_lazy_eviction = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"lazyfree-lazy-expire") && argc == 2) {
if ((server.lazyfree_lazy_expire = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"lazyfree-lazy-server-del") && argc == 2){
if ((server.lazyfree_lazy_server_del = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if ((!strcasecmp(argv[0],"slave-lazy-flush") ||
!strcasecmp(argv[0],"replica-lazy-flush")) && argc == 2)
{
if ((server.repl_slave_lazy_flush = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"activedefrag") && argc == 2) {
if ((server.active_defrag_enabled = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
if (server.active_defrag_enabled) {
#ifndef HAVE_DEFRAG
err = "active defrag can't be enabled without proper jemalloc support"; goto loaderr;
#endif
}
} else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
if ((server.daemonize = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"dynamic-hz") && argc == 2) {
if ((server.dynamic_hz = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"hz") && argc == 2) {
server.config_hz = atoi(argv[1]);
if (server.config_hz < CONFIG_MIN_HZ) server.config_hz = CONFIG_MIN_HZ;
if (server.config_hz > CONFIG_MAX_HZ) server.config_hz = CONFIG_MAX_HZ;
} else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
int yes;
if ((yes = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
server.aof_state = yes ? AOF_ON : AOF_OFF;
} else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
if (!pathIsBaseName(argv[1])) {
err = "appendfilename can't be a path, just a filename";
goto loaderr;
}
zfree(server.aof_filename);
server.aof_filename = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"no-appendfsync-on-rewrite")
&& argc == 2) {
if ((server.aof_no_fsync_on_rewrite= yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
server.aof_fsync = configEnumGetValue(aof_fsync_enum,argv[1]);
if (server.aof_fsync == INT_MIN) {
err = "argument must be 'no', 'always' or 'everysec'";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"auto-aof-rewrite-percentage") &&
argc == 2)
{
server.aof_rewrite_perc = atoi(argv[1]);
if (server.aof_rewrite_perc < 0) {
err = "Invalid negative percentage for AOF auto rewrite";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"auto-aof-rewrite-min-size") &&
argc == 2)
{
server.aof_rewrite_min_size = memtoll(argv[1],NULL);
} else if (!strcasecmp(argv[0],"aof-rewrite-incremental-fsync") &&
argc == 2)
{
if ((server.aof_rewrite_incremental_fsync =
yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"rdb-save-incremental-fsync") &&
argc == 2)
{
if ((server.rdb_save_incremental_fsync =
yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"aof-load-truncated") && argc == 2) {
if ((server.aof_load_truncated = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"aof-use-rdb-preamble") && argc == 2) {
if ((server.aof_use_rdb_preamble = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
if (strlen(argv[1]) > CONFIG_AUTHPASS_MAX_LEN) {
err = "Password is longer than CONFIG_AUTHPASS_MAX_LEN";
goto loaderr;
}
/* The old "requirepass" directive just translates to setting
* a password to the default user. */
ACLSetUser(DefaultUser,"resetpass",-1);
sds aclop = sdscatprintf(sdsempty(),">%s",argv[1]);
ACLSetUser(DefaultUser,aclop,sdslen(aclop));
sdsfree(aclop);
} else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
zfree(server.pidfile);
server.pidfile = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
if (!pathIsBaseName(argv[1])) {
err = "dbfilename can't be a path, just a filename";
goto loaderr;
}
zfree(server.rdb_filename);
server.rdb_filename = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"active-defrag-threshold-lower") && argc == 2) {
server.active_defrag_threshold_lower = atoi(argv[1]);
if (server.active_defrag_threshold_lower < 0 ||
server.active_defrag_threshold_lower > 1000) {
err = "active-defrag-threshold-lower must be between 0 and 1000";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"active-defrag-threshold-upper") && argc == 2) {
server.active_defrag_threshold_upper = atoi(argv[1]);
if (server.active_defrag_threshold_upper < 0 ||
server.active_defrag_threshold_upper > 1000) {
err = "active-defrag-threshold-upper must be between 0 and 1000";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"active-defrag-ignore-bytes") && argc == 2) {
server.active_defrag_ignore_bytes = memtoll(argv[1], NULL);
if (server.active_defrag_ignore_bytes <= 0) {
err = "active-defrag-ignore-bytes must above 0";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"active-defrag-cycle-min") && argc == 2) {
server.active_defrag_cycle_min = atoi(argv[1]);
if (server.active_defrag_cycle_min < 1 || server.active_defrag_cycle_min > 99) {
err = "active-defrag-cycle-min must be between 1 and 99";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"active-defrag-cycle-max") && argc == 2) {
server.active_defrag_cycle_max = atoi(argv[1]);
if (server.active_defrag_cycle_max < 1 || server.active_defrag_cycle_max > 99) {
err = "active-defrag-cycle-max must be between 1 and 99";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"active-defrag-max-scan-fields") && argc == 2) {
server.active_defrag_max_scan_fields = strtoll(argv[1],NULL,10);
if (server.active_defrag_max_scan_fields < 1) {
err = "active-defrag-max-scan-fields must be positive";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"hash-max-ziplist-entries") && argc == 2) {
server.hash_max_ziplist_entries = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"hash-max-ziplist-value") && argc == 2) {
server.hash_max_ziplist_value = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"stream-node-max-bytes") && argc == 2) {
server.stream_node_max_bytes = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"stream-node-max-entries") && argc == 2) {
server.stream_node_max_entries = atoi(argv[1]);
} else if (!strcasecmp(argv[0],"list-max-ziplist-entries") && argc == 2){
/* DEAD OPTION */
} else if (!strcasecmp(argv[0],"list-max-ziplist-value") && argc == 2) {
/* DEAD OPTION */
} else if (!strcasecmp(argv[0],"list-max-ziplist-size") && argc == 2) {
server.list_max_ziplist_size = atoi(argv[1]);
} else if (!strcasecmp(argv[0],"list-compress-depth") && argc == 2) {
server.list_compress_depth = atoi(argv[1]);
} else if (!strcasecmp(argv[0],"set-max-intset-entries") && argc == 2) {
server.set_max_intset_entries = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"zset-max-ziplist-entries") && argc == 2) {
server.zset_max_ziplist_entries = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"zset-max-ziplist-value") && argc == 2) {
server.zset_max_ziplist_value = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"hll-sparse-max-bytes") && argc == 2) {
server.hll_sparse_max_bytes = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"rename-command") && argc == 3) {
struct redisCommand *cmd = lookupCommand(argv[1]);
int retval;
if (!cmd) {
err = "No such command in rename-command";
goto loaderr;
}
/* If the target command name is the empty string we just
* remove it from the command table. */
retval = dictDelete(server.commands, argv[1]);
serverAssert(retval == DICT_OK);
/* Otherwise we re-add the command under a different name. */
if (sdslen(argv[2]) != 0) {
sds copy = sdsdup(argv[2]);
retval = dictAdd(server.commands, copy, cmd);
if (retval != DICT_OK) {
sdsfree(copy);
err = "Target command name already exists"; goto loaderr;
}
}
} else if (!strcasecmp(argv[0],"cluster-enabled") && argc == 2) {
if ((server.cluster_enabled = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"cluster-config-file") && argc == 2) {
zfree(server.cluster_configfile);
server.cluster_configfile = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"cluster-announce-ip") && argc == 2) {
zfree(server.cluster_announce_ip);
server.cluster_announce_ip = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"cluster-announce-port") && argc == 2) {
server.cluster_announce_port = atoi(argv[1]);
if (server.cluster_announce_port < 0 ||
server.cluster_announce_port > 65535)
{
err = "Invalid port"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"cluster-announce-bus-port") &&
argc == 2)
{
server.cluster_announce_bus_port = atoi(argv[1]);
if (server.cluster_announce_bus_port < 0 ||
server.cluster_announce_bus_port > 65535)
{
err = "Invalid port"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"cluster-require-full-coverage") &&
argc == 2)
{
if ((server.cluster_require_full_coverage = yesnotoi(argv[1])) == -1)
{
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"cluster-node-timeout") && argc == 2) {
server.cluster_node_timeout = strtoll(argv[1],NULL,10);
if (server.cluster_node_timeout <= 0) {
err = "cluster node timeout must be 1 or greater"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"cluster-migration-barrier")
&& argc == 2)
{
server.cluster_migration_barrier = atoi(argv[1]);
if (server.cluster_migration_barrier < 0) {
err = "cluster migration barrier must zero or positive";
goto loaderr;
}
} else if ((!strcasecmp(argv[0],"cluster-slave-validity-factor") ||
!strcasecmp(argv[0],"cluster-replica-validity-factor"))
&& argc == 2)
{
server.cluster_slave_validity_factor = atoi(argv[1]);
if (server.cluster_slave_validity_factor < 0) {
err = "cluster replica validity factor must be zero or positive";
goto loaderr;
}
} else if ((!strcasecmp(argv[0],"cluster-slave-no-failover") ||
!strcasecmp(argv[0],"cluster-replica-no-failover")) &&
argc == 2)
{
server.cluster_slave_no_failover = yesnotoi(argv[1]);
if (server.cluster_slave_no_failover == -1) {
err = "argument must be 'yes' or 'no'";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"lua-time-limit") && argc == 2) {
server.lua_time_limit = strtoll(argv[1],NULL,10);
} else if (!strcasecmp(argv[0],"lua-replicate-commands") && argc == 2) {
server.lua_always_replicate_commands = yesnotoi(argv[1]);
} else if (!strcasecmp(argv[0],"slowlog-log-slower-than") &&
argc == 2)
{
server.slowlog_log_slower_than = strtoll(argv[1],NULL,10);
} else if (!strcasecmp(argv[0],"latency-monitor-threshold") &&
argc == 2)
{
server.latency_monitor_threshold = strtoll(argv[1],NULL,10);
if (server.latency_monitor_threshold < 0) {
err = "The latency threshold can't be negative";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"slowlog-max-len") && argc == 2) {
server.slowlog_max_len = strtoll(argv[1],NULL,10);
} else if (!strcasecmp(argv[0],"client-output-buffer-limit") &&
argc == 5)
{
int class = getClientTypeByName(argv[1]);
unsigned long long hard, soft;
int soft_seconds;
if (class == -1 || class == CLIENT_TYPE_MASTER) {
err = "Unrecognized client limit class: the user specified "
"an invalid one, or 'master' which has no buffer limits.";
goto loaderr;
}
hard = memtoll(argv[2],NULL);
soft = memtoll(argv[3],NULL);
soft_seconds = atoi(argv[4]);
if (soft_seconds < 0) {
err = "Negative number of seconds in soft limit is invalid";
goto loaderr;
}
server.client_obuf_limits[class].hard_limit_bytes = hard;
server.client_obuf_limits[class].soft_limit_bytes = soft;
server.client_obuf_limits[class].soft_limit_seconds = soft_seconds;
} else if (!strcasecmp(argv[0],"stop-writes-on-bgsave-error") &&
argc == 2) {
if ((server.stop_writes_on_bgsave_err = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if ((!strcasecmp(argv[0],"slave-priority") ||
!strcasecmp(argv[0],"replica-priority")) && argc == 2)
{
server.slave_priority = atoi(argv[1]);
} else if ((!strcasecmp(argv[0],"slave-announce-ip") ||
!strcasecmp(argv[0],"replica-announce-ip")) && argc == 2)
{
zfree(server.slave_announce_ip);
server.slave_announce_ip = zstrdup(argv[1]);
} else if ((!strcasecmp(argv[0],"slave-announce-port") ||
!strcasecmp(argv[0],"replica-announce-port")) && argc == 2)
{
server.slave_announce_port = atoi(argv[1]);
if (server.slave_announce_port < 0 ||
server.slave_announce_port > 65535)
{
err = "Invalid port"; goto loaderr;
}
} else if ((!strcasecmp(argv[0],"min-slaves-to-write") ||
!strcasecmp(argv[0],"min-replicas-to-write")) && argc == 2)
{
server.repl_min_slaves_to_write = atoi(argv[1]);
if (server.repl_min_slaves_to_write < 0) {
err = "Invalid value for min-replicas-to-write."; goto loaderr;
}
} else if ((!strcasecmp(argv[0],"min-slaves-max-lag") ||
!strcasecmp(argv[0],"min-replicas-max-lag")) && argc == 2)
{
server.repl_min_slaves_max_lag = atoi(argv[1]);
if (server.repl_min_slaves_max_lag < 0) {
err = "Invalid value for min-replicas-max-lag."; goto loaderr;
}
} else if (!strcasecmp(argv[0],"notify-keyspace-events") && argc == 2) {
int flags = keyspaceEventsStringToFlags(argv[1]);
if (flags == -1) {
err = "Invalid event class character. Use 'g$lshzxeA'.";
goto loaderr;
}
server.notify_keyspace_events = flags;
} else if (!strcasecmp(argv[0],"supervised") && argc == 2) {
server.supervised_mode =
configEnumGetValue(supervised_mode_enum,argv[1]);
if (server.supervised_mode == INT_MIN) {
err = "Invalid option for 'supervised'. "
"Allowed values: 'upstart', 'systemd', 'auto', or 'no'";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"user") && argc >= 2) {
int argc_err;
if (ACLAppendUserForLoading(argv,argc,&argc_err) == C_ERR) {
char buf[1024];
char *errmsg = ACLSetUserStringError();
snprintf(buf,sizeof(buf),"Error in user declaration '%s': %s",
argv[argc_err],errmsg);
err = buf;
goto loaderr;
}
} else if (!strcasecmp(argv[0],"loadmodule") && argc >= 2) {
queueLoadModule(argv[1],&argv[2],argc-2);
} else if (!strcasecmp(argv[0],"sentinel")) {
/* argc == 1 is handled by main() as we need to enter the sentinel
* mode ASAP. */
if (argc != 1) {
if (!server.sentinel_mode) {
err = "sentinel directive while not in sentinel mode";
goto loaderr;
}
err = sentinelHandleConfiguration(argv+1,argc-1);
if (err) goto loaderr;
}
} else {
err = "Bad directive or wrong number of arguments"; goto loaderr;
}
sdsfreesplitres(argv,argc);
}
/* Sanity checks. */
if (server.cluster_enabled && server.masterhost) {
linenum = slaveof_linenum;
i = linenum-1;
err = "replicaof directive not allowed in cluster mode";
goto loaderr;
}
sdsfreesplitres(lines,totlines);
return;
loaderr:
fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
fprintf(stderr, ">>> '%s'\n", lines[i]);
fprintf(stderr, "%s\n", err);
exit(1);
}
/* Load the server configuration from the specified filename.
* The function appends the additional configuration directives stored
* in the 'options' string to the config file before loading.
*
* Both filename and options can be NULL, in such a case are considered
* empty. This way loadServerConfig can be used to just load a file or
* just load a string. */
void loadServerConfig(char *filename, char *options) {
sds config = sdsempty();
char buf[CONFIG_MAX_LINE+1];
/* Load the file content */
if (filename) {
FILE *fp;
if (filename[0] == '-' && filename[1] == '\0') {
fp = stdin;
} else {
if ((fp = fopen(filename,"r")) == NULL) {
serverLog(LL_WARNING,
"Fatal error, can't open config file '%s'", filename);
exit(1);
}
}
while(fgets(buf,CONFIG_MAX_LINE+1,fp) != NULL)
config = sdscat(config,buf);
if (fp != stdin) fclose(fp);
}
/* Append the additional options */
if (options) {
config = sdscat(config,"\n");
config = sdscat(config,options);
}
loadServerConfigFromString(config);
sdsfree(config);
}
/*-----------------------------------------------------------------------------
* CONFIG SET implementation
*----------------------------------------------------------------------------*/
#define config_set_bool_field(_name,_var) \
} else if (!strcasecmp(c->argv[2]->ptr,_name)) { \
int yn = yesnotoi(o->ptr); \
if (yn == -1) goto badfmt; \
_var = yn;
#define config_set_numerical_field(_name,_var,min,max) \
} else if (!strcasecmp(c->argv[2]->ptr,_name)) { \
if (getLongLongFromObject(o,&ll) == C_ERR) goto badfmt; \
if (min != LLONG_MIN && ll < min) goto badfmt; \
if (max != LLONG_MAX && ll > max) goto badfmt; \
_var = ll;
#define config_set_memory_field(_name,_var) \
} else if (!strcasecmp(c->argv[2]->ptr,_name)) { \
ll = memtoll(o->ptr,&err); \
if (err || ll < 0) goto badfmt; \
_var = ll;
#define config_set_enum_field(_name,_var,_enumvar) \
} else if (!strcasecmp(c->argv[2]->ptr,_name)) { \
int enumval = configEnumGetValue(_enumvar,o->ptr); \
if (enumval == INT_MIN) goto badfmt; \
_var = enumval;
#define config_set_special_field(_name) \
} else if (!strcasecmp(c->argv[2]->ptr,_name)) {
#define config_set_special_field_with_alias(_name1,_name2) \
} else if (!strcasecmp(c->argv[2]->ptr,_name1) || \
!strcasecmp(c->argv[2]->ptr,_name2)) {
#define config_set_else } else
void configSetCommand(client *c) {
robj *o;
long long ll;
int err;
serverAssertWithInfo(c,c->argv[2],sdsEncodedObject(c->argv[2]));
serverAssertWithInfo(c,c->argv[3],sdsEncodedObject(c->argv[3]));
o = c->argv[3];
if (0) { /* this starts the config_set macros else-if chain. */
/* Special fields that can't be handled with general macros. */
config_set_special_field("dbfilename") {
if (!pathIsBaseName(o->ptr)) {
addReplyError(c, "dbfilename can't be a path, just a filename");
return;
}
zfree(server.rdb_filename);
server.rdb_filename = zstrdup(o->ptr);
} config_set_special_field("requirepass") {
if (sdslen(o->ptr) > CONFIG_AUTHPASS_MAX_LEN) goto badfmt;
/* The old "requirepass" directive just translates to setting
* a password to the default user. */
ACLSetUser(DefaultUser,"resetpass",-1);
sds aclop = sdscatprintf(sdsempty(),">%s",(char*)o->ptr);
ACLSetUser(DefaultUser,aclop,sdslen(aclop));
sdsfree(aclop);
} config_set_special_field("masteruser") {
zfree(server.masteruser);
server.masteruser = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL;
} config_set_special_field("masterauth") {
zfree(server.masterauth);
server.masterauth = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL;
} config_set_special_field("cluster-announce-ip") {
zfree(server.cluster_announce_ip);
server.cluster_announce_ip = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL;
} config_set_special_field("maxclients") {
int orig_value = server.maxclients;
if (getLongLongFromObject(o,&ll) == C_ERR || ll < 1) goto badfmt;
/* Try to check if the OS is capable of supporting so many FDs. */
server.maxclients = ll;
if (ll > orig_value) {
adjustOpenFilesLimit();
if (server.maxclients != ll) {
addReplyErrorFormat(c,"The operating system is not able to handle the specified number of clients, try with %d", server.maxclients);
server.maxclients = orig_value;
return;
}
if ((unsigned int) aeGetSetSize(server.el) <
server.maxclients + CONFIG_FDSET_INCR)
{
if (aeResizeSetSize(server.el,
server.maxclients + CONFIG_FDSET_INCR) == AE_ERR)
{
addReplyError(c,"The event loop API used by Redis is not able to handle the specified number of clients");
server.maxclients = orig_value;
return;
}
}
}
} config_set_special_field("appendonly") {
int enable = yesnotoi(o->ptr);
if (enable == -1) goto badfmt;
if (enable == 0 && server.aof_state != AOF_OFF) {
stopAppendOnly();
} else if (enable && server.aof_state == AOF_OFF) {
if (startAppendOnly() == C_ERR) {
addReplyError(c,
"Unable to turn on AOF. Check server logs.");
return;
}
}
} config_set_special_field("save") {
int vlen, j;
sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
/* Perform sanity check before setting the new config:
* - Even number of args
* - Seconds >= 1, changes >= 0 */
if (vlen & 1) {
sdsfreesplitres(v,vlen);
goto badfmt;
}
for (j = 0; j < vlen; j++) {
char *eptr;
long val;
val = strtoll(v[j], &eptr, 10);
if (eptr[0] != '\0' ||
((j & 1) == 0 && val < 1) ||
((j & 1) == 1 && val < 0)) {
sdsfreesplitres(v,vlen);
goto badfmt;
}
}
/* Finally set the new config */
resetServerSaveParams();
for (j = 0; j < vlen; j += 2) {
time_t seconds;
int changes;
seconds = strtoll(v[j],NULL,10);
changes = strtoll(v[j+1],NULL,10);
appendServerSaveParams(seconds, changes);
}
sdsfreesplitres(v,vlen);
} config_set_special_field("dir") {
if (chdir((char*)o->ptr) == -1) {
addReplyErrorFormat(c,"Changing directory: %s", strerror(errno));
return;
}
} config_set_special_field("client-output-buffer-limit") {
int vlen, j;
sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
/* We need a multiple of 4: <class> <hard> <soft> <soft_seconds> */
if (vlen % 4) {
sdsfreesplitres(v,vlen);
goto badfmt;
}
/* Sanity check of single arguments, so that we either refuse the
* whole configuration string or accept it all, even if a single
* error in a single client class is present. */
for (j = 0; j < vlen; j++) {
long val;
if ((j % 4) == 0) {
int class = getClientTypeByName(v[j]);
if (class == -1 || class == CLIENT_TYPE_MASTER) {
sdsfreesplitres(v,vlen);
goto badfmt;
}
} else {
val = memtoll(v[j], &err);
if (err || val < 0) {
sdsfreesplitres(v,vlen);
goto badfmt;
}
}
}
/* Finally set the new config */
for (j = 0; j < vlen; j += 4) {
int class;
unsigned long long hard, soft;
int soft_seconds;
class = getClientTypeByName(v[j]);
hard = strtoll(v[j+1],NULL,10);
soft = strtoll(v[j+2],NULL,10);
soft_seconds = strtoll(v[j+3],NULL,10);
server.client_obuf_limits[class].hard_limit_bytes = hard;
server.client_obuf_limits[class].soft_limit_bytes = soft;
server.client_obuf_limits[class].soft_limit_seconds = soft_seconds;
}
sdsfreesplitres(v,vlen);
} config_set_special_field("notify-keyspace-events") {
int flags = keyspaceEventsStringToFlags(o->ptr);
if (flags == -1) goto badfmt;
server.notify_keyspace_events = flags;
} config_set_special_field_with_alias("slave-announce-ip",
"replica-announce-ip")
{
zfree(server.slave_announce_ip);
server.slave_announce_ip = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL;
/* Boolean fields.
* config_set_bool_field(name,var). */
} config_set_bool_field(
"rdbcompression", server.rdb_compression) {
} config_set_bool_field(
"repl-disable-tcp-nodelay",server.repl_disable_tcp_nodelay) {
} config_set_bool_field(
"repl-diskless-sync",server.repl_diskless_sync) {
} config_set_bool_field(
"cluster-require-full-coverage",server.cluster_require_full_coverage) {
} config_set_bool_field(
"cluster-slave-no-failover",server.cluster_slave_no_failover) {
} config_set_bool_field(
"cluster-replica-no-failover",server.cluster_slave_no_failover) {
} config_set_bool_field(
"aof-rewrite-incremental-fsync",server.aof_rewrite_incremental_fsync) {
} config_set_bool_field(
"rdb-save-incremental-fsync",server.rdb_save_incremental_fsync) {
} config_set_bool_field(
"aof-load-truncated",server.aof_load_truncated) {
} config_set_bool_field(
"aof-use-rdb-preamble",server.aof_use_rdb_preamble) {
} config_set_bool_field(
"slave-serve-stale-data",server.repl_serve_stale_data) {
} config_set_bool_field(
"replica-serve-stale-data",server.repl_serve_stale_data) {
} config_set_bool_field(
"slave-read-only",server.repl_slave_ro) {
} config_set_bool_field(
"replica-read-only",server.repl_slave_ro) {
} config_set_bool_field(
"slave-ignore-maxmemory",server.repl_slave_ignore_maxmemory) {
} config_set_bool_field(
"replica-ignore-maxmemory",server.repl_slave_ignore_maxmemory) {
} config_set_bool_field(
"activerehashing",server.activerehashing) {
} config_set_bool_field(
"activedefrag",server.active_defrag_enabled) {
#ifndef HAVE_DEFRAG
if (server.active_defrag_enabled) {
server.active_defrag_enabled = 0;
addReplyError(c,
"-DISABLED Active defragmentation cannot be enabled: it "
"requires a Redis server compiled with a modified Jemalloc "
"like the one shipped by default with the Redis source "
"distribution");
return;
}
#endif
} config_set_bool_field(
"protected-mode",server.protected_mode) {
} config_set_bool_field(
"stop-writes-on-bgsave-error",server.stop_writes_on_bgsave_err) {
} config_set_bool_field(
"lazyfree-lazy-eviction",server.lazyfree_lazy_eviction) {
} config_set_bool_field(
"lazyfree-lazy-expire",server.lazyfree_lazy_expire) {
} config_set_bool_field(
"lazyfree-lazy-server-del",server.lazyfree_lazy_server_del) {
} config_set_bool_field(
"slave-lazy-flush",server.repl_slave_lazy_flush) {
} config_set_bool_field(
"replica-lazy-flush",server.repl_slave_lazy_flush) {
} config_set_bool_field(
"no-appendfsync-on-rewrite",server.aof_no_fsync_on_rewrite) {
} config_set_bool_field(
"dynamic-hz",server.dynamic_hz) {
/* Numerical fields.
* config_set_numerical_field(name,var,min,max) */
} config_set_numerical_field(
"tcp-keepalive",server.tcpkeepalive,0,INT_MAX) {
} config_set_numerical_field(
"maxmemory-samples",server.maxmemory_samples,1,INT_MAX) {
} config_set_numerical_field(
"lfu-log-factor",server.lfu_log_factor,0,INT_MAX) {
} config_set_numerical_field(
"lfu-decay-time",server.lfu_decay_time,0,INT_MAX) {
} config_set_numerical_field(
"timeout",server.maxidletime,0,INT_MAX) {
} config_set_numerical_field(
"active-defrag-threshold-lower",server.active_defrag_threshold_lower,0,1000) {
} config_set_numerical_field(
"active-defrag-threshold-upper",server.active_defrag_threshold_upper,0,1000) {
} config_set_memory_field(
"active-defrag-ignore-bytes",server.active_defrag_ignore_bytes) {
} config_set_numerical_field(
"active-defrag-cycle-min",server.active_defrag_cycle_min,1,99) {
} config_set_numerical_field(
"active-defrag-cycle-max",server.active_defrag_cycle_max,1,99) {
} config_set_numerical_field(
"active-defrag-max-scan-fields",server.active_defrag_max_scan_fields,1,LONG_MAX) {
} config_set_numerical_field(
"auto-aof-rewrite-percentage",server.aof_rewrite_perc,0,INT_MAX){
} config_set_numerical_field(
"hash-max-ziplist-entries",server.hash_max_ziplist_entries,0,LONG_MAX) {
} config_set_numerical_field(
"hash-max-ziplist-value",server.hash_max_ziplist_value,0,LONG_MAX) {
} config_set_numerical_field(
"stream-node-max-bytes",server.stream_node_max_bytes,0,LONG_MAX) {
} config_set_numerical_field(
"stream-node-max-entries",server.stream_node_max_entries,0,LLONG_MAX) {
} config_set_numerical_field(
"list-max-ziplist-size",server.list_max_ziplist_size,INT_MIN,INT_MAX) {
} config_set_numerical_field(
"list-compress-depth",server.list_compress_depth,0,INT_MAX) {
} config_set_numerical_field(
"set-max-intset-entries",server.set_max_intset_entries,0,LONG_MAX) {
} config_set_numerical_field(
"zset-max-ziplist-entries",server.zset_max_ziplist_entries,0,LONG_MAX) {
} config_set_numerical_field(
"zset-max-ziplist-value",server.zset_max_ziplist_value,0,LONG_MAX) {
} config_set_numerical_field(
"hll-sparse-max-bytes",server.hll_sparse_max_bytes,0,LONG_MAX) {
} config_set_numerical_field(
"lua-time-limit",server.lua_time_limit,0,LONG_MAX) {
} config_set_numerical_field(
"slowlog-log-slower-than",server.slowlog_log_slower_than,-1,LLONG_MAX) {
} config_set_numerical_field(
"slowlog-max-len",ll,0,LONG_MAX) {
/* Cast to unsigned. */
server.slowlog_max_len = (unsigned long)ll;
} config_set_numerical_field(
"latency-monitor-threshold",server.latency_monitor_threshold,0,LLONG_MAX){
} config_set_numerical_field(
"repl-ping-slave-period",server.repl_ping_slave_period,1,INT_MAX) {
} config_set_numerical_field(
"repl-ping-replica-period",server.repl_ping_slave_period,1,INT_MAX) {
} config_set_numerical_field(
"repl-timeout",server.repl_timeout,1,INT_MAX) {
} config_set_numerical_field(
"repl-backlog-ttl",server.repl_backlog_time_limit,0,LONG_MAX) {
} config_set_numerical_field(
"repl-diskless-sync-delay",server.repl_diskless_sync_delay,0,INT_MAX) {
} config_set_numerical_field(
"slave-priority",server.slave_priority,0,INT_MAX) {
} config_set_numerical_field(
"replica-priority",server.slave_priority,0,INT_MAX) {
} config_set_numerical_field(
"slave-announce-port",server.slave_announce_port,0,65535) {
} config_set_numerical_field(
"replica-announce-port",server.slave_announce_port,0,65535) {
} config_set_numerical_field(
"min-slaves-to-write",server.repl_min_slaves_to_write,0,INT_MAX) {
refreshGoodSlavesCount();
} config_set_numerical_field(
"min-replicas-to-write",server.repl_min_slaves_to_write,0,INT_MAX) {
refreshGoodSlavesCount();
} config_set_numerical_field(
"min-slaves-max-lag",server.repl_min_slaves_max_lag,0,INT_MAX) {
refreshGoodSlavesCount();
} config_set_numerical_field(
"min-replicas-max-lag",server.repl_min_slaves_max_lag,0,INT_MAX) {
refreshGoodSlavesCount();
} config_set_numerical_field(
"cluster-node-timeout",server.cluster_node_timeout,0,LLONG_MAX) {
} config_set_numerical_field(
"cluster-announce-port",server.cluster_announce_port,0,65535) {
} config_set_numerical_field(
"cluster-announce-bus-port",server.cluster_announce_bus_port,0,65535) {
} config_set_numerical_field(
"cluster-migration-barrier",server.cluster_migration_barrier,0,INT_MAX){
} config_set_numerical_field(
"cluster-slave-validity-factor",server.cluster_slave_validity_factor,0,INT_MAX) {
} config_set_numerical_field(
"cluster-replica-validity-factor",server.cluster_slave_validity_factor,0,INT_MAX) {
} config_set_numerical_field(
"hz",server.config_hz,0,INT_MAX) {
/* Hz is more an hint from the user, so we accept values out of range
* but cap them to reasonable values. */
if (server.config_hz < CONFIG_MIN_HZ) server.config_hz = CONFIG_MIN_HZ;
if (server.config_hz > CONFIG_MAX_HZ) server.config_hz = CONFIG_MAX_HZ;
} config_set_numerical_field(
"watchdog-period",ll,0,INT_MAX) {
if (ll)
enableWatchdog(ll);
else
disableWatchdog();
/* Memory fields.
* config_set_memory_field(name,var) */
} config_set_memory_field("maxmemory",server.maxmemory) {
if (server.maxmemory) {
if (server.maxmemory < zmalloc_used_memory()) {
serverLog(LL_WARNING,"WARNING: the new maxmemory value set via CONFIG SET is smaller than the current memory usage. This will result in key eviction and/or the inability to accept new write commands depending on the maxmemory-policy.");
}
freeMemoryIfNeededAndSafe();
}
} config_set_memory_field(
"proto-max-bulk-len",server.proto_max_bulk_len) {
} config_set_memory_field(
"client-query-buffer-limit",server.client_max_querybuf_len) {
} config_set_memory_field("repl-backlog-size",ll) {
resizeReplicationBacklog(ll);
} config_set_memory_field("auto-aof-rewrite-min-size",ll) {
server.aof_rewrite_min_size = ll;
/* Enumeration fields.
* config_set_enum_field(name,var,enum_var) */
} config_set_enum_field(
"loglevel",server.verbosity,loglevel_enum) {
} config_set_enum_field(
"maxmemory-policy",server.maxmemory_policy,maxmemory_policy_enum) {
} config_set_enum_field(
"appendfsync",server.aof_fsync,aof_fsync_enum) {
/* Everyhing else is an error... */
} config_set_else {
addReplyErrorFormat(c,"Unsupported CONFIG parameter: %s",
(char*)c->argv[2]->ptr);
return;
}
/* On success we just return a generic OK for all the options. */
addReply(c,shared.ok);
return;
badfmt: /* Bad format errors */
addReplyErrorFormat(c,"Invalid argument '%s' for CONFIG SET '%s'",
(char*)o->ptr,
(char*)c->argv[2]->ptr);
}
/*-----------------------------------------------------------------------------
* CONFIG GET implementation
*----------------------------------------------------------------------------*/
#define config_get_string_field(_name,_var) do { \
if (stringmatch(pattern,_name,1)) { \
addReplyBulkCString(c,_name); \
addReplyBulkCString(c,_var ? _var : ""); \
matches++; \
} \
} while(0);
#define config_get_bool_field(_name,_var) do { \
if (stringmatch(pattern,_name,1)) { \
addReplyBulkCString(c,_name); \
addReplyBulkCString(c,_var ? "yes" : "no"); \
matches++; \
} \
} while(0);
#define config_get_numerical_field(_name,_var) do { \
if (stringmatch(pattern,_name,1)) { \
ll2string(buf,sizeof(buf),_var); \
addReplyBulkCString(c,_name); \
addReplyBulkCString(c,buf); \
matches++; \
} \
} while(0);
#define config_get_enum_field(_name,_var,_enumvar) do { \
if (stringmatch(pattern,_name,1)) { \
addReplyBulkCString(c,_name); \
addReplyBulkCString(c,configEnumGetNameOrUnknown(_enumvar,_var)); \
matches++; \
} \
} while(0);
void configGetCommand(client *c) {
robj *o = c->argv[2];
void *replylen = addReplyDeferredLen(c);
char *pattern = o->ptr;
char buf[128];
int matches = 0;
serverAssertWithInfo(c,o,sdsEncodedObject(o));
/* String values */
config_get_string_field("dbfilename",server.rdb_filename);
config_get_string_field("masteruser",server.masteruser);
config_get_string_field("masterauth",server.masterauth);
config_get_string_field("cluster-announce-ip",server.cluster_announce_ip);
config_get_string_field("unixsocket",server.unixsocket);
config_get_string_field("logfile",server.logfile);
config_get_string_field("aclfile",server.acl_filename);
config_get_string_field("pidfile",server.pidfile);
config_get_string_field("slave-announce-ip",server.slave_announce_ip);
config_get_string_field("replica-announce-ip",server.slave_announce_ip);
/* Numerical values */
config_get_numerical_field("maxmemory",server.maxmemory);
config_get_numerical_field("proto-max-bulk-len",server.proto_max_bulk_len);
config_get_numerical_field("client-query-buffer-limit",server.client_max_querybuf_len);
config_get_numerical_field("maxmemory-samples",server.maxmemory_samples);
config_get_numerical_field("lfu-log-factor",server.lfu_log_factor);
config_get_numerical_field("lfu-decay-time",server.lfu_decay_time);
config_get_numerical_field("timeout",server.maxidletime);
config_get_numerical_field("active-defrag-threshold-lower",server.active_defrag_threshold_lower);
config_get_numerical_field("active-defrag-threshold-upper",server.active_defrag_threshold_upper);
config_get_numerical_field("active-defrag-ignore-bytes",server.active_defrag_ignore_bytes);
config_get_numerical_field("active-defrag-cycle-min",server.active_defrag_cycle_min);
config_get_numerical_field("active-defrag-cycle-max",server.active_defrag_cycle_max);
config_get_numerical_field("active-defrag-max-scan-fields",server.active_defrag_max_scan_fields);
config_get_numerical_field("auto-aof-rewrite-percentage",
server.aof_rewrite_perc);
config_get_numerical_field("auto-aof-rewrite-min-size",
server.aof_rewrite_min_size);
config_get_numerical_field("hash-max-ziplist-entries",
server.hash_max_ziplist_entries);
config_get_numerical_field("hash-max-ziplist-value",
server.hash_max_ziplist_value);
config_get_numerical_field("stream-node-max-bytes",
server.stream_node_max_bytes);
config_get_numerical_field("stream-node-max-entries",
server.stream_node_max_entries);
config_get_numerical_field("list-max-ziplist-size",
server.list_max_ziplist_size);
config_get_numerical_field("list-compress-depth",
server.list_compress_depth);
config_get_numerical_field("set-max-intset-entries",
server.set_max_intset_entries);
config_get_numerical_field("zset-max-ziplist-entries",
server.zset_max_ziplist_entries);
config_get_numerical_field("zset-max-ziplist-value",
server.zset_max_ziplist_value);
config_get_numerical_field("hll-sparse-max-bytes",
server.hll_sparse_max_bytes);
config_get_numerical_field("lua-time-limit",server.lua_time_limit);
config_get_numerical_field("slowlog-log-slower-than",
server.slowlog_log_slower_than);
config_get_numerical_field("latency-monitor-threshold",
server.latency_monitor_threshold);
config_get_numerical_field("slowlog-max-len",
server.slowlog_max_len);
config_get_numerical_field("port",server.port);
config_get_numerical_field("cluster-announce-port",server.cluster_announce_port);
config_get_numerical_field("cluster-announce-bus-port",server.cluster_announce_bus_port);
config_get_numerical_field("tcp-backlog",server.tcp_backlog);
config_get_numerical_field("databases",server.dbnum);
config_get_numerical_field("repl-ping-slave-period",server.repl_ping_slave_period);
config_get_numerical_field("repl-ping-replica-period",server.repl_ping_slave_period);
config_get_numerical_field("repl-timeout",server.repl_timeout);
config_get_numerical_field("repl-backlog-size",server.repl_backlog_size);
config_get_numerical_field("repl-backlog-ttl",server.repl_backlog_time_limit);
config_get_numerical_field("maxclients",server.maxclients);
config_get_numerical_field("watchdog-period",server.watchdog_period);
config_get_numerical_field("slave-priority",server.slave_priority);
config_get_numerical_field("replica-priority",server.slave_priority);
config_get_numerical_field("slave-announce-port",server.slave_announce_port);
config_get_numerical_field("replica-announce-port",server.slave_announce_port);
config_get_numerical_field("min-slaves-to-write",server.repl_min_slaves_to_write);
config_get_numerical_field("min-replicas-to-write",server.repl_min_slaves_to_write);
config_get_numerical_field("min-slaves-max-lag",server.repl_min_slaves_max_lag);
config_get_numerical_field("min-replicas-max-lag",server.repl_min_slaves_max_lag);
config_get_numerical_field("hz",server.config_hz);
config_get_numerical_field("cluster-node-timeout",server.cluster_node_timeout);
config_get_numerical_field("cluster-migration-barrier",server.cluster_migration_barrier);
config_get_numerical_field("cluster-slave-validity-factor",server.cluster_slave_validity_factor);
config_get_numerical_field("cluster-replica-validity-factor",server.cluster_slave_validity_factor);
config_get_numerical_field("repl-diskless-sync-delay",server.repl_diskless_sync_delay);
config_get_numerical_field("tcp-keepalive",server.tcpkeepalive);
/* Bool (yes/no) values */
config_get_bool_field("cluster-require-full-coverage",
server.cluster_require_full_coverage);
config_get_bool_field("cluster-slave-no-failover",
server.cluster_slave_no_failover);
config_get_bool_field("cluster-replica-no-failover",
server.cluster_slave_no_failover);
config_get_bool_field("no-appendfsync-on-rewrite",
server.aof_no_fsync_on_rewrite);
config_get_bool_field("slave-serve-stale-data",
server.repl_serve_stale_data);
config_get_bool_field("replica-serve-stale-data",
server.repl_serve_stale_data);
config_get_bool_field("slave-read-only",
server.repl_slave_ro);
config_get_bool_field("replica-read-only",
server.repl_slave_ro);
config_get_bool_field("slave-ignore-maxmemory",
server.repl_slave_ignore_maxmemory);
config_get_bool_field("replica-ignore-maxmemory",
server.repl_slave_ignore_maxmemory);
config_get_bool_field("stop-writes-on-bgsave-error",
server.stop_writes_on_bgsave_err);
config_get_bool_field("daemonize", server.daemonize);
config_get_bool_field("rdbcompression", server.rdb_compression);
config_get_bool_field("rdbchecksum", server.rdb_checksum);
config_get_bool_field("activerehashing", server.activerehashing);
config_get_bool_field("activedefrag", server.active_defrag_enabled);
config_get_bool_field("protected-mode", server.protected_mode);
config_get_bool_field("repl-disable-tcp-nodelay",
server.repl_disable_tcp_nodelay);
config_get_bool_field("repl-diskless-sync",
server.repl_diskless_sync);
config_get_bool_field("aof-rewrite-incremental-fsync",
server.aof_rewrite_incremental_fsync);
config_get_bool_field("rdb-save-incremental-fsync",
server.rdb_save_incremental_fsync);
config_get_bool_field("aof-load-truncated",
server.aof_load_truncated);
config_get_bool_field("aof-use-rdb-preamble",
server.aof_use_rdb_preamble);
config_get_bool_field("lazyfree-lazy-eviction",
server.lazyfree_lazy_eviction);
config_get_bool_field("lazyfree-lazy-expire",
server.lazyfree_lazy_expire);
config_get_bool_field("lazyfree-lazy-server-del",
server.lazyfree_lazy_server_del);
config_get_bool_field("slave-lazy-flush",
server.repl_slave_lazy_flush);
config_get_bool_field("replica-lazy-flush",
server.repl_slave_lazy_flush);
config_get_bool_field("dynamic-hz",
server.dynamic_hz);
/* Enum values */
config_get_enum_field("maxmemory-policy",
server.maxmemory_policy,maxmemory_policy_enum);
config_get_enum_field("loglevel",
server.verbosity,loglevel_enum);
config_get_enum_field("supervised",
server.supervised_mode,supervised_mode_enum);
config_get_enum_field("appendfsync",
server.aof_fsync,aof_fsync_enum);
config_get_enum_field("syslog-facility",
server.syslog_facility,syslog_facility_enum);
/* Everything we can't handle with macros follows. */
if (stringmatch(pattern,"appendonly",1)) {
addReplyBulkCString(c,"appendonly");
addReplyBulkCString(c,server.aof_state == AOF_OFF ? "no" : "yes");
matches++;
}
if (stringmatch(pattern,"dir",1)) {
char buf[1024];
if (getcwd(buf,sizeof(buf)) == NULL)
buf[0] = '\0';
addReplyBulkCString(c,"dir");
addReplyBulkCString(c,buf);
matches++;
}
if (stringmatch(pattern,"save",1)) {
sds buf = sdsempty();
int j;
for (j = 0; j < server.saveparamslen; j++) {
buf = sdscatprintf(buf,"%jd %d",
(intmax_t)server.saveparams[j].seconds,
server.saveparams[j].changes);
if (j != server.saveparamslen-1)
buf = sdscatlen(buf," ",1);
}
addReplyBulkCString(c,"save");
addReplyBulkCString(c,buf);
sdsfree(buf);
matches++;
}
if (stringmatch(pattern,"client-output-buffer-limit",1)) {
sds buf = sdsempty();
int j;
for (j = 0; j < CLIENT_TYPE_OBUF_COUNT; j++) {
buf = sdscatprintf(buf,"%s %llu %llu %ld",
getClientTypeName(j),
server.client_obuf_limits[j].hard_limit_bytes,
server.client_obuf_limits[j].soft_limit_bytes,
(long) server.client_obuf_limits[j].soft_limit_seconds);
if (j != CLIENT_TYPE_OBUF_COUNT-1)
buf = sdscatlen(buf," ",1);
}
addReplyBulkCString(c,"client-output-buffer-limit");
addReplyBulkCString(c,buf);
sdsfree(buf);
matches++;
}
if (stringmatch(pattern,"unixsocketperm",1)) {
char buf[32];
snprintf(buf,sizeof(buf),"%o",server.unixsocketperm);
addReplyBulkCString(c,"unixsocketperm");
addReplyBulkCString(c,buf);
matches++;
}
if (stringmatch(pattern,"slaveof",1) ||
stringmatch(pattern,"replicaof",1))
{
char *optname = stringmatch(pattern,"slaveof",1) ?
"slaveof" : "replicaof";
char buf[256];
addReplyBulkCString(c,optname);
if (server.masterhost)
snprintf(buf,sizeof(buf),"%s %d",
server.masterhost, server.masterport);
else
buf[0] = '\0';
addReplyBulkCString(c,buf);
matches++;
}
if (stringmatch(pattern,"notify-keyspace-events",1)) {
robj *flagsobj = createObject(OBJ_STRING,
keyspaceEventsFlagsToString(server.notify_keyspace_events));
addReplyBulkCString(c,"notify-keyspace-events");
addReplyBulk(c,flagsobj);
decrRefCount(flagsobj);
matches++;
}
if (stringmatch(pattern,"bind",1)) {
sds aux = sdsjoin(server.bindaddr,server.bindaddr_count," ");
addReplyBulkCString(c,"bind");
addReplyBulkCString(c,aux);
sdsfree(aux);
matches++;
}
if (stringmatch(pattern,"requirepass",1)) {
addReplyBulkCString(c,"requirepass");
sds password = ACLDefaultUserFirstPassword();
if (password) {
addReplyBulkCBuffer(c,password,sdslen(password));
} else {
addReplyBulkCString(c,"");
}
matches++;
}
setDeferredMapLen(c,replylen,matches);
}
/*-----------------------------------------------------------------------------
* CONFIG REWRITE implementation
*----------------------------------------------------------------------------*/
#define REDIS_CONFIG_REWRITE_SIGNATURE "# Generated by CONFIG REWRITE"
/* We use the following dictionary type to store where a configuration
* option is mentioned in the old configuration file, so it's
* like "maxmemory" -> list of line numbers (first line is zero). */
uint64_t dictSdsCaseHash(const void *key);
int dictSdsKeyCaseCompare(void *privdata, const void *key1, const void *key2);
void dictSdsDestructor(void *privdata, void *val);
void dictListDestructor(void *privdata, void *val);
/* Sentinel config rewriting is implemented inside sentinel.c by
* rewriteConfigSentinelOption(). */
void rewriteConfigSentinelOption(struct rewriteConfigState *state);
dictType optionToLineDictType = {
dictSdsCaseHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictSdsKeyCaseCompare, /* key compare */
dictSdsDestructor, /* key destructor */
dictListDestructor /* val destructor */
};
dictType optionSetDictType = {
dictSdsCaseHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictSdsKeyCaseCompare, /* key compare */
dictSdsDestructor, /* key destructor */
NULL /* val destructor */
};
/* The config rewrite state. */
struct rewriteConfigState {
dict *option_to_line; /* Option -> list of config file lines map */
dict *rewritten; /* Dictionary of already processed options */
int numlines; /* Number of lines in current config */
sds *lines; /* Current lines as an array of sds strings */
int has_tail; /* True if we already added directives that were
not present in the original config file. */
};
/* Append the new line to the current configuration state. */
void rewriteConfigAppendLine(struct rewriteConfigState *state, sds line) {
state->lines = zrealloc(state->lines, sizeof(char*) * (state->numlines+1));
state->lines[state->numlines++] = line;
}
/* Populate the option -> list of line numbers map. */
void rewriteConfigAddLineNumberToOption(struct rewriteConfigState *state, sds option, int linenum) {
list *l = dictFetchValue(state->option_to_line,option);
if (l == NULL) {
l = listCreate();
dictAdd(state->option_to_line,sdsdup(option),l);
}
listAddNodeTail(l,(void*)(long)linenum);
}
/* Add the specified option to the set of processed options.
* This is useful as only unused lines of processed options will be blanked
* in the config file, while options the rewrite process does not understand
* remain untouched. */
void rewriteConfigMarkAsProcessed(struct rewriteConfigState *state, const char *option) {
sds opt = sdsnew(option);
if (dictAdd(state->rewritten,opt,NULL) != DICT_OK) sdsfree(opt);
}
/* Read the old file, split it into lines to populate a newly created
* config rewrite state, and return it to the caller.
*
* If it is impossible to read the old file, NULL is returned.
* If the old file does not exist at all, an empty state is returned. */
struct rewriteConfigState *rewriteConfigReadOldFile(char *path) {
FILE *fp = fopen(path,"r");
struct rewriteConfigState *state = zmalloc(sizeof(*state));
char buf[CONFIG_MAX_LINE+1];
int linenum = -1;
if (fp == NULL && errno != ENOENT) return NULL;
state->option_to_line = dictCreate(&optionToLineDictType,NULL);
state->rewritten = dictCreate(&optionSetDictType,NULL);
state->numlines = 0;
state->lines = NULL;
state->has_tail = 0;
if (fp == NULL) return state;
/* Read the old file line by line, populate the state. */
while(fgets(buf,CONFIG_MAX_LINE+1,fp) != NULL) {
int argc;
sds *argv;
sds line = sdstrim(sdsnew(buf),"\r\n\t ");
linenum++; /* Zero based, so we init at -1 */
/* Handle comments and empty lines. */
if (line[0] == '#' || line[0] == '\0') {
if (!state->has_tail && !strcmp(line,REDIS_CONFIG_REWRITE_SIGNATURE))
state->has_tail = 1;
rewriteConfigAppendLine(state,line);
continue;
}
/* Not a comment, split into arguments. */
argv = sdssplitargs(line,&argc);
if (argv == NULL) {
/* Apparently the line is unparsable for some reason, for
* instance it may have unbalanced quotes. Load it as a
* comment. */
sds aux = sdsnew("# ??? ");
aux = sdscatsds(aux,line);
sdsfree(line);
rewriteConfigAppendLine(state,aux);
continue;
}
sdstolower(argv[0]); /* We only want lowercase config directives. */
/* Now we populate the state according to the content of this line.
* Append the line and populate the option -> line numbers map. */
rewriteConfigAppendLine(state,line);
/* Translate options using the word "slave" to the corresponding name
* "replica", before adding such option to the config name -> lines
* mapping. */
char *p = strstr(argv[0],"slave");
if (p) {
sds alt = sdsempty();
alt = sdscatlen(alt,argv[0],p-argv[0]);;
alt = sdscatlen(alt,"replica",7);
alt = sdscatlen(alt,p+5,strlen(p+5));
sdsfree(argv[0]);
argv[0] = alt;
}
rewriteConfigAddLineNumberToOption(state,argv[0],linenum);
sdsfreesplitres(argv,argc);
}
fclose(fp);
return state;
}
/* Rewrite the specified configuration option with the new "line".
* It progressively uses lines of the file that were already used for the same
* configuration option in the old version of the file, removing that line from
* the map of options -> line numbers.
*
* If there are lines associated with a given configuration option and
* "force" is non-zero, the line is appended to the configuration file.
* Usually "force" is true when an option has not its default value, so it
* must be rewritten even if not present previously.
*
* The first time a line is appended into a configuration file, a comment
* is added to show that starting from that point the config file was generated
* by CONFIG REWRITE.
*
* "line" is either used, or freed, so the caller does not need to free it
* in any way. */
void rewriteConfigRewriteLine(struct rewriteConfigState *state, const char *option, sds line, int force) {
sds o = sdsnew(option);
list *l = dictFetchValue(state->option_to_line,o);
rewriteConfigMarkAsProcessed(state,option);
if (!l && !force) {
/* Option not used previously, and we are not forced to use it. */
sdsfree(line);
sdsfree(o);
return;
}
if (l) {
listNode *ln = listFirst(l);
int linenum = (long) ln->value;
/* There are still lines in the old configuration file we can reuse
* for this option. Replace the line with the new one. */
listDelNode(l,ln);
if (listLength(l) == 0) dictDelete(state->option_to_line,o);
sdsfree(state->lines[linenum]);
state->lines[linenum] = line;
} else {
/* Append a new line. */
if (!state->has_tail) {
rewriteConfigAppendLine(state,
sdsnew(REDIS_CONFIG_REWRITE_SIGNATURE));
state->has_tail = 1;
}
rewriteConfigAppendLine(state,line);
}
sdsfree(o);
}
/* Write the long long 'bytes' value as a string in a way that is parsable
* inside redis.conf. If possible uses the GB, MB, KB notation. */
int rewriteConfigFormatMemory(char *buf, size_t len, long long bytes) {
int gb = 1024*1024*1024;
int mb = 1024*1024;
int kb = 1024;
if (bytes && (bytes % gb) == 0) {
return snprintf(buf,len,"%lldgb",bytes/gb);
} else if (bytes && (bytes % mb) == 0) {
return snprintf(buf,len,"%lldmb",bytes/mb);
} else if (bytes && (bytes % kb) == 0) {
return snprintf(buf,len,"%lldkb",bytes/kb);
} else {
return snprintf(buf,len,"%lld",bytes);
}
}
/* Rewrite a simple "option-name <bytes>" configuration option. */
void rewriteConfigBytesOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) {
char buf[64];
int force = value != defvalue;
sds line;
rewriteConfigFormatMemory(buf,sizeof(buf),value);
line = sdscatprintf(sdsempty(),"%s %s",option,buf);
rewriteConfigRewriteLine(state,option,line,force);
}
/* Rewrite a yes/no option. */
void rewriteConfigYesNoOption(struct rewriteConfigState *state, char *option, int value, int defvalue) {
int force = value != defvalue;
sds line = sdscatprintf(sdsempty(),"%s %s",option,
value ? "yes" : "no");
rewriteConfigRewriteLine(state,option,line,force);
}
/* Rewrite a string option. */
void rewriteConfigStringOption(struct rewriteConfigState *state, char *option, char *value, char *defvalue) {
int force = 1;
sds line;
/* String options set to NULL need to be not present at all in the
* configuration file to be set to NULL again at the next reboot. */
if (value == NULL) {
rewriteConfigMarkAsProcessed(state,option);
return;
}
/* Set force to zero if the value is set to its default. */
if (defvalue && strcmp(value,defvalue) == 0) force = 0;
line = sdsnew(option);
line = sdscatlen(line, " ", 1);
line = sdscatrepr(line, value, strlen(value));
rewriteConfigRewriteLine(state,option,line,force);
}
/* Rewrite a numerical (long long range) option. */
void rewriteConfigNumericalOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) {
int force = value != defvalue;
sds line = sdscatprintf(sdsempty(),"%s %lld",option,value);
rewriteConfigRewriteLine(state,option,line,force);
}
/* Rewrite a octal option. */
void rewriteConfigOctalOption(struct rewriteConfigState *state, char *option, int value, int defvalue) {
int force = value != defvalue;
sds line = sdscatprintf(sdsempty(),"%s %o",option,value);
rewriteConfigRewriteLine(state,option,line,force);
}
/* Rewrite an enumeration option. It takes as usually state and option name,
* and in addition the enumeration array and the default value for the
* option. */
void rewriteConfigEnumOption(struct rewriteConfigState *state, char *option, int value, configEnum *ce, int defval) {
sds line;
const char *name = configEnumGetNameOrUnknown(ce,value);
int force = value != defval;
line = sdscatprintf(sdsempty(),"%s %s",option,name);
rewriteConfigRewriteLine(state,option,line,force);
}
/* Rewrite the syslog-facility option. */
void rewriteConfigSyslogfacilityOption(struct rewriteConfigState *state) {
int value = server.syslog_facility;
int force = value != LOG_LOCAL0;
const char *name = NULL, *option = "syslog-facility";
sds line;
name = configEnumGetNameOrUnknown(syslog_facility_enum,value);
line = sdscatprintf(sdsempty(),"%s %s",option,name);
rewriteConfigRewriteLine(state,option,line,force);
}
/* Rewrite the save option. */
void rewriteConfigSaveOption(struct rewriteConfigState *state) {
int j;
sds line;
/* Note that if there are no save parameters at all, all the current
* config line with "save" will be detected as orphaned and deleted,
* resulting into no RDB persistence as expected. */
for (j = 0; j < server.saveparamslen; j++) {
line = sdscatprintf(sdsempty(),"save %ld %d",
(long) server.saveparams[j].seconds, server.saveparams[j].changes);
rewriteConfigRewriteLine(state,"save",line,1);
}
/* Mark "save" as processed in case server.saveparamslen is zero. */
rewriteConfigMarkAsProcessed(state,"save");
}
/* Rewrite the user option. */
void rewriteConfigUserOption(struct rewriteConfigState *state) {
/* If there is a user file defined we just mark this configuration
* directive as processed, so that all the lines containing users
* inside the config file gets discarded. */
if (server.acl_filename[0] != '\0') {
rewriteConfigMarkAsProcessed(state,"user");
return;
}
/* Otherwise scan the list of users and rewrite every line. Note that
* in case the list here is empty, the effect will just be to comment
* all the users directive inside the config file. */
raxIterator ri;
raxStart(&ri,Users);
raxSeek(&ri,"^",NULL,0);
while(raxNext(&ri)) {
user *u = ri.data;
sds line = sdsnew("user ");
line = sdscatsds(line,u->name);
line = sdscatlen(line," ",1);
sds descr = ACLDescribeUser(u);
line = sdscatsds(line,descr);
sdsfree(descr);
rewriteConfigRewriteLine(state,"user",line,1);
}
raxStop(&ri);
/* Mark "user" as processed in case there are no defined users. */
rewriteConfigMarkAsProcessed(state,"user");
}
/* Rewrite the dir option, always using absolute paths.*/
void rewriteConfigDirOption(struct rewriteConfigState *state) {
char cwd[1024];
if (getcwd(cwd,sizeof(cwd)) == NULL) {
rewriteConfigMarkAsProcessed(state,"dir");
return; /* no rewrite on error. */
}
rewriteConfigStringOption(state,"dir",cwd,NULL);
}
/* Rewrite the slaveof option. */
void rewriteConfigSlaveofOption(struct rewriteConfigState *state, char *option) {
sds line;
/* If this is a master, we want all the slaveof config options
* in the file to be removed. Note that if this is a cluster instance
* we don't want a slaveof directive inside redis.conf. */
if (server.cluster_enabled || server.masterhost == NULL) {
rewriteConfigMarkAsProcessed(state,option);
return;
}
line = sdscatprintf(sdsempty(),"%s %s %d", option,
server.masterhost, server.masterport);
rewriteConfigRewriteLine(state,option,line,1);
}
/* Rewrite the notify-keyspace-events option. */
void rewriteConfigNotifykeyspaceeventsOption(struct rewriteConfigState *state) {
int force = server.notify_keyspace_events != 0;
char *option = "notify-keyspace-events";
sds line, flags;
flags = keyspaceEventsFlagsToString(server.notify_keyspace_events);
line = sdsnew(option);
line = sdscatlen(line, " ", 1);
line = sdscatrepr(line, flags, sdslen(flags));
sdsfree(flags);
rewriteConfigRewriteLine(state,option,line,force);
}
/* Rewrite the client-output-buffer-limit option. */
void rewriteConfigClientoutputbufferlimitOption(struct rewriteConfigState *state) {
int j;
char *option = "client-output-buffer-limit";
for (j = 0; j < CLIENT_TYPE_OBUF_COUNT; j++) {
int force = (server.client_obuf_limits[j].hard_limit_bytes !=
clientBufferLimitsDefaults[j].hard_limit_bytes) ||
(server.client_obuf_limits[j].soft_limit_bytes !=
clientBufferLimitsDefaults[j].soft_limit_bytes) ||
(server.client_obuf_limits[j].soft_limit_seconds !=
clientBufferLimitsDefaults[j].soft_limit_seconds);
sds line;
char hard[64], soft[64];
rewriteConfigFormatMemory(hard,sizeof(hard),
server.client_obuf_limits[j].hard_limit_bytes);
rewriteConfigFormatMemory(soft,sizeof(soft),
server.client_obuf_limits[j].soft_limit_bytes);
char *typename = getClientTypeName(j);
if (!strcmp(typename,"slave")) typename = "replica";
line = sdscatprintf(sdsempty(),"%s %s %s %s %ld",
option, typename, hard, soft,
(long) server.client_obuf_limits[j].soft_limit_seconds);
rewriteConfigRewriteLine(state,option,line,force);
}
}
/* Rewrite the bind option. */
void rewriteConfigBindOption(struct rewriteConfigState *state) {
int force = 1;
sds line, addresses;
char *option = "bind";
/* Nothing to rewrite if we don't have bind addresses. */
if (server.bindaddr_count == 0) {
rewriteConfigMarkAsProcessed(state,option);
return;
}
/* Rewrite as bind <addr1> <addr2> ... <addrN> */
addresses = sdsjoin(server.bindaddr,server.bindaddr_count," ");
line = sdsnew(option);
line = sdscatlen(line, " ", 1);
line = sdscatsds(line, addresses);
sdsfree(addresses);
rewriteConfigRewriteLine(state,option,line,force);
}
/* Rewrite the requirepass option. */
void rewriteConfigRequirepassOption(struct rewriteConfigState *state, char *option) {
int force = 1;
sds line;
sds password = ACLDefaultUserFirstPassword();
/* If there is no password set, we don't want the requirepass option
* to be present in the configuration at all. */
if (password == NULL) {
rewriteConfigMarkAsProcessed(state,option);
return;
}
line = sdsnew(option);
line = sdscatlen(line, " ", 1);
line = sdscatsds(line, password);
rewriteConfigRewriteLine(state,option,line,force);
}
/* Glue together the configuration lines in the current configuration
* rewrite state into a single string, stripping multiple empty lines. */
sds rewriteConfigGetContentFromState(struct rewriteConfigState *state) {
sds content = sdsempty();
int j, was_empty = 0;
for (j = 0; j < state->numlines; j++) {
/* Every cluster of empty lines is turned into a single empty line. */
if (sdslen(state->lines[j]) == 0) {
if (was_empty) continue;
was_empty = 1;
} else {
was_empty = 0;
}
content = sdscatsds(content,state->lines[j]);
content = sdscatlen(content,"\n",1);
}
return content;
}
/* Free the configuration rewrite state. */
void rewriteConfigReleaseState(struct rewriteConfigState *state) {
sdsfreesplitres(state->lines,state->numlines);
dictRelease(state->option_to_line);
dictRelease(state->rewritten);
zfree(state);
}
/* At the end of the rewrite process the state contains the remaining
* map between "option name" => "lines in the original config file".
* Lines used by the rewrite process were removed by the function
* rewriteConfigRewriteLine(), all the other lines are "orphaned" and
* should be replaced by empty lines.
*
* This function does just this, iterating all the option names and
* blanking all the lines still associated. */
void rewriteConfigRemoveOrphaned(struct rewriteConfigState *state) {
dictIterator *di = dictGetIterator(state->option_to_line);
dictEntry *de;
while((de = dictNext(di)) != NULL) {
list *l = dictGetVal(de);
sds option = dictGetKey(de);
/* Don't blank lines about options the rewrite process
* don't understand. */
if (dictFind(state->rewritten,option) == NULL) {
serverLog(LL_DEBUG,"Not rewritten option: %s", option);
continue;
}
while(listLength(l)) {
listNode *ln = listFirst(l);
int linenum = (long) ln->value;
sdsfree(state->lines[linenum]);
state->lines[linenum] = sdsempty();
listDelNode(l,ln);
}
}
dictReleaseIterator(di);
}
/* This function overwrites the old configuration file with the new content.
*
* 1) The old file length is obtained.
* 2) If the new content is smaller, padding is added.
* 3) A single write(2) call is used to replace the content of the file.
* 4) Later the file is truncated to the length of the new content.
*
* This way we are sure the file is left in a consistent state even if the
* process is stopped between any of the four operations.
*
* The function returns 0 on success, otherwise -1 is returned and errno
* set accordingly. */
int rewriteConfigOverwriteFile(char *configfile, sds content) {
int retval = 0;
int fd = open(configfile,O_RDWR|O_CREAT,0644);
int content_size = sdslen(content), padding = 0;
struct stat sb;
sds content_padded;
/* 1) Open the old file (or create a new one if it does not
* exist), get the size. */
if (fd == -1) return -1; /* errno set by open(). */
if (fstat(fd,&sb) == -1) {
close(fd);
return -1; /* errno set by fstat(). */
}
/* 2) Pad the content at least match the old file size. */
content_padded = sdsdup(content);
if (content_size < sb.st_size) {
/* If the old file was bigger, pad the content with
* a newline plus as many "#" chars as required. */
padding = sb.st_size - content_size;
content_padded = sdsgrowzero(content_padded,sb.st_size);
content_padded[content_size] = '\n';
memset(content_padded+content_size+1,'#',padding-1);
}
/* 3) Write the new content using a single write(2). */
if (write(fd,content_padded,strlen(content_padded)) == -1) {
retval = -1;
goto cleanup;
}
/* 4) Truncate the file to the right length if we used padding. */
if (padding) {
if (ftruncate(fd,content_size) == -1) {
/* Non critical error... */
}
}
cleanup:
sdsfree(content_padded);
close(fd);
return retval;
}
/* Rewrite the configuration file at "path".
* If the configuration file already exists, we try at best to retain comments
* and overall structure.
*
* Configuration parameters that are at their default value, unless already
* explicitly included in the old configuration file, are not rewritten.
*
* On error -1 is returned and errno is set accordingly, otherwise 0. */
int rewriteConfig(char *path) {
struct rewriteConfigState *state;
sds newcontent;
int retval;
/* Step 1: read the old config into our rewrite state. */
if ((state = rewriteConfigReadOldFile(path)) == NULL) return -1;
/* Step 2: rewrite every single option, replacing or appending it inside
* the rewrite state. */
rewriteConfigYesNoOption(state,"daemonize",server.daemonize,0);
rewriteConfigStringOption(state,"pidfile",server.pidfile,CONFIG_DEFAULT_PID_FILE);
rewriteConfigNumericalOption(state,"port",server.port,CONFIG_DEFAULT_SERVER_PORT);
rewriteConfigNumericalOption(state,"cluster-announce-port",server.cluster_announce_port,CONFIG_DEFAULT_CLUSTER_ANNOUNCE_PORT);
rewriteConfigNumericalOption(state,"cluster-announce-bus-port",server.cluster_announce_bus_port,CONFIG_DEFAULT_CLUSTER_ANNOUNCE_BUS_PORT);
rewriteConfigNumericalOption(state,"tcp-backlog",server.tcp_backlog,CONFIG_DEFAULT_TCP_BACKLOG);
rewriteConfigBindOption(state);
rewriteConfigStringOption(state,"unixsocket",server.unixsocket,NULL);
rewriteConfigOctalOption(state,"unixsocketperm",server.unixsocketperm,CONFIG_DEFAULT_UNIX_SOCKET_PERM);
rewriteConfigNumericalOption(state,"timeout",server.maxidletime,CONFIG_DEFAULT_CLIENT_TIMEOUT);
rewriteConfigNumericalOption(state,"tcp-keepalive",server.tcpkeepalive,CONFIG_DEFAULT_TCP_KEEPALIVE);
rewriteConfigNumericalOption(state,"replica-announce-port",server.slave_announce_port,CONFIG_DEFAULT_SLAVE_ANNOUNCE_PORT);
rewriteConfigEnumOption(state,"loglevel",server.verbosity,loglevel_enum,CONFIG_DEFAULT_VERBOSITY);
rewriteConfigStringOption(state,"logfile",server.logfile,CONFIG_DEFAULT_LOGFILE);
rewriteConfigStringOption(state,"aclfile",server.acl_filename,CONFIG_DEFAULT_ACL_FILENAME);
rewriteConfigYesNoOption(state,"syslog-enabled",server.syslog_enabled,CONFIG_DEFAULT_SYSLOG_ENABLED);
rewriteConfigStringOption(state,"syslog-ident",server.syslog_ident,CONFIG_DEFAULT_SYSLOG_IDENT);
rewriteConfigSyslogfacilityOption(state);
rewriteConfigSaveOption(state);
rewriteConfigUserOption(state);
rewriteConfigNumericalOption(state,"databases",server.dbnum,CONFIG_DEFAULT_DBNUM);
rewriteConfigYesNoOption(state,"stop-writes-on-bgsave-error",server.stop_writes_on_bgsave_err,CONFIG_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR);
rewriteConfigYesNoOption(state,"rdbcompression",server.rdb_compression,CONFIG_DEFAULT_RDB_COMPRESSION);
rewriteConfigYesNoOption(state,"rdbchecksum",server.rdb_checksum,CONFIG_DEFAULT_RDB_CHECKSUM);
rewriteConfigStringOption(state,"dbfilename",server.rdb_filename,CONFIG_DEFAULT_RDB_FILENAME);
rewriteConfigDirOption(state);
rewriteConfigSlaveofOption(state,"replicaof");
rewriteConfigStringOption(state,"replica-announce-ip",server.slave_announce_ip,CONFIG_DEFAULT_SLAVE_ANNOUNCE_IP);
rewriteConfigStringOption(state,"masteruser",server.masteruser,NULL);
rewriteConfigStringOption(state,"masterauth",server.masterauth,NULL);
rewriteConfigStringOption(state,"cluster-announce-ip",server.cluster_announce_ip,NULL);
rewriteConfigYesNoOption(state,"replica-serve-stale-data",server.repl_serve_stale_data,CONFIG_DEFAULT_SLAVE_SERVE_STALE_DATA);
rewriteConfigYesNoOption(state,"replica-read-only",server.repl_slave_ro,CONFIG_DEFAULT_SLAVE_READ_ONLY);
rewriteConfigYesNoOption(state,"replica-ignore-maxmemory",server.repl_slave_ignore_maxmemory,CONFIG_DEFAULT_SLAVE_IGNORE_MAXMEMORY);
rewriteConfigNumericalOption(state,"repl-ping-replica-period",server.repl_ping_slave_period,CONFIG_DEFAULT_REPL_PING_SLAVE_PERIOD);
rewriteConfigNumericalOption(state,"repl-timeout",server.repl_timeout,CONFIG_DEFAULT_REPL_TIMEOUT);
rewriteConfigBytesOption(state,"repl-backlog-size",server.repl_backlog_size,CONFIG_DEFAULT_REPL_BACKLOG_SIZE);
rewriteConfigBytesOption(state,"repl-backlog-ttl",server.repl_backlog_time_limit,CONFIG_DEFAULT_REPL_BACKLOG_TIME_LIMIT);
rewriteConfigYesNoOption(state,"repl-disable-tcp-nodelay",server.repl_disable_tcp_nodelay,CONFIG_DEFAULT_REPL_DISABLE_TCP_NODELAY);
rewriteConfigYesNoOption(state,"repl-diskless-sync",server.repl_diskless_sync,CONFIG_DEFAULT_REPL_DISKLESS_SYNC);
rewriteConfigNumericalOption(state,"repl-diskless-sync-delay",server.repl_diskless_sync_delay,CONFIG_DEFAULT_REPL_DISKLESS_SYNC_DELAY);
rewriteConfigNumericalOption(state,"replica-priority",server.slave_priority,CONFIG_DEFAULT_SLAVE_PRIORITY);
rewriteConfigNumericalOption(state,"min-replicas-to-write",server.repl_min_slaves_to_write,CONFIG_DEFAULT_MIN_SLAVES_TO_WRITE);
rewriteConfigNumericalOption(state,"min-replicas-max-lag",server.repl_min_slaves_max_lag,CONFIG_DEFAULT_MIN_SLAVES_MAX_LAG);
rewriteConfigRequirepassOption(state,"requirepass");
rewriteConfigNumericalOption(state,"maxclients",server.maxclients,CONFIG_DEFAULT_MAX_CLIENTS);
rewriteConfigBytesOption(state,"maxmemory",server.maxmemory,CONFIG_DEFAULT_MAXMEMORY);
rewriteConfigBytesOption(state,"proto-max-bulk-len",server.proto_max_bulk_len,CONFIG_DEFAULT_PROTO_MAX_BULK_LEN);
rewriteConfigBytesOption(state,"client-query-buffer-limit",server.client_max_querybuf_len,PROTO_MAX_QUERYBUF_LEN);
rewriteConfigEnumOption(state,"maxmemory-policy",server.maxmemory_policy,maxmemory_policy_enum,CONFIG_DEFAULT_MAXMEMORY_POLICY);
rewriteConfigNumericalOption(state,"maxmemory-samples",server.maxmemory_samples,CONFIG_DEFAULT_MAXMEMORY_SAMPLES);
rewriteConfigNumericalOption(state,"lfu-log-factor",server.lfu_log_factor,CONFIG_DEFAULT_LFU_LOG_FACTOR);
rewriteConfigNumericalOption(state,"lfu-decay-time",server.lfu_decay_time,CONFIG_DEFAULT_LFU_DECAY_TIME);
rewriteConfigNumericalOption(state,"active-defrag-threshold-lower",server.active_defrag_threshold_lower,CONFIG_DEFAULT_DEFRAG_THRESHOLD_LOWER);
rewriteConfigNumericalOption(state,"active-defrag-threshold-upper",server.active_defrag_threshold_upper,CONFIG_DEFAULT_DEFRAG_THRESHOLD_UPPER);
rewriteConfigBytesOption(state,"active-defrag-ignore-bytes",server.active_defrag_ignore_bytes,CONFIG_DEFAULT_DEFRAG_IGNORE_BYTES);
rewriteConfigNumericalOption(state,"active-defrag-cycle-min",server.active_defrag_cycle_min,CONFIG_DEFAULT_DEFRAG_CYCLE_MIN);
rewriteConfigNumericalOption(state,"active-defrag-cycle-max",server.active_defrag_cycle_max,CONFIG_DEFAULT_DEFRAG_CYCLE_MAX);
rewriteConfigNumericalOption(state,"active-defrag-max-scan-fields",server.active_defrag_max_scan_fields,CONFIG_DEFAULT_DEFRAG_MAX_SCAN_FIELDS);
rewriteConfigYesNoOption(state,"appendonly",server.aof_state != AOF_OFF,0);
rewriteConfigStringOption(state,"appendfilename",server.aof_filename,CONFIG_DEFAULT_AOF_FILENAME);
rewriteConfigEnumOption(state,"appendfsync",server.aof_fsync,aof_fsync_enum,CONFIG_DEFAULT_AOF_FSYNC);
rewriteConfigYesNoOption(state,"no-appendfsync-on-rewrite",server.aof_no_fsync_on_rewrite,CONFIG_DEFAULT_AOF_NO_FSYNC_ON_REWRITE);
rewriteConfigNumericalOption(state,"auto-aof-rewrite-percentage",server.aof_rewrite_perc,AOF_REWRITE_PERC);
rewriteConfigBytesOption(state,"auto-aof-rewrite-min-size",server.aof_rewrite_min_size,AOF_REWRITE_MIN_SIZE);
rewriteConfigNumericalOption(state,"lua-time-limit",server.lua_time_limit,LUA_SCRIPT_TIME_LIMIT);
rewriteConfigYesNoOption(state,"cluster-enabled",server.cluster_enabled,0);
rewriteConfigStringOption(state,"cluster-config-file",server.cluster_configfile,CONFIG_DEFAULT_CLUSTER_CONFIG_FILE);
rewriteConfigYesNoOption(state,"cluster-require-full-coverage",server.cluster_require_full_coverage,CLUSTER_DEFAULT_REQUIRE_FULL_COVERAGE);
rewriteConfigYesNoOption(state,"cluster-replica-no-failover",server.cluster_slave_no_failover,CLUSTER_DEFAULT_SLAVE_NO_FAILOVER);
rewriteConfigNumericalOption(state,"cluster-node-timeout",server.cluster_node_timeout,CLUSTER_DEFAULT_NODE_TIMEOUT);
rewriteConfigNumericalOption(state,"cluster-migration-barrier",server.cluster_migration_barrier,CLUSTER_DEFAULT_MIGRATION_BARRIER);
rewriteConfigNumericalOption(state,"cluster-replica-validity-factor",server.cluster_slave_validity_factor,CLUSTER_DEFAULT_SLAVE_VALIDITY);
rewriteConfigNumericalOption(state,"slowlog-log-slower-than",server.slowlog_log_slower_than,CONFIG_DEFAULT_SLOWLOG_LOG_SLOWER_THAN);
rewriteConfigNumericalOption(state,"latency-monitor-threshold",server.latency_monitor_threshold,CONFIG_DEFAULT_LATENCY_MONITOR_THRESHOLD);
rewriteConfigNumericalOption(state,"slowlog-max-len",server.slowlog_max_len,CONFIG_DEFAULT_SLOWLOG_MAX_LEN);
rewriteConfigNotifykeyspaceeventsOption(state);
rewriteConfigNumericalOption(state,"hash-max-ziplist-entries",server.hash_max_ziplist_entries,OBJ_HASH_MAX_ZIPLIST_ENTRIES);
rewriteConfigNumericalOption(state,"hash-max-ziplist-value",server.hash_max_ziplist_value,OBJ_HASH_MAX_ZIPLIST_VALUE);
rewriteConfigNumericalOption(state,"stream-node-max-bytes",server.stream_node_max_bytes,OBJ_STREAM_NODE_MAX_BYTES);
rewriteConfigNumericalOption(state,"stream-node-max-entries",server.stream_node_max_entries,OBJ_STREAM_NODE_MAX_ENTRIES);
rewriteConfigNumericalOption(state,"list-max-ziplist-size",server.list_max_ziplist_size,OBJ_LIST_MAX_ZIPLIST_SIZE);
rewriteConfigNumericalOption(state,"list-compress-depth",server.list_compress_depth,OBJ_LIST_COMPRESS_DEPTH);
rewriteConfigNumericalOption(state,"set-max-intset-entries",server.set_max_intset_entries,OBJ_SET_MAX_INTSET_ENTRIES);
rewriteConfigNumericalOption(state,"zset-max-ziplist-entries",server.zset_max_ziplist_entries,OBJ_ZSET_MAX_ZIPLIST_ENTRIES);
rewriteConfigNumericalOption(state,"zset-max-ziplist-value",server.zset_max_ziplist_value,OBJ_ZSET_MAX_ZIPLIST_VALUE);
rewriteConfigNumericalOption(state,"hll-sparse-max-bytes",server.hll_sparse_max_bytes,CONFIG_DEFAULT_HLL_SPARSE_MAX_BYTES);
rewriteConfigYesNoOption(state,"activerehashing",server.activerehashing,CONFIG_DEFAULT_ACTIVE_REHASHING);
rewriteConfigYesNoOption(state,"activedefrag",server.active_defrag_enabled,CONFIG_DEFAULT_ACTIVE_DEFRAG);
rewriteConfigYesNoOption(state,"protected-mode",server.protected_mode,CONFIG_DEFAULT_PROTECTED_MODE);
rewriteConfigClientoutputbufferlimitOption(state);
rewriteConfigNumericalOption(state,"hz",server.config_hz,CONFIG_DEFAULT_HZ);
rewriteConfigYesNoOption(state,"aof-rewrite-incremental-fsync",server.aof_rewrite_incremental_fsync,CONFIG_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC);
rewriteConfigYesNoOption(state,"rdb-save-incremental-fsync",server.rdb_save_incremental_fsync,CONFIG_DEFAULT_RDB_SAVE_INCREMENTAL_FSYNC);
rewriteConfigYesNoOption(state,"aof-load-truncated",server.aof_load_truncated,CONFIG_DEFAULT_AOF_LOAD_TRUNCATED);
rewriteConfigYesNoOption(state,"aof-use-rdb-preamble",server.aof_use_rdb_preamble,CONFIG_DEFAULT_AOF_USE_RDB_PREAMBLE);
rewriteConfigEnumOption(state,"supervised",server.supervised_mode,supervised_mode_enum,SUPERVISED_NONE);
rewriteConfigYesNoOption(state,"lazyfree-lazy-eviction",server.lazyfree_lazy_eviction,CONFIG_DEFAULT_LAZYFREE_LAZY_EVICTION);
rewriteConfigYesNoOption(state,"lazyfree-lazy-expire",server.lazyfree_lazy_expire,CONFIG_DEFAULT_LAZYFREE_LAZY_EXPIRE);
rewriteConfigYesNoOption(state,"lazyfree-lazy-server-del",server.lazyfree_lazy_server_del,CONFIG_DEFAULT_LAZYFREE_LAZY_SERVER_DEL);
rewriteConfigYesNoOption(state,"replica-lazy-flush",server.repl_slave_lazy_flush,CONFIG_DEFAULT_SLAVE_LAZY_FLUSH);
rewriteConfigYesNoOption(state,"dynamic-hz",server.dynamic_hz,CONFIG_DEFAULT_DYNAMIC_HZ);
/* Rewrite Sentinel config if in Sentinel mode. */
if (server.sentinel_mode) rewriteConfigSentinelOption(state);
/* Step 3: remove all the orphaned lines in the old file, that is, lines
* that were used by a config option and are no longer used, like in case
* of multiple "save" options or duplicated options. */
rewriteConfigRemoveOrphaned(state);
/* Step 4: generate a new configuration file from the modified state
* and write it into the original file. */
newcontent = rewriteConfigGetContentFromState(state);
retval = rewriteConfigOverwriteFile(server.configfile,newcontent);
sdsfree(newcontent);
rewriteConfigReleaseState(state);
return retval;
}
/*-----------------------------------------------------------------------------
* CONFIG command entry point
*----------------------------------------------------------------------------*/
void configCommand(client *c) {
/* Only allow CONFIG GET while loading. */
if (server.loading && strcasecmp(c->argv[1]->ptr,"get")) {
addReplyError(c,"Only CONFIG GET is allowed during loading");
return;
}
if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"help")) {
const char *help[] = {
"GET <pattern> -- Return parameters matching the glob-like <pattern> and their values.",
"SET <parameter> <value> -- Set parameter to value.",
"RESETSTAT -- Reset statistics reported by INFO.",
"REWRITE -- Rewrite the configuration file.",
NULL
};
addReplyHelp(c, help);
} else if (!strcasecmp(c->argv[1]->ptr,"set") && c->argc == 4) {
configSetCommand(c);
} else if (!strcasecmp(c->argv[1]->ptr,"get") && c->argc == 3) {
configGetCommand(c);
} else if (!strcasecmp(c->argv[1]->ptr,"resetstat") && c->argc == 2) {
resetServerStats();
resetCommandTableStats();
addReply(c,shared.ok);
} else if (!strcasecmp(c->argv[1]->ptr,"rewrite") && c->argc == 2) {
if (server.configfile == NULL) {
addReplyError(c,"The server is running without a config file");
return;
}
if (rewriteConfig(server.configfile) == -1) {
serverLog(LL_WARNING,"CONFIG REWRITE failed: %s", strerror(errno));
addReplyErrorFormat(c,"Rewriting config file: %s", strerror(errno));
} else {
serverLog(LL_WARNING,"CONFIG REWRITE executed with success.");
addReply(c,shared.ok);
}
} else {
addReplySubcommandSyntaxError(c);
return;
}
}
|
222581.c | /**
* @file
*
* @brief Source for mathcheck plugin
*
* @copyright BSD License (see doc/LICENSE.md or http://www.libelektra.org)
*
*/
#ifndef HAVE_KDBCONFIG
#include "kdbconfig.h"
#endif
#include "floathelper.h"
#include "mathcheck.h"
#include <ctype.h>
#include <kdberrors.h>
#include <math.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MIN_VALID_STACK 3
#define EPSILON 0.00001
#define str(s) #s
#define xstr(s) str (s)
typedef enum {
ERROR = 0,
ADD = 1,
SUB = 2,
MUL = 3,
DIV = 4,
NOT = 5,
EQU = 6,
LT = 7,
GT = 8,
LE = 9,
GE = 10,
RES = 11,
VAL = 12,
END = 13,
SET = 14,
NA = 15,
EMPTY = 16
} Operation;
typedef struct
{
double value;
Operation op;
} PNElem;
int elektraMathcheckGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey)
{
if (!strcmp (keyName (parentKey), "system/elektra/modules/mathcheck"))
{
KeySet * contract = ksNew (
30, keyNew ("system/elektra/modules/mathcheck", KEY_VALUE, "mathcheck plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/mathcheck/exports", KEY_END),
keyNew ("system/elektra/modules/mathcheck/exports/get", KEY_FUNC, elektraMathcheckGet, KEY_END),
keyNew ("system/elektra/modules/mathcheck/exports/set", KEY_FUNC, elektraMathcheckSet, KEY_END),
#include ELEKTRA_README (mathcheck)
keyNew ("system/elektra/modules/mathcheck/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END),
keyNew ("system/elektra/modules/mathcheck/export/constants", KEY_END),
keyNew ("system/elektra/modules/mathcheck/export/constants/EPSILON", KEY_VALUE, xstr (EPSILON), KEY_END), KS_END);
ksAppend (returned, contract);
ksDel (contract);
return 1; /* success */
}
return 1; /* success */
}
static PNElem nextVal (const PNElem * stackPtr)
{
PNElem * ptr = (PNElem *)stackPtr;
PNElem result;
result.op = ERROR;
while (ptr->op != END)
{
if (ptr->op == VAL)
{
ptr->op = EMPTY;
result.op = VAL;
result.value = ptr->value;
break;
}
else if (ptr->op == NA)
{
ptr->op = EMPTY;
result.op = NA;
result.value = 0;
break;
}
++ptr;
}
return result;
}
static PNElem doPrefixCalculation (PNElem * stack, PNElem * stackPtr)
{
--stackPtr;
PNElem result;
if (stackPtr < stack)
{
result.op = ERROR;
}
while (stackPtr >= stack)
{
if ((stackPtr->op == VAL || stackPtr->op == NA) && stackPtr != stack)
{
--stackPtr;
continue;
}
else if ((stackPtr->op == VAL || stackPtr->op == NA) && stackPtr == stack)
{
break;
}
PNElem e1 = nextVal (stackPtr);
PNElem e2 = nextVal (stackPtr);
if (e1.op == NA)
{
if (stackPtr->op == ADD || stackPtr->op == SUB)
{
e1.value = 0;
e1.op = VAL;
}
else if (stackPtr->op == DIV || stackPtr->op == MUL)
{
e1.value = 1;
e1.op = VAL;
}
}
if (e2.op == NA)
{
if (stackPtr->op == ADD || stackPtr->op == SUB)
{
e2.value = 0;
e2.op = VAL;
}
else if (stackPtr->op == DIV || stackPtr->op == MUL)
{
e2.value = 1;
e2.op = VAL;
}
}
if (e1.op == VAL && e2.op == VAL)
{
switch (stackPtr->op)
{
case ADD:
stackPtr->value = e1.value + e2.value;
stackPtr->op = VAL;
break;
case SUB:
stackPtr->value = e1.value - e2.value;
stackPtr->op = VAL;
break;
case DIV:
if (e2.value < EPSILON)
{
result.op = ERROR;
return result;
}
stackPtr->value = e1.value / e2.value;
stackPtr->op = VAL;
break;
case MUL:
stackPtr->value = e1.value * e2.value;
stackPtr->op = VAL;
break;
default:
break;
}
result.op = stackPtr->op;
result.value = stackPtr->value;
}
else
{
return result;
}
}
if (stackPtr->op != VAL)
{
result.op = ERROR;
}
else
{
result.op = RES;
}
result.value = stackPtr->value;
return result;
}
static PNElem parsePrefixString (const char * prefixString, Key * curKey, KeySet * ks, Key * parentKey)
{
const char * regexString =
"(((((\\.)|(\\.\\.\\/)*|(@)|(\\/))([[:alnum:]]*/)*[[:alnum:]]+))|('[0-9]*[.,]{0,1}[0-9]*')|(==)|([-+:/<>=!{*]))";
char * ptr = (char *)prefixString;
regex_t regex;
Key * key;
PNElem * stack = elektraMalloc (MIN_VALID_STACK * sizeof (PNElem));
PNElem * stackPtr = stack;
PNElem result;
Operation resultOp = ERROR;
result.op = ERROR;
int ret;
if ((ret = regcomp (®ex, regexString, REG_EXTENDED | REG_NEWLINE)))
{
ksDel (ks);
return result;
}
regmatch_t match;
int nomatch;
int start;
int len;
char * searchKey = NULL;
while (1)
{
stackPtr->op = ERROR;
stackPtr->value = 0;
nomatch = regexec (®ex, ptr, 1, &match, 0);
if (nomatch)
{
break;
}
len = match.rm_eo - match.rm_so;
start = match.rm_so + (ptr - prefixString);
if (!strncmp (prefixString + start, "==", 2))
{
resultOp = EQU;
}
else if (len == 1 && !isalpha (prefixString[start]) && prefixString[start] != '\'' && prefixString[start] != '.' &&
prefixString[start] != '@')
{
switch (prefixString[start])
{
case '+':
stackPtr->op = ADD;
break;
case '-':
stackPtr->op = SUB;
break;
case '/':
stackPtr->op = DIV;
break;
case '*':
stackPtr->op = MUL;
break;
case ':':
resultOp = SET;
break;
case '=':
if (resultOp == LT)
{
resultOp = LE;
}
else if (resultOp == GT)
{
resultOp = GE;
}
else if (resultOp == ERROR)
{
resultOp = EQU;
}
else if (resultOp == EQU)
{
resultOp = EQU;
}
else if (resultOp == NOT)
{
resultOp = NOT;
}
else if (resultOp == SET)
{
resultOp = SET;
}
break;
case '<':
resultOp = LT;
break;
case '>':
resultOp = GT;
break;
case '!':
resultOp = NOT;
break;
default:
ELEKTRA_SET_ERRORF (122, parentKey, "%c isn't a valid operation", prefixString[start]);
regfree (®ex);
if (searchKey)
{
elektraFree (searchKey);
}
elektraFree (stack);
ksDel (ks);
return result;
break;
}
}
else
{
char * subString = elektraMalloc (len + 1);
strncpy (subString, prefixString + start, len);
subString[len] = '\0';
if (subString[0] == '\'' && subString[len - 1] == '\'')
{
subString[len - 1] = '\0';
char * subPtr = (subString + 1);
stackPtr->value = elektraEFtoF (subPtr);
elektraFree (subString);
}
else
{
ksRewind (ks);
if (subString[0] == '@')
{
searchKey = realloc (searchKey, len + 2 + strlen (keyName (parentKey)));
strcpy (searchKey, keyName (parentKey));
strcat (searchKey, "/");
strcat (searchKey, subString + 2);
}
else if (subString[0] == '.')
{
searchKey = realloc (searchKey, len + 2 + strlen (keyName (curKey)));
strcpy (searchKey, keyName (curKey));
strcat (searchKey, "/");
strcat (searchKey, subString);
}
else
{
searchKey = realloc (searchKey, len + 1);
strcpy (searchKey, subString);
}
key = ksLookupByName (ks, searchKey, 0);
if (!key)
{
stackPtr->value = 0;
stackPtr->op = NA;
}
else
{
stackPtr->value = elektraEFtoF (keyString (key));
}
elektraFree (subString);
}
if (stackPtr->op != NA) stackPtr->op = VAL;
}
++stackPtr;
int offset = stackPtr - stack;
stack = realloc (stack, (offset + 1) * sizeof (PNElem));
stackPtr = stack;
stackPtr += offset;
ptr += match.rm_eo;
}
regfree (®ex);
elektraFree (searchKey);
ksDel (ks);
stackPtr->op = END;
result = doPrefixCalculation (stack, stackPtr);
if (result.op != ERROR)
{
result.op = resultOp;
}
else
{
ELEKTRA_SET_ERRORF (122, parentKey, "%s\n", prefixString);
}
elektraFree (stack);
return result;
}
int elektraMathcheckSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
Key * cur;
const Key * meta;
PNElem result;
while ((cur = ksNext (returned)) != NULL)
{
meta = keyGetMeta (cur, "check/math");
if (!meta) continue;
result = parsePrefixString (keyString (meta), cur, ksDup (returned), parentKey);
char val1[MAX_CHARS_DOUBLE];
char val2[MAX_CHARS_DOUBLE];
strncpy (val1, keyString (cur), sizeof (val1));
elektraFtoA (val2, sizeof (val2), result.value);
if (result.op == ERROR)
{
return 1;
}
else if (result.op == EQU)
{
if (fabs (elektraEFtoF (keyString (cur)) - result.value) > EPSILON)
{
ELEKTRA_SET_ERRORF (123, parentKey, "%s != %s", val1, val2);
return -1;
}
}
else if (result.op == NOT)
{
if (fabs (elektraEFtoF (keyString (cur)) - result.value) < EPSILON)
{
ELEKTRA_SET_ERRORF (123, parentKey, "%s == %s but requirement was !=", val1, val2);
return -1;
}
}
else if (result.op == LT)
{
if (elektraEFtoF (keyString (cur)) >= result.value)
{
ELEKTRA_SET_ERRORF (123, parentKey, "%s not < %s", val1, val2);
return -1;
}
}
else if (result.op == GT)
{
if (elektraEFtoF (keyString (cur)) <= result.value)
{
ELEKTRA_SET_ERRORF (123, parentKey, "%s not > %s", val1, val2);
return -1;
}
}
else if (result.op == LE)
{
if (elektraEFtoF (keyString (cur)) > result.value)
{
ELEKTRA_SET_ERRORF (123, parentKey, "%s not <= %s", val1, val2);
return -1;
}
}
else if (result.op == GE)
{
if (elektraEFtoF (keyString (cur)) < result.value)
{
ELEKTRA_SET_ERRORF (123, parentKey, "%s not >= %s", val1, val2);
return -1;
}
}
else if (result.op == SET)
{
keySetString (cur, val2);
}
}
return 1; /* success */
}
Plugin * ELEKTRA_PLUGIN_EXPORT (mathcheck)
{
// clang-format off
return elektraPluginExport("mathcheck",
ELEKTRA_PLUGIN_GET, &elektraMathcheckGet,
ELEKTRA_PLUGIN_SET, &elektraMathcheckSet,
ELEKTRA_PLUGIN_END);
}
|
704912.c | /* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usb_device.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "math.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define BUFF 2
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
static uint16_t ADCBUFF[BUFF];
static uint16_t SPI_Buff[2 * BUFF];
static double carrier = 0.0;
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;
RTC_HandleTypeDef hrtc;
SPI_HandleTypeDef hspi2;
DMA_HandleTypeDef hdma_spi2_tx;
TIM_HandleTypeDef htim3;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_ADC1_Init(void);
static void MX_TIM3_Init(void);
static void MX_SPI2_Init(void);
static void MX_RTC_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void AD9833_tx(SPI_HandleTypeDef *hspi, uint16_t dt) {
static uint16_t data[1] = { 0 };
data[0] = dt;
//HAL_GPIO_WritePin(CS_GPIO_Port, CS_Pin, 0);
HAL_SPI_Transmit(hspi, &data[0], 1, HAL_MAX_DELAY);
//HAL_GPIO_WritePin(CS_GPIO_Port, CS_Pin, 1);
}
void AD9833_Init(SPI_HandleTypeDef *hspi) {
uint16_t data;
data = 0x21 << 8;
AD9833_tx(hspi, data);
}
uint64_t AD9833_freq_calc(uint64_t freq, uint64_t clk) {
static uint64_t ret;
static uint64_t retf;
retf = (freq * (2 << 27)) / clk;
ret = retf;
return ret;
}
void AD9833_set(SPI_HandleTypeDef *hspi, uint32_t freq, uint16_t phase,
uint8_t reset) {
static uint16_t fq1maskand = 0b0011111111111111;
static uint16_t fq1maskor = 0b0100000000000000;
static uint16_t ph1maskand = 0b1101111111111111;
static uint16_t ph1markor = 0b1100000000000000;
static uint16_t ftmask = 0b0011111111111111;
static uint16_t twmask = 0b0000111111111111;
static uint16_t fqlsb;
static uint16_t fqmsb;
static uint64_t FreqReg;
static uint16_t PhReg;
const uint64_t fmclk = 25000000;
if (reset)
AD9833_Init(hspi);
//FreqReg = (freq << 28) / fmclk;
FreqReg = AD9833_freq_calc(freq, fmclk);
fqlsb = FreqReg & ftmask;
fqmsb = (FreqReg >> 14) & ftmask;
fqlsb = fq1maskand & fqlsb;
fqlsb = fq1maskor | fqlsb;
fqmsb = fq1maskand & fqmsb;
fqmsb = fq1maskor | fqmsb;
PhReg = (phase * 2 * M_PI) / 4096;
PhReg &= twmask;
PhReg &= ph1maskand;
PhReg |= ph1markor;
AD9833_tx(hspi, fqlsb);
AD9833_tx(hspi, fqmsb);
AD9833_tx(hspi, PhReg);
if (reset)
AD9833_tx(hspi, 0x2000);
}
void AD9833_set_DMA(SPI_HandleTypeDef *hspi, uint32_t freq, uint16_t phase,
uint8_t reset) {
static uint16_t fq1maskand = 0b0011111111111111;
static uint16_t fq1maskor = 0b0100000000000000;
static uint16_t ph1maskand = 0b1101111111111111;
static uint16_t ph1markor = 0b1100000000000000;
static uint16_t ftmask = 0b0011111111111111;
static uint16_t twmask = 0b0000111111111111;
static uint16_t fqlsb;
static uint16_t fqmsb;
static uint64_t FreqReg;
static uint16_t PhReg;
const uint64_t fmclk = 25000000;
static uint16_t Tx_Buff[5] = { 0, 0, 0, 0, 0 };
static uint8_t i;
i = 0;
if (reset) {
Tx_Buff[i] = 0x2100;
i++;
}
//FreqReg = (freq << 28) / fmclk;
FreqReg = AD9833_freq_calc(freq, fmclk);
fqlsb = FreqReg & ftmask;
fqmsb = (FreqReg >> 14) & ftmask;
fqlsb = fq1maskand & fqlsb;
fqlsb = fq1maskor | fqlsb;
fqmsb = fq1maskand & fqmsb;
fqmsb = fq1maskor | fqmsb;
PhReg = (phase * 2 * M_PI) / 4096;
PhReg &= twmask;
PhReg &= ph1maskand;
PhReg |= ph1markor;
//AD9833_tx(hspi, fqlsb);
//AD9833_tx(hspi, fqmsb);
//AD9833_tx(hspi, PhReg);
Tx_Buff[i] = fqlsb;
i++;
Tx_Buff[i] = fqmsb;
i++;
Tx_Buff[i] = PhReg;
i++;
//Tx_Buff[i] = 0xC000;
//i++;
if (reset) {
Tx_Buff[i] = 0x2000;
i++;
}
HAL_SPI_Transmit_DMA(hspi, Tx_Buff, i);
}
void AD9833_set_DMA_reg(uint32_t freq, uint16_t *Tx_Buff) {
static uint16_t fq1maskand = 0b0011111111111111;
static uint16_t fq1maskor = 0b0100000000000000;
static uint16_t ftmask = 0b0011111111111111;
static uint16_t fqlsb;
static uint16_t fqmsb;
static uint64_t FreqReg;
const uint64_t fmclk = 25000000;
FreqReg = AD9833_freq_calc(freq, fmclk);
fqlsb = FreqReg & ftmask;
fqmsb = (FreqReg >> 14) & ftmask;
fqlsb = fq1maskand & fqlsb;
fqlsb = fq1maskor | fqlsb;
fqmsb = fq1maskand & fqmsb;
fqmsb = fq1maskor | fqmsb;
//Tx_Buff[0] = 0b1000000000000000;
//Tx_Buff[1] = 0b1000000000000000;
Tx_Buff[0] = fqlsb;
Tx_Buff[1] = fqmsb;
}
void HAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi) {
// do what you want , par example, un I/O toggle pour voir au scope si c'est ok
HAL_GPIO_WritePin(SPI_GPIO_Port, SPI_Pin, 0);
}
void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) {
// do what you want par example, un I/O toggle pour voir au scope si c'est ok
HAL_GPIO_WritePin(SPI_GPIO_Port, SPI_Pin, 1);
}
void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc) {
static uint16_t i;
i = 0;
while (i < BUFF / 2) {
//AD9833_set_DMA_reg(ADCBUFF[i], &SPI_Buff[2 * i]);
AD9833_set_DMA_reg(400, &SPI_Buff[2 * i]);
i++;
}
HAL_GPIO_WritePin(ADC_GPIO_Port, ADC_Pin, 1);
}
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) {
static uint16_t i;
i = BUFF / 2;
while (i < BUFF) {
//AD9833_set_DMA_reg(ADCBUFF[i], &SPI_Buff[2 * i]);
AD9833_set_DMA_reg(800, &SPI_Buff[2 * i]);
i++;
}
HAL_GPIO_WritePin(ADC_GPIO_Port, ADC_Pin, 0);
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_ADC1_Init();
MX_TIM3_Init();
MX_SPI2_Init();
MX_USB_DEVICE_Init();
MX_RTC_Init();
/* USER CODE BEGIN 2 */
//AD9833_set_DMA(&hspi2, 50.0, 0, 1);
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, 1);
AD9833_set(&hspi2, 1000000, 0, 1);
HAL_Delay(1000);
//AD9833_set_DMA(&hspi2, 50.0, 0, 1);
//HAL_TIM_Base_Start(&htim3);
HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_4);
HAL_TIM_OC_Start(&htim3, TIM_CHANNEL_1);
//HAL_SPI_Transmit_DMA(&hspi2, (uint8_t*) SPI_Buff, BUFF * 2);
HAL_Delay(5);
//HAL_ADC_Start_DMA(&hadc1, ADCBUFF, BUFF);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1) {
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
return 0;
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI|RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.LSIState = RCC_LSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC|RCC_PERIPHCLK_ADC
|RCC_PERIPHCLK_USB;
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6;
PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief ADC1 Initialization Function
* @param None
* @retval None
*/
static void MX_ADC1_Init(void)
{
/* USER CODE BEGIN ADC1_Init 0 */
/* USER CODE END ADC1_Init 0 */
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC1_Init 1 */
/* USER CODE END ADC1_Init 1 */
/** Common config
*/
hadc1.Instance = ADC1;
hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
hadc1.Init.ContinuousConvMode = DISABLE;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T3_TRGO;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.NbrOfConversion = 1;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_0;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_13CYCLES_5;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC1_Init 2 */
/* USER CODE END ADC1_Init 2 */
}
/**
* @brief RTC Initialization Function
* @param None
* @retval None
*/
static void MX_RTC_Init(void)
{
/* USER CODE BEGIN RTC_Init 0 */
/* USER CODE END RTC_Init 0 */
RTC_TimeTypeDef sTime = {0};
RTC_DateTypeDef DateToUpdate = {0};
/* USER CODE BEGIN RTC_Init 1 */
/* USER CODE END RTC_Init 1 */
/** Initialize RTC Only
*/
hrtc.Instance = RTC;
hrtc.Init.AsynchPrediv = RTC_AUTO_1_SECOND;
hrtc.Init.OutPut = RTC_OUTPUTSOURCE_NONE;
if (HAL_RTC_Init(&hrtc) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN Check_RTC_BKUP */
/* USER CODE END Check_RTC_BKUP */
/** Initialize RTC and set the Time and Date
*/
sTime.Hours = 0x0;
sTime.Minutes = 0x0;
sTime.Seconds = 0x0;
if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD) != HAL_OK)
{
Error_Handler();
}
DateToUpdate.WeekDay = RTC_WEEKDAY_MONDAY;
DateToUpdate.Month = RTC_MONTH_JANUARY;
DateToUpdate.Date = 0x1;
DateToUpdate.Year = 0x0;
if (HAL_RTC_SetDate(&hrtc, &DateToUpdate, RTC_FORMAT_BCD) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN RTC_Init 2 */
/* USER CODE END RTC_Init 2 */
}
/**
* @brief SPI2 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI2_Init(void)
{
/* USER CODE BEGIN SPI2_Init 0 */
/* USER CODE END SPI2_Init 0 */
/* USER CODE BEGIN SPI2_Init 1 */
/* USER CODE END SPI2_Init 1 */
/* SPI2 parameter configuration*/
hspi2.Instance = SPI2;
hspi2.Init.Mode = SPI_MODE_MASTER;
hspi2.Init.Direction = SPI_DIRECTION_2LINES;
hspi2.Init.DataSize = SPI_DATASIZE_16BIT;
hspi2.Init.CLKPolarity = SPI_POLARITY_HIGH;
hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi2.Init.NSS = SPI_NSS_HARD_OUTPUT;
hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi2.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI2_Init 2 */
/* USER CODE END SPI2_Init 2 */
}
/**
* @brief TIM3 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM3_Init(void)
{
/* USER CODE BEGIN TIM3_Init 0 */
/* USER CODE END TIM3_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM3_Init 1 */
/* USER CODE END TIM3_Init 1 */
htim3.Instance = TIM3;
htim3.Init.Prescaler = 1023;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = 1;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_OC_Init(&htim3) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_Init(&htim3) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_ENABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_ACTIVE;
sConfigOC.Pulse = 1;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_OC_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM3_Init 2 */
/* USER CODE END TIM3_Init 2 */
HAL_TIM_MspPostInit(&htim3);
}
/**
* Enable DMA controller clock
*/
static void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
/* DMA1_Channel5_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel5_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel5_IRQn);
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, ADC_Pin|SPI_Pin, GPIO_PIN_SET);
/*Configure GPIO pin : LED_Pin */
GPIO_InitStruct.Pin = LED_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(LED_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : ADC_Pin SPI_Pin */
GPIO_InitStruct.Pin = ADC_Pin|SPI_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
950049.c | #include<stdio.h>
int main(){
int n;
printf("Enter size: ");
scanf("%d",&n);
int a[n];
for (int i=0; i<n; i++){
scanf("%d",&a[i]);
}
printf("\nEven numbers: ");
for(int i=0; i<n; i++){
if(a[i]%2==0) printf("%d ",a[i]);
}
printf("\nOdd numbers: ");
for(int i=0; i<n; i++){
if(a[i]%2!=0) printf("%d ",a[i]);
}
printf("\n");
return 0;
}
// (or another aproach)
// int n;
// printf("Enter size: ");
// scanf("%d",&n);
// int a[n], even[n], odd[n];
// for (int i=0; i<n; i++){
// scanf("%d",&a[i]);
// even[i]=0; odd[i]=0;
// if(a[i]%2==0){ even[i] = a[i]; }
// else { odd[i] = a[i]; }
// }
// printf("\nEven numbers: ");
// for(int i=0; i<n; i++){
// if(even[i]!=0) printf("%d ",even[i]);
// }
// printf("\nOdd numbers: ");
// for(int i=0; i<n; i++){
// if(odd[i]!=0) printf("%d ",odd[i]);
// }
|
685663.c | /* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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 "ecma-bigint.h"
#include "ecma-builtins.h"
#include "ecma-exceptions.h"
#if ENABLED (JERRY_BUILTIN_BIGINT)
#define ECMA_BUILTINS_INTERNAL
#include "ecma-builtins-internal.h"
#define BUILTIN_INC_HEADER_NAME "ecma-builtin-bigint.inc.h"
#define BUILTIN_UNDERSCORED_ID bigint
#include "ecma-builtin-internal-routines-template.inc.h"
/** \addtogroup ecma ECMA
* @{
*
* \addtogroup ecmabuiltins
* @{
*
* \addtogroup bigint ECMA BigInt object built-in
* @{
*/
/**
* Handle calling [[Call]] of built-in BigInt object
*
* See also:
* ECMA-262 v11, 20.2.1.1
*
* @return ecma value
*/
ecma_value_t
ecma_builtin_bigint_dispatch_call (const ecma_value_t *arguments_list_p, /**< arguments list */
uint32_t arguments_list_len) /**< number of arguments */
{
JERRY_ASSERT (arguments_list_len == 0 || arguments_list_p != NULL);
ecma_value_t value = (arguments_list_len == 0) ? ECMA_VALUE_UNDEFINED : arguments_list_p[0];
if (!ecma_is_value_string (value))
{
return ecma_raise_type_error (ECMA_ERR_MSG ("TODO: Only strings are supported now"));
}
ecma_string_t *string_p = ecma_get_string_from_value (value);
ECMA_STRING_TO_UTF8_STRING (string_p, string_buffer_p, string_buffer_size);
ecma_value_t result = ecma_bigint_parse_string (string_buffer_p, string_buffer_size);
ECMA_FINALIZE_UTF8_STRING (string_buffer_p, string_buffer_size);
return result;
} /* ecma_builtin_bigint_dispatch_call */
/**
* Handle calling [[Construct]] of built-in BigInt object
*
* See also:
* ECMA-262 v11, 20.2.1
*
* @return ecma value
*/
ecma_value_t
ecma_builtin_bigint_dispatch_construct (const ecma_value_t *arguments_list_p, /**< arguments list */
uint32_t arguments_list_len) /**< number of arguments */
{
JERRY_ASSERT (arguments_list_len == 0 || arguments_list_p != NULL);
return ecma_raise_type_error (ECMA_ERR_MSG ("BigInt function is not a constructor."));
} /* ecma_builtin_bigint_dispatch_construct */
/**
* @}
* @}
* @}
*/
#endif /* ENABLED (JERRY_BUILTIN_BIGINT) */
|
939983.c | /*-
* Copyright 2016 Vsevolod Stakhov
*
* 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 "config.h"
#include "printf.h"
#include "message.h"
#include "util.h"
#include "content_type.h"
#include "task.h"
#include "mime_parser.h"
#include "unix-std.h"
#define MODE_NORMAL 0
#define MODE_GMIME 1
static gdouble total_time = 0.0;
static void
rspamd_show_normal (struct rspamd_mime_part *part)
{
rspamd_printf ("got normal part %p: parent: %p, type: %T/%T,"
"length: %z (%z raw)\n",
part, part->parent_part,
&part->ct->type, &part->ct->subtype,
part->parsed_data.len,
part->raw_data.len);
}
static void
rspamd_show_multipart (struct rspamd_mime_part *part)
{
struct rspamd_mime_part *cur;
guint i;
rspamd_printf ("got multipart part %p, boundary: %T: parent: %p, type: %T/%T, children: [",
part, &part->ct->boundary,
part->parent_part,
&part->ct->type, &part->ct->subtype);
if (part->specific.mp.children) {
for (i = 0; i < part->specific.mp.children->len; i ++) {
cur = g_ptr_array_index (part->specific.mp.children, i);
if (i != 0) {
rspamd_printf (", %p{%T/%T}", cur,
&cur->ct->type, &cur->ct->subtype);
}
else {
rspamd_printf ("%p{%T/%T}", cur,
&cur->ct->type, &cur->ct->subtype);
}
}
}
rspamd_printf ("]\n");
}
static void
rspamd_show_message (struct rspamd_mime_part *part)
{
rspamd_printf ("got message part %p: parent: %p\n",
part, part->parent_part);
}
#if 0
static void
mime_foreach_callback (GMimeObject * parent,
GMimeObject * part,
gpointer user_data)
{
GMimeContentType *type;
if (GMIME_IS_MESSAGE_PART (part)) {
/* message/rfc822 or message/news */
GMimeMessage *message;
/* g_mime_message_foreach_part() won't descend into
child message parts, so if we want to count any
subparts of this child message, we'll have to call
g_mime_message_foreach_part() again here. */
rspamd_printf ("got message part %p: parent: %p\n",
part, parent);
message = g_mime_message_part_get_message ((GMimeMessagePart *) part);
g_mime_message_foreach (message, mime_foreach_callback, part);
}
else if (GMIME_IS_MULTIPART (part)) {
type = (GMimeContentType *) g_mime_object_get_content_type (GMIME_OBJECT (
part));
rspamd_printf ("got multipart part %p, boundary: %s: parent: %p, type: %s/%s\n",
part, g_mime_multipart_get_boundary (GMIME_MULTIPART(part)),
parent,
g_mime_content_type_get_media_type (type),
g_mime_content_type_get_media_subtype (type));
}
else {
type = (GMimeContentType *) g_mime_object_get_content_type (GMIME_OBJECT (
part));
rspamd_printf ("got normal part %p, parent: %p, type: %s/%s\n",
part,
parent,
g_mime_content_type_get_media_type (type),
g_mime_content_type_get_media_subtype (type));
}
}
#endif
static void
rspamd_process_file (struct rspamd_config *cfg, const gchar *fname, gint mode)
{
struct rspamd_task *task;
gint fd;
gpointer map;
struct stat st;
GError *err = NULL;
#if 0
GMimeMessage *message;
GMimeParser *parser;
GMimeStream *stream;
GByteArray tmp;
#endif
struct rspamd_mime_part *part;
guint i;
gdouble ts1, ts2;
fd = open (fname, O_RDONLY);
if (fd == -1) {
rspamd_fprintf (stderr, "cannot open %s: %s\n", fname, strerror (errno));
exit (EXIT_FAILURE);
}
if (fstat (fd, &st) == -1) {
rspamd_fprintf (stderr, "cannot stat %s: %s\n", fname, strerror (errno));
exit (EXIT_FAILURE);
}
map = mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
close (fd);
if (map == MAP_FAILED) {
rspamd_fprintf (stderr, "cannot mmap %s: %s\n", fname, strerror (errno));
exit (EXIT_FAILURE);
}
task = rspamd_task_new (NULL, cfg, NULL);
task->msg.begin = map;
task->msg.len = st.st_size;
ts1 = rspamd_get_ticks ();
if (mode == MODE_NORMAL) {
if (!rspamd_mime_parse_task (task, &err)) {
rspamd_fprintf (stderr, "cannot parse %s: %e\n", fname, err);
g_error_free (err);
}
}
#if 0
else if (mode == MODE_GMIME) {
tmp.data = map;
tmp.len = st.st_size;
stream = g_mime_stream_mem_new_with_byte_array (&tmp);
g_mime_stream_mem_set_owner (GMIME_STREAM_MEM (stream), FALSE);
parser = g_mime_parser_new_with_stream (stream);
message = g_mime_parser_construct_message (parser);
}
#endif
ts2 = rspamd_get_ticks ();
total_time += ts2 - ts1;
if (mode == MODE_NORMAL) {
for (i = 0; i < task->parts->len; i ++) {
part = g_ptr_array_index (task->parts, i);
if (part->ct->flags & RSPAMD_CONTENT_TYPE_MULTIPART) {
rspamd_show_multipart (part);
}
else if (part->ct->flags & RSPAMD_CONTENT_TYPE_MESSAGE) {
rspamd_show_message (part);
}
else {
rspamd_show_normal (part);
}
}
}
#if 0
else if (mode == MODE_GMIME) {
g_mime_message_foreach (message, mime_foreach_callback, NULL);
}
#endif
rspamd_task_free (task);
munmap (map, st.st_size);
#if 0
if (mode == MODE_GMIME) {
g_object_unref (message);
}
#endif
}
int
main (int argc, char **argv)
{
gint i, start = 1, mode = MODE_NORMAL;
struct rspamd_config *cfg;
rspamd_logger_t *logger = NULL;
if (argc > 2 && *argv[1] == '-') {
start = 2;
if (argv[1][1] == 'g') {
mode = MODE_GMIME;
}
}
cfg = rspamd_config_new ();
cfg->libs_ctx = rspamd_init_libs ();
cfg->log_type = RSPAMD_LOG_CONSOLE;
rspamd_set_logger (cfg, g_quark_from_static_string ("mime"), &logger, NULL);
(void) rspamd_log_open (logger);
g_log_set_default_handler (rspamd_glib_log_function, logger);
g_set_printerr_handler (rspamd_glib_printerr_function);
rspamd_config_post_load (cfg,
RSPAMD_CONFIG_INIT_LIBS|RSPAMD_CONFIG_INIT_URL|RSPAMD_CONFIG_INIT_NO_TLD);
for (i = start; i < argc; i ++) {
if (argv[i]) {
rspamd_process_file (cfg, argv[i], mode);
}
}
rspamd_printf ("Total time parsing: %.4f seconds\n", total_time);
rspamd_log_close (logger);
REF_RELEASE (cfg);
return 0;
}
|
3728.c | /* ****************************************************************************
* Copyright (C) 2017 Maxim Integrated Products, Inc., All Rights Reserved.
*
* 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 MAXIM INTEGRATED 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 Maxim Integrated
* Products, Inc. shall not be used except as stated in the Maxim Integrated
* Products, Inc. Branding Policy.
*
* The mere transfer of this software does not imply any licenses
* of trade secrets, proprietary technology, copyrights, patents,
* trademarks, maskwork rights, or any other form of intellectual
* property whatsoever. Maxim Integrated Products, Inc. retains all
* ownership rights.
*
* $Date: 2018-08-28 17:03:02 -0500 (Tue, 28 Aug 2018) $
* $Revision: 37424 $
*
*************************************************************************** */
/****** Includes *******/
#include <stddef.h>
#include <stdint.h>
#include "mxc_device.h"
#include "mxc_assert.h"
#include "mxc_lock.h"
#include "mxc_sys.h"
#include "dma.h"
#include "dma_reva.h"
/***** Definitions *****/
/******* Globals *******/
/****** Functions ******/
int MXC_DMA_Init(void)
{
if(!MXC_SYS_IsClockEnabled(MXC_SYS_PERIPH_CLOCK_DMA)) {
MXC_SYS_ClockEnable(MXC_SYS_PERIPH_CLOCK_DMA);
MXC_SYS_Reset_Periph(MXC_SYS_RESET0_DMA);
}
return MXC_DMA_RevA_Init((mxc_dma_reva_regs_t*) MXC_DMA);
}
int MXC_DMA_AcquireChannel(void)
{
return MXC_DMA_RevA_AcquireChannel((mxc_dma_reva_regs_t*) MXC_DMA);
}
int MXC_DMA_ReleaseChannel(int ch)
{
return MXC_DMA_RevA_ReleaseChannel(ch);
}
int MXC_DMA_ConfigChannel(mxc_dma_config_t config, mxc_dma_srcdst_t srcdst)
{
return MXC_DMA_RevA_ConfigChannel(config, srcdst);
}
int MXC_DMA_AdvConfigChannel(mxc_dma_adv_config_t advConfig)
{
return MXC_DMA_RevA_AdvConfigChannel(advConfig);
}
int MXC_DMA_SetSrcDst(mxc_dma_srcdst_t srcdst)
{
return MXC_DMA_RevA_SetSrcDst(srcdst);
}
int MXC_DMA_GetSrcDst(mxc_dma_srcdst_t* srcdst)
{
return MXC_DMA_RevA_GetSrcDst(srcdst);
}
int MXC_DMA_SetSrcReload(mxc_dma_srcdst_t srcdst)
{
return MXC_DMA_RevA_SetSrcReload(srcdst);
}
int MXC_DMA_GetSrcReload(mxc_dma_srcdst_t* srcdst)
{
return MXC_DMA_RevA_GetSrcReload(srcdst);
}
int MXC_DMA_SetCallback(int ch, void (*callback)(int, int))
{
return MXC_DMA_RevA_SetCallback(ch, callback);
}
int MXC_DMA_SetChannelInterruptEn(int ch, bool chdis, bool ctz)
{
return MXC_DMA_RevA_SetChannelInterruptEn(ch, chdis, ctz);
}
int MXC_DMA_ChannelEnableInt(int ch, int flags)
{
return MXC_DMA_RevA_ChannelEnableInt(ch, flags);
}
int MXC_DMA_ChannelDisableInt(int ch, int flags)
{
return MXC_DMA_RevA_ChannelDisableInt(ch, flags);
}
int MXC_DMA_ChannelGetFlags(int ch)
{
return MXC_DMA_RevA_ChannelGetFlags(ch);
}
int MXC_DMA_ChannelClearFlags(int ch, int flags)
{
return MXC_DMA_RevA_ChannelClearFlags(ch, flags);
}
int MXC_DMA_EnableInt(int ch)
{
return MXC_DMA_RevA_EnableInt((mxc_dma_reva_regs_t*) MXC_DMA, ch);
}
int MXC_DMA_DisableInt(int ch)
{
return MXC_DMA_RevA_DisableInt((mxc_dma_reva_regs_t*) MXC_DMA, ch);
}
int MXC_DMA_Start(int ch)
{
return MXC_DMA_RevA_Start(ch);
}
int MXC_DMA_Stop(int ch)
{
return MXC_DMA_RevA_Stop(ch);
}
mxc_dma_ch_regs_t* MXC_DMA_GetCHRegs(int ch)
{
return MXC_DMA_RevA_GetCHRegs(ch);
}
void MXC_DMA_Handler(void)
{
return MXC_DMA_RevA_Handler((mxc_dma_reva_regs_t*) MXC_DMA);
}
int MXC_DMA_MemCpy(void* dest, void* src, int len, mxc_dma_complete_cb_t callback)
{
return MXC_DMA_RevA_MemCpy((mxc_dma_reva_regs_t*) MXC_DMA, dest, src, len, callback);
}
int MXC_DMA_DoTransfer(mxc_dma_config_t config, mxc_dma_srcdst_t firstSrcDst, mxc_dma_trans_chain_t callback)
{
return MXC_DMA_RevA_DoTransfer((mxc_dma_reva_regs_t*) MXC_DMA, config, firstSrcDst, callback);
}
|
583940.c | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* TI BQ25890 charger driver
*
* Copyright (C) 2015 Intel Corporation
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/power_supply.h>
#include <linux/regmap.h>
#include <linux/types.h>
#include <linux/gpio/consumer.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/usb/phy.h>
#include <linux/acpi.h>
#include <linux/of.h>
#define BQ25890_MANUFACTURER "Texas Instruments"
#define BQ25890_IRQ_PIN "bq25890_irq"
#define BQ25890_ID 3
#define BQ25895_ID 7
#define BQ25896_ID 0
enum bq25890_fields {
F_EN_HIZ, F_EN_ILIM, F_IILIM, /* Reg00 */
F_BHOT, F_BCOLD, F_VINDPM_OFS, /* Reg01 */
F_CONV_START, F_CONV_RATE, F_BOOSTF, F_ICO_EN,
F_HVDCP_EN, F_MAXC_EN, F_FORCE_DPM, F_AUTO_DPDM_EN, /* Reg02 */
F_BAT_LOAD_EN, F_WD_RST, F_OTG_CFG, F_CHG_CFG, F_SYSVMIN, /* Reg03 */
F_PUMPX_EN, F_ICHG, /* Reg04 */
F_IPRECHG, F_ITERM, /* Reg05 */
F_VREG, F_BATLOWV, F_VRECHG, /* Reg06 */
F_TERM_EN, F_STAT_DIS, F_WD, F_TMR_EN, F_CHG_TMR,
F_JEITA_ISET, /* Reg07 */
F_BATCMP, F_VCLAMP, F_TREG, /* Reg08 */
F_FORCE_ICO, F_TMR2X_EN, F_BATFET_DIS, F_JEITA_VSET,
F_BATFET_DLY, F_BATFET_RST_EN, F_PUMPX_UP, F_PUMPX_DN, /* Reg09 */
F_BOOSTV, F_BOOSTI, /* Reg0A */
F_VBUS_STAT, F_CHG_STAT, F_PG_STAT, F_SDP_STAT, F_VSYS_STAT, /* Reg0B */
F_WD_FAULT, F_BOOST_FAULT, F_CHG_FAULT, F_BAT_FAULT,
F_NTC_FAULT, /* Reg0C */
F_FORCE_VINDPM, F_VINDPM, /* Reg0D */
F_THERM_STAT, F_BATV, /* Reg0E */
F_SYSV, /* Reg0F */
F_TSPCT, /* Reg10 */
F_VBUS_GD, F_VBUSV, /* Reg11 */
F_ICHGR, /* Reg12 */
F_VDPM_STAT, F_IDPM_STAT, F_IDPM_LIM, /* Reg13 */
F_REG_RST, F_ICO_OPTIMIZED, F_PN, F_TS_PROFILE, F_DEV_REV, /* Reg14 */
F_MAX_FIELDS
};
/* initial field values, converted to register values */
struct bq25890_init_data {
u8 ichg; /* charge current */
u8 vreg; /* regulation voltage */
u8 iterm; /* termination current */
u8 iprechg; /* precharge current */
u8 sysvmin; /* minimum system voltage limit */
u8 boostv; /* boost regulation voltage */
u8 boosti; /* boost current limit */
u8 boostf; /* boost frequency */
u8 ilim_en; /* enable ILIM pin */
u8 treg; /* thermal regulation threshold */
};
struct bq25890_state {
u8 online;
u8 chrg_status;
u8 chrg_fault;
u8 vsys_status;
u8 boost_fault;
u8 bat_fault;
};
struct bq25890_device {
struct i2c_client *client;
struct device *dev;
struct power_supply *charger;
struct usb_phy *usb_phy;
struct notifier_block usb_nb;
struct work_struct usb_work;
unsigned long usb_event;
struct regmap *rmap;
struct regmap_field *rmap_fields[F_MAX_FIELDS];
int chip_id;
struct bq25890_init_data init_data;
struct bq25890_state state;
struct mutex lock; /* protect state data */
};
static const struct regmap_range bq25890_readonly_reg_ranges[] = {
regmap_reg_range(0x0b, 0x0c),
regmap_reg_range(0x0e, 0x13),
};
static const struct regmap_access_table bq25890_writeable_regs = {
.no_ranges = bq25890_readonly_reg_ranges,
.n_no_ranges = ARRAY_SIZE(bq25890_readonly_reg_ranges),
};
static const struct regmap_range bq25890_volatile_reg_ranges[] = {
regmap_reg_range(0x00, 0x00),
regmap_reg_range(0x09, 0x09),
regmap_reg_range(0x0b, 0x0c),
regmap_reg_range(0x0e, 0x14),
};
static const struct regmap_access_table bq25890_volatile_regs = {
.yes_ranges = bq25890_volatile_reg_ranges,
.n_yes_ranges = ARRAY_SIZE(bq25890_volatile_reg_ranges),
};
static const struct regmap_config bq25890_regmap_config = {
.reg_bits = 8,
.val_bits = 8,
.max_register = 0x14,
.cache_type = REGCACHE_RBTREE,
.wr_table = &bq25890_writeable_regs,
.volatile_table = &bq25890_volatile_regs,
};
static const struct reg_field bq25890_reg_fields[] = {
/* REG00 */
[F_EN_HIZ] = REG_FIELD(0x00, 7, 7),
[F_EN_ILIM] = REG_FIELD(0x00, 6, 6),
[F_IILIM] = REG_FIELD(0x00, 0, 5),
/* REG01 */
[F_BHOT] = REG_FIELD(0x01, 6, 7),
[F_BCOLD] = REG_FIELD(0x01, 5, 5),
[F_VINDPM_OFS] = REG_FIELD(0x01, 0, 4),
/* REG02 */
[F_CONV_START] = REG_FIELD(0x02, 7, 7),
[F_CONV_RATE] = REG_FIELD(0x02, 6, 6),
[F_BOOSTF] = REG_FIELD(0x02, 5, 5),
[F_ICO_EN] = REG_FIELD(0x02, 4, 4),
[F_HVDCP_EN] = REG_FIELD(0x02, 3, 3), // reserved on BQ25896
[F_MAXC_EN] = REG_FIELD(0x02, 2, 2), // reserved on BQ25896
[F_FORCE_DPM] = REG_FIELD(0x02, 1, 1),
[F_AUTO_DPDM_EN] = REG_FIELD(0x02, 0, 0),
/* REG03 */
[F_BAT_LOAD_EN] = REG_FIELD(0x03, 7, 7),
[F_WD_RST] = REG_FIELD(0x03, 6, 6),
[F_OTG_CFG] = REG_FIELD(0x03, 5, 5),
[F_CHG_CFG] = REG_FIELD(0x03, 4, 4),
[F_SYSVMIN] = REG_FIELD(0x03, 1, 3),
/* MIN_VBAT_SEL on BQ25896 */
/* REG04 */
[F_PUMPX_EN] = REG_FIELD(0x04, 7, 7),
[F_ICHG] = REG_FIELD(0x04, 0, 6),
/* REG05 */
[F_IPRECHG] = REG_FIELD(0x05, 4, 7),
[F_ITERM] = REG_FIELD(0x05, 0, 3),
/* REG06 */
[F_VREG] = REG_FIELD(0x06, 2, 7),
[F_BATLOWV] = REG_FIELD(0x06, 1, 1),
[F_VRECHG] = REG_FIELD(0x06, 0, 0),
/* REG07 */
[F_TERM_EN] = REG_FIELD(0x07, 7, 7),
[F_STAT_DIS] = REG_FIELD(0x07, 6, 6),
[F_WD] = REG_FIELD(0x07, 4, 5),
[F_TMR_EN] = REG_FIELD(0x07, 3, 3),
[F_CHG_TMR] = REG_FIELD(0x07, 1, 2),
[F_JEITA_ISET] = REG_FIELD(0x07, 0, 0), // reserved on BQ25895
/* REG08 */
[F_BATCMP] = REG_FIELD(0x08, 5, 7),
[F_VCLAMP] = REG_FIELD(0x08, 2, 4),
[F_TREG] = REG_FIELD(0x08, 0, 1),
/* REG09 */
[F_FORCE_ICO] = REG_FIELD(0x09, 7, 7),
[F_TMR2X_EN] = REG_FIELD(0x09, 6, 6),
[F_BATFET_DIS] = REG_FIELD(0x09, 5, 5),
[F_JEITA_VSET] = REG_FIELD(0x09, 4, 4), // reserved on BQ25895
[F_BATFET_DLY] = REG_FIELD(0x09, 3, 3),
[F_BATFET_RST_EN] = REG_FIELD(0x09, 2, 2),
[F_PUMPX_UP] = REG_FIELD(0x09, 1, 1),
[F_PUMPX_DN] = REG_FIELD(0x09, 0, 0),
/* REG0A */
[F_BOOSTV] = REG_FIELD(0x0A, 4, 7),
/* PFM_OTG_DIS 3 on BQ25896 */
[F_BOOSTI] = REG_FIELD(0x0A, 0, 2), // reserved on BQ25895
/* REG0B */
[F_VBUS_STAT] = REG_FIELD(0x0B, 5, 7),
[F_CHG_STAT] = REG_FIELD(0x0B, 3, 4),
[F_PG_STAT] = REG_FIELD(0x0B, 2, 2),
[F_SDP_STAT] = REG_FIELD(0x0B, 1, 1), // reserved on BQ25896
[F_VSYS_STAT] = REG_FIELD(0x0B, 0, 0),
/* REG0C */
[F_WD_FAULT] = REG_FIELD(0x0C, 7, 7),
[F_BOOST_FAULT] = REG_FIELD(0x0C, 6, 6),
[F_CHG_FAULT] = REG_FIELD(0x0C, 4, 5),
[F_BAT_FAULT] = REG_FIELD(0x0C, 3, 3),
[F_NTC_FAULT] = REG_FIELD(0x0C, 0, 2),
/* REG0D */
[F_FORCE_VINDPM] = REG_FIELD(0x0D, 7, 7),
[F_VINDPM] = REG_FIELD(0x0D, 0, 6),
/* REG0E */
[F_THERM_STAT] = REG_FIELD(0x0E, 7, 7),
[F_BATV] = REG_FIELD(0x0E, 0, 6),
/* REG0F */
[F_SYSV] = REG_FIELD(0x0F, 0, 6),
/* REG10 */
[F_TSPCT] = REG_FIELD(0x10, 0, 6),
/* REG11 */
[F_VBUS_GD] = REG_FIELD(0x11, 7, 7),
[F_VBUSV] = REG_FIELD(0x11, 0, 6),
/* REG12 */
[F_ICHGR] = REG_FIELD(0x12, 0, 6),
/* REG13 */
[F_VDPM_STAT] = REG_FIELD(0x13, 7, 7),
[F_IDPM_STAT] = REG_FIELD(0x13, 6, 6),
[F_IDPM_LIM] = REG_FIELD(0x13, 0, 5),
/* REG14 */
[F_REG_RST] = REG_FIELD(0x14, 7, 7),
[F_ICO_OPTIMIZED] = REG_FIELD(0x14, 6, 6),
[F_PN] = REG_FIELD(0x14, 3, 5),
[F_TS_PROFILE] = REG_FIELD(0x14, 2, 2),
[F_DEV_REV] = REG_FIELD(0x14, 0, 1)
};
/*
* Most of the val -> idx conversions can be computed, given the minimum,
* maximum and the step between values. For the rest of conversions, we use
* lookup tables.
*/
enum bq25890_table_ids {
/* range tables */
TBL_ICHG,
TBL_ITERM,
TBL_VREG,
TBL_BOOSTV,
TBL_SYSVMIN,
/* lookup tables */
TBL_TREG,
TBL_BOOSTI,
};
/* Thermal Regulation Threshold lookup table, in degrees Celsius */
static const u32 bq25890_treg_tbl[] = { 60, 80, 100, 120 };
#define BQ25890_TREG_TBL_SIZE ARRAY_SIZE(bq25890_treg_tbl)
/* Boost mode current limit lookup table, in uA */
static const u32 bq25890_boosti_tbl[] = {
500000, 700000, 1100000, 1300000, 1600000, 1800000, 2100000, 2400000
};
#define BQ25890_BOOSTI_TBL_SIZE ARRAY_SIZE(bq25890_boosti_tbl)
struct bq25890_range {
u32 min;
u32 max;
u32 step;
};
struct bq25890_lookup {
const u32 *tbl;
u32 size;
};
static const union {
struct bq25890_range rt;
struct bq25890_lookup lt;
} bq25890_tables[] = {
/* range tables */
[TBL_ICHG] = { .rt = {0, 5056000, 64000} }, /* uA */
[TBL_ITERM] = { .rt = {64000, 1024000, 64000} }, /* uA */
[TBL_VREG] = { .rt = {3840000, 4608000, 16000} }, /* uV */
[TBL_BOOSTV] = { .rt = {4550000, 5510000, 64000} }, /* uV */
[TBL_SYSVMIN] = { .rt = {3000000, 3700000, 100000} }, /* uV */
/* lookup tables */
[TBL_TREG] = { .lt = {bq25890_treg_tbl, BQ25890_TREG_TBL_SIZE} },
[TBL_BOOSTI] = { .lt = {bq25890_boosti_tbl, BQ25890_BOOSTI_TBL_SIZE} }
};
static int bq25890_field_read(struct bq25890_device *bq,
enum bq25890_fields field_id)
{
int ret;
int val;
ret = regmap_field_read(bq->rmap_fields[field_id], &val);
if (ret < 0)
return ret;
return val;
}
static int bq25890_field_write(struct bq25890_device *bq,
enum bq25890_fields field_id, u8 val)
{
return regmap_field_write(bq->rmap_fields[field_id], val);
}
static u8 bq25890_find_idx(u32 value, enum bq25890_table_ids id)
{
u8 idx;
if (id >= TBL_TREG) {
const u32 *tbl = bq25890_tables[id].lt.tbl;
u32 tbl_size = bq25890_tables[id].lt.size;
for (idx = 1; idx < tbl_size && tbl[idx] <= value; idx++)
;
} else {
const struct bq25890_range *rtbl = &bq25890_tables[id].rt;
u8 rtbl_size;
rtbl_size = (rtbl->max - rtbl->min) / rtbl->step + 1;
for (idx = 1;
idx < rtbl_size && (idx * rtbl->step + rtbl->min <= value);
idx++)
;
}
return idx - 1;
}
static u32 bq25890_find_val(u8 idx, enum bq25890_table_ids id)
{
const struct bq25890_range *rtbl;
/* lookup table? */
if (id >= TBL_TREG)
return bq25890_tables[id].lt.tbl[idx];
/* range table */
rtbl = &bq25890_tables[id].rt;
return (rtbl->min + idx * rtbl->step);
}
enum bq25890_status {
STATUS_NOT_CHARGING,
STATUS_PRE_CHARGING,
STATUS_FAST_CHARGING,
STATUS_TERMINATION_DONE,
};
enum bq25890_chrg_fault {
CHRG_FAULT_NORMAL,
CHRG_FAULT_INPUT,
CHRG_FAULT_THERMAL_SHUTDOWN,
CHRG_FAULT_TIMER_EXPIRED,
};
static int bq25890_power_supply_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
int ret;
struct bq25890_device *bq = power_supply_get_drvdata(psy);
struct bq25890_state state;
mutex_lock(&bq->lock);
state = bq->state;
mutex_unlock(&bq->lock);
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
if (!state.online)
val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
else if (state.chrg_status == STATUS_NOT_CHARGING)
val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
else if (state.chrg_status == STATUS_PRE_CHARGING ||
state.chrg_status == STATUS_FAST_CHARGING)
val->intval = POWER_SUPPLY_STATUS_CHARGING;
else if (state.chrg_status == STATUS_TERMINATION_DONE)
val->intval = POWER_SUPPLY_STATUS_FULL;
else
val->intval = POWER_SUPPLY_STATUS_UNKNOWN;
break;
case POWER_SUPPLY_PROP_MANUFACTURER:
val->strval = BQ25890_MANUFACTURER;
break;
case POWER_SUPPLY_PROP_MODEL_NAME:
if (bq->chip_id == BQ25890_ID)
val->strval = "BQ25890";
else if (bq->chip_id == BQ25895_ID)
val->strval = "BQ25895";
else if (bq->chip_id == BQ25896_ID)
val->strval = "BQ25896";
else
val->strval = "UNKNOWN";
break;
case POWER_SUPPLY_PROP_ONLINE:
val->intval = state.online;
break;
case POWER_SUPPLY_PROP_HEALTH:
if (!state.chrg_fault && !state.bat_fault && !state.boost_fault)
val->intval = POWER_SUPPLY_HEALTH_GOOD;
else if (state.bat_fault)
val->intval = POWER_SUPPLY_HEALTH_OVERVOLTAGE;
else if (state.chrg_fault == CHRG_FAULT_TIMER_EXPIRED)
val->intval = POWER_SUPPLY_HEALTH_SAFETY_TIMER_EXPIRE;
else if (state.chrg_fault == CHRG_FAULT_THERMAL_SHUTDOWN)
val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
else
val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
break;
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT:
ret = bq25890_field_read(bq, F_ICHGR); /* read measured value */
if (ret < 0)
return ret;
/* converted_val = ADC_val * 50mA (table 10.3.19) */
val->intval = ret * 50000;
break;
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX:
val->intval = bq25890_find_val(bq->init_data.ichg, TBL_ICHG);
break;
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
if (!state.online) {
val->intval = 0;
break;
}
ret = bq25890_field_read(bq, F_BATV); /* read measured value */
if (ret < 0)
return ret;
/* converted_val = 2.304V + ADC_val * 20mV (table 10.3.15) */
val->intval = 2304000 + ret * 20000;
break;
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX:
val->intval = bq25890_find_val(bq->init_data.vreg, TBL_VREG);
break;
case POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT:
val->intval = bq25890_find_val(bq->init_data.iterm, TBL_ITERM);
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
ret = bq25890_field_read(bq, F_SYSV); /* read measured value */
if (ret < 0)
return ret;
/* converted_val = 2.304V + ADC_val * 20mV (table 10.3.15) */
val->intval = 2304000 + ret * 20000;
break;
default:
return -EINVAL;
}
return 0;
}
static int bq25890_get_chip_state(struct bq25890_device *bq,
struct bq25890_state *state)
{
int i, ret;
struct {
enum bq25890_fields id;
u8 *data;
} state_fields[] = {
{F_CHG_STAT, &state->chrg_status},
{F_PG_STAT, &state->online},
{F_VSYS_STAT, &state->vsys_status},
{F_BOOST_FAULT, &state->boost_fault},
{F_BAT_FAULT, &state->bat_fault},
{F_CHG_FAULT, &state->chrg_fault}
};
for (i = 0; i < ARRAY_SIZE(state_fields); i++) {
ret = bq25890_field_read(bq, state_fields[i].id);
if (ret < 0)
return ret;
*state_fields[i].data = ret;
}
dev_dbg(bq->dev, "S:CHG/PG/VSYS=%d/%d/%d, F:CHG/BOOST/BAT=%d/%d/%d\n",
state->chrg_status, state->online, state->vsys_status,
state->chrg_fault, state->boost_fault, state->bat_fault);
return 0;
}
static bool bq25890_state_changed(struct bq25890_device *bq,
struct bq25890_state *new_state)
{
struct bq25890_state old_state;
mutex_lock(&bq->lock);
old_state = bq->state;
mutex_unlock(&bq->lock);
return (old_state.chrg_status != new_state->chrg_status ||
old_state.chrg_fault != new_state->chrg_fault ||
old_state.online != new_state->online ||
old_state.bat_fault != new_state->bat_fault ||
old_state.boost_fault != new_state->boost_fault ||
old_state.vsys_status != new_state->vsys_status);
}
static void bq25890_handle_state_change(struct bq25890_device *bq,
struct bq25890_state *new_state)
{
int ret;
struct bq25890_state old_state;
mutex_lock(&bq->lock);
old_state = bq->state;
mutex_unlock(&bq->lock);
if (!new_state->online) { /* power removed */
/* disable ADC */
ret = bq25890_field_write(bq, F_CONV_START, 0);
if (ret < 0)
goto error;
} else if (!old_state.online) { /* power inserted */
/* enable ADC, to have control of charge current/voltage */
ret = bq25890_field_write(bq, F_CONV_START, 1);
if (ret < 0)
goto error;
}
return;
error:
dev_err(bq->dev, "Error communicating with the chip.\n");
}
static irqreturn_t bq25890_irq_handler_thread(int irq, void *private)
{
struct bq25890_device *bq = private;
int ret;
struct bq25890_state state;
ret = bq25890_get_chip_state(bq, &state);
if (ret < 0)
goto handled;
if (!bq25890_state_changed(bq, &state))
goto handled;
bq25890_handle_state_change(bq, &state);
mutex_lock(&bq->lock);
bq->state = state;
mutex_unlock(&bq->lock);
power_supply_changed(bq->charger);
handled:
return IRQ_HANDLED;
}
static int bq25890_chip_reset(struct bq25890_device *bq)
{
int ret;
int rst_check_counter = 10;
ret = bq25890_field_write(bq, F_REG_RST, 1);
if (ret < 0)
return ret;
do {
ret = bq25890_field_read(bq, F_REG_RST);
if (ret < 0)
return ret;
usleep_range(5, 10);
} while (ret == 1 && --rst_check_counter);
if (!rst_check_counter)
return -ETIMEDOUT;
return 0;
}
static int bq25890_hw_init(struct bq25890_device *bq)
{
int ret;
int i;
struct bq25890_state state;
const struct {
enum bq25890_fields id;
u32 value;
} init_data[] = {
{F_ICHG, bq->init_data.ichg},
{F_VREG, bq->init_data.vreg},
{F_ITERM, bq->init_data.iterm},
{F_IPRECHG, bq->init_data.iprechg},
{F_SYSVMIN, bq->init_data.sysvmin},
{F_BOOSTV, bq->init_data.boostv},
{F_BOOSTI, bq->init_data.boosti},
{F_BOOSTF, bq->init_data.boostf},
{F_EN_ILIM, bq->init_data.ilim_en},
{F_TREG, bq->init_data.treg}
};
ret = bq25890_chip_reset(bq);
if (ret < 0) {
dev_dbg(bq->dev, "Reset failed %d\n", ret);
return ret;
}
/* disable watchdog */
ret = bq25890_field_write(bq, F_WD, 0);
if (ret < 0) {
dev_dbg(bq->dev, "Disabling watchdog failed %d\n", ret);
return ret;
}
/* initialize currents/voltages and other parameters */
for (i = 0; i < ARRAY_SIZE(init_data); i++) {
ret = bq25890_field_write(bq, init_data[i].id,
init_data[i].value);
if (ret < 0) {
dev_dbg(bq->dev, "Writing init data failed %d\n", ret);
return ret;
}
}
/* Configure ADC for continuous conversions. This does not enable it. */
ret = bq25890_field_write(bq, F_CONV_RATE, 1);
if (ret < 0) {
dev_dbg(bq->dev, "Config ADC failed %d\n", ret);
return ret;
}
ret = bq25890_get_chip_state(bq, &state);
if (ret < 0) {
dev_dbg(bq->dev, "Get state failed %d\n", ret);
return ret;
}
mutex_lock(&bq->lock);
bq->state = state;
mutex_unlock(&bq->lock);
return 0;
}
static enum power_supply_property bq25890_power_supply_props[] = {
POWER_SUPPLY_PROP_MANUFACTURER,
POWER_SUPPLY_PROP_MODEL_NAME,
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX,
POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
};
static char *bq25890_charger_supplied_to[] = {
"main-battery",
};
static const struct power_supply_desc bq25890_power_supply_desc = {
.name = "bq25890-charger",
.type = POWER_SUPPLY_TYPE_USB,
.properties = bq25890_power_supply_props,
.num_properties = ARRAY_SIZE(bq25890_power_supply_props),
.get_property = bq25890_power_supply_get_property,
};
static int bq25890_power_supply_init(struct bq25890_device *bq)
{
struct power_supply_config psy_cfg = { .drv_data = bq, };
psy_cfg.supplied_to = bq25890_charger_supplied_to;
psy_cfg.num_supplicants = ARRAY_SIZE(bq25890_charger_supplied_to);
bq->charger = power_supply_register(bq->dev, &bq25890_power_supply_desc,
&psy_cfg);
return PTR_ERR_OR_ZERO(bq->charger);
}
static void bq25890_usb_work(struct work_struct *data)
{
int ret;
struct bq25890_device *bq =
container_of(data, struct bq25890_device, usb_work);
switch (bq->usb_event) {
case USB_EVENT_ID:
/* Enable boost mode */
ret = bq25890_field_write(bq, F_OTG_CFG, 1);
if (ret < 0)
goto error;
break;
case USB_EVENT_NONE:
/* Disable boost mode */
ret = bq25890_field_write(bq, F_OTG_CFG, 0);
if (ret < 0)
goto error;
power_supply_changed(bq->charger);
break;
}
return;
error:
dev_err(bq->dev, "Error switching to boost/charger mode.\n");
}
static int bq25890_usb_notifier(struct notifier_block *nb, unsigned long val,
void *priv)
{
struct bq25890_device *bq =
container_of(nb, struct bq25890_device, usb_nb);
bq->usb_event = val;
queue_work(system_power_efficient_wq, &bq->usb_work);
return NOTIFY_OK;
}
static int bq25890_irq_probe(struct bq25890_device *bq)
{
struct gpio_desc *irq;
irq = devm_gpiod_get(bq->dev, BQ25890_IRQ_PIN, GPIOD_IN);
if (IS_ERR(irq)) {
dev_err(bq->dev, "Could not probe irq pin.\n");
return PTR_ERR(irq);
}
return gpiod_to_irq(irq);
}
static int bq25890_fw_read_u32_props(struct bq25890_device *bq)
{
int ret;
u32 property;
int i;
struct bq25890_init_data *init = &bq->init_data;
struct {
char *name;
bool optional;
enum bq25890_table_ids tbl_id;
u8 *conv_data; /* holds converted value from given property */
} props[] = {
/* required properties */
{"ti,charge-current", false, TBL_ICHG, &init->ichg},
{"ti,battery-regulation-voltage", false, TBL_VREG, &init->vreg},
{"ti,termination-current", false, TBL_ITERM, &init->iterm},
{"ti,precharge-current", false, TBL_ITERM, &init->iprechg},
{"ti,minimum-sys-voltage", false, TBL_SYSVMIN, &init->sysvmin},
{"ti,boost-voltage", false, TBL_BOOSTV, &init->boostv},
{"ti,boost-max-current", false, TBL_BOOSTI, &init->boosti},
/* optional properties */
{"ti,thermal-regulation-threshold", true, TBL_TREG, &init->treg}
};
/* initialize data for optional properties */
init->treg = 3; /* 120 degrees Celsius */
for (i = 0; i < ARRAY_SIZE(props); i++) {
ret = device_property_read_u32(bq->dev, props[i].name,
&property);
if (ret < 0) {
if (props[i].optional)
continue;
dev_err(bq->dev, "Unable to read property %d %s\n", ret,
props[i].name);
return ret;
}
*props[i].conv_data = bq25890_find_idx(property,
props[i].tbl_id);
}
return 0;
}
static int bq25890_fw_probe(struct bq25890_device *bq)
{
int ret;
struct bq25890_init_data *init = &bq->init_data;
ret = bq25890_fw_read_u32_props(bq);
if (ret < 0)
return ret;
init->ilim_en = device_property_read_bool(bq->dev, "ti,use-ilim-pin");
init->boostf = device_property_read_bool(bq->dev, "ti,boost-low-freq");
return 0;
}
static int bq25890_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = client->adapter;
struct device *dev = &client->dev;
struct bq25890_device *bq;
int ret;
int i;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
dev_err(dev, "No support for SMBUS_BYTE_DATA\n");
return -ENODEV;
}
bq = devm_kzalloc(dev, sizeof(*bq), GFP_KERNEL);
if (!bq)
return -ENOMEM;
bq->client = client;
bq->dev = dev;
mutex_init(&bq->lock);
bq->rmap = devm_regmap_init_i2c(client, &bq25890_regmap_config);
if (IS_ERR(bq->rmap)) {
dev_err(dev, "failed to allocate register map\n");
return PTR_ERR(bq->rmap);
}
for (i = 0; i < ARRAY_SIZE(bq25890_reg_fields); i++) {
const struct reg_field *reg_fields = bq25890_reg_fields;
bq->rmap_fields[i] = devm_regmap_field_alloc(dev, bq->rmap,
reg_fields[i]);
if (IS_ERR(bq->rmap_fields[i])) {
dev_err(dev, "cannot allocate regmap field\n");
return PTR_ERR(bq->rmap_fields[i]);
}
}
i2c_set_clientdata(client, bq);
bq->chip_id = bq25890_field_read(bq, F_PN);
if (bq->chip_id < 0) {
dev_err(dev, "Cannot read chip ID.\n");
return bq->chip_id;
}
if ((bq->chip_id != BQ25890_ID) && (bq->chip_id != BQ25895_ID)
&& (bq->chip_id != BQ25896_ID)) {
dev_err(dev, "Chip with ID=%d, not supported!\n", bq->chip_id);
return -ENODEV;
}
if (!dev->platform_data) {
ret = bq25890_fw_probe(bq);
if (ret < 0) {
dev_err(dev, "Cannot read device properties.\n");
return ret;
}
} else {
return -ENODEV;
}
ret = bq25890_hw_init(bq);
if (ret < 0) {
dev_err(dev, "Cannot initialize the chip.\n");
return ret;
}
if (client->irq <= 0)
client->irq = bq25890_irq_probe(bq);
if (client->irq < 0) {
dev_err(dev, "No irq resource found.\n");
return client->irq;
}
/* OTG reporting */
bq->usb_phy = devm_usb_get_phy(dev, USB_PHY_TYPE_USB2);
if (!IS_ERR_OR_NULL(bq->usb_phy)) {
INIT_WORK(&bq->usb_work, bq25890_usb_work);
bq->usb_nb.notifier_call = bq25890_usb_notifier;
usb_register_notifier(bq->usb_phy, &bq->usb_nb);
}
ret = devm_request_threaded_irq(dev, client->irq, NULL,
bq25890_irq_handler_thread,
IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
BQ25890_IRQ_PIN, bq);
if (ret)
goto irq_fail;
ret = bq25890_power_supply_init(bq);
if (ret < 0) {
dev_err(dev, "Failed to register power supply\n");
goto irq_fail;
}
return 0;
irq_fail:
if (!IS_ERR_OR_NULL(bq->usb_phy))
usb_unregister_notifier(bq->usb_phy, &bq->usb_nb);
return ret;
}
static int bq25890_remove(struct i2c_client *client)
{
struct bq25890_device *bq = i2c_get_clientdata(client);
power_supply_unregister(bq->charger);
if (!IS_ERR_OR_NULL(bq->usb_phy))
usb_unregister_notifier(bq->usb_phy, &bq->usb_nb);
/* reset all registers to default values */
bq25890_chip_reset(bq);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int bq25890_suspend(struct device *dev)
{
struct bq25890_device *bq = dev_get_drvdata(dev);
/*
* If charger is removed, while in suspend, make sure ADC is diabled
* since it consumes slightly more power.
*/
return bq25890_field_write(bq, F_CONV_START, 0);
}
static int bq25890_resume(struct device *dev)
{
int ret;
struct bq25890_state state;
struct bq25890_device *bq = dev_get_drvdata(dev);
ret = bq25890_get_chip_state(bq, &state);
if (ret < 0)
return ret;
mutex_lock(&bq->lock);
bq->state = state;
mutex_unlock(&bq->lock);
/* Re-enable ADC only if charger is plugged in. */
if (state.online) {
ret = bq25890_field_write(bq, F_CONV_START, 1);
if (ret < 0)
return ret;
}
/* signal userspace, maybe state changed while suspended */
power_supply_changed(bq->charger);
return 0;
}
#endif
static const struct dev_pm_ops bq25890_pm = {
SET_SYSTEM_SLEEP_PM_OPS(bq25890_suspend, bq25890_resume)
};
static const struct i2c_device_id bq25890_i2c_ids[] = {
{ "bq25890", 0 },
{},
};
MODULE_DEVICE_TABLE(i2c, bq25890_i2c_ids);
static const struct of_device_id bq25890_of_match[] = {
{ .compatible = "ti,bq25890", },
{ },
};
MODULE_DEVICE_TABLE(of, bq25890_of_match);
static const struct acpi_device_id bq25890_acpi_match[] = {
{"BQ258900", 0},
{},
};
MODULE_DEVICE_TABLE(acpi, bq25890_acpi_match);
static struct i2c_driver bq25890_driver = {
.driver = {
.name = "bq25890-charger",
.of_match_table = of_match_ptr(bq25890_of_match),
.acpi_match_table = ACPI_PTR(bq25890_acpi_match),
.pm = &bq25890_pm,
},
.probe = bq25890_probe,
.remove = bq25890_remove,
.id_table = bq25890_i2c_ids,
};
module_i2c_driver(bq25890_driver);
MODULE_AUTHOR("Laurentiu Palcu <[email protected]>");
MODULE_DESCRIPTION("bq25890 charger driver");
MODULE_LICENSE("GPL");
|
223609.c | #include "spritepack.h"
#include "sprite.h"
#include "label.h"
#include "shader.h"
#include <lua.h>
#include <lauxlib.h>
#define SRT_X 1
#define SRT_Y 2
#define SRT_SX 3
#define SRT_SY 4
#define SRT_ROT 5
#define SRT_SCALE 6
static struct sprite *
newlabel(lua_State *L, struct pack_label *label) {
int sz = sizeof(struct sprite) + sizeof(struct pack_label);
struct sprite *s = (struct sprite *)lua_newuserdata(L, sz);
s->parent = NULL;
// label never has a child
struct pack_label * pl = (struct pack_label *)(s+1);
*pl = *label;
s->s.label = pl;
s->t.mat = NULL;
s->t.color = 0xffffffff;
s->t.additive = 0;
s->t.program = PROGRAM_DEFAULT;
s->message = false;
s->visible = true;
s->name = NULL;
s->id = 0;
s->type = TYPE_LABEL;
s->start_frame = 0;
s->total_frame = 0;
s->frame = 0;
s->data.text = NULL;
return s;
}
/*
integer width
integer height
integer size
uinteger color
string l/r/c
ret: userdata
*/
static int
lnewlabel(lua_State *L) {
struct pack_label label;
label.width = (int)luaL_checkinteger(L,1);
label.height = (int)luaL_checkinteger(L,2);
label.size = (int)luaL_checkinteger(L,3);
label.color = (uint32_t)luaL_optunsigned(L,4,0xffffffff);
label.space_w = 0;
label.space_h = 0;
label.auto_scale = 1;
label.edge = 1;
const char * align = lua_tostring(L,5);
if (align == NULL) {
label.align = LABEL_ALIGN_LEFT;
} else {
switch(align[0]) {
case 'l':
case 'L':
label.align = LABEL_ALIGN_LEFT;
break;
case 'r':
case 'R':
label.align = LABEL_ALIGN_RIGHT;
break;
case 'c':
case 'C':
label.align = LABEL_ALIGN_CENTER;
break;
default:
return luaL_error(L, "Align must be left/right/center");
}
}
newlabel(L, &label);
return 1;
}
static int
lgenoutline(lua_State *L) {
label_gen_outline(lua_toboolean(L, 1));
return 0;
}
static const char * srt_key[] = {
"x",
"y",
"sx",
"sy",
"rot",
"scale",
};
static void
update_message(struct sprite * s, struct sprite_pack * pack, int parentid, int componentid, int frame) {
struct pack_animation * ani = (struct pack_animation *)pack->data[parentid];
if (frame < 0 || frame >= ani->frame_number) {
return;
}
struct pack_frame pframe = ani->frame[frame];
int i = 0;
for (; i < pframe.n; i++) {
if (pframe.part[i].component_id == componentid && pframe.part[i].touchable) {
s->message = true;
return;
}
}
}
static struct sprite *
newanchor(lua_State *L) {
int sz = sizeof(struct sprite) + sizeof(struct matrix);
struct sprite * s = (struct sprite *)lua_newuserdata(L, sz);
s->parent = NULL;
s->t.mat = NULL;
s->t.color = 0xffffffff;
s->t.additive = 0;
s->t.program = PROGRAM_DEFAULT;
s->message = false;
s->visible = false; // anchor is invisible by default
s->name = NULL;
s->id = ANCHOR_ID;
s->type = TYPE_ANCHOR;
s->s.mat = (struct matrix *)(s+1);
matrix_identity(s->s.mat);
return s;
}
static struct sprite *
newsprite(lua_State *L, struct sprite_pack *pack, int id) {
if (id == ANCHOR_ID) {
return newanchor(L);
}
int sz = sprite_size(pack, id);
if (sz == 0) {
return NULL;
}
struct sprite * s = (struct sprite *)lua_newuserdata(L, sz);
sprite_init(s, pack, id, sz);
int i;
for (i=0;;i++) {
int childid = sprite_component(s, i);
if (childid < 0)
break;
if (i==0) {
lua_newtable(L);
lua_pushvalue(L,-1);
lua_setuservalue(L, -3); // set uservalue for sprite
}
struct sprite *c = newsprite(L, pack, childid);
c->name = sprite_childname(s, i);
sprite_mount(s, i, c);
update_message(c, pack, id, i, s->frame);
if (c) {
lua_rawseti(L, -2, i+1);
}
}
if (i>0) {
lua_pop(L,1);
}
return s;
}
/*
userdata sprite_pack
integer id
ret: userdata sprite
*/
static int
lnew(lua_State *L) {
struct sprite_pack * pack = (struct sprite_pack *)lua_touserdata(L, 1);
if (pack == NULL) {
return luaL_error(L, "Need a sprite pack");
}
int id = (int)luaL_checkinteger(L, 2);
struct sprite * s = newsprite(L, pack, id);
if (s) {
return 1;
}
return 0;
}
static double
readkey(lua_State *L, int idx, int key, double def) {
lua_pushvalue(L, lua_upvalueindex(key));
lua_rawget(L, idx);
double ret = luaL_optnumber(L, -1, def);
lua_pop(L,1);
return ret;
}
static struct sprite *
self(lua_State *L) {
struct sprite * s = (struct sprite *)lua_touserdata(L, 1);
if (s == NULL) {
luaL_error(L, "Need sprite");
}
return s;
}
static int
lgetframe(lua_State *L) {
struct sprite * s = self(L);
lua_pushinteger(L, s->frame);
return 1;
}
static int
lsetframe(lua_State *L) {
struct sprite * s = self(L);
int frame = (int)luaL_checkinteger(L,2);
sprite_setframe(s, frame, false);
return 0;
}
static int
lsetaction(lua_State *L) {
struct sprite * s = self(L);
const char * name = lua_tostring(L,2);
sprite_action(s, name);
return 0;
}
static int
lgettotalframe(lua_State *L) {
struct sprite *s = self(L);
int f = s->total_frame;
if (f<=0) {
f = 0;
}
lua_pushinteger(L, f);
return 1;
}
static int
lgetvisible(lua_State *L) {
struct sprite *s = self(L);
lua_pushboolean(L, s->visible);
return 1;
}
static int
lsetvisible(lua_State *L) {
struct sprite *s = self(L);
s->visible = lua_toboolean(L, 2);
return 0;
}
static int
lgetmessage(lua_State *L) {
struct sprite *s = self(L);
lua_pushboolean(L, s->message);
return 1;
}
static int
lsetmessage(lua_State *L) {
struct sprite *s = self(L);
s->message = lua_toboolean(L, 2);
return 0;
}
static int
lsetmat(lua_State *L) {
struct sprite *s = self(L);
struct matrix *m = (struct matrix *)lua_touserdata(L, 2);
if (m == NULL)
return luaL_error(L, "Need a matrix");
s->t.mat = &s->mat;
s->mat = *m;
return 0;
}
static int
lgetmat(lua_State *L) {
struct sprite *s = self(L);
if (s->t.mat == NULL) {
s->t.mat = &s->mat;
matrix_identity(&s->mat);
}
lua_pushlightuserdata(L, s->t.mat);
return 1;
}
static int
lgetwmat(lua_State *L) {
struct sprite *s = self(L);
if (s->type == TYPE_ANCHOR) {
lua_pushlightuserdata(L, s->s.mat);
return 1;
}
return luaL_error(L, "Only anchor can get world matrix");
}
static int
lgetwpos(lua_State *L) {
struct sprite *s = self(L);
if (s->type == TYPE_ANCHOR) {
struct matrix* mat = s->s.mat;
lua_pushnumber(L,mat->m[4] /(float)SCREEN_SCALE);
lua_pushnumber(L,mat->m[5] /(float)SCREEN_SCALE);
return 2;
}
return luaL_error(L, "Only anchor can get world matrix");
}
static int
lsetprogram(lua_State *L) {
struct sprite *s = self(L);
if (lua_isnoneornil(L,2)) {
s->t.program = PROGRAM_DEFAULT;
} else {
s->t.program = (int)luaL_checkinteger(L,2);
}
return 0;
}
static int
lsetscissor(lua_State *L) {
struct sprite *s = self(L);
if (s->type != TYPE_PANNEL) {
return luaL_error(L, "Only pannel can set scissor");
}
s->data.scissor = lua_toboolean(L,2);
return 0;
}
static int
lsetpicmask(lua_State *L) {
struct sprite *s = self(L);
if (s->type != TYPE_PICTURE) {
return luaL_error(L, "Only picture can set mask");
}
struct sprite *mask = (struct sprite*) lua_touserdata(L, 2);
if (mask && mask->type != TYPE_PICTURE) {
return luaL_error(L, "Mask must be picture");
}
struct pack_picture *m = NULL;
if (mask) {
m = mask->s.pic;
}
s->data.mask = m;
return 0;
}
static int
lgetname(lua_State *L) {
struct sprite *s = self(L);
if (s->name == NULL)
return 0;
lua_pushstring(L, s->name);
return 1;
}
static int
lgettype(lua_State *L) {
struct sprite *s = self(L);
lua_pushinteger(L, s->type);
return 1;
}
static int
lgetparentname(lua_State *L) {
struct sprite *s = self(L);
if (s->parent == NULL)
return 0;
lua_pushstring(L, s->parent->name);
return 1;
}
static int
lhasparent(lua_State *L) {
struct sprite *s = self(L);
lua_pushboolean(L, s->parent != NULL);
return 1;
}
static int
lsettext(lua_State *L) {
struct sprite *s = self(L);
if (s->type != TYPE_LABEL) {
return luaL_error(L, "Only label can set text");
}
lua_settop(L,2);
if (lua_isnil(L,2)) {
s->data.text = NULL;
lua_setuservalue(L,1);
return 0;
}
s->data.text = luaL_checkstring(L,2);
lua_createtable(L,1,0);
lua_pushvalue(L, -2);
lua_rawseti(L, -2, 1);
lua_setuservalue(L, 1);
return 0;
}
static int
lgettext(lua_State *L) {
struct sprite *s = self(L);
if (s->type != TYPE_LABEL) {
return luaL_error(L, "Only label can get text");
}
lua_getuservalue(L, 1);
if (!lua_istable(L,-1)) {
return 0;
}
lua_rawgeti(L, -1, 1);
return 1;
}
static int
lgetcolor(lua_State *L) {
struct sprite *s = self(L);
if (s->type != TYPE_LABEL)
{
lua_pushunsigned(L, s->t.color);
}
else
{
lua_pushunsigned(L, label_get_color(s->s.label, &s->t));
}
return 1;
}
static int
lsetcolor(lua_State *L) {
struct sprite *s = self(L);
uint32_t color = luaL_checkunsigned(L,2);
s->t.color = color;
return 0;
}
static int
lsetalpha(lua_State *L) {
struct sprite *s = self(L);
uint8_t alpha = luaL_checkunsigned(L, 2);
s->t.color = (s->t.color >> 8) | (alpha << 24);
return 0;
}
static int
lgetalpha(lua_State *L) {
struct sprite *s = self(L);
lua_pushunsigned(L, s->t.color >> 24);
return 1;
}
static int
lgetadditive(lua_State *L) {
struct sprite *s = self(L);
lua_pushunsigned(L, s->t.additive);
return 1;
}
static int
lsetadditive(lua_State *L) {
struct sprite *s = self(L);
uint32_t additive = luaL_checkunsigned(L,2);
s->t.additive = additive;
return 0;
}
static void
lgetter(lua_State *L) {
luaL_Reg l[] = {
{"frame", lgetframe},
{"frame_count", lgettotalframe },
{"visible", lgetvisible },
{"name", lgetname },
{"type", lgettype },
{"text", lgettext},
{"color", lgetcolor },
{"alpha", lgetalpha },
{"additive", lgetadditive },
{"message", lgetmessage },
{"matrix", lgetmat },
{"world_matrix", lgetwmat },
{"parent_name", lgetparentname },
{"has_parent", lhasparent },
{NULL, NULL},
};
luaL_newlib(L,l);
}
static void
lsetter(lua_State *L) {
luaL_Reg l[] = {
{"frame", lsetframe},
{"action", lsetaction},
{"visible", lsetvisible},
{"matrix" , lsetmat},
{"text", lsettext},
{"color", lsetcolor},
{"alpha", lsetalpha},
{"additive", lsetadditive },
{"message", lsetmessage },
{"program", lsetprogram },
{"scissor", lsetscissor },
{"picture_mask", lsetpicmask },
{NULL, NULL},
};
luaL_newlib(L,l);
}
static int
lfetch(lua_State *L) {
struct sprite *s = self(L);
const char * name = luaL_checkstring(L,2);
int index = sprite_child(s, name);
if (index < 0)
return 0;
lua_getuservalue(L, 1);
lua_rawgeti(L, -1, index+1);
return 1;
}
static int
lfetch_by_index(lua_State *L) {
struct sprite *s = self(L);
if (s->type != TYPE_ANIMATION) {
return luaL_error(L, "Only animation can fetch by index");
}
int index = (int)luaL_checkinteger(L, 2);
struct pack_animation *ani = s->s.ani;
if (index < 0 || index >= ani->component_number) {
return luaL_error(L, "Component index out of range:%d", index);
}
lua_getuservalue(L, 1);
lua_rawgeti(L, -1, index+1);
return 1;
}
static int
lmount(lua_State *L) {
struct sprite *s = self(L);
const char * name = luaL_checkstring(L,2);
int index = sprite_child(s, name);
if (index < 0) {
return luaL_error(L, "No child name %s", name);
}
lua_getuservalue(L, 1);
struct sprite * child = (struct sprite *)lua_touserdata(L, 3);
if (child == NULL) {
sprite_mount(s, index, NULL);
lua_pushnil(L);
lua_rawseti(L, -2, index+1);
} else {
if (child->parent) {
struct sprite* p = child->parent;
sprite_mount(p, index, NULL);
//return luaL_error(L, "Can't mount sprite %p twice,pre parent:%p: %s", child,child->parent,child->name);
}
sprite_mount(s, index, child);
lua_pushvalue(L, 3);
lua_rawseti(L, -2, index+1);
}
return 0;
}
static void
fill_srt(lua_State *L, struct srt *srt, int idx) {
if (lua_isnoneornil(L, idx)) {
srt->offx = 0;
srt->offy = 0;
srt->rot = 0;
srt->scalex = 1024;
srt->scaley = 1024;
return;
}
luaL_checktype(L,idx,LUA_TTABLE);
double x = readkey(L, idx, SRT_X, 0);
double y = readkey(L, idx, SRT_Y, 0);
double scale = readkey(L, idx, SRT_SCALE, 0);
double sx;
double sy;
double rot = readkey(L, idx, SRT_ROT, 0);
if (scale > 0) {
sx = sy = scale;
} else {
sx = readkey(L, idx, SRT_SX, 1);
sy = readkey(L, idx, SRT_SY, 1);
}
srt->offx = x*SCREEN_SCALE;
srt->offy = y*SCREEN_SCALE;
srt->scalex = sx*1024;
srt->scaley = sy*1024;
srt->rot = rot * (1024.0 / 360.0);
}
/*
userdata sprite
table { .x .y .sx .sy .rot }
*/
static int
ldraw(lua_State *L) {
struct sprite *s = self(L);
struct srt srt;
fill_srt(L,&srt,2);
sprite_draw(s, &srt);
return 0;
}
static int
laabb(lua_State *L) {
struct sprite *s = self(L);
struct srt srt;
fill_srt(L,&srt,2);
int aabb[4];
sprite_aabb(s, &srt, aabb);
int i;
for (i=0;i<4;i++) {
lua_pushinteger(L, aabb[i]);
}
return 4;
}
static int
ltext_size(lua_State *L) {
struct sprite *s = self(L);
if (s->type != TYPE_LABEL) {
return luaL_error(L, "Ony label can get label_size");
}
int width = 0, height = 0;
if (s->data.text != NULL)
label_size(s->data.text, s->s.label, &width, &height);
lua_pushinteger(L, width);
lua_pushinteger(L, height);
lua_pushinteger(L, s->s.label->size);
return 3;
}
static int
lchild_visible(lua_State *L) {
struct sprite *s = self(L);
const char * name = luaL_checkstring(L,2);
lua_pushboolean(L, sprite_child_visible(s, name));
return 1;
}
static int
lchildren_name(lua_State *L) {
struct sprite *s = self(L);
if (s->type != TYPE_ANIMATION)
return 0;
int i;
int cnt=0;
struct pack_animation * ani = s->s.ani;
for (i=0;i<ani->component_number;i++) {
if (ani->component[i].name != NULL) {
lua_pushstring(L, ani->component[i].name);
cnt++;
}
}
return cnt;
}
static int
lmatrix_multi_draw(lua_State *L) {
struct sprite *s = self(L);
int cnt = (int)luaL_checkinteger(L,3);
if (cnt == 0)
return 0;
luaL_checktype(L,4,LUA_TTABLE);
luaL_checktype(L,5,LUA_TTABLE);
// luaL_checktype(L,6,LUA_TTABLE);
if (lua_rawlen(L, 4) < cnt) {
return luaL_error(L, "matrix length less then particle count");
}
struct matrix *mat = (struct matrix *)lua_touserdata(L, 2);
if (s->t.mat == NULL) {
s->t.mat = &s->mat;
matrix_identity(&s->mat);
}
struct matrix *parent_mat = s->t.mat;
uint32_t parent_color = s->t.color;
int i;
if (mat) {
struct matrix tmp;
for (i = 0; i < cnt; i++) {
lua_rawgeti(L, 4, i+1);
lua_rawgeti(L, 5, i+1);
struct matrix *m = (struct matrix *)lua_touserdata(L, -2);
matrix_mul(&tmp, m, mat);
s->t.mat = &tmp;
s->t.color = (uint32_t)lua_tounsigned(L, -1);
lua_pop(L, 2);
sprite_draw(s, NULL);
}
} else {
for (i = 0; i < cnt; i++) {
lua_rawgeti(L, 4, i+1);
lua_rawgeti(L, 5, i+1);
struct matrix *m = (struct matrix *)lua_touserdata(L, -2);
s->t.mat = m;
s->t.color = (uint32_t)lua_tounsigned(L, -1);
lua_pop(L, 2);
sprite_draw(s, NULL);
}
}
s->t.mat = parent_mat;
s->t.color = parent_color;
return 0;
}
static int
lmulti_draw(lua_State *L) {
struct sprite *s = self(L);
int cnt = (int)luaL_checkinteger(L,3);
if (cnt == 0)
return 0;
int n = lua_gettop(L);
luaL_checktype(L,4,LUA_TTABLE);
luaL_checktype(L,5,LUA_TTABLE);
if (lua_rawlen(L, 4) < cnt) {
return luaL_error(L, "matrix length less then particle count");
}
if (n == 6) {
luaL_checktype(L,6,LUA_TTABLE);
if (lua_rawlen(L, 6) < cnt) {
return luaL_error(L, "additive length less then particle count");
}
}
struct srt srt;
fill_srt(L, &srt, 2);
if (s->t.mat == NULL) {
s->t.mat = &s->mat;
matrix_identity(&s->mat);
}
struct matrix *parent_mat = s->t.mat;
uint32_t parent_color = s->t.color;
int i;
if (n == 5) {
for (i = 0; i < cnt; i++) {
lua_rawgeti(L, 4, i+1);
lua_rawgeti(L, 5, i+1);
s->t.mat = (struct matrix *)lua_touserdata(L, -2);
s->t.color = (uint32_t)lua_tounsigned(L, -1);
lua_pop(L, 2);
sprite_draw_as_child(s, &srt, parent_mat, parent_color);
}
}else {
for (i = 0; i < cnt; i++) {
lua_rawgeti(L, 4, i+1);
lua_rawgeti(L, 5, i+1);
lua_rawgeti(L, 6, i+1);
s->t.mat = (struct matrix *)lua_touserdata(L, -3);
s->t.color = (uint32_t)lua_tounsigned(L, -2);
s->t.additive = (uint32_t)lua_tounsigned(L, -1);
lua_pop(L, 3);
sprite_draw_as_child(s, &srt, parent_mat, parent_color);
}
}
s->t.mat = parent_mat;
s->t.color = parent_color;
return 0;
}
static struct sprite *
lookup(lua_State *L, struct sprite * spr) {
int i;
struct sprite * root = (struct sprite *)lua_touserdata(L, -1);
lua_getuservalue(L,-1);
for (i=0;sprite_component(root, i)>=0;i++) {
struct sprite * child = root->data.children[i];
if (child) {
lua_rawgeti(L, -1, i+1);
if (child == spr) {
lua_replace(L,-2);
return child;
} else {
lua_pop(L,1);
}
}
}
lua_pop(L,1);
return NULL;
}
static int
unwind(lua_State *L, struct sprite *root, struct sprite *spr) {
int n = 0;
while (spr) {
if (spr == root) {
return n;
}
++n;
lua_checkstack(L,3);
lua_pushlightuserdata(L, spr);
spr = spr->parent;
}
return -1;
}
static int
ltest(lua_State *L) {
struct sprite *s = self(L);
struct srt srt;
fill_srt(L,&srt,4);
float x = luaL_checknumber(L, 2);
float y = luaL_checknumber(L, 3);
struct sprite * m = sprite_test(s, &srt, x*SCREEN_SCALE, y*SCREEN_SCALE);
if (m == NULL)
return 0;
if (m==s) {
lua_settop(L,1);
return 1;
}
lua_settop(L,1);
int depth = unwind(L, s , m);
if (depth < 0) {
return luaL_error(L, "Unwind an invalid sprite");
}
int i;
lua_pushvalue(L,1);
for (i=depth+1;i>1;i--) {
struct sprite * tmp = (struct sprite *)lua_touserdata(L, i);
tmp = lookup(L, tmp);
if (tmp == NULL) {
return luaL_error(L, "find an invalid sprite");
}
lua_replace(L, -2);
}
return 1;
}
static int
lps(lua_State *L) {
struct sprite *s = self(L);
struct matrix *m = &s->mat;
if (s->t.mat == NULL) {
matrix_identity(m);
s->t.mat = m;
}
int *mat = m->m;
int n = lua_gettop(L);
int x,y,scale;
switch (n) {
case 4:
// x,y,scale
x = luaL_checknumber(L,2) * SCREEN_SCALE;
y = luaL_checknumber(L,3) * SCREEN_SCALE;
scale = luaL_checknumber(L,4) * 1024;
mat[0] = scale;
mat[1] = 0;
mat[2] = 0;
mat[3] = scale;
mat[4] = x;
mat[5] = y;
break;
case 3:
// x,y
x = luaL_checknumber(L,2) * SCREEN_SCALE;
y = luaL_checknumber(L,3) * SCREEN_SCALE;
mat[4] = x;
mat[5] = y;
break;
case 2:
// scale
scale = luaL_checknumber(L,2) * 1024;
mat[0] = scale;
mat[1] = 0;
mat[2] = 0;
mat[3] = scale;
break;
default:
return luaL_error(L, "Invalid parm");
}
return 0;
}
static int
lsr(lua_State *L) {
struct sprite *s = self(L);
struct matrix *m = &s->mat;
if (s->t.mat == NULL) {
matrix_identity(m);
s->t.mat = m;
}
int sx=1024,sy=1024,r=0;
int n = lua_gettop(L);
switch (n) {
case 4:
// sx,sy,rot
r = luaL_checknumber(L,4) * (1024.0 / 360.0);
// go through
case 3:
// sx, sy
sx = luaL_checknumber(L,2) * 1024;
sy = luaL_checknumber(L,3) * 1024;
break;
case 2:
// rot
r = luaL_checknumber(L,2) * (1024.0 / 360.0);
break;
}
matrix_sr(m, sx, sy, r);
return 0;
}
static int
lrecursion_frame(lua_State *L) {
struct sprite * s = self(L);
int frame = (int)luaL_checkinteger(L,2);
int f = sprite_setframe(s, frame, true);
lua_pushinteger(L, f);
return 1;
}
static void
lmethod(lua_State *L) {
luaL_Reg l[] = {
{ "fetch", lfetch },
{ "fetch_by_index", lfetch_by_index },
{ "mount", lmount },
{ NULL, NULL },
};
luaL_newlib(L,l);
int i;
int nk = sizeof(srt_key)/sizeof(srt_key[0]);
for (i=0;i<nk;i++) {
lua_pushstring(L, srt_key[i]);
}
luaL_Reg l2[] = {
{ "ps", lps },
{ "sr", lsr },
{ "draw", ldraw },
{ "recursion_frame", lrecursion_frame },
{ "multi_draw", lmulti_draw },
{ "matrix_multi_draw", lmatrix_multi_draw },
{ "test", ltest },
{ "aabb", laabb },
{ "text_size", ltext_size},
{ "child_visible", lchild_visible },
{ "children_name", lchildren_name },
{ "world_pos", lgetwpos },
{ NULL, NULL, },
};
luaL_setfuncs(L,l2,nk);
}
int
ejoy2d_sprite(lua_State *L) {
luaL_Reg l[] ={
{ "new", lnew },
{ "label", lnewlabel },
{ "label_gen_outline", lgenoutline },
{ NULL, NULL },
};
luaL_newlib(L,l);
lmethod(L);
lua_setfield(L, -2, "method");
lgetter(L);
lua_setfield(L, -2, "get");
lsetter(L);
lua_setfield(L, -2, "set");
return 1;
}
|
402631.c | /*
* Asihpi soundcard
* Copyright (c) by AudioScience Inc <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* The following is not a condition of use, merely a request:
* If you modify this program, particularly if you fix errors, AudioScience Inc
* would appreciate it if you grant us the right to use those modifications
* for any purpose including commercial applications.
*/
/* >0: print Hw params, timer vars. >1: print stream write/copy sizes */
#define REALLY_VERBOSE_LOGGING 0
#if REALLY_VERBOSE_LOGGING
#define VPRINTK1 snd_printd
#else
#define VPRINTK1(...)
#endif
#if REALLY_VERBOSE_LOGGING > 1
#define VPRINTK2 snd_printd
#else
#define VPRINTK2(...)
#endif
#ifndef ASI_STYLE_NAMES
/* not sure how ALSA style name should look */
#define ASI_STYLE_NAMES 1
#endif
#include "hpi_internal.h"
#include "hpimsginit.h"
#include "hpioctl.h"
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/info.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include <sound/hwdep.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("AudioScience inc. <[email protected]>");
MODULE_DESCRIPTION("AudioScience ALSA ASI5000 ASI6000 ASI87xx ASI89xx");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
static int enable_hpi_hwdep = 1;
module_param_array(index, int, NULL, S_IRUGO);
MODULE_PARM_DESC(index, "ALSA index value for AudioScience soundcard.");
module_param_array(id, charp, NULL, S_IRUGO);
MODULE_PARM_DESC(id, "ALSA ID string for AudioScience soundcard.");
module_param_array(enable, bool, NULL, S_IRUGO);
MODULE_PARM_DESC(enable, "ALSA enable AudioScience soundcard.");
module_param(enable_hpi_hwdep, bool, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(enable_hpi_hwdep,
"ALSA enable HPI hwdep for AudioScience soundcard ");
/* identify driver */
#ifdef KERNEL_ALSA_BUILD
static char *build_info = "built using headers from kernel source";
module_param(build_info, charp, S_IRUGO);
MODULE_PARM_DESC(build_info, "built using headers from kernel source");
#else
static char *build_info = "built within ALSA source";
module_param(build_info, charp, S_IRUGO);
MODULE_PARM_DESC(build_info, "built within ALSA source");
#endif
/* set to 1 to dump every control from adapter to log */
static const int mixer_dump;
#define DEFAULT_SAMPLERATE 44100
static int adapter_fs = DEFAULT_SAMPLERATE;
static struct hpi_hsubsys *ss; /* handle to HPI audio subsystem */
/* defaults */
#define PERIODS_MIN 2
#define PERIOD_BYTES_MIN 2304
#define BUFFER_BYTES_MAX (512 * 1024)
/*#define TIMER_MILLISECONDS 20
#define FORCE_TIMER_JIFFIES ((TIMER_MILLISECONDS * HZ + 999)/1000)
*/
#define MAX_CLOCKSOURCES (HPI_SAMPLECLOCK_SOURCE_LAST + 1 + 7)
struct clk_source {
int source;
int index;
char *name;
};
struct clk_cache {
int count;
int has_local;
struct clk_source s[MAX_CLOCKSOURCES];
};
/* Per card data */
struct snd_card_asihpi {
struct snd_card *card;
struct pci_dev *pci;
u16 adapter_index;
u32 serial_number;
u16 type;
u16 version;
u16 num_outstreams;
u16 num_instreams;
u32 h_mixer;
struct clk_cache cc;
u16 support_mmap;
u16 support_grouping;
u16 support_mrx;
u16 update_interval_frames;
u16 in_max_chans;
u16 out_max_chans;
};
/* Per stream data */
struct snd_card_asihpi_pcm {
struct timer_list timer;
unsigned int respawn_timer;
unsigned int hpi_buffer_attached;
unsigned int pcm_size;
unsigned int pcm_count;
unsigned int bytes_per_sec;
unsigned int pcm_irq_pos; /* IRQ position */
unsigned int pcm_buf_pos; /* position in buffer */
struct snd_pcm_substream *substream;
u32 h_stream;
struct hpi_format format;
};
/* universal stream verbs work with out or in stream handles */
/* Functions to allow driver to give a buffer to HPI for busmastering */
static u16 hpi_stream_host_buffer_attach(
struct hpi_hsubsys *hS,
u32 h_stream, /* handle to outstream. */
u32 size_in_bytes, /* size in bytes of bus mastering buffer */
u32 pci_address
)
{
struct hpi_message hm;
struct hpi_response hr;
unsigned int obj = hpi_handle_object(h_stream);
if (!h_stream)
return HPI_ERROR_INVALID_OBJ;
hpi_init_message_response(&hm, &hr, obj,
obj == HPI_OBJ_OSTREAM ?
HPI_OSTREAM_HOSTBUFFER_ALLOC :
HPI_ISTREAM_HOSTBUFFER_ALLOC);
hpi_handle_to_indexes(h_stream, &hm.adapter_index,
&hm.obj_index);
hm.u.d.u.buffer.buffer_size = size_in_bytes;
hm.u.d.u.buffer.pci_address = pci_address;
hm.u.d.u.buffer.command = HPI_BUFFER_CMD_INTERNAL_GRANTADAPTER;
hpi_send_recv(&hm, &hr);
return hr.error;
}
static u16 hpi_stream_host_buffer_detach(
struct hpi_hsubsys *hS,
u32 h_stream
)
{
struct hpi_message hm;
struct hpi_response hr;
unsigned int obj = hpi_handle_object(h_stream);
if (!h_stream)
return HPI_ERROR_INVALID_OBJ;
hpi_init_message_response(&hm, &hr, obj,
obj == HPI_OBJ_OSTREAM ?
HPI_OSTREAM_HOSTBUFFER_FREE :
HPI_ISTREAM_HOSTBUFFER_FREE);
hpi_handle_to_indexes(h_stream, &hm.adapter_index,
&hm.obj_index);
hm.u.d.u.buffer.command = HPI_BUFFER_CMD_INTERNAL_REVOKEADAPTER;
hpi_send_recv(&hm, &hr);
return hr.error;
}
static inline u16 hpi_stream_start(struct hpi_hsubsys *hS, u32 h_stream)
{
if (hpi_handle_object(h_stream) == HPI_OBJ_OSTREAM)
return hpi_outstream_start(hS, h_stream);
else
return hpi_instream_start(hS, h_stream);
}
static inline u16 hpi_stream_stop(struct hpi_hsubsys *hS, u32 h_stream)
{
if (hpi_handle_object(h_stream) == HPI_OBJ_OSTREAM)
return hpi_outstream_stop(hS, h_stream);
else
return hpi_instream_stop(hS, h_stream);
}
static inline u16 hpi_stream_get_info_ex(
struct hpi_hsubsys *hS,
u32 h_stream,
u16 *pw_state,
u32 *pbuffer_size,
u32 *pdata_in_buffer,
u32 *psample_count,
u32 *pauxiliary_data
)
{
if (hpi_handle_object(h_stream) == HPI_OBJ_OSTREAM)
return hpi_outstream_get_info_ex(hS, h_stream, pw_state,
pbuffer_size, pdata_in_buffer,
psample_count, pauxiliary_data);
else
return hpi_instream_get_info_ex(hS, h_stream, pw_state,
pbuffer_size, pdata_in_buffer,
psample_count, pauxiliary_data);
}
static inline u16 hpi_stream_group_add(struct hpi_hsubsys *hS,
u32 h_master,
u32 h_stream)
{
if (hpi_handle_object(h_master) == HPI_OBJ_OSTREAM)
return hpi_outstream_group_add(hS, h_master, h_stream);
else
return hpi_instream_group_add(hS, h_master, h_stream);
}
static inline u16 hpi_stream_group_reset(struct hpi_hsubsys *hS,
u32 h_stream)
{
if (hpi_handle_object(h_stream) == HPI_OBJ_OSTREAM)
return hpi_outstream_group_reset(hS, h_stream);
else
return hpi_instream_group_reset(hS, h_stream);
}
static inline u16 hpi_stream_group_get_map(struct hpi_hsubsys *hS,
u32 h_stream, u32 *mo, u32 *mi)
{
if (hpi_handle_object(h_stream) == HPI_OBJ_OSTREAM)
return hpi_outstream_group_get_map(hS, h_stream, mo, mi);
else
return hpi_instream_group_get_map(hS, h_stream, mo, mi);
}
static u16 handle_error(u16 err, int line, char *filename)
{
if (err)
printk(KERN_WARNING
"in file %s, line %d: HPI error %d\n",
filename, line, err);
return err;
}
#define hpi_handle_error(x) handle_error(x, __LINE__, __FILE__)
/***************************** GENERAL PCM ****************/
#if REALLY_VERBOSE_LOGGING
static void print_hwparams(struct snd_pcm_hw_params *p)
{
snd_printd("HWPARAMS \n");
snd_printd("samplerate %d \n", params_rate(p));
snd_printd("channels %d \n", params_channels(p));
snd_printd("format %d \n", params_format(p));
snd_printd("subformat %d \n", params_subformat(p));
snd_printd("buffer bytes %d \n", params_buffer_bytes(p));
snd_printd("period bytes %d \n", params_period_bytes(p));
snd_printd("access %d \n", params_access(p));
snd_printd("period_size %d \n", params_period_size(p));
snd_printd("periods %d \n", params_periods(p));
snd_printd("buffer_size %d \n", params_buffer_size(p));
}
#else
#define print_hwparams(x)
#endif
static snd_pcm_format_t hpi_to_alsa_formats[] = {
-1, /* INVALID */
SNDRV_PCM_FORMAT_U8, /* HPI_FORMAT_PCM8_UNSIGNED 1 */
SNDRV_PCM_FORMAT_S16, /* HPI_FORMAT_PCM16_SIGNED 2 */
-1, /* HPI_FORMAT_MPEG_L1 3 */
SNDRV_PCM_FORMAT_MPEG, /* HPI_FORMAT_MPEG_L2 4 */
SNDRV_PCM_FORMAT_MPEG, /* HPI_FORMAT_MPEG_L3 5 */
-1, /* HPI_FORMAT_DOLBY_AC2 6 */
-1, /* HPI_FORMAT_DOLBY_AC3 7 */
SNDRV_PCM_FORMAT_S16_BE,/* HPI_FORMAT_PCM16_BIGENDIAN 8 */
-1, /* HPI_FORMAT_AA_TAGIT1_HITS 9 */
-1, /* HPI_FORMAT_AA_TAGIT1_INSERTS 10 */
SNDRV_PCM_FORMAT_S32, /* HPI_FORMAT_PCM32_SIGNED 11 */
-1, /* HPI_FORMAT_RAW_BITSTREAM 12 */
-1, /* HPI_FORMAT_AA_TAGIT1_HITS_EX1 13 */
SNDRV_PCM_FORMAT_FLOAT, /* HPI_FORMAT_PCM32_FLOAT 14 */
/* ALSA can't handle 3 byte sample size together with power-of-2
* constraint on buffer_bytes, so disable this format
*/
-1
};
static int snd_card_asihpi_format_alsa2hpi(snd_pcm_format_t alsa_format,
u16 *hpi_format)
{
u16 format;
for (format = HPI_FORMAT_PCM8_UNSIGNED;
format <= HPI_FORMAT_PCM24_SIGNED; format++) {
if (hpi_to_alsa_formats[format] == alsa_format) {
*hpi_format = format;
return 0;
}
}
snd_printd(KERN_WARNING "failed match for alsa format %d\n",
alsa_format);
*hpi_format = 0;
return -EINVAL;
}
static void snd_card_asihpi_pcm_samplerates(struct snd_card_asihpi *asihpi,
struct snd_pcm_hardware *pcmhw)
{
u16 err;
u32 h_control;
u32 sample_rate;
int idx;
unsigned int rate_min = 200000;
unsigned int rate_max = 0;
unsigned int rates = 0;
if (asihpi->support_mrx) {
rates |= SNDRV_PCM_RATE_CONTINUOUS;
rates |= SNDRV_PCM_RATE_8000_96000;
rate_min = 8000;
rate_max = 100000;
} else {
/* on cards without SRC,
valid rates are determined by sampleclock */
err = hpi_mixer_get_control(ss, asihpi->h_mixer,
HPI_SOURCENODE_CLOCK_SOURCE, 0, 0, 0,
HPI_CONTROL_SAMPLECLOCK, &h_control);
if (err) {
snd_printk(KERN_ERR
"no local sampleclock, err %d\n", err);
}
for (idx = 0; idx < 100; idx++) {
if (hpi_sample_clock_query_local_rate(ss,
h_control, idx, &sample_rate)) {
if (!idx)
snd_printk(KERN_ERR
"local rate query failed\n");
break;
}
rate_min = min(rate_min, sample_rate);
rate_max = max(rate_max, sample_rate);
switch (sample_rate) {
case 5512:
rates |= SNDRV_PCM_RATE_5512;
break;
case 8000:
rates |= SNDRV_PCM_RATE_8000;
break;
case 11025:
rates |= SNDRV_PCM_RATE_11025;
break;
case 16000:
rates |= SNDRV_PCM_RATE_16000;
break;
case 22050:
rates |= SNDRV_PCM_RATE_22050;
break;
case 32000:
rates |= SNDRV_PCM_RATE_32000;
break;
case 44100:
rates |= SNDRV_PCM_RATE_44100;
break;
case 48000:
rates |= SNDRV_PCM_RATE_48000;
break;
case 64000:
rates |= SNDRV_PCM_RATE_64000;
break;
case 88200:
rates |= SNDRV_PCM_RATE_88200;
break;
case 96000:
rates |= SNDRV_PCM_RATE_96000;
break;
case 176400:
rates |= SNDRV_PCM_RATE_176400;
break;
case 192000:
rates |= SNDRV_PCM_RATE_192000;
break;
default: /* some other rate */
rates |= SNDRV_PCM_RATE_KNOT;
}
}
}
/* printk(KERN_INFO "Supported rates %X %d %d\n",
rates, rate_min, rate_max); */
pcmhw->rates = rates;
pcmhw->rate_min = rate_min;
pcmhw->rate_max = rate_max;
}
static int snd_card_asihpi_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
struct snd_card_asihpi *card = snd_pcm_substream_chip(substream);
int err;
u16 format;
int width;
unsigned int bytes_per_sec;
print_hwparams(params);
err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(params));
if (err < 0)
return err;
err = snd_card_asihpi_format_alsa2hpi(params_format(params), &format);
if (err)
return err;
VPRINTK1(KERN_INFO "format %d, %d chans, %d_hz\n",
format, params_channels(params),
params_rate(params));
hpi_handle_error(hpi_format_create(&dpcm->format,
params_channels(params),
format, params_rate(params), 0, 0));
if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) {
if (hpi_instream_reset(ss, dpcm->h_stream) != 0)
return -EINVAL;
if (hpi_instream_set_format(ss,
dpcm->h_stream, &dpcm->format) != 0)
return -EINVAL;
}
dpcm->hpi_buffer_attached = 0;
if (card->support_mmap) {
err = hpi_stream_host_buffer_attach(ss, dpcm->h_stream,
params_buffer_bytes(params), runtime->dma_addr);
if (err == 0) {
snd_printd(KERN_INFO
"stream_host_buffer_attach succeeded %u %lu\n",
params_buffer_bytes(params),
(unsigned long)runtime->dma_addr);
} else {
snd_printd(KERN_INFO
"stream_host_buffer_attach error %d\n",
err);
return -ENOMEM;
}
err = hpi_stream_get_info_ex(ss, dpcm->h_stream, NULL,
&dpcm->hpi_buffer_attached,
NULL, NULL, NULL);
snd_printd(KERN_INFO "stream_host_buffer_attach status 0x%x\n",
dpcm->hpi_buffer_attached);
}
bytes_per_sec = params_rate(params) * params_channels(params);
width = snd_pcm_format_width(params_format(params));
bytes_per_sec *= width;
bytes_per_sec /= 8;
if (width < 0 || bytes_per_sec == 0)
return -EINVAL;
dpcm->bytes_per_sec = bytes_per_sec;
dpcm->pcm_size = params_buffer_bytes(params);
dpcm->pcm_count = params_period_bytes(params);
snd_printd(KERN_INFO "pcm_size=%d, pcm_count=%d, bps=%d\n",
dpcm->pcm_size, dpcm->pcm_count, bytes_per_sec);
dpcm->pcm_irq_pos = 0;
dpcm->pcm_buf_pos = 0;
return 0;
}
static void snd_card_asihpi_pcm_timer_start(struct snd_pcm_substream *
substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
int expiry;
expiry = (dpcm->pcm_count * HZ / dpcm->bytes_per_sec);
/* wait longer the first time, for samples to propagate */
expiry = max(expiry, 20);
dpcm->timer.expires = jiffies + expiry;
dpcm->respawn_timer = 1;
add_timer(&dpcm->timer);
}
static void snd_card_asihpi_pcm_timer_stop(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
dpcm->respawn_timer = 0;
del_timer(&dpcm->timer);
}
static int snd_card_asihpi_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_card_asihpi_pcm *dpcm = substream->runtime->private_data;
struct snd_card_asihpi *card = snd_pcm_substream_chip(substream);
struct snd_pcm_substream *s;
u16 e;
snd_printd("trigger %dstream %d\n",
substream->stream, substream->number);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
snd_pcm_group_for_each_entry(s, substream) {
struct snd_card_asihpi_pcm *ds;
ds = s->runtime->private_data;
if (snd_pcm_substream_chip(s) != card)
continue;
if ((s->stream == SNDRV_PCM_STREAM_PLAYBACK) &&
(card->support_mmap)) {
/* How do I know how much valid data is present
* in buffer? Just guessing 2 periods, but if
* buffer is bigger it may contain even more
* data??
*/
unsigned int preload = ds->pcm_count * 2;
VPRINTK2("preload %d\n", preload);
hpi_handle_error(hpi_outstream_write_buf(
ss, ds->h_stream,
&s->runtime->dma_area[0],
preload,
&ds->format));
}
if (card->support_grouping) {
VPRINTK1("\t_group %dstream %d\n", s->stream,
s->number);
e = hpi_stream_group_add(ss,
dpcm->h_stream,
ds->h_stream);
if (!e) {
snd_pcm_trigger_done(s, substream);
} else {
hpi_handle_error(e);
break;
}
} else
break;
}
snd_printd("start\n");
/* start the master stream */
snd_card_asihpi_pcm_timer_start(substream);
hpi_handle_error(hpi_stream_start(ss, dpcm->h_stream));
break;
case SNDRV_PCM_TRIGGER_STOP:
snd_card_asihpi_pcm_timer_stop(substream);
snd_pcm_group_for_each_entry(s, substream) {
if (snd_pcm_substream_chip(s) != card)
continue;
s->runtime->status->state = SNDRV_PCM_STATE_SETUP;
if (card->support_grouping) {
VPRINTK1("\t_group %dstream %d\n", s->stream,
s->number);
snd_pcm_trigger_done(s, substream);
} else
break;
}
snd_printd("stop\n");
/* _prepare and _hwparams reset the stream */
hpi_handle_error(hpi_stream_stop(ss, dpcm->h_stream));
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
hpi_handle_error(
hpi_outstream_reset(ss, dpcm->h_stream));
if (card->support_grouping)
hpi_handle_error(hpi_stream_group_reset(ss,
dpcm->h_stream));
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
snd_printd("pause release\n");
hpi_handle_error(hpi_stream_start(ss, dpcm->h_stream));
snd_card_asihpi_pcm_timer_start(substream);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
snd_printd("pause\n");
snd_card_asihpi_pcm_timer_stop(substream);
hpi_handle_error(hpi_stream_stop(ss, dpcm->h_stream));
break;
default:
snd_printd("\tINVALID\n");
return -EINVAL;
}
return 0;
}
static int
snd_card_asihpi_hw_free(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
if (dpcm->hpi_buffer_attached)
hpi_stream_host_buffer_detach(ss, dpcm->h_stream);
snd_pcm_lib_free_pages(substream);
return 0;
}
static void snd_card_asihpi_runtime_free(struct snd_pcm_runtime *runtime)
{
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
kfree(dpcm);
}
/*algorithm outline
Without linking degenerates to getting single stream pos etc
Without mmap 2nd loop degenerates to snd_pcm_period_elapsed
*/
/*
buf_pos=get_buf_pos(s);
for_each_linked_stream(s) {
buf_pos=get_buf_pos(s);
min_buf_pos = modulo_min(min_buf_pos, buf_pos, pcm_size)
new_data = min(new_data, calc_new_data(buf_pos,irq_pos)
}
timer.expires = jiffies + predict_next_period_ready(min_buf_pos);
for_each_linked_stream(s) {
s->buf_pos = min_buf_pos;
if (new_data > pcm_count) {
if (mmap) {
irq_pos = (irq_pos + pcm_count) % pcm_size;
if (playback) {
write(pcm_count);
} else {
read(pcm_count);
}
}
snd_pcm_period_elapsed(s);
}
}
*/
/** Minimum of 2 modulo values. Works correctly when the difference between
* the values is less than half the modulus
*/
static inline unsigned int modulo_min(unsigned int a, unsigned int b,
unsigned long int modulus)
{
unsigned int result;
if (((a-b) % modulus) < (modulus/2))
result = b;
else
result = a;
return result;
}
/** Timer function, equivalent to interrupt service routine for cards
*/
static void snd_card_asihpi_timer_function(unsigned long data)
{
struct snd_card_asihpi_pcm *dpcm = (struct snd_card_asihpi_pcm *)data;
struct snd_card_asihpi *card = snd_pcm_substream_chip(dpcm->substream);
struct snd_pcm_runtime *runtime;
struct snd_pcm_substream *s;
unsigned int newdata = 0;
unsigned int buf_pos, min_buf_pos = 0;
unsigned int remdata, xfercount, next_jiffies;
int first = 1;
u16 state;
u32 buffer_size, data_avail, samples_played, aux;
/* find minimum newdata and buffer pos in group */
snd_pcm_group_for_each_entry(s, dpcm->substream) {
struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
runtime = s->runtime;
if (snd_pcm_substream_chip(s) != card)
continue;
hpi_handle_error(hpi_stream_get_info_ex(ss,
ds->h_stream, &state,
&buffer_size, &data_avail,
&samples_played, &aux));
/* number of bytes in on-card buffer */
runtime->delay = aux;
if (state == HPI_STATE_DRAINED) {
snd_printd(KERN_WARNING "outstream %d drained\n",
s->number);
snd_pcm_stop(s, SNDRV_PCM_STATE_XRUN);
return;
}
if (s->stream == SNDRV_PCM_STREAM_PLAYBACK) {
buf_pos = frames_to_bytes(runtime, samples_played);
} else {
buf_pos = data_avail + ds->pcm_irq_pos;
}
if (first) {
/* can't statically init min when wrap is involved */
min_buf_pos = buf_pos;
newdata = (buf_pos - ds->pcm_irq_pos) % ds->pcm_size;
first = 0;
} else {
min_buf_pos =
modulo_min(min_buf_pos, buf_pos, UINT_MAX+1L);
newdata = min(
(buf_pos - ds->pcm_irq_pos) % ds->pcm_size,
newdata);
}
VPRINTK1("PB timer hw_ptr x%04lX, appl_ptr x%04lX\n",
(unsigned long)frames_to_bytes(runtime,
runtime->status->hw_ptr),
(unsigned long)frames_to_bytes(runtime,
runtime->control->appl_ptr));
VPRINTK1("%d S=%d, irq=%04X, pos=x%04X, left=x%04X,"
" aux=x%04X space=x%04X\n", s->number,
state, ds->pcm_irq_pos, buf_pos, (int)data_avail,
(int)aux, buffer_size-data_avail);
}
remdata = newdata % dpcm->pcm_count;
xfercount = newdata - remdata; /* a multiple of pcm_count */
next_jiffies = ((dpcm->pcm_count-remdata) * HZ / dpcm->bytes_per_sec)+1;
next_jiffies = max(next_jiffies, 2U * HZ / 1000U);
dpcm->timer.expires = jiffies + next_jiffies;
VPRINTK1("jif %d buf pos x%04X newdata x%04X xc x%04X\n",
next_jiffies, min_buf_pos, newdata, xfercount);
snd_pcm_group_for_each_entry(s, dpcm->substream) {
struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
ds->pcm_buf_pos = min_buf_pos;
if (xfercount) {
if (card->support_mmap) {
ds->pcm_irq_pos = ds->pcm_irq_pos + xfercount;
if (s->stream == SNDRV_PCM_STREAM_PLAYBACK) {
VPRINTK2("write OS%d x%04x\n",
s->number,
ds->pcm_count);
hpi_handle_error(
hpi_outstream_write_buf(
ss, ds->h_stream,
&s->runtime->
dma_area[0],
xfercount,
&ds->format));
} else {
VPRINTK2("read IS%d x%04x\n",
s->number,
dpcm->pcm_count);
hpi_handle_error(
hpi_instream_read_buf(
ss, ds->h_stream,
NULL, xfercount));
}
} /* else R/W will be handled by read/write callbacks */
snd_pcm_period_elapsed(s);
}
}
if (dpcm->respawn_timer)
add_timer(&dpcm->timer);
}
/***************************** PLAYBACK OPS ****************/
static int snd_card_asihpi_playback_ioctl(struct snd_pcm_substream *substream,
unsigned int cmd, void *arg)
{
/* snd_printd(KERN_INFO "Playback ioctl %d\n", cmd); */
return snd_pcm_lib_ioctl(substream, cmd, arg);
}
static int snd_card_asihpi_playback_prepare(struct snd_pcm_substream *
substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
snd_printd(KERN_INFO "playback prepare %d\n", substream->number);
hpi_handle_error(hpi_outstream_reset(ss, dpcm->h_stream));
dpcm->pcm_irq_pos = 0;
dpcm->pcm_buf_pos = 0;
return 0;
}
static snd_pcm_uframes_t
snd_card_asihpi_playback_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
snd_pcm_uframes_t ptr;
u32 samples_played;
u16 err;
if (!snd_pcm_stream_linked(substream)) {
/* NOTE, can use samples played for playback position here and
* in timer fn because it LAGS the actual read pointer, and is a
* better representation of actual playout position
*/
err = hpi_outstream_get_info_ex(ss, dpcm->h_stream, NULL,
NULL, NULL,
&samples_played, NULL);
hpi_handle_error(err);
dpcm->pcm_buf_pos = frames_to_bytes(runtime, samples_played);
}
/* else must return most conservative value found in timer func
* by looping over all streams
*/
ptr = bytes_to_frames(runtime, dpcm->pcm_buf_pos % dpcm->pcm_size);
VPRINTK2("playback_pointer=%04ld\n", (unsigned long)ptr);
return ptr;
}
static void snd_card_asihpi_playback_format(struct snd_card_asihpi *asihpi,
u32 h_stream,
struct snd_pcm_hardware *pcmhw)
{
struct hpi_format hpi_format;
u16 format;
u16 err;
u32 h_control;
u32 sample_rate = 48000;
/* on cards without SRC, must query at valid rate,
* maybe set by external sync
*/
err = hpi_mixer_get_control(ss, asihpi->h_mixer,
HPI_SOURCENODE_CLOCK_SOURCE, 0, 0, 0,
HPI_CONTROL_SAMPLECLOCK, &h_control);
if (!err)
err = hpi_sample_clock_get_sample_rate(ss, h_control,
&sample_rate);
for (format = HPI_FORMAT_PCM8_UNSIGNED;
format <= HPI_FORMAT_PCM24_SIGNED; format++) {
err = hpi_format_create(&hpi_format,
2, format, sample_rate, 128000, 0);
if (!err)
err = hpi_outstream_query_format(ss, h_stream,
&hpi_format);
if (!err && (hpi_to_alsa_formats[format] != -1))
pcmhw->formats |=
(1ULL << hpi_to_alsa_formats[format]);
}
}
static struct snd_pcm_hardware snd_card_asihpi_playback = {
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = BUFFER_BYTES_MAX,
.period_bytes_min = PERIOD_BYTES_MIN,
.period_bytes_max = BUFFER_BYTES_MAX / PERIODS_MIN,
.periods_min = PERIODS_MIN,
.periods_max = BUFFER_BYTES_MAX / PERIOD_BYTES_MIN,
.fifo_size = 0,
};
static int snd_card_asihpi_playback_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm;
struct snd_card_asihpi *card = snd_pcm_substream_chip(substream);
int err;
dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
if (dpcm == NULL)
return -ENOMEM;
err =
hpi_outstream_open(ss, card->adapter_index,
substream->number, &dpcm->h_stream);
hpi_handle_error(err);
if (err)
kfree(dpcm);
if (err == HPI_ERROR_OBJ_ALREADY_OPEN)
return -EBUSY;
if (err)
return -EIO;
/*? also check ASI5000 samplerate source
If external, only support external rate.
If internal and other stream playing, cant switch
*/
init_timer(&dpcm->timer);
dpcm->timer.data = (unsigned long) dpcm;
dpcm->timer.function = snd_card_asihpi_timer_function;
dpcm->substream = substream;
runtime->private_data = dpcm;
runtime->private_free = snd_card_asihpi_runtime_free;
snd_card_asihpi_playback.channels_max = card->out_max_chans;
/*?snd_card_asihpi_playback.period_bytes_min =
card->out_max_chans * 4096; */
snd_card_asihpi_playback_format(card, dpcm->h_stream,
&snd_card_asihpi_playback);
snd_card_asihpi_pcm_samplerates(card, &snd_card_asihpi_playback);
snd_card_asihpi_playback.info = SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_DOUBLE |
SNDRV_PCM_INFO_BATCH |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_PAUSE;
if (card->support_mmap)
snd_card_asihpi_playback.info |= SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID;
if (card->support_grouping)
snd_card_asihpi_playback.info |= SNDRV_PCM_INFO_SYNC_START;
/* struct is copied, so can create initializer dynamically */
runtime->hw = snd_card_asihpi_playback;
if (card->support_mmap)
err = snd_pcm_hw_constraint_pow2(runtime, 0,
SNDRV_PCM_HW_PARAM_BUFFER_BYTES);
if (err < 0)
return err;
snd_pcm_hw_constraint_step(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
card->update_interval_frames);
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
card->update_interval_frames * 4, UINT_MAX);
snd_pcm_set_sync(substream);
snd_printd(KERN_INFO "playback open\n");
return 0;
}
static int snd_card_asihpi_playback_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
hpi_handle_error(hpi_outstream_close(ss, dpcm->h_stream));
snd_printd(KERN_INFO "playback close\n");
return 0;
}
static int snd_card_asihpi_playback_copy(struct snd_pcm_substream *substream,
int channel,
snd_pcm_uframes_t pos,
void __user *src,
snd_pcm_uframes_t count)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
unsigned int len;
len = frames_to_bytes(runtime, count);
if (copy_from_user(runtime->dma_area, src, len))
return -EFAULT;
VPRINTK2(KERN_DEBUG "playback copy%d %u bytes\n",
substream->number, len);
hpi_handle_error(hpi_outstream_write_buf(ss, dpcm->h_stream,
runtime->dma_area, len, &dpcm->format));
return 0;
}
static int snd_card_asihpi_playback_silence(struct snd_pcm_substream *
substream, int channel,
snd_pcm_uframes_t pos,
snd_pcm_uframes_t count)
{
unsigned int len;
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
len = frames_to_bytes(runtime, count);
snd_printd(KERN_INFO "playback silence %u bytes\n", len);
memset(runtime->dma_area, 0, len);
hpi_handle_error(hpi_outstream_write_buf(ss, dpcm->h_stream,
runtime->dma_area, len, &dpcm->format));
return 0;
}
static struct snd_pcm_ops snd_card_asihpi_playback_ops = {
.open = snd_card_asihpi_playback_open,
.close = snd_card_asihpi_playback_close,
.ioctl = snd_card_asihpi_playback_ioctl,
.hw_params = snd_card_asihpi_pcm_hw_params,
.hw_free = snd_card_asihpi_hw_free,
.prepare = snd_card_asihpi_playback_prepare,
.trigger = snd_card_asihpi_trigger,
.pointer = snd_card_asihpi_playback_pointer,
.copy = snd_card_asihpi_playback_copy,
.silence = snd_card_asihpi_playback_silence,
};
static struct snd_pcm_ops snd_card_asihpi_playback_mmap_ops = {
.open = snd_card_asihpi_playback_open,
.close = snd_card_asihpi_playback_close,
.ioctl = snd_card_asihpi_playback_ioctl,
.hw_params = snd_card_asihpi_pcm_hw_params,
.hw_free = snd_card_asihpi_hw_free,
.prepare = snd_card_asihpi_playback_prepare,
.trigger = snd_card_asihpi_trigger,
.pointer = snd_card_asihpi_playback_pointer,
};
/***************************** CAPTURE OPS ****************/
static snd_pcm_uframes_t
snd_card_asihpi_capture_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
VPRINTK2("capture pointer %d=%d\n",
substream->number, dpcm->pcm_buf_pos);
/* NOTE Unlike playback can't use actual dwSamplesPlayed
for the capture position, because those samples aren't yet in
the local buffer available for reading.
*/
return bytes_to_frames(runtime, dpcm->pcm_buf_pos % dpcm->pcm_size);
}
static int snd_card_asihpi_capture_ioctl(struct snd_pcm_substream *substream,
unsigned int cmd, void *arg)
{
return snd_pcm_lib_ioctl(substream, cmd, arg);
}
static int snd_card_asihpi_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
hpi_handle_error(hpi_instream_reset(ss, dpcm->h_stream));
dpcm->pcm_irq_pos = 0;
dpcm->pcm_buf_pos = 0;
snd_printd("capture prepare %d\n", substream->number);
return 0;
}
static void snd_card_asihpi_capture_format(struct snd_card_asihpi *asihpi,
u32 h_stream,
struct snd_pcm_hardware *pcmhw)
{
struct hpi_format hpi_format;
u16 format;
u16 err;
u32 h_control;
u32 sample_rate = 48000;
/* on cards without SRC, must query at valid rate,
maybe set by external sync */
err = hpi_mixer_get_control(ss, asihpi->h_mixer,
HPI_SOURCENODE_CLOCK_SOURCE, 0, 0, 0,
HPI_CONTROL_SAMPLECLOCK, &h_control);
if (!err)
err = hpi_sample_clock_get_sample_rate(ss, h_control,
&sample_rate);
for (format = HPI_FORMAT_PCM8_UNSIGNED;
format <= HPI_FORMAT_PCM24_SIGNED; format++) {
err = hpi_format_create(&hpi_format, 2, format,
sample_rate, 128000, 0);
if (!err)
err = hpi_instream_query_format(ss, h_stream,
&hpi_format);
if (!err)
pcmhw->formats |=
(1ULL << hpi_to_alsa_formats[format]);
}
}
static struct snd_pcm_hardware snd_card_asihpi_capture = {
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = BUFFER_BYTES_MAX,
.period_bytes_min = PERIOD_BYTES_MIN,
.period_bytes_max = BUFFER_BYTES_MAX / PERIODS_MIN,
.periods_min = PERIODS_MIN,
.periods_max = BUFFER_BYTES_MAX / PERIOD_BYTES_MIN,
.fifo_size = 0,
};
static int snd_card_asihpi_capture_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi *card = snd_pcm_substream_chip(substream);
struct snd_card_asihpi_pcm *dpcm;
int err;
dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
if (dpcm == NULL)
return -ENOMEM;
snd_printd("hpi_instream_open adapter %d stream %d\n",
card->adapter_index, substream->number);
err = hpi_handle_error(
hpi_instream_open(ss, card->adapter_index,
substream->number, &dpcm->h_stream));
if (err)
kfree(dpcm);
if (err == HPI_ERROR_OBJ_ALREADY_OPEN)
return -EBUSY;
if (err)
return -EIO;
init_timer(&dpcm->timer);
dpcm->timer.data = (unsigned long) dpcm;
dpcm->timer.function = snd_card_asihpi_timer_function;
dpcm->substream = substream;
runtime->private_data = dpcm;
runtime->private_free = snd_card_asihpi_runtime_free;
snd_card_asihpi_capture.channels_max = card->in_max_chans;
snd_card_asihpi_capture_format(card, dpcm->h_stream,
&snd_card_asihpi_capture);
snd_card_asihpi_pcm_samplerates(card, &snd_card_asihpi_capture);
snd_card_asihpi_capture.info = SNDRV_PCM_INFO_INTERLEAVED;
if (card->support_mmap)
snd_card_asihpi_capture.info |= SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID;
runtime->hw = snd_card_asihpi_capture;
if (card->support_mmap)
err = snd_pcm_hw_constraint_pow2(runtime, 0,
SNDRV_PCM_HW_PARAM_BUFFER_BYTES);
if (err < 0)
return err;
snd_pcm_hw_constraint_step(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
card->update_interval_frames);
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
card->update_interval_frames * 2, UINT_MAX);
snd_pcm_set_sync(substream);
return 0;
}
static int snd_card_asihpi_capture_close(struct snd_pcm_substream *substream)
{
struct snd_card_asihpi_pcm *dpcm = substream->runtime->private_data;
hpi_handle_error(hpi_instream_close(ss, dpcm->h_stream));
return 0;
}
static int snd_card_asihpi_capture_copy(struct snd_pcm_substream *substream,
int channel, snd_pcm_uframes_t pos,
void __user *dst, snd_pcm_uframes_t count)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
u32 data_size;
data_size = frames_to_bytes(runtime, count);
VPRINTK2("capture copy%d %d bytes\n", substream->number, data_size);
hpi_handle_error(hpi_instream_read_buf(ss, dpcm->h_stream,
runtime->dma_area, data_size));
/* Used by capture_pointer */
dpcm->pcm_irq_pos = dpcm->pcm_irq_pos + data_size;
if (copy_to_user(dst, runtime->dma_area, data_size))
return -EFAULT;
return 0;
}
static struct snd_pcm_ops snd_card_asihpi_capture_mmap_ops = {
.open = snd_card_asihpi_capture_open,
.close = snd_card_asihpi_capture_close,
.ioctl = snd_card_asihpi_capture_ioctl,
.hw_params = snd_card_asihpi_pcm_hw_params,
.hw_free = snd_card_asihpi_hw_free,
.prepare = snd_card_asihpi_capture_prepare,
.trigger = snd_card_asihpi_trigger,
.pointer = snd_card_asihpi_capture_pointer,
};
static struct snd_pcm_ops snd_card_asihpi_capture_ops = {
.open = snd_card_asihpi_capture_open,
.close = snd_card_asihpi_capture_close,
.ioctl = snd_card_asihpi_capture_ioctl,
.hw_params = snd_card_asihpi_pcm_hw_params,
.hw_free = snd_card_asihpi_hw_free,
.prepare = snd_card_asihpi_capture_prepare,
.trigger = snd_card_asihpi_trigger,
.pointer = snd_card_asihpi_capture_pointer,
.copy = snd_card_asihpi_capture_copy
};
static int __devinit snd_card_asihpi_pcm_new(struct snd_card_asihpi *asihpi,
int device, int substreams)
{
struct snd_pcm *pcm;
int err;
err = snd_pcm_new(asihpi->card, "asihpi PCM", device,
asihpi->num_outstreams, asihpi->num_instreams,
&pcm);
if (err < 0)
return err;
/* pointer to ops struct is stored, dont change ops afterwards! */
if (asihpi->support_mmap) {
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
&snd_card_asihpi_playback_mmap_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
&snd_card_asihpi_capture_mmap_ops);
} else {
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
&snd_card_asihpi_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
&snd_card_asihpi_capture_ops);
}
pcm->private_data = asihpi;
pcm->info_flags = 0;
strcpy(pcm->name, "asihpi PCM");
/*? do we want to emulate MMAP for non-BBM cards?
Jack doesn't work with ALSAs MMAP emulation - WHY NOT? */
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(asihpi->pci),
64*1024, BUFFER_BYTES_MAX);
return 0;
}
/***************************** MIXER CONTROLS ****************/
struct hpi_control {
u32 h_control;
u16 control_type;
u16 src_node_type;
u16 src_node_index;
u16 dst_node_type;
u16 dst_node_index;
u16 band;
char name[44]; /* copied to snd_ctl_elem_id.name[44]; */
};
static char *asihpi_tuner_band_names[] =
{
"invalid",
"AM",
"FM mono",
"TV NTSC-M",
"FM stereo",
"AUX",
"TV PAL BG",
"TV PAL I",
"TV PAL DK",
"TV SECAM",
};
compile_time_assert(
(ARRAY_SIZE(asihpi_tuner_band_names) ==
(HPI_TUNER_BAND_LAST+1)),
assert_tuner_band_names_size);
#if ASI_STYLE_NAMES
static char *asihpi_src_names[] =
{
"no source",
"outstream",
"line_in",
"aes_in",
"tuner",
"RF",
"clock",
"bitstr",
"mic",
"cobranet",
"analog_in",
"adapter",
};
#else
static char *asihpi_src_names[] =
{
"no source",
"PCM playback",
"line in",
"digital in",
"tuner",
"RF",
"clock",
"bitstream",
"mic",
"cobranet in",
"analog in",
"adapter",
};
#endif
compile_time_assert(
(ARRAY_SIZE(asihpi_src_names) ==
(HPI_SOURCENODE_LAST_INDEX-HPI_SOURCENODE_NONE+1)),
assert_src_names_size);
#if ASI_STYLE_NAMES
static char *asihpi_dst_names[] =
{
"no destination",
"instream",
"line_out",
"aes_out",
"RF",
"speaker" ,
"cobranet",
"analog_out",
};
#else
static char *asihpi_dst_names[] =
{
"no destination",
"PCM capture",
"line out",
"digital out",
"RF",
"speaker",
"cobranet out",
"analog out"
};
#endif
compile_time_assert(
(ARRAY_SIZE(asihpi_dst_names) ==
(HPI_DESTNODE_LAST_INDEX-HPI_DESTNODE_NONE+1)),
assert_dst_names_size);
static inline int ctl_add(struct snd_card *card, struct snd_kcontrol_new *ctl,
struct snd_card_asihpi *asihpi)
{
int err;
err = snd_ctl_add(card, snd_ctl_new1(ctl, asihpi));
if (err < 0)
return err;
else if (mixer_dump)
snd_printk(KERN_INFO "added %s(%d)\n", ctl->name, ctl->index);
return 0;
}
/* Convert HPI control name and location into ALSA control name */
static void asihpi_ctl_init(struct snd_kcontrol_new *snd_control,
struct hpi_control *hpi_ctl,
char *name)
{
memset(snd_control, 0, sizeof(*snd_control));
snd_control->name = hpi_ctl->name;
snd_control->private_value = hpi_ctl->h_control;
snd_control->iface = SNDRV_CTL_ELEM_IFACE_MIXER;
snd_control->index = 0;
if (hpi_ctl->src_node_type && hpi_ctl->dst_node_type)
sprintf(hpi_ctl->name, "%s%d to %s%d %s",
asihpi_src_names[hpi_ctl->src_node_type],
hpi_ctl->src_node_index,
asihpi_dst_names[hpi_ctl->dst_node_type],
hpi_ctl->dst_node_index,
name);
else if (hpi_ctl->dst_node_type) {
sprintf(hpi_ctl->name, "%s%d %s",
asihpi_dst_names[hpi_ctl->dst_node_type],
hpi_ctl->dst_node_index,
name);
} else {
sprintf(hpi_ctl->name, "%s%d %s",
asihpi_src_names[hpi_ctl->src_node_type],
hpi_ctl->src_node_index,
name);
}
}
/*------------------------------------------------------------
Volume controls
------------------------------------------------------------*/
#define VOL_STEP_mB 1
static int snd_asihpi_volume_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
u32 h_control = kcontrol->private_value;
u16 err;
/* native gains are in millibels */
short min_gain_mB;
short max_gain_mB;
short step_gain_mB;
err = hpi_volume_query_range(ss, h_control,
&min_gain_mB, &max_gain_mB, &step_gain_mB);
if (err) {
max_gain_mB = 0;
min_gain_mB = -10000;
step_gain_mB = VOL_STEP_mB;
}
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = min_gain_mB / VOL_STEP_mB;
uinfo->value.integer.max = max_gain_mB / VOL_STEP_mB;
uinfo->value.integer.step = step_gain_mB / VOL_STEP_mB;
return 0;
}
static int snd_asihpi_volume_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 h_control = kcontrol->private_value;
short an_gain_mB[HPI_MAX_CHANNELS];
hpi_handle_error(hpi_volume_get_gain(ss, h_control, an_gain_mB));
ucontrol->value.integer.value[0] = an_gain_mB[0] / VOL_STEP_mB;
ucontrol->value.integer.value[1] = an_gain_mB[1] / VOL_STEP_mB;
return 0;
}
static int snd_asihpi_volume_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int change;
u32 h_control = kcontrol->private_value;
short an_gain_mB[HPI_MAX_CHANNELS];
an_gain_mB[0] =
(ucontrol->value.integer.value[0]) * VOL_STEP_mB;
an_gain_mB[1] =
(ucontrol->value.integer.value[1]) * VOL_STEP_mB;
/* change = asihpi->mixer_volume[addr][0] != left ||
asihpi->mixer_volume[addr][1] != right;
*/
change = 1;
hpi_handle_error(hpi_volume_set_gain(ss, h_control, an_gain_mB));
return change;
}
static const DECLARE_TLV_DB_SCALE(db_scale_100, -10000, VOL_STEP_mB, 0);
static int __devinit snd_asihpi_volume_add(struct snd_card_asihpi *asihpi,
struct hpi_control *hpi_ctl)
{
struct snd_card *card = asihpi->card;
struct snd_kcontrol_new snd_control;
asihpi_ctl_init(&snd_control, hpi_ctl, "volume");
snd_control.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ;
snd_control.info = snd_asihpi_volume_info;
snd_control.get = snd_asihpi_volume_get;
snd_control.put = snd_asihpi_volume_put;
snd_control.tlv.p = db_scale_100;
return ctl_add(card, &snd_control, asihpi);
}
/*------------------------------------------------------------
Level controls
------------------------------------------------------------*/
static int snd_asihpi_level_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
u32 h_control = kcontrol->private_value;
u16 err;
short min_gain_mB;
short max_gain_mB;
short step_gain_mB;
err =
hpi_level_query_range(ss, h_control, &min_gain_mB,
&max_gain_mB, &step_gain_mB);
if (err) {
max_gain_mB = 2400;
min_gain_mB = -1000;
step_gain_mB = 100;
}
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = min_gain_mB / HPI_UNITS_PER_dB;
uinfo->value.integer.max = max_gain_mB / HPI_UNITS_PER_dB;
uinfo->value.integer.step = step_gain_mB / HPI_UNITS_PER_dB;
return 0;
}
static int snd_asihpi_level_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 h_control = kcontrol->private_value;
short an_gain_mB[HPI_MAX_CHANNELS];
hpi_handle_error(hpi_level_get_gain(ss, h_control, an_gain_mB));
ucontrol->value.integer.value[0] =
an_gain_mB[0] / HPI_UNITS_PER_dB;
ucontrol->value.integer.value[1] =
an_gain_mB[1] / HPI_UNITS_PER_dB;
return 0;
}
static int snd_asihpi_level_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int change;
u32 h_control = kcontrol->private_value;
short an_gain_mB[HPI_MAX_CHANNELS];
an_gain_mB[0] =
(ucontrol->value.integer.value[0]) * HPI_UNITS_PER_dB;
an_gain_mB[1] =
(ucontrol->value.integer.value[1]) * HPI_UNITS_PER_dB;
/* change = asihpi->mixer_level[addr][0] != left ||
asihpi->mixer_level[addr][1] != right;
*/
change = 1;
hpi_handle_error(hpi_level_set_gain(ss, h_control, an_gain_mB));
return change;
}
static const DECLARE_TLV_DB_SCALE(db_scale_level, -1000, 100, 0);
static int __devinit snd_asihpi_level_add(struct snd_card_asihpi *asihpi,
struct hpi_control *hpi_ctl)
{
struct snd_card *card = asihpi->card;
struct snd_kcontrol_new snd_control;
/* can't use 'volume' cos some nodes have volume as well */
asihpi_ctl_init(&snd_control, hpi_ctl, "level");
snd_control.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ;
snd_control.info = snd_asihpi_level_info;
snd_control.get = snd_asihpi_level_get;
snd_control.put = snd_asihpi_level_put;
snd_control.tlv.p = db_scale_level;
return ctl_add(card, &snd_control, asihpi);
}
/*------------------------------------------------------------
AESEBU controls
------------------------------------------------------------*/
/* AESEBU format */
static char *asihpi_aesebu_format_names[] =
{
"N/A",
"S/PDIF",
"AES/EBU",
};
static int snd_asihpi_aesebu_format_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 3;
if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items)
uinfo->value.enumerated.item =
uinfo->value.enumerated.items - 1;
strcpy(uinfo->value.enumerated.name,
asihpi_aesebu_format_names[uinfo->value.enumerated.item]);
return 0;
}
static int snd_asihpi_aesebu_format_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol,
u16 (*func)(const struct hpi_hsubsys *, u32, u16 *))
{
u32 h_control = kcontrol->private_value;
u16 source, err;
err = func(ss, h_control, &source);
/* default to N/A */
ucontrol->value.enumerated.item[0] = 0;
/* return success but set the control to N/A */
if (err)
return 0;
if (source == HPI_AESEBU_FORMAT_SPDIF)
ucontrol->value.enumerated.item[0] = 1;
if (source == HPI_AESEBU_FORMAT_AESEBU)
ucontrol->value.enumerated.item[0] = 2;
return 0;
}
static int snd_asihpi_aesebu_format_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol,
u16 (*func)(const struct hpi_hsubsys *, u32, u16))
{
u32 h_control = kcontrol->private_value;
/* default to S/PDIF */
u16 source = HPI_AESEBU_FORMAT_SPDIF;
if (ucontrol->value.enumerated.item[0] == 1)
source = HPI_AESEBU_FORMAT_SPDIF;
if (ucontrol->value.enumerated.item[0] == 2)
source = HPI_AESEBU_FORMAT_AESEBU;
if (func(ss, h_control, source) != 0)
return -EINVAL;
return 1;
}
static int snd_asihpi_aesebu_rx_format_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol) {
return snd_asihpi_aesebu_format_get(kcontrol, ucontrol,
HPI_AESEBU__receiver_get_format);
}
static int snd_asihpi_aesebu_rx_format_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol) {
return snd_asihpi_aesebu_format_put(kcontrol, ucontrol,
HPI_AESEBU__receiver_set_format);
}
static int snd_asihpi_aesebu_rxstatus_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 0X1F;
uinfo->value.integer.step = 1;
return 0;
}
static int snd_asihpi_aesebu_rxstatus_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol) {
u32 h_control = kcontrol->private_value;
u16 status;
hpi_handle_error(HPI_AESEBU__receiver_get_error_status(
ss, h_control, &status));
ucontrol->value.integer.value[0] = status;
return 0;
}
static int __devinit snd_asihpi_aesebu_rx_add(struct snd_card_asihpi *asihpi,
struct hpi_control *hpi_ctl)
{
struct snd_card *card = asihpi->card;
struct snd_kcontrol_new snd_control;
asihpi_ctl_init(&snd_control, hpi_ctl, "format");
snd_control.access = SNDRV_CTL_ELEM_ACCESS_READWRITE;
snd_control.info = snd_asihpi_aesebu_format_info;
snd_control.get = snd_asihpi_aesebu_rx_format_get;
snd_control.put = snd_asihpi_aesebu_rx_format_put;
if (ctl_add(card, &snd_control, asihpi) < 0)
return -EINVAL;
asihpi_ctl_init(&snd_control, hpi_ctl, "status");
snd_control.access =
SNDRV_CTL_ELEM_ACCESS_VOLATILE | SNDRV_CTL_ELEM_ACCESS_READ;
snd_control.info = snd_asihpi_aesebu_rxstatus_info;
snd_control.get = snd_asihpi_aesebu_rxstatus_get;
return ctl_add(card, &snd_control, asihpi);
}
static int snd_asihpi_aesebu_tx_format_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol) {
return snd_asihpi_aesebu_format_get(kcontrol, ucontrol,
HPI_AESEBU__transmitter_get_format);
}
static int snd_asihpi_aesebu_tx_format_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol) {
return snd_asihpi_aesebu_format_put(kcontrol, ucontrol,
HPI_AESEBU__transmitter_set_format);
}
static int __devinit snd_asihpi_aesebu_tx_add(struct snd_card_asihpi *asihpi,
struct hpi_control *hpi_ctl)
{
struct snd_card *card = asihpi->card;
struct snd_kcontrol_new snd_control;
asihpi_ctl_init(&snd_control, hpi_ctl, "format");
snd_control.access = SNDRV_CTL_ELEM_ACCESS_READWRITE;
snd_control.info = snd_asihpi_aesebu_format_info;
snd_control.get = snd_asihpi_aesebu_tx_format_get;
snd_control.put = snd_asihpi_aesebu_tx_format_put;
return ctl_add(card, &snd_control, asihpi);
}
/*------------------------------------------------------------
Tuner controls
------------------------------------------------------------*/
/* Gain */
static int snd_asihpi_tuner_gain_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
u32 h_control = kcontrol->private_value;
u16 err;
short idx;
u16 gain_range[3];
for (idx = 0; idx < 3; idx++) {
err = hpi_tuner_query_gain(ss, h_control,
idx, &gain_range[idx]);
if (err != 0)
return err;
}
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = ((int)gain_range[0]) / HPI_UNITS_PER_dB;
uinfo->value.integer.max = ((int)gain_range[1]) / HPI_UNITS_PER_dB;
uinfo->value.integer.step = ((int) gain_range[2]) / HPI_UNITS_PER_dB;
return 0;
}
static int snd_asihpi_tuner_gain_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
/*
struct snd_card_asihpi *asihpi = snd_kcontrol_chip(kcontrol);
*/
u32 h_control = kcontrol->private_value;
short gain;
hpi_handle_error(hpi_tuner_get_gain(ss, h_control, &gain));
ucontrol->value.integer.value[0] = gain / HPI_UNITS_PER_dB;
return 0;
}
static int snd_asihpi_tuner_gain_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
/*
struct snd_card_asihpi *asihpi = snd_kcontrol_chip(kcontrol);
*/
u32 h_control = kcontrol->private_value;
short gain;
gain = (ucontrol->value.integer.value[0]) * HPI_UNITS_PER_dB;
hpi_handle_error(hpi_tuner_set_gain(ss, h_control, gain));
return 1;
}
/* Band */
static int asihpi_tuner_band_query(struct snd_kcontrol *kcontrol,
u16 *band_list, u32 len) {
u32 h_control = kcontrol->private_value;
u16 err = 0;
u32 i;
for (i = 0; i < len; i++) {
err = hpi_tuner_query_band(ss,
h_control, i, &band_list[i]);
if (err != 0)
break;
}
if (err && (err != HPI_ERROR_INVALID_OBJ_INDEX))
return -EIO;
return i;
}
static int snd_asihpi_tuner_band_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
u16 tuner_bands[HPI_TUNER_BAND_LAST];
int num_bands = 0;
num_bands = asihpi_tuner_band_query(kcontrol, tuner_bands,
HPI_TUNER_BAND_LAST);
if (num_bands < 0)
return num_bands;
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = num_bands;
if (num_bands > 0) {
if (uinfo->value.enumerated.item >=
uinfo->value.enumerated.items)
uinfo->value.enumerated.item =
uinfo->value.enumerated.items - 1;
strcpy(uinfo->value.enumerated.name,
asihpi_tuner_band_names[
tuner_bands[uinfo->value.enumerated.item]]);
}
return 0;
}
static int snd_asihpi_tuner_band_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 h_control = kcontrol->private_value;
/*
struct snd_card_asihpi *asihpi = snd_kcontrol_chip(kcontrol);
*/
u16 band, idx;
u16 tuner_bands[HPI_TUNER_BAND_LAST];
u32 num_bands = 0;
num_bands = asihpi_tuner_band_query(kcontrol, tuner_bands,
HPI_TUNER_BAND_LAST);
hpi_handle_error(hpi_tuner_get_band(ss, h_control, &band));
ucontrol->value.enumerated.item[0] = -1;
for (idx = 0; idx < HPI_TUNER_BAND_LAST; idx++)
if (tuner_bands[idx] == band) {
ucontrol->value.enumerated.item[0] = idx;
break;
}
return 0;
}
static int snd_asihpi_tuner_band_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
/*
struct snd_card_asihpi *asihpi = snd_kcontrol_chip(kcontrol);
*/
u32 h_control = kcontrol->private_value;
u16 band;
u16 tuner_bands[HPI_TUNER_BAND_LAST];
u32 num_bands = 0;
num_bands = asihpi_tuner_band_query(kcontrol, tuner_bands,
HPI_TUNER_BAND_LAST);
band = tuner_bands[ucontrol->value.enumerated.item[0]];
hpi_handle_error(hpi_tuner_set_band(ss, h_control, band));
return 1;
}
/* Freq */
static int snd_asihpi_tuner_freq_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
u32 h_control = kcontrol->private_value;
u16 err;
u16 tuner_bands[HPI_TUNER_BAND_LAST];
u16 num_bands = 0, band_iter, idx;
u32 freq_range[3], temp_freq_range[3];
num_bands = asihpi_tuner_band_query(kcontrol, tuner_bands,
HPI_TUNER_BAND_LAST);
freq_range[0] = INT_MAX;
freq_range[1] = 0;
freq_range[2] = INT_MAX;
for (band_iter = 0; band_iter < num_bands; band_iter++) {
for (idx = 0; idx < 3; idx++) {
err = hpi_tuner_query_frequency(ss, h_control,
idx, tuner_bands[band_iter],
&temp_freq_range[idx]);
if (err != 0)
return err;
}
/* skip band with bogus stepping */
if (temp_freq_range[2] <= 0)
continue;
if (temp_freq_range[0] < freq_range[0])
freq_range[0] = temp_freq_range[0];
if (temp_freq_range[1] > freq_range[1])
freq_range[1] = temp_freq_range[1];
if (temp_freq_range[2] < freq_range[2])
freq_range[2] = temp_freq_range[2];
}
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = ((int)freq_range[0]);
uinfo->value.integer.max = ((int)freq_range[1]);
uinfo->value.integer.step = ((int)freq_range[2]);
return 0;
}
static int snd_asihpi_tuner_freq_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 h_control = kcontrol->private_value;
u32 freq;
hpi_handle_error(hpi_tuner_get_frequency(ss, h_control, &freq));
ucontrol->value.integer.value[0] = freq;
return 0;
}
static int snd_asihpi_tuner_freq_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 h_control = kcontrol->private_value;
u32 freq;
freq = ucontrol->value.integer.value[0];
hpi_handle_error(hpi_tuner_set_frequency(ss, h_control, freq));
return 1;
}
/* Tuner control group initializer */
static int __devinit snd_asihpi_tuner_add(struct snd_card_asihpi *asihpi,
struct hpi_control *hpi_ctl)
{
struct snd_card *card = asihpi->card;
struct snd_kcontrol_new snd_control;
snd_control.private_value = hpi_ctl->h_control;
snd_control.access = SNDRV_CTL_ELEM_ACCESS_READWRITE;
if (!hpi_tuner_get_gain(ss, hpi_ctl->h_control, NULL)) {
asihpi_ctl_init(&snd_control, hpi_ctl, "gain");
snd_control.info = snd_asihpi_tuner_gain_info;
snd_control.get = snd_asihpi_tuner_gain_get;
snd_control.put = snd_asihpi_tuner_gain_put;
if (ctl_add(card, &snd_control, asihpi) < 0)
return -EINVAL;
}
asihpi_ctl_init(&snd_control, hpi_ctl, "band");
snd_control.info = snd_asihpi_tuner_band_info;
snd_control.get = snd_asihpi_tuner_band_get;
snd_control.put = snd_asihpi_tuner_band_put;
if (ctl_add(card, &snd_control, asihpi) < 0)
return -EINVAL;
asihpi_ctl_init(&snd_control, hpi_ctl, "freq");
snd_control.info = snd_asihpi_tuner_freq_info;
snd_control.get = snd_asihpi_tuner_freq_get;
snd_control.put = snd_asihpi_tuner_freq_put;
return ctl_add(card, &snd_control, asihpi);
}
/*------------------------------------------------------------
Meter controls
------------------------------------------------------------*/
static int snd_asihpi_meter_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = HPI_MAX_CHANNELS;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 0x7FFFFFFF;
return 0;
}
/* linear values for 10dB steps */
static int log2lin[] = {
0x7FFFFFFF, /* 0dB */
679093956,
214748365,
67909396,
21474837,
6790940,
2147484, /* -60dB */
679094,
214748, /* -80 */
67909,
21475, /* -100 */
6791,
2147,
679,
214,
68,
21,
7,
2
};
static int snd_asihpi_meter_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 h_control = kcontrol->private_value;
short an_gain_mB[HPI_MAX_CHANNELS], i;
u16 err;
err = hpi_meter_get_peak(ss, h_control, an_gain_mB);
for (i = 0; i < HPI_MAX_CHANNELS; i++) {
if (err) {
ucontrol->value.integer.value[i] = 0;
} else if (an_gain_mB[i] >= 0) {
ucontrol->value.integer.value[i] =
an_gain_mB[i] << 16;
} else {
/* -ve is log value in millibels < -60dB,
* convert to (roughly!) linear,
*/
ucontrol->value.integer.value[i] =
log2lin[an_gain_mB[i] / -1000];
}
}
return 0;
}
static int __devinit snd_asihpi_meter_add(struct snd_card_asihpi *asihpi,
struct hpi_control *hpi_ctl, int subidx)
{
struct snd_card *card = asihpi->card;
struct snd_kcontrol_new snd_control;
asihpi_ctl_init(&snd_control, hpi_ctl, "meter");
snd_control.access =
SNDRV_CTL_ELEM_ACCESS_VOLATILE | SNDRV_CTL_ELEM_ACCESS_READ;
snd_control.info = snd_asihpi_meter_info;
snd_control.get = snd_asihpi_meter_get;
snd_control.index = subidx;
return ctl_add(card, &snd_control, asihpi);
}
/*------------------------------------------------------------
Multiplexer controls
------------------------------------------------------------*/
static int snd_card_asihpi_mux_count_sources(struct snd_kcontrol *snd_control)
{
u32 h_control = snd_control->private_value;
struct hpi_control hpi_ctl;
int s, err;
for (s = 0; s < 32; s++) {
err = hpi_multiplexer_query_source(ss, h_control, s,
&hpi_ctl.
src_node_type,
&hpi_ctl.
src_node_index);
if (err)
break;
}
return s;
}
static int snd_asihpi_mux_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
int err;
u16 src_node_type, src_node_index;
u32 h_control = kcontrol->private_value;
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items =
snd_card_asihpi_mux_count_sources(kcontrol);
if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items)
uinfo->value.enumerated.item =
uinfo->value.enumerated.items - 1;
err =
hpi_multiplexer_query_source(ss, h_control,
uinfo->value.enumerated.item,
&src_node_type, &src_node_index);
sprintf(uinfo->value.enumerated.name, "%s %d",
asihpi_src_names[src_node_type - HPI_SOURCENODE_NONE],
src_node_index);
return 0;
}
static int snd_asihpi_mux_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 h_control = kcontrol->private_value;
u16 source_type, source_index;
u16 src_node_type, src_node_index;
int s;
hpi_handle_error(hpi_multiplexer_get_source(ss, h_control,
&source_type, &source_index));
/* Should cache this search result! */
for (s = 0; s < 256; s++) {
if (hpi_multiplexer_query_source(ss, h_control, s,
&src_node_type, &src_node_index))
break;
if ((source_type == src_node_type)
&& (source_index == src_node_index)) {
ucontrol->value.enumerated.item[0] = s;
return 0;
}
}
snd_printd(KERN_WARNING
"control %x failed to match mux source %hu %hu\n",
h_control, source_type, source_index);
ucontrol->value.enumerated.item[0] = 0;
return 0;
}
static int snd_asihpi_mux_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int change;
u32 h_control = kcontrol->private_value;
u16 source_type, source_index;
u16 e;
change = 1;
e = hpi_multiplexer_query_source(ss, h_control,
ucontrol->value.enumerated.item[0],
&source_type, &source_index);
if (!e)
hpi_handle_error(
hpi_multiplexer_set_source(ss, h_control,
source_type, source_index));
return change;
}
static int __devinit snd_asihpi_mux_add(struct snd_card_asihpi *asihpi,
struct hpi_control *hpi_ctl)
{
struct snd_card *card = asihpi->card;
struct snd_kcontrol_new snd_control;
#if ASI_STYLE_NAMES
asihpi_ctl_init(&snd_control, hpi_ctl, "multiplexer");
#else
asihpi_ctl_init(&snd_control, hpi_ctl, "route");
#endif
snd_control.access = SNDRV_CTL_ELEM_ACCESS_READWRITE;
snd_control.info = snd_asihpi_mux_info;
snd_control.get = snd_asihpi_mux_get;
snd_control.put = snd_asihpi_mux_put;
return ctl_add(card, &snd_control, asihpi);
}
/*------------------------------------------------------------
Channel mode controls
------------------------------------------------------------*/
static int snd_asihpi_cmode_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static char *mode_names[HPI_CHANNEL_MODE_LAST] = {
"normal", "swap",
"from_left", "from_right",
"to_left", "to_right"
};
u32 h_control = kcontrol->private_value;
u16 mode;
int i;
/* HPI channel mode values can be from 1 to 6
Some adapters only support a contiguous subset
*/
for (i = 0; i < HPI_CHANNEL_MODE_LAST; i++)
if (hpi_channel_mode_query_mode(
ss, h_control, i, &mode))
break;
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = i;
if (uinfo->value.enumerated.item >= i)
uinfo->value.enumerated.item = i - 1;
strcpy(uinfo->value.enumerated.name,
mode_names[uinfo->value.enumerated.item]);
return 0;
}
static int snd_asihpi_cmode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 h_control = kcontrol->private_value;
u16 mode;
if (hpi_channel_mode_get(ss, h_control, &mode))
mode = 1;
ucontrol->value.enumerated.item[0] = mode - 1;
return 0;
}
static int snd_asihpi_cmode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int change;
u32 h_control = kcontrol->private_value;
change = 1;
hpi_handle_error(hpi_channel_mode_set(ss, h_control,
ucontrol->value.enumerated.item[0] + 1));
return change;
}
static int __devinit snd_asihpi_cmode_add(struct snd_card_asihpi *asihpi,
struct hpi_control *hpi_ctl)
{
struct snd_card *card = asihpi->card;
struct snd_kcontrol_new snd_control;
asihpi_ctl_init(&snd_control, hpi_ctl, "channel mode");
snd_control.access = SNDRV_CTL_ELEM_ACCESS_READWRITE;
snd_control.info = snd_asihpi_cmode_info;
snd_control.get = snd_asihpi_cmode_get;
snd_control.put = snd_asihpi_cmode_put;
return ctl_add(card, &snd_control, asihpi);
}
/*------------------------------------------------------------
Sampleclock source controls
------------------------------------------------------------*/
static char *sampleclock_sources[MAX_CLOCKSOURCES] =
{ "N/A", "local PLL", "AES/EBU sync", "word external", "word header",
"SMPTE", "AES/EBU in1", "auto", "network", "invalid",
"prev module",
"AES/EBU in2", "AES/EBU in3", "AES/EBU in4", "AES/EBU in5",
"AES/EBU in6", "AES/EBU in7", "AES/EBU in8"};
static int snd_asihpi_clksrc_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct snd_card_asihpi *asihpi =
(struct snd_card_asihpi *)(kcontrol->private_data);
struct clk_cache *clkcache = &asihpi->cc;
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = clkcache->count;
if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items)
uinfo->value.enumerated.item =
uinfo->value.enumerated.items - 1;
strcpy(uinfo->value.enumerated.name,
clkcache->s[uinfo->value.enumerated.item].name);
return 0;
}
static int snd_asihpi_clksrc_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_card_asihpi *asihpi =
(struct snd_card_asihpi *)(kcontrol->private_data);
struct clk_cache *clkcache = &asihpi->cc;
u32 h_control = kcontrol->private_value;
u16 source, srcindex = 0;
int i;
ucontrol->value.enumerated.item[0] = 0;
if (hpi_sample_clock_get_source(ss, h_control, &source))
source = 0;
if (source == HPI_SAMPLECLOCK_SOURCE_AESEBU_INPUT)
if (hpi_sample_clock_get_source_index(ss, h_control, &srcindex))
srcindex = 0;
for (i = 0; i < clkcache->count; i++)
if ((clkcache->s[i].source == source) &&
(clkcache->s[i].index == srcindex))
break;
ucontrol->value.enumerated.item[0] = i;
return 0;
}
static int snd_asihpi_clksrc_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_card_asihpi *asihpi =
(struct snd_card_asihpi *)(kcontrol->private_data);
struct clk_cache *clkcache = &asihpi->cc;
int change, item;
u32 h_control = kcontrol->private_value;
change = 1;
item = ucontrol->value.enumerated.item[0];
if (item >= clkcache->count)
item = clkcache->count-1;
hpi_handle_error(hpi_sample_clock_set_source(ss,
h_control, clkcache->s[item].source));
if (clkcache->s[item].source == HPI_SAMPLECLOCK_SOURCE_AESEBU_INPUT)
hpi_handle_error(hpi_sample_clock_set_source_index(ss,
h_control, clkcache->s[item].index));
return change;
}
/*------------------------------------------------------------
Clkrate controls
------------------------------------------------------------*/
/* Need to change this to enumerated control with list of rates */
static int snd_asihpi_clklocal_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = 8000;
uinfo->value.integer.max = 192000;
uinfo->value.integer.step = 100;
return 0;
}
static int snd_asihpi_clklocal_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 h_control = kcontrol->private_value;
u32 rate;
u16 e;
e = hpi_sample_clock_get_local_rate(ss, h_control, &rate);
if (!e)
ucontrol->value.integer.value[0] = rate;
else
ucontrol->value.integer.value[0] = 0;
return 0;
}
static int snd_asihpi_clklocal_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int change;
u32 h_control = kcontrol->private_value;
/* change = asihpi->mixer_clkrate[addr][0] != left ||
asihpi->mixer_clkrate[addr][1] != right;
*/
change = 1;
hpi_handle_error(hpi_sample_clock_set_local_rate(ss, h_control,
ucontrol->value.integer.value[0]));
return change;
}
static int snd_asihpi_clkrate_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = 8000;
uinfo->value.integer.max = 192000;
uinfo->value.integer.step = 100;
return 0;
}
static int snd_asihpi_clkrate_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 h_control = kcontrol->private_value;
u32 rate;
u16 e;
e = hpi_sample_clock_get_sample_rate(ss, h_control, &rate);
if (!e)
ucontrol->value.integer.value[0] = rate;
else
ucontrol->value.integer.value[0] = 0;
return 0;
}
static int __devinit snd_asihpi_sampleclock_add(struct snd_card_asihpi *asihpi,
struct hpi_control *hpi_ctl)
{
struct snd_card *card = asihpi->card;
struct snd_kcontrol_new snd_control;
struct clk_cache *clkcache = &asihpi->cc;
u32 hSC = hpi_ctl->h_control;
int has_aes_in = 0;
int i, j;
u16 source;
snd_control.private_value = hpi_ctl->h_control;
clkcache->has_local = 0;
for (i = 0; i <= HPI_SAMPLECLOCK_SOURCE_LAST; i++) {
if (hpi_sample_clock_query_source(ss, hSC,
i, &source))
break;
clkcache->s[i].source = source;
clkcache->s[i].index = 0;
clkcache->s[i].name = sampleclock_sources[source];
if (source == HPI_SAMPLECLOCK_SOURCE_AESEBU_INPUT)
has_aes_in = 1;
if (source == HPI_SAMPLECLOCK_SOURCE_LOCAL)
clkcache->has_local = 1;
}
if (has_aes_in)
/* already will have picked up index 0 above */
for (j = 1; j < 8; j++) {
if (hpi_sample_clock_query_source_index(ss, hSC,
j, HPI_SAMPLECLOCK_SOURCE_AESEBU_INPUT,
&source))
break;
clkcache->s[i].source =
HPI_SAMPLECLOCK_SOURCE_AESEBU_INPUT;
clkcache->s[i].index = j;
clkcache->s[i].name = sampleclock_sources[
j+HPI_SAMPLECLOCK_SOURCE_LAST];
i++;
}
clkcache->count = i;
asihpi_ctl_init(&snd_control, hpi_ctl, "source");
snd_control.access = SNDRV_CTL_ELEM_ACCESS_READWRITE ;
snd_control.info = snd_asihpi_clksrc_info;
snd_control.get = snd_asihpi_clksrc_get;
snd_control.put = snd_asihpi_clksrc_put;
if (ctl_add(card, &snd_control, asihpi) < 0)
return -EINVAL;
if (clkcache->has_local) {
asihpi_ctl_init(&snd_control, hpi_ctl, "local_rate");
snd_control.access = SNDRV_CTL_ELEM_ACCESS_READWRITE ;
snd_control.info = snd_asihpi_clklocal_info;
snd_control.get = snd_asihpi_clklocal_get;
snd_control.put = snd_asihpi_clklocal_put;
if (ctl_add(card, &snd_control, asihpi) < 0)
return -EINVAL;
}
asihpi_ctl_init(&snd_control, hpi_ctl, "rate");
snd_control.access =
SNDRV_CTL_ELEM_ACCESS_VOLATILE | SNDRV_CTL_ELEM_ACCESS_READ;
snd_control.info = snd_asihpi_clkrate_info;
snd_control.get = snd_asihpi_clkrate_get;
return ctl_add(card, &snd_control, asihpi);
}
/*------------------------------------------------------------
Mixer
------------------------------------------------------------*/
static int __devinit snd_card_asihpi_mixer_new(struct snd_card_asihpi *asihpi)
{
struct snd_card *card = asihpi->card;
unsigned int idx = 0;
unsigned int subindex = 0;
int err;
struct hpi_control hpi_ctl, prev_ctl;
if (snd_BUG_ON(!asihpi))
return -EINVAL;
strcpy(card->mixername, "asihpi mixer");
err =
hpi_mixer_open(ss, asihpi->adapter_index,
&asihpi->h_mixer);
hpi_handle_error(err);
if (err)
return -err;
memset(&prev_ctl, 0, sizeof(prev_ctl));
prev_ctl.control_type = -1;
for (idx = 0; idx < 2000; idx++) {
err = hpi_mixer_get_control_by_index(
ss, asihpi->h_mixer,
idx,
&hpi_ctl.src_node_type,
&hpi_ctl.src_node_index,
&hpi_ctl.dst_node_type,
&hpi_ctl.dst_node_index,
&hpi_ctl.control_type,
&hpi_ctl.h_control);
if (err) {
if (err == HPI_ERROR_CONTROL_DISABLED) {
if (mixer_dump)
snd_printk(KERN_INFO
"disabled HPI control(%d)\n",
idx);
continue;
} else
break;
}
hpi_ctl.src_node_type -= HPI_SOURCENODE_NONE;
hpi_ctl.dst_node_type -= HPI_DESTNODE_NONE;
/* ASI50xx in SSX mode has multiple meters on the same node.
Use subindex to create distinct ALSA controls
for any duplicated controls.
*/
if ((hpi_ctl.control_type == prev_ctl.control_type) &&
(hpi_ctl.src_node_type == prev_ctl.src_node_type) &&
(hpi_ctl.src_node_index == prev_ctl.src_node_index) &&
(hpi_ctl.dst_node_type == prev_ctl.dst_node_type) &&
(hpi_ctl.dst_node_index == prev_ctl.dst_node_index))
subindex++;
else
subindex = 0;
prev_ctl = hpi_ctl;
switch (hpi_ctl.control_type) {
case HPI_CONTROL_VOLUME:
err = snd_asihpi_volume_add(asihpi, &hpi_ctl);
break;
case HPI_CONTROL_LEVEL:
err = snd_asihpi_level_add(asihpi, &hpi_ctl);
break;
case HPI_CONTROL_MULTIPLEXER:
err = snd_asihpi_mux_add(asihpi, &hpi_ctl);
break;
case HPI_CONTROL_CHANNEL_MODE:
err = snd_asihpi_cmode_add(asihpi, &hpi_ctl);
break;
case HPI_CONTROL_METER:
err = snd_asihpi_meter_add(asihpi, &hpi_ctl, subindex);
break;
case HPI_CONTROL_SAMPLECLOCK:
err = snd_asihpi_sampleclock_add(
asihpi, &hpi_ctl);
break;
case HPI_CONTROL_CONNECTION: /* ignore these */
continue;
case HPI_CONTROL_TUNER:
err = snd_asihpi_tuner_add(asihpi, &hpi_ctl);
break;
case HPI_CONTROL_AESEBU_TRANSMITTER:
err = snd_asihpi_aesebu_tx_add(asihpi, &hpi_ctl);
break;
case HPI_CONTROL_AESEBU_RECEIVER:
err = snd_asihpi_aesebu_rx_add(asihpi, &hpi_ctl);
break;
case HPI_CONTROL_VOX:
case HPI_CONTROL_BITSTREAM:
case HPI_CONTROL_MICROPHONE:
case HPI_CONTROL_PARAMETRIC_EQ:
case HPI_CONTROL_COMPANDER:
default:
if (mixer_dump)
snd_printk(KERN_INFO
"untranslated HPI control"
"(%d) %d %d %d %d %d\n",
idx,
hpi_ctl.control_type,
hpi_ctl.src_node_type,
hpi_ctl.src_node_index,
hpi_ctl.dst_node_type,
hpi_ctl.dst_node_index);
continue;
};
if (err < 0)
return err;
}
if (HPI_ERROR_INVALID_OBJ_INDEX != err)
hpi_handle_error(err);
snd_printk(KERN_INFO "%d mixer controls found\n", idx);
return 0;
}
/*------------------------------------------------------------
/proc interface
------------------------------------------------------------*/
static void
snd_asihpi_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_card_asihpi *asihpi = entry->private_data;
u16 version;
u32 h_control;
u32 rate = 0;
u16 source = 0;
int err;
snd_iprintf(buffer, "ASIHPI driver proc file\n");
snd_iprintf(buffer,
"adapter ID=%4X\n_index=%d\n"
"num_outstreams=%d\n_num_instreams=%d\n",
asihpi->type, asihpi->adapter_index,
asihpi->num_outstreams, asihpi->num_instreams);
version = asihpi->version;
snd_iprintf(buffer,
"serial#=%d\n_hw version %c%d\nDSP code version %03d\n",
asihpi->serial_number, ((version >> 3) & 0xf) + 'A',
version & 0x7,
((version >> 13) * 100) + ((version >> 7) & 0x3f));
err = hpi_mixer_get_control(ss, asihpi->h_mixer,
HPI_SOURCENODE_CLOCK_SOURCE, 0, 0, 0,
HPI_CONTROL_SAMPLECLOCK, &h_control);
if (!err) {
err = hpi_sample_clock_get_sample_rate(ss,
h_control, &rate);
err += hpi_sample_clock_get_source(ss, h_control, &source);
if (!err)
snd_iprintf(buffer, "sample_clock=%d_hz, source %s\n",
rate, sampleclock_sources[source]);
}
}
static void __devinit snd_asihpi_proc_init(struct snd_card_asihpi *asihpi)
{
struct snd_info_entry *entry;
if (!snd_card_proc_new(asihpi->card, "info", &entry))
snd_info_set_text_ops(entry, asihpi, snd_asihpi_proc_read);
}
/*------------------------------------------------------------
HWDEP
------------------------------------------------------------*/
static int snd_asihpi_hpi_open(struct snd_hwdep *hw, struct file *file)
{
if (enable_hpi_hwdep)
return 0;
else
return -ENODEV;
}
static int snd_asihpi_hpi_release(struct snd_hwdep *hw, struct file *file)
{
if (enable_hpi_hwdep)
return asihpi_hpi_release(file);
else
return -ENODEV;
}
static int snd_asihpi_hpi_ioctl(struct snd_hwdep *hw, struct file *file,
unsigned int cmd, unsigned long arg)
{
if (enable_hpi_hwdep)
return asihpi_hpi_ioctl(file, cmd, arg);
else
return -ENODEV;
}
/* results in /dev/snd/hwC#D0 file for each card with index #
also /proc/asound/hwdep will contain '#-00: asihpi (HPI) for each card'
*/
static int __devinit snd_asihpi_hpi_new(struct snd_card_asihpi *asihpi,
int device, struct snd_hwdep **rhwdep)
{
struct snd_hwdep *hw;
int err;
if (rhwdep)
*rhwdep = NULL;
err = snd_hwdep_new(asihpi->card, "HPI", device, &hw);
if (err < 0)
return err;
strcpy(hw->name, "asihpi (HPI)");
hw->iface = SNDRV_HWDEP_IFACE_LAST;
hw->ops.open = snd_asihpi_hpi_open;
hw->ops.ioctl = snd_asihpi_hpi_ioctl;
hw->ops.release = snd_asihpi_hpi_release;
hw->private_data = asihpi;
if (rhwdep)
*rhwdep = hw;
return 0;
}
/*------------------------------------------------------------
CARD
------------------------------------------------------------*/
static int __devinit snd_asihpi_probe(struct pci_dev *pci_dev,
const struct pci_device_id *pci_id)
{
int err;
u16 version;
int pcm_substreams;
struct hpi_adapter *hpi_card;
struct snd_card *card;
struct snd_card_asihpi *asihpi;
u32 h_control;
u32 h_stream;
static int dev;
if (dev >= SNDRV_CARDS)
return -ENODEV;
/* Should this be enable[hpi_card->index] ? */
if (!enable[dev]) {
dev++;
return -ENOENT;
}
err = asihpi_adapter_probe(pci_dev, pci_id);
if (err < 0)
return err;
hpi_card = pci_get_drvdata(pci_dev);
/* first try to give the card the same index as its hardware index */
err = snd_card_create(hpi_card->index,
id[hpi_card->index], THIS_MODULE,
sizeof(struct snd_card_asihpi),
&card);
if (err < 0) {
/* if that fails, try the default index==next available */
err =
snd_card_create(index[dev], id[dev],
THIS_MODULE,
sizeof(struct snd_card_asihpi),
&card);
if (err < 0)
return err;
snd_printk(KERN_WARNING
"**** WARNING **** adapter index %d->ALSA index %d\n",
hpi_card->index, card->number);
}
asihpi = (struct snd_card_asihpi *) card->private_data;
asihpi->card = card;
asihpi->pci = hpi_card->pci;
asihpi->adapter_index = hpi_card->index;
hpi_handle_error(hpi_adapter_get_info(ss,
asihpi->adapter_index,
&asihpi->num_outstreams,
&asihpi->num_instreams,
&asihpi->version,
&asihpi->serial_number, &asihpi->type));
version = asihpi->version;
snd_printk(KERN_INFO "adapter ID=%4X index=%d num_outstreams=%d "
"num_instreams=%d S/N=%d\n"
"hw version %c%d DSP code version %03d\n",
asihpi->type, asihpi->adapter_index,
asihpi->num_outstreams,
asihpi->num_instreams, asihpi->serial_number,
((version >> 3) & 0xf) + 'A',
version & 0x7,
((version >> 13) * 100) + ((version >> 7) & 0x3f));
pcm_substreams = asihpi->num_outstreams;
if (pcm_substreams < asihpi->num_instreams)
pcm_substreams = asihpi->num_instreams;
err = hpi_adapter_get_property(ss, asihpi->adapter_index,
HPI_ADAPTER_PROPERTY_CAPS1,
NULL, &asihpi->support_grouping);
if (err)
asihpi->support_grouping = 0;
err = hpi_adapter_get_property(ss, asihpi->adapter_index,
HPI_ADAPTER_PROPERTY_CAPS2,
&asihpi->support_mrx, NULL);
if (err)
asihpi->support_mrx = 0;
err = hpi_adapter_get_property(ss, asihpi->adapter_index,
HPI_ADAPTER_PROPERTY_INTERVAL,
NULL, &asihpi->update_interval_frames);
if (err)
asihpi->update_interval_frames = 512;
hpi_handle_error(hpi_instream_open(ss, asihpi->adapter_index,
0, &h_stream));
err = hpi_instream_host_buffer_free(ss, h_stream);
asihpi->support_mmap = (!err);
hpi_handle_error(hpi_instream_close(ss, h_stream));
err = hpi_adapter_get_property(ss, asihpi->adapter_index,
HPI_ADAPTER_PROPERTY_CURCHANNELS,
&asihpi->in_max_chans, &asihpi->out_max_chans);
if (err) {
asihpi->in_max_chans = 2;
asihpi->out_max_chans = 2;
}
snd_printk(KERN_INFO "supports mmap:%d grouping:%d mrx:%d\n",
asihpi->support_mmap,
asihpi->support_grouping,
asihpi->support_mrx
);
err = snd_card_asihpi_pcm_new(asihpi, 0, pcm_substreams);
if (err < 0) {
snd_printk(KERN_ERR "pcm_new failed\n");
goto __nodev;
}
err = snd_card_asihpi_mixer_new(asihpi);
if (err < 0) {
snd_printk(KERN_ERR "mixer_new failed\n");
goto __nodev;
}
err = hpi_mixer_get_control(ss, asihpi->h_mixer,
HPI_SOURCENODE_CLOCK_SOURCE, 0, 0, 0,
HPI_CONTROL_SAMPLECLOCK, &h_control);
if (!err)
err = hpi_sample_clock_set_local_rate(
ss, h_control, adapter_fs);
snd_asihpi_proc_init(asihpi);
/* always create, can be enabled or disabled dynamically
by enable_hwdep module param*/
snd_asihpi_hpi_new(asihpi, 0, NULL);
if (asihpi->support_mmap)
strcpy(card->driver, "ASIHPI-MMAP");
else
strcpy(card->driver, "ASIHPI");
sprintf(card->shortname, "AudioScience ASI%4X", asihpi->type);
sprintf(card->longname, "%s %i",
card->shortname, asihpi->adapter_index);
err = snd_card_register(card);
if (!err) {
hpi_card->snd_card_asihpi = card;
dev++;
return 0;
}
__nodev:
snd_card_free(card);
snd_printk(KERN_ERR "snd_asihpi_probe error %d\n", err);
return err;
}
static void __devexit snd_asihpi_remove(struct pci_dev *pci_dev)
{
struct hpi_adapter *hpi_card = pci_get_drvdata(pci_dev);
snd_card_free(hpi_card->snd_card_asihpi);
hpi_card->snd_card_asihpi = NULL;
asihpi_adapter_remove(pci_dev);
}
static DEFINE_PCI_DEVICE_TABLE(asihpi_pci_tbl) = {
{HPI_PCI_VENDOR_ID_TI, HPI_PCI_DEV_ID_DSP6205,
HPI_PCI_VENDOR_ID_AUDIOSCIENCE, PCI_ANY_ID, 0, 0,
(kernel_ulong_t)HPI_6205},
{HPI_PCI_VENDOR_ID_TI, HPI_PCI_DEV_ID_PCI2040,
HPI_PCI_VENDOR_ID_AUDIOSCIENCE, PCI_ANY_ID, 0, 0,
(kernel_ulong_t)HPI_6000},
{0,}
};
MODULE_DEVICE_TABLE(pci, asihpi_pci_tbl);
static struct pci_driver driver = {
.name = "asihpi",
.id_table = asihpi_pci_tbl,
.probe = snd_asihpi_probe,
.remove = __devexit_p(snd_asihpi_remove),
#ifdef CONFIG_PM
/* .suspend = snd_asihpi_suspend,
.resume = snd_asihpi_resume, */
#endif
};
static int __init snd_asihpi_init(void)
{
asihpi_init();
return pci_register_driver(&driver);
}
static void __exit snd_asihpi_exit(void)
{
pci_unregister_driver(&driver);
asihpi_exit();
}
module_init(snd_asihpi_init)
module_exit(snd_asihpi_exit)
|
997249.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* map_next.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ourgot <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/10 06:49:27 by ourgot #+# #+# */
/* Updated: 2020/03/10 06:49:27 by ourgot ### ########.fr */
/* */
/* ************************************************************************** */
#include "filtermapobj.h"
#include "libft.h"
void *map_next(t_obj *it)
{
t_state *state;
t_f1 f;
void *item;
state = it->state;
if ((item = next(state->inner)))
{
f = state->func;
ft_memcpy(state->item, item, it->meta->itemsize);
return ((*f)(state->item));
}
state->inner = NULL;
return (NULL);
}
void *map_next_r(t_obj *it)
{
t_state *state;
t_f2_r f;
void *item;
state = it->state;
if ((item = next(state->inner)))
{
f = state->func;
ft_memcpy(state->item, item, it->meta->itemsize);
return ((*f)(state->arg, state->item));
}
state->inner = NULL;
return (NULL);
}
|
425177.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "darray.h"
struct Darray {
char *da;
size_t data_size;
int array_length;
};
Darray *da_new(size_t data_size)
{
Darray *da = malloc(sizeof(Darray));
if ( da == NULL )
{
perror("da_new()");
exit(1);
}
da->da = NULL;
da->data_size = data_size;
da->array_length = 0;
return da;
}
void da_push(Darray *da, void *v)
{
if ( da->array_length == 0 )
da->da = malloc(da->data_size);
else if ( !(da->array_length & (da->array_length - 1)) )
{
da->da = realloc(da->da, 2 * da->array_length * da->data_size);
if ( da->da == NULL )
{
perror("da_append()");
exit(1);
}
}
char *dest = da->da + da->data_size * da->array_length;
if ( v != NULL )
memcpy(dest, (char *) v, da->data_size);
da->array_length++;
}
void *da_unpack(Darray *da, int *length)
{
char *a = NULL;
if ( da->array_length > 0 )
{
a = realloc(da->da, da->array_length * da->data_size);
if ( a == NULL )
{
perror("da_unpack()");
exit(1);
}
}
*length = da->array_length;
free(da);
return a;
}
|
665325.c | //------------------------------------------------------------------------------
// GB_Asaxpy3B_M: hard-coded saxpy3 method for a semiring
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB_AxB_defs__lor_second_bool.h"
#ifndef GBCOMPACT
//------------------------------------------------------------------------------
// C=A*B, C<M>=A*B, C<!M>=A*B: saxpy method (Gustavson + Hash)
//------------------------------------------------------------------------------
#if ( !GB_DISABLE )
#include "GB_AxB_saxpy3_template.h"
GrB_Info GB (_Asaxpy3B_M__lor_second_bool)
(
GrB_Matrix C, // C<M>=A*B, C sparse or hypersparse
const GrB_Matrix M, const bool Mask_struct,
const bool M_packed_in_place,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
GB_saxpy3task_struct *restrict SaxpyTasks,
const int ntasks, const int nfine, const int nthreads,
const int do_sort,
GB_Context Context
)
{
if (GB_IS_SPARSE (A) && GB_IS_SPARSE (B))
{
// both A and B are sparse
#define GB_META16
#define GB_NO_MASK 0
#define GB_MASK_COMP 0
#define GB_A_IS_SPARSE 1
#define GB_A_IS_HYPER 0
#define GB_A_IS_BITMAP 0
#define GB_A_IS_FULL 0
#define GB_B_IS_SPARSE 1
#define GB_B_IS_HYPER 0
#define GB_B_IS_BITMAP 0
#define GB_B_IS_FULL 0
#include "GB_meta16_definitions.h"
#include "GB_AxB_saxpy3_template.c"
}
else
{
// general case
#undef GB_META16
#define GB_NO_MASK 0
#define GB_MASK_COMP 0
#include "GB_meta16_definitions.h"
#include "GB_AxB_saxpy3_template.c"
}
return (GrB_SUCCESS) ;
}
#endif
#endif
|
976487.c | #include <ctype.h>
#include <string.h>
#include "cixl/arg.h"
#include "cixl/bin.h"
#include "cixl/cx.h"
#include "cixl/error.h"
#include "cixl/fimp.h"
#include "cixl/func.h"
#include "cixl/lib.h"
#include "cixl/lib/const.h"
#include "cixl/op.h"
#include "cixl/scope.h"
#include "cixl/str.h"
static ssize_t define_eval(struct cx_rmacro_eval *eval,
struct cx_bin *bin,
size_t tok_idx,
struct cx *cx) {
for (struct cx_tok *t = cx_vec_start(&eval->toks);
t != cx_vec_end(&eval->toks);
t++) {
struct cx_op *op = cx_op_new(bin, CX_OPUTCONST(), tok_idx);
op->as_putconst.id = cx_sym(cx, t->as_ptr);
op->as_putconst.lib = *cx->lib;
}
return tok_idx+1;
}
static bool define_parse(struct cx *cx, FILE *in, struct cx_vec *out) {
int row = cx->row, col = cx->col;
struct cx_vec toks;
cx_vec_init(&toks, sizeof(struct cx_tok));
struct cx_rmacro_eval *eval = cx_rmacro_eval_new(define_eval);
bool ok = false;
if (!cx_parse_tok(cx, in, &toks, false)) {
cx_error(cx, row, col, "Missing define id");
goto exit1;
}
struct cx_tok id_tok = *(struct cx_tok *)cx_vec_pop(&toks);
if (id_tok.type != CX_TID() && id_tok.type != CX_TGROUP()) {
cx_error(cx, id_tok.row, id_tok.col, "Invalid define id");
goto exit1;
}
if (!cx_parse_end(cx, in, &toks, true)) {
if (!cx->errors.count) { cx_error(cx, row, col, "Missing define end"); }
goto exit1;
}
struct cx_scope *s = cx_begin(cx, NULL);
if (!cx_eval_toks(cx, &toks)) { goto exit2; }
bool put(struct cx_tok *id, struct cx_type *type) {
struct cx_box *src = cx_pop(s, true);
if (!src) {
cx_error(cx, row, col, "Missing value for id: %s", id);
return false;
}
if (type && !cx_is(src->type, type)) {
cx_error(cx, row, col,
"Expected type %s, actual: %s",
type->id, src->type->id);
return false;
}
struct cx_box *dst = cx_put_const(*cx->lib, cx_sym(cx, id->as_ptr), false);
if (dst) {
*dst = *src;
cx_tok_copy(cx_vec_push(&eval->toks), id);
}
return true;
}
if (id_tok.type == CX_TID()) {
if (!put(&id_tok, NULL)) { goto exit2; }
ok = true;
} else {
struct cx_vec *id_toks = &id_tok.as_vec, ids, types;
cx_vec_init(&ids, sizeof(struct cx_tok));
cx_vec_init(&types, sizeof(struct cx_type *));
bool push_type(struct cx_type *type) {
if (ids.count == types.count) {
cx_error(cx, cx->row, cx->col, "Missing define id");
return false;
}
for (struct cx_tok *id = cx_vec_get(&ids, types.count);
id != cx_vec_end(&ids);
id++) {
*(struct cx_type **)cx_vec_push(&types) = type;
}
return true;
}
cx_do_vec(id_toks, struct cx_tok, t) {
if (t->type == CX_TID()) {
char *id = t->as_ptr;
if (isupper(id[0])) {
struct cx_type *type = cx_get_type(cx, id, false);
if (!type || !push_type(type)) { goto exit3; }
} else {
*(struct cx_tok *)cx_vec_push(&ids) = *t;
}
} else {
goto exit3;
}
}
if (ids.count > types.count && !push_type(NULL)) { goto exit3; }
struct cx_tok *id = cx_vec_peek(&ids, 0);
struct cx_type **type = cx_vec_peek(&types, 0);
for (; id >= (struct cx_tok *)ids.items; id--, type--) {
if (!put(id, *type)) { goto exit3; }
}
ok = true;
exit3:
cx_vec_deinit(&ids);
cx_vec_deinit(&types);
}
cx_tok_deinit(&id_tok);
if (ok && s->stack.count) { cx_error(cx, row, col, "Too many values in define"); }
exit2:
cx_reset(s);
cx_end(cx);
exit1: {
cx_do_vec(&toks, struct cx_tok, t) { cx_tok_deinit(t); }
cx_vec_deinit(&toks);
if (ok) {
cx_tok_init(cx_vec_push(out), CX_TRMACRO(), row, col)->as_ptr = eval;
} else {
cx_rmacro_eval_deref(eval);
}
return ok;
}
}
cx_lib(cx_init_const, "cx/const") {
//struct cx *cx = lib->cx;
cx_add_rmacro(lib, "define:", define_parse);
return true;
}
|
642463.c | /* NMshowcell.c -
*
* This file provides procedures that highlight all the paint
* in a given cell by drawing it on the highlight layer. It
* is used for things like displaying all the wiring in a net,
* or for displaying splotches around labels with a given name.
*
* *********************************************************************
* * Copyright (C) 1985, 1990 Regents of the University of California. *
* * Permission to use, copy, modify, and distribute this *
* * software and its documentation for any purpose and without *
* * fee is hereby granted, provided that the above copyright *
* * notice appear in all copies. The University of California *
* * makes no representations about the suitability of this *
* * software for any purpose. It is provided "as is" without *
* * express or implied warranty. Export of this software outside *
* * of the United States of America may require an export license. *
* *********************************************************************
*/
#ifndef lint
static char rcsid[] __attribute__ ((unused)) = "$Header: /usr/cvsroot/magic-8.0/netmenu/NMshowcell.c,v 1.1.1.1 2008/02/03 20:43:50 tim Exp $";
#endif /* not lint */
#include <stdio.h>
#include "utils/magic.h"
#include "utils/geometry.h"
#include "tiles/tile.h"
#include "utils/hash.h"
#include "database/database.h"
#include "windows/windows.h"
#include "graphics/graphics.h"
#include "dbwind/dbwind.h"
#include "utils/styles.h"
#include "textio/textio.h"
#include "utils/main.h"
#include "select/select.h"
#include "netmenu/nmInt.h"
/* The following owns describe the cell currently being highlighted,
* and the root cell that identifies windows in which the highlighting
* is to occur. The cell's coordinate system is assumed to be the
* same as the coordinate system of the root cell.
*/
static CellUse *nmscUse = NULL;
static CellDef *nmscRootDef = NULL; /* NULL means no cell currently
* being highlighted.
*/
/* The use and def below are used for highlighting nets and
* labels.
*/
static CellUse *nmscShowUse = NULL;
static CellDef *nmscShowDef = NULL;
/*
* ----------------------------------------------------------------------------
*
* NMRedrawCell --
*
* This procedure is invoked by the highlight code to redraw
* the highlights managed by this file. The window has been
* already locked by the highlight code.
*
* Results:
* None.
*
* Side effects:
* Highlights are redrawn, if there is a cell to be highlighted
* and if it contains information in the area to be redrawn.
*
* ----------------------------------------------------------------------------
*/
static Plane *nmscPlane; /* Shared between procs below. */
extern int nmscRedrawFunc(); /* Forward declaration. */
int
NMRedrawCell(window, plane)
MagWindow *window; /* Window in which to redisplay. */
Plane *plane; /* Non-space tiles on this plane indicate,
* in root cell coordinates, the areas where
* highlight information must be redrawn.
*/
{
int i;
Rect area;
/* Make sure that cell highlights are supposed to appear in
* this window.
*/
if (((CellUse *)(window->w_surfaceID))->cu_def != nmscRootDef) return 0;
/* If this window is zoomed way out (less than 1 pixel per lambda)
* use solid highlighting to maximize visibility. It the window
* is at a reasonably high magnification, then use a paler stipple
* so that the material type is easy to see through the highlighting.
*/
if (window->w_scale > SUBPIXEL)
GrSetStuff(STYLE_PALEHIGHLIGHTS);
else
GrSetStuff(STYLE_SOLIDHIGHLIGHTS);
/* Find all paint on all layers in the area where we may have to
* redraw.
*/
if (!DBBoundPlane(plane, &area)) return 0;
nmscPlane = plane;
for (i = PL_TECHDEPBASE; i < DBNumPlanes; i += 1)
{
(void) DBSrPaintArea((Tile *) NULL, nmscUse->cu_def->cd_planes[i],
&area, &DBAllButSpaceAndDRCBits,
nmscRedrawFunc, (ClientData) window);
}
return 0;
}
int
nmscRedrawFunc(tile, window)
Tile *tile; /* Tile to be redisplayed on highlight layer.*/
MagWindow *window; /* Window in which to redisplay. */
{
Rect area, screenArea;
extern int nmscAlways1(); /* Forward reference. */
TiToRect(tile, &area);
if (!DBSrPaintArea((Tile *) NULL, nmscPlane, &area,
&DBAllButSpaceBits, nmscAlways1, (ClientData) NULL))
return 0;
WindSurfaceToScreen(window, &area, &screenArea);
GrFastBox(&screenArea);
return 0;
}
int
nmscAlways1()
{
return 1;
}
/*
* ----------------------------------------------------------------------------
*
* NMUnsetCell --
*
* This procedure causes us to forget about the cell currently
* being highlighted, and erase the highlights from the screen.
*
* Results:
* None.
*
* Side effects:
* From now on, no cell will be highlighted. The screen is
* redrawn to remove existing cell highlights.
*
* ----------------------------------------------------------------------------
*/
void
NMUnsetCell()
{
CellDef *oldDef;
if (nmscRootDef == NULL) return;
oldDef = nmscRootDef;
nmscRootDef = NULL;
DBWHLRedraw(oldDef, &nmscUse->cu_def->cd_bbox, TRUE);
}
/*
* ----------------------------------------------------------------------------
*
* NMShowCell --
*
* This procedure sets up a particular cell to be highlighted,
* and draws its paint on the highlight layer.
*
* Results:
* None.
*
* Side effects:
* If there was already a cell being highlighted, it is unset
* and erased. Then the new cell is remembered, and the screen
* is redisplayed.
*
* Notes:
* When using this, make sure the highlight use's bounds are
* properly recomputed.
*
* ----------------------------------------------------------------------------
*/
void
NMShowCell(use, rootDef)
CellUse *use; /* Cell whose contents are to be drawn
* on the highlight plane.
*/
CellDef *rootDef; /* Highlights will appear in all windows
* with this root definition.
*/
{
if (nmscRootDef != NULL) NMUnsetCell();
nmscRootDef = rootDef;
nmscUse = use;
DBWHLRedraw(nmscRootDef, &nmscUse->cu_def->cd_bbox, FALSE);
}
/*
* ----------------------------------------------------------------------------
*
* nmGetShowCell --
*
* This procedure makes sure that nmscShowUse and nmscShowDef
* have been properlay initialized to refer to a cell definition
* named "__SHOW__".
*
* Results:
* None.
*
* Side effects:
* A new cell use and/or def are created if necessary.
*
* ----------------------------------------------------------------------------
*/
void
nmGetShowCell()
{
if (nmscShowUse != NULL) return;
nmscShowDef = DBCellLookDef("__SHOW__");
if (nmscShowDef == NULL)
{
nmscShowDef = DBCellNewDef("__SHOW__");
ASSERT (nmscShowDef != (CellDef *) NULL, "nmGetShowCell");
DBCellSetAvail(nmscShowDef);
nmscShowDef->cd_flags |= CDINTERNAL;
}
nmscShowUse = DBCellNewUse(nmscShowDef, (char *) NULL);
DBSetTrans(nmscShowUse, &GeoIdentityTransform);
nmscShowUse->cu_expandMask = CU_DESCEND_SPECIAL;
}
/*
* ----------------------------------------------------------------------------
*
* NMShowUnderBox --
*
* This procedure copies into the show cell all paint connected to
* anything underneath the box. The show cell is then highlighted.
*
* Results:
* None.
*
* Side effects:
* Any previous highlighted cell is unset, and any previous contents
* of the show cell are destroyed.
*
* ----------------------------------------------------------------------------
*/
void
NMShowUnderBox()
{
CellDef *rootDef;
MagWindow *w;
SearchContext scx;
NMUnsetCell();
nmGetShowCell();
w = ToolGetBoxWindow(&scx.scx_area, (int *) NULL); if (w == NULL)
{
TxError("There's no box! Please use the box to select one\n");
TxError("or more nets to be highlighted.\n");
return;
}
scx.scx_use = (CellUse *) w->w_surfaceID;
scx.scx_trans = GeoIdentityTransform;
/* Expand the box area by one so we'll get everything that even
* touches it.
*/
GEO_EXPAND(&scx.scx_area, 1, &scx.scx_area);
rootDef = scx.scx_use->cu_def;
DBWAreaChanged(nmscShowDef, &nmscShowDef->cd_bbox, DBW_ALLWINDOWS,
&DBAllButSpaceBits);
DBCellClearDef(nmscShowUse->cu_def);
DBTreeCopyConnect(&scx, &DBAllButSpaceAndDRCBits, 0,
DBConnectTbl, &TiPlaneRect, SEL_DO_LABELS, nmscShowUse);
DBWAreaChanged(nmscShowDef, &nmscShowDef->cd_bbox, DBW_ALLWINDOWS,
&DBAllButSpaceBits);
NMShowCell(nmscShowUse, rootDef);
}
/*
* ----------------------------------------------------------------------------
*
* NMShowRoutedNet --
*
* This procedure copies into the show cell all paint connected to
* any terminal of the currently selected net. The show cell is then
* highlighted. If an argument is given, that net is selected and then
* highlighted, instead.
*
* Results:
* None.
*
* Side effects:
* Any previous highlighted cell is unset, and any previous contents
* of the show cell are destroyed.
*
* ----------------------------------------------------------------------------
*/
int
NMShowRoutedNet(netName)
char * netName;
{
int nmShowRoutedNetFunc();
if (netName == NULL)
{
if (NMCurNetName == NULL)
{
TxError("You must select a net before you can trace it.\n");
return 0;
}
else netName = NMCurNetName;
}
NMUnsetCell();
nmGetShowCell();
DBWAreaChanged(nmscShowDef, &nmscShowDef->cd_bbox, DBW_ALLWINDOWS,
&DBAllButSpaceBits);
DBCellClearDef(nmscShowUse->cu_def);
NMSelectNet(netName);
if(NMCurNetName==NULL)
{
TxError("The net list has no net containing the terminal \"%s\"\n",
netName);
return 0;
}
(void) NMEnumTerms(NMCurNetName, nmShowRoutedNetFunc,
(ClientData) EditCellUse);
DBWAreaChanged(nmscShowDef, &nmscShowDef->cd_bbox, DBW_ALLWINDOWS,
&DBAllButSpaceBits);
NMShowCell(nmscShowUse, EditCellUse->cu_def);
return 0;
}
/*
* ----------------------------------------------------------------------------
*
* nmShowRoutedNetFunc --
*
* This procedure simply calls nmSRNFunc with the name of a terminal.
*
* Results:
* Returns 0.
*
* Side effects:
* Paints into the highlight cell.
*
* ----------------------------------------------------------------------------
*/
int
nmShowRoutedNetFunc(name, clientData)
char *name;
ClientData clientData;
{
int nmSRNFunc();
(void) DBSrLabelLoc((CellUse *) clientData, name, nmSRNFunc, clientData);
return(0);
}
/*
* ----------------------------------------------------------------------------
*
* nmSRNFunc --
*
* This procedure copies into the show cell all paint connected to
* anything underneath the terminal.
*
* Results:
* Returns 0.
*
* Side effects:
* None.
*
* ----------------------------------------------------------------------------
*/
/*ARGSUSED*/
int
nmSRNFunc(rect, name, label, cdarg)
Rect *rect;
char *name; /* Unused */
Label *label;
ClientData cdarg;
{
SearchContext scx;
/* Expand the box area by one so we'll get everything that even
* touches it. Search on layers connected to the layer of the label.
*/
scx.scx_area = *rect;
GEO_EXPAND(&scx.scx_area, 1, &scx.scx_area);
scx.scx_use = (CellUse *) cdarg;
scx.scx_trans = GeoIdentityTransform;
DBTreeCopyConnect(&scx, &DBConnectTbl[label->lab_type], 0,
DBConnectTbl, &TiPlaneRect, SEL_DO_LABELS, nmscShowUse);
return(0);
}
|
515480.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_w32_vsnprintf_53d.c
Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml
Template File: sources-vasinks-53d.tmpl.c
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Copy a fixed string into data
* Sinks: w32_vsnprintf
* GoodSink: _vsnwprintf with a format string
* BadSink : _vsnwprintf without a format string
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include <stdarg.h>
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#ifndef OMITBAD
static void badVaSink(wchar_t * data, ...)
{
{
wchar_t dest[100] = L"";
va_list args;
va_start(args, data);
/* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
_vsnwprintf(dest, 100-1, data, args);
va_end(args);
printWLine(dest);
}
}
void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_w32_vsnprintf_53d_badSink(wchar_t * data)
{
badVaSink(data, data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2BVaSink(wchar_t * data, ...)
{
{
wchar_t dest[100] = L"";
va_list args;
va_start(args, data);
/* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
_vsnwprintf(dest, 100-1, data, args);
va_end(args);
printWLine(dest);
}
}
void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_w32_vsnprintf_53d_goodG2BSink(wchar_t * data)
{
goodG2BVaSink(data, data);
}
/* goodB2G uses the BadSource with the GoodSink */
static void goodB2GVaSink(wchar_t * data, ...)
{
{
wchar_t dest[100] = L"";
va_list args;
va_start(args, data);
/* FIX: Specify the format disallowing a format string vulnerability */
_vsnwprintf(dest, 100-1, L"%s", args);
va_end(args);
printWLine(dest);
}
}
void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_w32_vsnprintf_53d_goodB2GSink(wchar_t * data)
{
goodB2GVaSink(data, data);
}
#endif /* OMITGOOD */
|
861636.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <stdlib.h>
#include <libcork/core.h>
#include <libcork/helpers/errors.h>
#include <pthread.h>
#include "vrt/queue.h"
#include "helpers.h"
#include "queue.h"
int
vrt_test_queue_threaded(struct vrt_queue *q, struct vrt_queue_client *clients,
vrt_clock *elapsed)
{
vrt_clock start_time;
vrt_clock end_time;
vrt_get_clock(&start_time);
size_t i;
size_t client_count = 0;
struct vrt_queue_client *client;
for (client = clients; client->run != NULL; client++) {
client_count++;
}
pthread_t *thread_ids;
thread_ids = cork_calloc(client_count, sizeof(pthread_t));
for (i = 0; i < cork_array_size(&q->producers); i++) {
struct vrt_producer *p = cork_array_at(&q->producers, i);
p->yield = vrt_yield_strategy_threaded();
}
for (i = 0; i < cork_array_size(&q->consumers); i++) {
struct vrt_consumer *c = cork_array_at(&q->consumers, i);
c->yield = vrt_yield_strategy_threaded();
}
for (i = 0; i < client_count; i++) {
pthread_create(&thread_ids[i], NULL, clients[i].run, clients[i].ud);
}
for (i = 0; i < client_count; i++) {
pthread_join(thread_ids[i], NULL);
}
cork_cfree(thread_ids, client_count, sizeof(pthread_t));
vrt_get_clock(&end_time);
*elapsed = (end_time - start_time);
return 0;
}
int
vrt_test_queue_threaded_spin(struct vrt_queue *q,
struct vrt_queue_client *clients,
vrt_clock *elapsed)
{
vrt_clock start_time;
vrt_clock end_time;
vrt_get_clock(&start_time);
size_t i;
size_t client_count = 0;
struct vrt_queue_client *client;
for (client = clients; client->run != NULL; client++) {
client_count++;
}
pthread_t *thread_ids;
thread_ids = cork_calloc(client_count, sizeof(pthread_t));
for (i = 0; i < cork_array_size(&q->producers); i++) {
struct vrt_producer *p = cork_array_at(&q->producers, i);
p->yield = vrt_yield_strategy_spin_wait();
}
for (i = 0; i < cork_array_size(&q->consumers); i++) {
struct vrt_consumer *c = cork_array_at(&q->consumers, i);
c->yield = vrt_yield_strategy_spin_wait();
}
for (i = 0; i < client_count; i++) {
pthread_create(&thread_ids[i], NULL, clients[i].run, clients[i].ud);
}
for (i = 0; i < client_count; i++) {
pthread_join(thread_ids[i], NULL);
}
cork_cfree(thread_ids, client_count, sizeof(pthread_t));
vrt_get_clock(&end_time);
*elapsed = (end_time - start_time);
return 0;
}
int
vrt_test_queue_threaded_hybrid(struct vrt_queue *q,
struct vrt_queue_client *clients,
vrt_clock *elapsed)
{
vrt_clock start_time;
vrt_clock end_time;
vrt_get_clock(&start_time);
size_t i;
size_t client_count = 0;
struct vrt_queue_client *client;
for (client = clients; client->run != NULL; client++) {
client_count++;
}
pthread_t *thread_ids;
thread_ids = cork_calloc(client_count, sizeof(pthread_t));
for (i = 0; i < cork_array_size(&q->producers); i++) {
struct vrt_producer *p = cork_array_at(&q->producers, i);
p->yield = vrt_yield_strategy_hybrid();
}
for (i = 0; i < cork_array_size(&q->consumers); i++) {
struct vrt_consumer *c = cork_array_at(&q->consumers, i);
c->yield = vrt_yield_strategy_hybrid();
}
for (i = 0; i < client_count; i++) {
pthread_create(&thread_ids[i], NULL, clients[i].run, clients[i].ud);
}
for (i = 0; i < client_count; i++) {
pthread_join(thread_ids[i], NULL);
}
cork_cfree(thread_ids, client_count, sizeof(pthread_t));
vrt_get_clock(&end_time);
*elapsed = (end_time - start_time);
return 0;
}
|
846170.c | #include <stdio.h>
#include <stdlib.h>
#define ESC 0
#define DIE 1
void die(int x, int score)
{
puts((x == ESC) ? ("Yes") : ("No"));
printf("%d\n", (score == 331) ? 330 : score);
exit(0);
}
int main(void)
{
int M, S, T, s = 0, t = 0;
#ifdef DEBUG
freopen("in", "r", stdin);
#endif
scanf("%d%d%d", &M, &S, &T);
for (; ;) {
while (M >= 10) {
++t, s += 60, M -= 10;
if (s >= S)
die(ESC, t);
if (t == T)
die(DIE, s);
}
if (
(((10 - M - 1) / 4 + 2) > (T - t)) ||
(((10 - M - 1) / 4 + 1) * 17 >= (S - s))
)
for (; ; ) {
s += 17, ++t;
if (s >= S)
die(ESC, t);
if (t == T)
die(DIE, s);
}
while (M < 10) {
++t, M += 4;
if (t == T)
die(DIE, s);
}
}
return 0;
}
|
772194.c | /*********************************************************************/
/* Copyright 2009, 2010 The University of Texas at Austin. */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* 1. Redistributions of source code must retain the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer. */
/* */
/* 2. Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials */
/* provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */
/* AUSTIN ``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 UNIVERSITY OF TEXAS AT */
/* AUSTIN 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. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#include <stdio.h>
#include "common.h"
static FLOAT dm1 = -1.;
double sqrt(double);
#ifndef CACHE_LINE_SIZE
#define CACHE_LINE_SIZE 8
#endif
#ifndef DIVIDE_RATE
#define DIVIDE_RATE 2
#endif
#define GEMM_PQ MAX(GEMM_P, GEMM_Q)
#define REAL_GEMM_R (GEMM_R - GEMM_PQ)
#ifndef GETRF_FACTOR
#define GETRF_FACTOR 0.75
#endif
#undef GETRF_FACTOR
#define GETRF_FACTOR 1.00
static inline long FORMULA1(long M, long N, long IS, long BK, long T) {
double m = (double)(M - IS - BK);
double n = (double)(N - IS - BK);
double b = (double)BK;
double a = (double)T;
return (long)((n + GETRF_FACTOR * m * b * (1. - a) / (b + m)) / a);
}
#define FORMULA2(M, N, IS, BK, T) (BLASLONG)((double)(N - IS + BK) * (1. - sqrt(1. - 1. / (double)(T))))
static void inner_basic_thread(blas_arg_t *args, BLASLONG *range_m, BLASLONG *range_n, FLOAT *sa, FLOAT *sb, BLASLONG mypos){
BLASLONG is, min_i;
BLASLONG js, min_j;
BLASLONG jjs, min_jj;
BLASLONG m = args -> m;
BLASLONG n = args -> n;
BLASLONG k = args -> k;
BLASLONG lda = args -> lda;
BLASLONG off = args -> ldb;
FLOAT *b = (FLOAT *)args -> b + (k ) * COMPSIZE;
FLOAT *c = (FLOAT *)args -> b + ( k * lda) * COMPSIZE;
FLOAT *d = (FLOAT *)args -> b + (k + k * lda) * COMPSIZE;
FLOAT *sbb = sb;
volatile BLASLONG *flag = (volatile BLASLONG *)args -> d;
blasint *ipiv = (blasint *)args -> c;
if (range_n) {
n = range_n[1] - range_n[0];
c += range_n[0] * lda * COMPSIZE;
d += range_n[0] * lda * COMPSIZE;
}
if (args -> a == NULL) {
TRSM_ILTCOPY(k, k, (FLOAT *)args -> b, lda, 0, sb);
sbb = (FLOAT *)((((long)(sb + k * k * COMPSIZE) + GEMM_ALIGN) & ~GEMM_ALIGN) + GEMM_OFFSET_B);
} else {
sb = (FLOAT *)args -> a;
}
for (js = 0; js < n; js += REAL_GEMM_R) {
min_j = n - js;
if (min_j > REAL_GEMM_R) min_j = REAL_GEMM_R;
for (jjs = js; jjs < js + min_j; jjs += GEMM_UNROLL_N){
min_jj = js + min_j - jjs;
if (min_jj > GEMM_UNROLL_N) min_jj = GEMM_UNROLL_N;
if (GEMM_UNROLL_N <= 8) {
LASWP_NCOPY(min_jj, off + 1, off + k,
c + (- off + jjs * lda) * COMPSIZE, lda,
ipiv, sbb + k * (jjs - js) * COMPSIZE);
} else {
LASWP_PLUS(min_jj, off + 1, off + k, ZERO,
#ifdef COMPLEX
ZERO,
#endif
c + (- off + jjs * lda) * COMPSIZE, lda, NULL, 0, ipiv, 1);
GEMM_ONCOPY (k, min_jj, c + jjs * lda * COMPSIZE, lda, sbb + (jjs - js) * k * COMPSIZE);
}
for (is = 0; is < k; is += GEMM_P) {
min_i = k - is;
if (min_i > GEMM_P) min_i = GEMM_P;
TRSM_KERNEL_LT(min_i, min_jj, k, dm1,
#ifdef COMPLEX
ZERO,
#endif
sb + k * is * COMPSIZE,
sbb + (jjs - js) * k * COMPSIZE,
c + (is + jjs * lda) * COMPSIZE, lda, is);
}
}
if ((js + REAL_GEMM_R >= n) && (mypos >= 0)) flag[mypos * CACHE_LINE_SIZE] = 0;
for (is = 0; is < m; is += GEMM_P){
min_i = m - is;
if (min_i > GEMM_P) min_i = GEMM_P;
GEMM_ITCOPY (k, min_i, b + is * COMPSIZE, lda, sa);
GEMM_KERNEL_N(min_i, min_j, k, dm1,
#ifdef COMPLEX
ZERO,
#endif
sa, sbb, d + (is + js * lda) * COMPSIZE, lda);
}
}
}
/* Non blocking implementation */
typedef struct {
volatile BLASLONG working[MAX_CPU_NUMBER][CACHE_LINE_SIZE * DIVIDE_RATE];
} job_t;
#define ICOPY_OPERATION(M, N, A, LDA, X, Y, BUFFER) GEMM_ITCOPY(M, N, (FLOAT *)(A) + ((Y) + (X) * (LDA)) * COMPSIZE, LDA, BUFFER);
#define OCOPY_OPERATION(M, N, A, LDA, X, Y, BUFFER) GEMM_ONCOPY(M, N, (FLOAT *)(A) + ((X) + (Y) * (LDA)) * COMPSIZE, LDA, BUFFER);
#ifndef COMPLEX
#define KERNEL_OPERATION(M, N, K, SA, SB, C, LDC, X, Y) \
GEMM_KERNEL_N(M, N, K, dm1, SA, SB, (FLOAT *)(C) + ((X) + (Y) * LDC) * COMPSIZE, LDC)
#else
#define KERNEL_OPERATION(M, N, K, SA, SB, C, LDC, X, Y) \
GEMM_KERNEL_N(M, N, K, dm1, ZERO, SA, SB, (FLOAT *)(C) + ((X) + (Y) * LDC) * COMPSIZE, LDC)
#endif
static int inner_advanced_thread(blas_arg_t *args, BLASLONG *range_m, BLASLONG *range_n, FLOAT *sa, FLOAT *sb, BLASLONG mypos){
job_t *job = (job_t *)args -> common;
BLASLONG xxx, bufferside;
FLOAT *buffer[DIVIDE_RATE];
BLASLONG jjs, min_jj, div_n;
BLASLONG i, current;
BLASLONG is, min_i;
BLASLONG m, n_from, n_to;
BLASLONG k = args -> k;
BLASLONG lda = args -> lda;
BLASLONG off = args -> ldb;
FLOAT *a = (FLOAT *)args -> b + (k ) * COMPSIZE;
FLOAT *b = (FLOAT *)args -> b + ( k * lda) * COMPSIZE;
FLOAT *c = (FLOAT *)args -> b + (k + k * lda) * COMPSIZE;
FLOAT *sbb= sb;
blasint *ipiv = (blasint *)args -> c;
volatile BLASLONG *flag = (volatile BLASLONG *)args -> d;
if (args -> a == NULL) {
TRSM_ILTCOPY(k, k, (FLOAT *)args -> b, lda, 0, sb);
sbb = (FLOAT *)((((long)(sb + k * k * COMPSIZE) + GEMM_ALIGN) & ~GEMM_ALIGN) + GEMM_OFFSET_B);
} else {
sb = (FLOAT *)args -> a;
}
m = range_m[1] - range_m[0];
n_from = range_n[mypos + 0];
n_to = range_n[mypos + 1];
a += range_m[0] * COMPSIZE;
c += range_m[0] * COMPSIZE;
div_n = (n_to - n_from + DIVIDE_RATE - 1) / DIVIDE_RATE;
buffer[0] = sbb;
for (i = 1; i < DIVIDE_RATE; i++) {
buffer[i] = buffer[i - 1] + GEMM_Q * ((div_n + GEMM_UNROLL_N - 1) & ~(GEMM_UNROLL_N - 1)) * COMPSIZE;
}
for (xxx = n_from, bufferside = 0; xxx < n_to; xxx += div_n, bufferside ++) {
for (i = 0; i < args -> nthreads; i++)
while (job[mypos].working[i][CACHE_LINE_SIZE * bufferside]) {};
for(jjs = xxx; jjs < MIN(n_to, xxx + div_n); jjs += min_jj){
min_jj = MIN(n_to, xxx + div_n) - jjs;
if (min_jj > GEMM_UNROLL_N) min_jj = GEMM_UNROLL_N;
if (GEMM_UNROLL_N <= 8) {
LASWP_NCOPY(min_jj, off + 1, off + k,
b + (- off + jjs * lda) * COMPSIZE, lda,
ipiv, buffer[bufferside] + (jjs - xxx) * k * COMPSIZE);
} else {
LASWP_PLUS(min_jj, off + 1, off + k, ZERO,
#ifdef COMPLEX
ZERO,
#endif
b + (- off + jjs * lda) * COMPSIZE, lda, NULL, 0, ipiv, 1);
GEMM_ONCOPY (k, min_jj, b + jjs * lda * COMPSIZE, lda,
buffer[bufferside] + (jjs - xxx) * k * COMPSIZE);
}
for (is = 0; is < k; is += GEMM_P) {
min_i = k - is;
if (min_i > GEMM_P) min_i = GEMM_P;
TRSM_KERNEL_LT(min_i, min_jj, k, dm1,
#ifdef COMPLEX
ZERO,
#endif
sb + k * is * COMPSIZE,
buffer[bufferside] + (jjs - xxx) * k * COMPSIZE,
b + (is + jjs * lda) * COMPSIZE, lda, is);
}
}
for (i = 0; i < args -> nthreads; i++)
job[mypos].working[i][CACHE_LINE_SIZE * bufferside] = (BLASLONG)buffer[bufferside];
}
flag[mypos * CACHE_LINE_SIZE] = 0;
if (m == 0) {
for (xxx = 0; xxx < DIVIDE_RATE; xxx++) {
job[mypos].working[mypos][CACHE_LINE_SIZE * xxx] = 0;
}
}
for(is = 0; is < m; is += min_i){
min_i = m - is;
if (min_i >= GEMM_P * 2) {
min_i = GEMM_P;
} else
if (min_i > GEMM_P) {
min_i = ((min_i + 1) / 2 + GEMM_UNROLL_M - 1) & ~(GEMM_UNROLL_M - 1);
}
ICOPY_OPERATION(k, min_i, a, lda, 0, is, sa);
current = mypos;
do {
div_n = (range_n[current + 1] - range_n[current] + DIVIDE_RATE - 1) / DIVIDE_RATE;
for (xxx = range_n[current], bufferside = 0; xxx < range_n[current + 1]; xxx += div_n, bufferside ++) {
if ((current != mypos) && (!is)) {
while(job[current].working[mypos][CACHE_LINE_SIZE * bufferside] == 0) {};
}
KERNEL_OPERATION(min_i, MIN(range_n[current + 1] - xxx, div_n), k,
sa, (FLOAT *)job[current].working[mypos][CACHE_LINE_SIZE * bufferside],
c, lda, is, xxx);
if (is + min_i >= m) {
job[current].working[mypos][CACHE_LINE_SIZE * bufferside] = 0;
}
}
current ++;
if (current >= args -> nthreads) current = 0;
} while (current != mypos);
}
for (i = 0; i < args -> nthreads; i++) {
for (xxx = 0; xxx < DIVIDE_RATE; xxx++) {
while (job[mypos].working[i][CACHE_LINE_SIZE * xxx] ) {};
}
}
return 0;
}
#if 1
blasint CNAME(blas_arg_t *args, BLASLONG *range_m, BLASLONG *range_n, FLOAT *sa, FLOAT *sb, BLASLONG myid) {
BLASLONG m, n, mn, lda, offset;
BLASLONG init_bk, next_bk, range_n_mine[2], range_n_new[2];
blasint *ipiv, iinfo, info;
int mode;
blas_arg_t newarg;
FLOAT *a, *sbb;
FLOAT dummyalpha[2] = {ZERO, ZERO};
blas_queue_t queue[MAX_CPU_NUMBER];
BLASLONG range_M[MAX_CPU_NUMBER + 1];
BLASLONG range_N[MAX_CPU_NUMBER + 1];
job_t job[MAX_CPU_NUMBER];
BLASLONG width, nn, mm;
BLASLONG i, j, k, is, bk;
BLASLONG num_cpu;
volatile BLASLONG flag[MAX_CPU_NUMBER * CACHE_LINE_SIZE] __attribute__((aligned(128)));
#ifndef COMPLEX
#ifdef XDOUBLE
mode = BLAS_XDOUBLE | BLAS_REAL;
#elif defined(DOUBLE)
mode = BLAS_DOUBLE | BLAS_REAL;
#else
mode = BLAS_SINGLE | BLAS_REAL;
#endif
#else
#ifdef XDOUBLE
mode = BLAS_XDOUBLE | BLAS_COMPLEX;
#elif defined(DOUBLE)
mode = BLAS_DOUBLE | BLAS_COMPLEX;
#else
mode = BLAS_SINGLE | BLAS_COMPLEX;
#endif
#endif
m = args -> m;
n = args -> n;
a = (FLOAT *)args -> a;
lda = args -> lda;
ipiv = (blasint *)args -> c;
offset = 0;
if (range_n) {
m -= range_n[0];
n = range_n[1] - range_n[0];
offset = range_n[0];
a += range_n[0] * (lda + 1) * COMPSIZE;
}
if (m <= 0 || n <= 0) return 0;
newarg.c = ipiv;
newarg.lda = lda;
newarg.common = (void *)job;
info = 0;
mn = MIN(m, n);
init_bk = (mn / 2 + GEMM_UNROLL_N - 1) & ~(GEMM_UNROLL_N - 1);
if (init_bk > GEMM_Q) init_bk = GEMM_Q;
if (init_bk <= GEMM_UNROLL_N) {
info = GETF2(args, NULL, range_n, sa, sb, 0);
return info;
}
next_bk = init_bk;
bk = mn;
if (bk > next_bk) bk = next_bk;
range_n_new[0] = offset;
range_n_new[1] = offset + bk;
iinfo = CNAME(args, NULL, range_n_new, sa, sb, 0);
if (iinfo && !info) info = iinfo;
TRSM_ILTCOPY(bk, bk, a, lda, 0, sb);
sbb = (FLOAT *)((((long)(sb + bk * bk * COMPSIZE) + GEMM_ALIGN) & ~GEMM_ALIGN) + GEMM_OFFSET_B);
is = 0;
num_cpu = 0;
while (is < mn) {
width = (FORMULA1(m, n, is, bk, args -> nthreads) + GEMM_UNROLL_N - 1) & ~(GEMM_UNROLL_N - 1);
if (width > mn - is - bk) width = mn - is - bk;
if (width < bk) {
next_bk = (FORMULA2(m, n, is, bk, args -> nthreads) + GEMM_UNROLL_N) & ~(GEMM_UNROLL_N - 1);
if (next_bk > bk) next_bk = bk;
width = next_bk;
if (width > mn - is - bk) width = mn - is - bk;
}
if (num_cpu > 0) exec_blas_async_wait(num_cpu, &queue[0]);
mm = m - bk - is;
nn = n - bk - is;
newarg.a = sb;
newarg.b = a + (is + is * lda) * COMPSIZE;
newarg.d = (void *)flag;
newarg.m = mm;
newarg.n = nn;
newarg.k = bk;
newarg.ldb = is + offset;
nn -= width;
range_n_mine[0] = 0;
range_n_mine[1] = width;
range_N[0] = width;
range_M[0] = 0;
num_cpu = 0;
while (nn > 0){
if (mm >= nn) {
width = blas_quickdivide(nn + args -> nthreads - num_cpu, args -> nthreads - num_cpu - 1);
if (nn < width) width = nn;
nn -= width;
range_N[num_cpu + 1] = range_N[num_cpu] + width;
width = blas_quickdivide(mm + args -> nthreads - num_cpu, args -> nthreads - num_cpu - 1);
if (mm < width) width = mm;
if (nn <= 0) width = mm;
mm -= width;
range_M[num_cpu + 1] = range_M[num_cpu] + width;
} else {
width = blas_quickdivide(mm + args -> nthreads - num_cpu, args -> nthreads - num_cpu - 1);
if (mm < width) width = mm;
mm -= width;
range_M[num_cpu + 1] = range_M[num_cpu] + width;
width = blas_quickdivide(nn + args -> nthreads - num_cpu, args -> nthreads - num_cpu - 1);
if (nn < width) width = nn;
if (mm <= 0) width = nn;
nn -= width;
range_N[num_cpu + 1] = range_N[num_cpu] + width;
}
queue[num_cpu].mode = mode;
queue[num_cpu].routine = inner_advanced_thread;
queue[num_cpu].args = &newarg;
queue[num_cpu].range_m = &range_M[num_cpu];
queue[num_cpu].range_n = &range_N[0];
queue[num_cpu].sa = NULL;
queue[num_cpu].sb = NULL;
queue[num_cpu].next = &queue[num_cpu + 1];
flag[num_cpu * CACHE_LINE_SIZE] = 1;
num_cpu ++;
}
newarg.nthreads = num_cpu;
if (num_cpu > 0) {
for (j = 0; j < num_cpu; j++) {
for (i = 0; i < num_cpu; i++) {
for (k = 0; k < DIVIDE_RATE; k++) {
job[j].working[i][CACHE_LINE_SIZE * k] = 0;
}
}
}
}
is += bk;
bk = mn - is;
if (bk > next_bk) bk = next_bk;
range_n_new[0] = offset + is;
range_n_new[1] = offset + is + bk;
if (num_cpu > 0) {
queue[num_cpu - 1].next = NULL;
exec_blas_async(0, &queue[0]);
inner_basic_thread(&newarg, NULL, range_n_mine, sa, sbb, -1);
iinfo = GETRF_SINGLE(args, NULL, range_n_new, sa, sbb, 0);
if (iinfo && !info) info = iinfo + is;
for (i = 0; i < num_cpu; i ++) while (flag[i * CACHE_LINE_SIZE]) {};
TRSM_ILTCOPY(bk, bk, a + (is + is * lda) * COMPSIZE, lda, 0, sb);
} else {
inner_basic_thread(&newarg, NULL, range_n_mine, sa, sbb, -1);
iinfo = GETRF_SINGLE(args, NULL, range_n_new, sa, sbb, 0);
if (iinfo && !info) info = iinfo + is;
}
}
next_bk = init_bk;
is = 0;
while (is < mn) {
bk = mn - is;
if (bk > next_bk) bk = next_bk;
width = (FORMULA1(m, n, is, bk, args -> nthreads) + GEMM_UNROLL_N - 1) & ~(GEMM_UNROLL_N - 1);
if (width > mn - is - bk) width = mn - is - bk;
if (width < bk) {
next_bk = (FORMULA2(m, n, is, bk, args -> nthreads) + GEMM_UNROLL_N) & ~(GEMM_UNROLL_N - 1);
if (next_bk > bk) next_bk = bk;
}
blas_level1_thread(mode, bk, is + bk + offset + 1, mn + offset, (void *)dummyalpha,
a + (- offset + is * lda) * COMPSIZE, lda, NULL, 0,
ipiv, 1, (void *)LASWP_PLUS, args -> nthreads);
is += bk;
}
return info;
}
#else
blasint CNAME(blas_arg_t *args, BLASLONG *range_m, BLASLONG *range_n, FLOAT *sa, FLOAT *sb, BLASLONG myid) {
BLASLONG m, n, mn, lda, offset;
BLASLONG i, is, bk, init_bk, next_bk, range_n_new[2];
blasint *ipiv, iinfo, info;
int mode;
blas_arg_t newarg;
FLOAT *a, *sbb;
FLOAT dummyalpha[2] = {ZERO, ZERO};
blas_queue_t queue[MAX_CPU_NUMBER];
BLASLONG range[MAX_CPU_NUMBER + 1];
BLASLONG width, nn, num_cpu;
volatile BLASLONG flag[MAX_CPU_NUMBER * CACHE_LINE_SIZE] __attribute__((aligned(128)));
#ifndef COMPLEX
#ifdef XDOUBLE
mode = BLAS_XDOUBLE | BLAS_REAL;
#elif defined(DOUBLE)
mode = BLAS_DOUBLE | BLAS_REAL;
#else
mode = BLAS_SINGLE | BLAS_REAL;
#endif
#else
#ifdef XDOUBLE
mode = BLAS_XDOUBLE | BLAS_COMPLEX;
#elif defined(DOUBLE)
mode = BLAS_DOUBLE | BLAS_COMPLEX;
#else
mode = BLAS_SINGLE | BLAS_COMPLEX;
#endif
#endif
m = args -> m;
n = args -> n;
a = (FLOAT *)args -> a;
lda = args -> lda;
ipiv = (blasint *)args -> c;
offset = 0;
if (range_n) {
m -= range_n[0];
n = range_n[1] - range_n[0];
offset = range_n[0];
a += range_n[0] * (lda + 1) * COMPSIZE;
}
if (m <= 0 || n <= 0) return 0;
newarg.c = ipiv;
newarg.lda = lda;
newarg.common = NULL;
newarg.nthreads = args -> nthreads;
mn = MIN(m, n);
init_bk = (mn / 2 + GEMM_UNROLL_N - 1) & ~(GEMM_UNROLL_N - 1);
if (init_bk > GEMM_Q) init_bk = GEMM_Q;
if (init_bk <= GEMM_UNROLL_N) {
info = GETF2(args, NULL, range_n, sa, sb, 0);
return info;
}
width = FORMULA1(m, n, 0, init_bk, args -> nthreads);
width = (width + GEMM_UNROLL_N - 1) & ~(GEMM_UNROLL_N - 1);
if (width > n - init_bk) width = n - init_bk;
if (width < init_bk) {
long temp;
temp = FORMULA2(m, n, 0, init_bk, args -> nthreads);
temp = (temp + GEMM_UNROLL_N - 1) & ~(GEMM_UNROLL_N - 1);
if (temp < GEMM_UNROLL_N) temp = GEMM_UNROLL_N;
if (temp < init_bk) init_bk = temp;
}
next_bk = init_bk;
bk = init_bk;
range_n_new[0] = offset;
range_n_new[1] = offset + bk;
info = CNAME(args, NULL, range_n_new, sa, sb, 0);
TRSM_ILTCOPY(bk, bk, a, lda, 0, sb);
is = 0;
num_cpu = 0;
sbb = (FLOAT *)((((long)(sb + GEMM_PQ * GEMM_PQ * COMPSIZE) + GEMM_ALIGN) & ~GEMM_ALIGN) + GEMM_OFFSET_B);
while (is < mn) {
width = FORMULA1(m, n, is, bk, args -> nthreads);
width = (width + GEMM_UNROLL_N - 1) & ~(GEMM_UNROLL_N - 1);
if (width < bk) {
next_bk = FORMULA2(m, n, is, bk, args -> nthreads);
next_bk = (next_bk + GEMM_UNROLL_N - 1) & ~(GEMM_UNROLL_N - 1);
if (next_bk > bk) next_bk = bk;
#if 0
if (next_bk < GEMM_UNROLL_N) next_bk = MIN(GEMM_UNROLL_N, mn - bk - is);
#else
if (next_bk < GEMM_UNROLL_N) next_bk = MAX(GEMM_UNROLL_N, mn - bk - is);
#endif
width = next_bk;
}
if (width > mn - is - bk) {
next_bk = mn - is - bk;
width = next_bk;
}
nn = n - bk - is;
if (width > nn) width = nn;
if (num_cpu > 1) exec_blas_async_wait(num_cpu - 1, &queue[1]);
range[0] = 0;
range[1] = width;
num_cpu = 1;
nn -= width;
newarg.a = sb;
newarg.b = a + (is + is * lda) * COMPSIZE;
newarg.d = (void *)flag;
newarg.m = m - bk - is;
newarg.n = n - bk - is;
newarg.k = bk;
newarg.ldb = is + offset;
while (nn > 0){
width = blas_quickdivide(nn + args -> nthreads - num_cpu, args -> nthreads - num_cpu);
nn -= width;
if (nn < 0) width = width + nn;
range[num_cpu + 1] = range[num_cpu] + width;
queue[num_cpu].mode = mode;
//queue[num_cpu].routine = inner_advanced_thread;
queue[num_cpu].routine = (void *)inner_basic_thread;
queue[num_cpu].args = &newarg;
queue[num_cpu].range_m = NULL;
queue[num_cpu].range_n = &range[num_cpu];
queue[num_cpu].sa = NULL;
queue[num_cpu].sb = NULL;
queue[num_cpu].next = &queue[num_cpu + 1];
flag[num_cpu * CACHE_LINE_SIZE] = 1;
num_cpu ++;
}
queue[num_cpu - 1].next = NULL;
is += bk;
bk = n - is;
if (bk > next_bk) bk = next_bk;
range_n_new[0] = offset + is;
range_n_new[1] = offset + is + bk;
if (num_cpu > 1) {
exec_blas_async(1, &queue[1]);
#if 0
inner_basic_thread(&newarg, NULL, &range[0], sa, sbb, 0);
iinfo = GETRF_SINGLE(args, NULL, range_n_new, sa, sbb, 0);
#else
if (range[1] >= bk * 4) {
BLASLONG myrange[2];
myrange[0] = 0;
myrange[1] = bk;
inner_basic_thread(&newarg, NULL, &myrange[0], sa, sbb, -1);
iinfo = GETRF_SINGLE(args, NULL, range_n_new, sa, sbb, 0);
myrange[0] = bk;
myrange[1] = range[1];
inner_basic_thread(&newarg, NULL, &myrange[0], sa, sbb, -1);
} else {
inner_basic_thread(&newarg, NULL, &range[0], sa, sbb, -1);
iinfo = GETRF_SINGLE(args, NULL, range_n_new, sa, sbb, 0);
}
#endif
for (i = 1; i < num_cpu; i ++) while (flag[i * CACHE_LINE_SIZE]) {};
TRSM_ILTCOPY(bk, bk, a + (is + is * lda) * COMPSIZE, lda, 0, sb);
} else {
inner_basic_thread(&newarg, NULL, &range[0], sa, sbb, -1);
iinfo = GETRF_SINGLE(args, NULL, range_n_new, sa, sbb, 0);
}
if (iinfo && !info) info = iinfo + is;
}
next_bk = init_bk;
bk = init_bk;
is = 0;
while (is < mn) {
bk = mn - is;
if (bk > next_bk) bk = next_bk;
width = FORMULA1(m, n, is, bk, args -> nthreads);
width = (width + GEMM_UNROLL_N - 1) & ~(GEMM_UNROLL_N - 1);
if (width < bk) {
next_bk = FORMULA2(m, n, is, bk, args -> nthreads);
next_bk = (next_bk + GEMM_UNROLL_N - 1) & ~(GEMM_UNROLL_N - 1);
if (next_bk > bk) next_bk = bk;
#if 0
if (next_bk < GEMM_UNROLL_N) next_bk = MIN(GEMM_UNROLL_N, mn - bk - is);
#else
if (next_bk < GEMM_UNROLL_N) next_bk = MAX(GEMM_UNROLL_N, mn - bk - is);
#endif
}
if (width > mn - is - bk) {
next_bk = mn - is - bk;
width = next_bk;
}
blas_level1_thread(mode, bk, is + bk + offset + 1, mn + offset, (void *)dummyalpha,
a + (- offset + is * lda) * COMPSIZE, lda, NULL, 0,
ipiv, 1, (void *)LASWP_PLUS, args -> nthreads);
is += bk;
}
return info;
}
#endif
|
968643.c | /*
* Copyright (c) 2017 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This hash is based on FNV-1a, using different lengths. Please see the FNV-1a
* website for details on the algorithm: http://www.isthe.com/chongo/tech/comp/fnv
*
*/
#include <config.h>
#include <stdint.h>
#include <unistd.h>
#include <parc/algol/parc_Hash.h>
#include <parc/algol/parc_Object.h>
struct parc_hash_32bits {
uint32_t accumulator;
};
parcObject_ExtendPARCObject(PARCHash32Bits, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
PARCHash32Bits *
parcHash32Bits_Create(void)
{
PARCHash32Bits *result = parcObject_CreateInstance(PARCHash32Bits);
if (result != NULL) {
result->accumulator = 0;
}
return result;
}
PARCHash32Bits *
parcHash32Bits_Update(PARCHash32Bits *hash, const void *data, size_t length)
{
hash->accumulator = parcHash32_Data_Cumulative(data, length, hash->accumulator);
return hash;
}
PARCHash32Bits *
parcHash32Bits_UpdateUint32(PARCHash32Bits *hash, uint32_t value)
{
hash->accumulator = parcHash32_Data_Cumulative(&value, sizeof(value), hash->accumulator);
return hash;
}
uint32_t
parcHash32Bits_Hash(PARCHash32Bits *hash)
{
return hash->accumulator;
}
parcObject_ImplementAcquire(parcHash32Bits, PARCHash32Bits);
parcObject_ImplementRelease(parcHash32Bits, PARCHash32Bits);
/*
* Based on 64-bit FNV-1a
*/
uint64_t
parcHash64_Data(const void *data, size_t len)
{
// Standard FNV 64-bit offset: see http://www.isthe.com/chongo/tech/comp/fnv/#FNV-param
const uint64_t fnv1a_offset = 0xCBF29CE484222325ULL;
return parcHash64_Data_Cumulative(data, len, fnv1a_offset);
}
uint64_t
parcHash64_Data_Cumulative(const void *data, size_t len, uint64_t lastValue)
{
// Standard FNV 64-bit prime: see http://www.isthe.com/chongo/tech/comp/fnv/#FNV-param
const uint64_t fnv1a_prime = 0x00000100000001B3ULL;
uint64_t hash = lastValue;
const char *chardata = data;
for (size_t i = 0; i < len; i++) {
hash = hash ^ chardata[i];
hash = hash * fnv1a_prime;
}
return hash;
}
uint64_t
parcHash64_Int64(uint64_t int64)
{
return parcHash64_Data(&int64, sizeof(uint64_t));
}
uint64_t
parcHash64_Int32(uint32_t int32)
{
return parcHash64_Data(&int32, sizeof(uint32_t));
}
uint32_t
parcHash32_Data(const void *data, size_t len)
{
// Standard FNV 32-bit offset: see http://www.isthe.com/chongo/tech/comp/fnv/#FNV-param
const uint32_t fnv1a_offset = 0x811C9DC5;
return parcHash32_Data_Cumulative(data, len, fnv1a_offset);
}
uint32_t
parcHash32_Data_Cumulative(const void *data, size_t len, uint32_t lastValue)
{
// Standard FNV 32-bit prime: see http://www.isthe.com/chongo/tech/comp/fnv/#FNV-param
const uint32_t fnv1a_prime = 0x01000193;
uint32_t hash = lastValue;
const char *chardata = data;
for (size_t i = 0; i < len; i++) {
hash = hash ^ chardata[i];
hash = hash * fnv1a_prime;
}
return hash;
}
uint32_t
parcHash32_Int64(uint64_t int64)
{
return parcHash32_Data(&int64, sizeof(uint64_t));
}
uint32_t
parcHash32_Int32(uint32_t int32)
{
return parcHash32_Data(&int32, sizeof(uint32_t));
}
|
195024.c | /**
* WinPR: Windows Portable Runtime
* Data Alignment
*
* Copyright 2012 Marc-Andre Moreau <[email protected]>
*
* 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.
*/
#ifdef HAVE_CONFIG_FREERDP_H
#include "config_freerdp.h"
#endif
#include <winpr/crt.h>
/* Data Alignment: http://msdn.microsoft.com/en-us/library/fs9stz4e/ */
#ifndef _WIN32
#include <stdint.h>
#include <limits.h>
#define WINPR_ALIGNED_MEM_SIGNATURE 0x0BA0BAB
#define WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(_memptr) \
(WINPR_ALIGNED_MEM*)(((size_t)(((BYTE*)_memptr) - sizeof(WINPR_ALIGNED_MEM))));
#include <stdlib.h>
#ifdef __APPLE__
#include <malloc/malloc.h>
#elif __FreeBSD__ || __OpenBSD__
#include <stdlib.h>
#else
#include <malloc.h>
#endif
#include "../log.h"
#define TAG WINPR_TAG("crt")
struct winpr_aligned_mem
{
UINT32 sig;
size_t size;
void* base_addr;
};
typedef struct winpr_aligned_mem WINPR_ALIGNED_MEM;
void* _aligned_malloc(size_t size, size_t alignment)
{
return _aligned_offset_malloc(size, alignment, 0);
}
void* _aligned_realloc(void* memblock, size_t size, size_t alignment)
{
return _aligned_offset_realloc(memblock, size, alignment, 0);
}
void* _aligned_recalloc(void* memblock, size_t num, size_t size, size_t alignment)
{
return _aligned_offset_recalloc(memblock, num, size, alignment, 0);
}
void* _aligned_offset_malloc(size_t size, size_t alignment, size_t offset)
{
size_t header, alignsize;
uintptr_t basesize;
void* base;
void* memblock;
WINPR_ALIGNED_MEM* pMem;
/* alignment must be a power of 2 */
if (alignment % 2 == 1)
return NULL;
/* offset must be less than size */
if (offset >= size)
return NULL;
/* minimum alignment is pointer size */
if (alignment < sizeof(void*))
alignment = sizeof(void*);
if (alignment > SIZE_MAX - sizeof(WINPR_ALIGNED_MEM))
return NULL;
header = sizeof(WINPR_ALIGNED_MEM) + alignment;
if (size > SIZE_MAX - header)
return NULL;
alignsize = size + header;
/* malloc size + alignment to make sure we can align afterwards */
base = malloc(alignsize);
if (!base)
return NULL;
basesize = (uintptr_t)base;
if ((offset > UINTPTR_MAX) || (header > UINTPTR_MAX - offset) ||
(basesize > UINTPTR_MAX - header - offset))
{
free(base);
return NULL;
}
memblock = (void*)(((basesize + header + offset) & ~(alignment - 1)) - offset);
pMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(memblock);
pMem->sig = WINPR_ALIGNED_MEM_SIGNATURE;
pMem->base_addr = base;
pMem->size = size;
return memblock;
}
void* _aligned_offset_realloc(void* memblock, size_t size, size_t alignment, size_t offset)
{
size_t copySize;
void* newMemblock;
WINPR_ALIGNED_MEM* pMem;
WINPR_ALIGNED_MEM* pNewMem;
if (!memblock)
return _aligned_offset_malloc(size, alignment, offset);
pMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(memblock);
if (pMem->sig != WINPR_ALIGNED_MEM_SIGNATURE)
{
WLog_ERR(TAG,
"_aligned_offset_realloc: memory block was not allocated by _aligned_malloc!");
return NULL;
}
if (size == 0)
{
_aligned_free(memblock);
return NULL;
}
newMemblock = _aligned_offset_malloc(size, alignment, offset);
if (!newMemblock)
return NULL;
pNewMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(newMemblock);
copySize = (pNewMem->size < pMem->size) ? pNewMem->size : pMem->size;
CopyMemory(newMemblock, memblock, copySize);
_aligned_free(memblock);
return newMemblock;
}
void* _aligned_offset_recalloc(void* memblock, size_t num, size_t size, size_t alignment,
size_t offset)
{
void* newMemblock;
WINPR_ALIGNED_MEM* pMem;
WINPR_ALIGNED_MEM* pNewMem;
if (!memblock)
{
newMemblock = _aligned_offset_malloc(size * num, alignment, offset);
if (newMemblock)
{
pNewMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(newMemblock);
ZeroMemory(newMemblock, pNewMem->size);
}
return memblock;
}
pMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(memblock);
if (pMem->sig != WINPR_ALIGNED_MEM_SIGNATURE)
{
WLog_ERR(TAG,
"_aligned_offset_recalloc: memory block was not allocated by _aligned_malloc!");
return NULL;
}
if (size == 0)
{
_aligned_free(memblock);
return NULL;
}
newMemblock = _aligned_offset_malloc(size * num, alignment, offset);
if (!newMemblock)
return NULL;
pNewMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(newMemblock);
ZeroMemory(newMemblock, pNewMem->size);
_aligned_free(memblock);
return newMemblock;
}
size_t _aligned_msize(void* memblock, size_t alignment, size_t offset)
{
WINPR_ALIGNED_MEM* pMem;
if (!memblock)
return 0;
pMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(memblock);
if (pMem->sig != WINPR_ALIGNED_MEM_SIGNATURE)
{
WLog_ERR(TAG, "_aligned_msize: memory block was not allocated by _aligned_malloc!");
return 0;
}
return pMem->size;
}
void _aligned_free(void* memblock)
{
WINPR_ALIGNED_MEM* pMem;
if (!memblock)
return;
pMem = WINPR_ALIGNED_MEM_STRUCT_FROM_PTR(memblock);
if (pMem->sig != WINPR_ALIGNED_MEM_SIGNATURE)
{
WLog_ERR(TAG, "_aligned_free: memory block was not allocated by _aligned_malloc!");
return;
}
free(pMem->base_addr);
}
#endif
|
514708.c | /*BHEADER**********************************************************************
* Copyright (c) 2008, Lawrence Livermore National Security, LLC.
* Produced at the Lawrence Livermore National Laboratory.
* This file is part of HYPRE. See file COPYRIGHT for details.
*
* HYPRE 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) version 2.1 dated February 1999.
*
* $Revision: 2.6 $
***********************************************************************EHEADER*/
#include "_hypre_parcsr_ls.h"
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESCreate
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESCreate( MPI_Comm comm, HYPRE_Solver *solver )
{
hypre_LGMRESFunctions * lgmres_functions;
if (!solver)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
lgmres_functions =
hypre_LGMRESFunctionsCreate(
hypre_CAlloc, hypre_ParKrylovFree, hypre_ParKrylovCommInfo,
hypre_ParKrylovCreateVector,
hypre_ParKrylovCreateVectorArray,
hypre_ParKrylovDestroyVector, hypre_ParKrylovMatvecCreate,
hypre_ParKrylovMatvec, hypre_ParKrylovMatvecDestroy,
hypre_ParKrylovInnerProd, hypre_ParKrylovCopyVector,
hypre_ParKrylovClearVector,
hypre_ParKrylovScaleVector, hypre_ParKrylovAxpy,
hypre_ParKrylovIdentitySetup, hypre_ParKrylovIdentity );
*solver = ( (HYPRE_Solver) hypre_LGMRESCreate( lgmres_functions ) );
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESDestroy
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESDestroy( HYPRE_Solver solver )
{
return( hypre_LGMRESDestroy( (void *) solver ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESSetup
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESSetup( HYPRE_Solver solver,
HYPRE_ParCSRMatrix A,
HYPRE_ParVector b,
HYPRE_ParVector x )
{
return( HYPRE_LGMRESSetup( solver,
(HYPRE_Matrix) A,
(HYPRE_Vector) b,
(HYPRE_Vector) x ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESSolve
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESSolve( HYPRE_Solver solver,
HYPRE_ParCSRMatrix A,
HYPRE_ParVector b,
HYPRE_ParVector x )
{
return( HYPRE_LGMRESSolve( solver,
(HYPRE_Matrix) A,
(HYPRE_Vector) b,
(HYPRE_Vector) x ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESSetKDim
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESSetKDim( HYPRE_Solver solver,
HYPRE_Int k_dim )
{
return( HYPRE_LGMRESSetKDim( solver, k_dim ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESSetAugDim
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESSetAugDim( HYPRE_Solver solver,
HYPRE_Int aug_dim )
{
return( HYPRE_LGMRESSetAugDim( solver, aug_dim ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESSetTol
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESSetTol( HYPRE_Solver solver,
double tol )
{
return( HYPRE_LGMRESSetTol( solver, tol ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESSetAbsoluteTol
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESSetAbsoluteTol( HYPRE_Solver solver,
double a_tol )
{
return( HYPRE_LGMRESSetAbsoluteTol( solver, a_tol ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESSetMinIter
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESSetMinIter( HYPRE_Solver solver,
HYPRE_Int min_iter )
{
return( HYPRE_LGMRESSetMinIter( solver, min_iter ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESSetMaxIter
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESSetMaxIter( HYPRE_Solver solver,
HYPRE_Int max_iter )
{
return( HYPRE_LGMRESSetMaxIter( solver, max_iter ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESSetPrecond
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESSetPrecond( HYPRE_Solver solver,
HYPRE_PtrToParSolverFcn precond,
HYPRE_PtrToParSolverFcn precond_setup,
HYPRE_Solver precond_solver )
{
return( HYPRE_LGMRESSetPrecond( solver,
(HYPRE_PtrToSolverFcn) precond,
(HYPRE_PtrToSolverFcn) precond_setup,
precond_solver ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESGetPrecond
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESGetPrecond( HYPRE_Solver solver,
HYPRE_Solver *precond_data_ptr )
{
return( HYPRE_LGMRESGetPrecond( solver, precond_data_ptr ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESSetLogging
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESSetLogging( HYPRE_Solver solver,
HYPRE_Int logging)
{
return( HYPRE_LGMRESSetLogging( solver, logging ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESSetPrintLevel
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESSetPrintLevel( HYPRE_Solver solver,
HYPRE_Int print_level)
{
return( HYPRE_LGMRESSetPrintLevel( solver, print_level ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESGetNumIterations
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESGetNumIterations( HYPRE_Solver solver,
HYPRE_Int *num_iterations )
{
return( HYPRE_LGMRESGetNumIterations( solver, num_iterations ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRLGMRESGetFinalRelativeResidualNorm
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRLGMRESGetFinalRelativeResidualNorm( HYPRE_Solver solver,
double *norm )
{
return( HYPRE_LGMRESGetFinalRelativeResidualNorm( solver, norm ) );
}
|
63778.c | /*
Copyright 2010, Volca
Licenced under Academic Free License version 3.0
Review OpenUsbLd README & LICENSE files for further details.
*/
#include "include/opl.h"
#include "include/gui.h"
#include "include/renderman.h"
#include "include/menusys.h"
#include "include/fntsys.h"
#include "include/ioman.h"
#include "include/lang.h"
#include "include/themes.h"
#include "include/pad.h"
#include "include/util.h"
#include "include/config.h"
#include "include/system.h"
#include "include/ethsupport.h"
#include "include/compatupd.h"
#include "include/pggsm.h"
#include "include/cheatman.h"
#include "include/sound.h"
#include "include/guigame.h"
#include <limits.h>
#include <stdlib.h>
#include <libvux.h>
// Last Played Auto Start
#include <time.h>
static int gScheduledOps;
static int gCompletedOps;
static int gTerminate;
static int gInitComplete;
static gui_callback_t gFrameHook;
static s32 gSemaId;
static s32 gGUILockSemaId;
static ee_sema_t gQueueSema;
static int screenWidth;
static int screenHeight;
static int showThmPopup;
static int showLngPopup;
static clock_t popupTimer = 0;
// forward decl.
static void guiShow();
#ifdef __DEBUG
// debug version displays an FPS meter
static clock_t prevtime = 0;
static clock_t curtime = 0;
static float fps = 0.0f;
extern GSGLOBAL *gsGlobal;
#endif
// Global data
int guiInactiveFrames;
int guiFrameId;
struct gui_update_list_t
{
struct gui_update_t *item;
struct gui_update_list_t *next;
};
struct gui_update_list_t *gUpdateList;
struct gui_update_list_t *gUpdateEnd;
typedef struct
{
void (*handleInput)(void);
void (*renderScreen)(void);
short inMenu;
} gui_screen_handler_t;
static gui_screen_handler_t screenHandlers[] = {{&menuHandleInputMain, &menuRenderMain, 0},
{&menuHandleInputMenu, &menuRenderMenu, 1},
{&menuHandleInputInfo, &menuRenderInfo, 1},
{&menuHandleInputGameMenu, &menuRenderGameMenu, 1},
{&menuHandleInputAppMenu, &menuRenderAppMenu, 1}};
// default screen handler (menu screen)
static gui_screen_handler_t *screenHandler = &screenHandlers[GUI_SCREEN_MENU];
// screen transition handling
static gui_screen_handler_t *screenHandlerTarget = NULL;
static int transIndex;
// Helper perlin noise data
#define PLASMA_H 32
#define PLASMA_W 32
#define PLASMA_ROWS_PER_FRAME 6
#define FADE_SIZE 256
static GSTEXTURE gBackgroundTex;
static int pperm[512];
static float fadetbl[FADE_SIZE + 1];
static VU_VECTOR pgrad3[12] = {{1, 1, 0, 1}, {-1, 1, 0, 1}, {1, -1, 0, 1}, {-1, -1, 0, 1}, {1, 0, 1, 1}, {-1, 0, 1, 1}, {1, 0, -1, 1}, {-1, 0, -1, 1}, {0, 1, 1, 1}, {0, -1, 1, 1}, {0, 1, -1, 1}, {0, -1, -1, 1}};
void guiReloadScreenExtents()
{
rmGetScreenExtents(&screenWidth, &screenHeight);
}
void guiInit(void)
{
guiFrameId = 0;
guiInactiveFrames = 0;
gFrameHook = NULL;
gTerminate = 0;
gInitComplete = 0;
gScheduledOps = 0;
gCompletedOps = 0;
gUpdateList = NULL;
gUpdateEnd = NULL;
gQueueSema.init_count = 1;
gQueueSema.max_count = 1;
gQueueSema.option = 0;
gSemaId = CreateSema(&gQueueSema);
gGUILockSemaId = CreateSema(&gQueueSema);
guiReloadScreenExtents();
// background texture - for perlin
gBackgroundTex.Width = PLASMA_W;
gBackgroundTex.Height = PLASMA_H;
gBackgroundTex.Mem = memalign(128, PLASMA_W * PLASMA_H * 4);
gBackgroundTex.PSM = GS_PSM_CT32;
gBackgroundTex.Filter = GS_FILTER_LINEAR;
gBackgroundTex.Vram = 0;
gBackgroundTex.VramClut = 0;
gBackgroundTex.Clut = NULL;
// Precalculate the values for the perlin noise plasma
int i;
for (i = 0; i < 256; ++i) {
pperm[i] = rand() % 256;
pperm[i + 256] = pperm[i];
}
for (i = 0; i <= FADE_SIZE; ++i) {
float t = (float)(i) / FADE_SIZE;
fadetbl[i] = t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f);
}
}
void guiEnd()
{
if (gBackgroundTex.Mem)
free(gBackgroundTex.Mem);
DeleteSema(gSemaId);
DeleteSema(gGUILockSemaId);
}
void guiLock(void)
{
WaitSema(gGUILockSemaId);
}
void guiUnlock(void)
{
SignalSema(gGUILockSemaId);
}
void guiStartFrame(void)
{
guiLock();
rmStartFrame();
guiFrameId++;
}
void guiEndFrame(void)
{
rmEndFrame();
#ifdef __DEBUG
// Measure time directly after vsync
prevtime = curtime;
curtime = clock();
#endif
guiUnlock();
}
void guiShowAbout()
{
char OPLVersion[40];
char OPLBuildDetails[40];
snprintf(OPLVersion, sizeof(OPLVersion), _l(_STR_OPL_VER), OPL_VERSION);
diaSetLabel(diaAbout, ABOUT_TITLE, OPLVersion);
snprintf(OPLBuildDetails, sizeof(OPLBuildDetails), "GSM %s"
#ifdef __RTL
" - RTL"
#endif
#ifdef IGS
" - IGS %s"
#endif
#ifdef PADEMU
" - PADEMU"
#endif
// Version numbers
,
GSM_VERSION
#ifdef IGS
,
IGS_VERSION
#endif
);
diaSetLabel(diaAbout, ABOUT_BUILD_DETAILS, OPLBuildDetails);
diaExecuteDialog(diaAbout, -1, 1, NULL);
}
void guiCheckNotifications(int checkTheme, int checkLang)
{
if (gEnableNotifications) {
if (checkTheme) {
if (thmGetGuiValue() != 0)
showThmPopup = 1;
}
if (checkLang) {
if (lngGetGuiValue() != 0)
showLngPopup = 1;
}
}
}
static void guiResetNotifications(void)
{
showThmPopup = 0;
showLngPopup = 0;
popupTimer = 0;
}
static void guiRenderNotifications(char *type, char *path, int y)
{
char notification[128];
char *col_pos;
int x;
snprintf(notification, sizeof(notification), _l(_STR_NOTIFICATIONS), type, path);
if ((col_pos = strchr(notification, ':')) != NULL)
*(col_pos + 1) = '\0';
x = screenWidth - rmUnScaleX(fntCalcDimensions(gTheme->fonts[0], notification)) - 10;
rmDrawRect(x - 10, y, screenWidth - x, MENU_ITEM_HEIGHT + 10, gColDarker);
fntRenderString(gTheme->fonts[0], x - 5, y + 5, ALIGN_NONE, 0, 0, notification, gTheme->textColor);
}
static void guiShowNotifications(void)
{
int y = 10;
int yadd = 35;
clock_t currentTime;
currentTime = clock();
if (showThmPopup || showLngPopup || showCfgPopup) {
if (!popupTimer) {
popupTimer = clock() + 5000 * (CLOCKS_PER_SEC / 1000);
sfxPlay(SFX_MESSAGE);
}
if (showCfgPopup) {
guiRenderNotifications("CFG", configGetDir(), y);
y += yadd;
}
if (showThmPopup) {
guiRenderNotifications("THM", thmGetFilePath(thmGetGuiValue()), y);
y += yadd;
}
if (showLngPopup)
guiRenderNotifications("LNG", lngGetFilePath(lngGetGuiValue()), y);
if (currentTime >= popupTimer) {
guiResetNotifications();
showCfgPopup = 0;
}
}
}
static int guiNetCompatUpdRefresh(int modified)
{
int result;
unsigned int done, total;
if ((result = oplGetUpdateGameCompatStatus(&done, &total)) == OPL_COMPAT_UPDATE_STAT_WIP) {
diaSetInt(diaNetCompatUpdate, NETUPD_PROGRESS, (done == 0 || total == 0) ? 0 : (int)((float)done / total * 100.0f));
}
return result;
}
static void guiShowNetCompatUpdateResult(int result)
{
switch (result) {
case OPL_COMPAT_UPDATE_STAT_DONE:
// Completed with no errors.
guiMsgBox(_l(_STR_NET_UPDATE_DONE), 0, NULL);
break;
case OPL_COMPAT_UPDATE_STAT_ERROR:
// Completed with errors.
guiMsgBox(_l(_STR_NET_UPDATE_FAILED), 0, NULL);
break;
case OPL_COMPAT_UPDATE_STAT_CONN_ERROR:
// Completed with errors.
guiMsgBox(_l(_STR_NET_UPDATE_CONN_FAILED), 0, NULL);
break;
case OPL_COMPAT_UPDATE_STAT_ABORTED:
// User-aborted.
guiMsgBox(_l(_STR_NET_UPDATE_CANCELLED), 0, NULL);
break;
}
}
void guiShowNetCompatUpdate(void)
{
int ret, UpdateAll;
u8 done, started;
void *UpdateFunction;
diaSetVisible(diaNetCompatUpdate, NETUPD_BTN_START, 1);
diaSetVisible(diaNetCompatUpdate, NETUPD_BTN_CANCEL, 0);
diaSetVisible(diaNetCompatUpdate, NETUPD_PROGRESS_LBL, 0);
diaSetVisible(diaNetCompatUpdate, NETUPD_PROGRESS_PERC_LBL, 0);
diaSetVisible(diaNetCompatUpdate, NETUPD_PROGRESS, 0);
diaSetInt(diaNetCompatUpdate, NETUPD_OPT_UPD_ALL, 0);
diaSetEnabled(diaNetCompatUpdate, NETUPD_OPT_UPD_ALL, 1);
done = 0;
started = 0;
UpdateFunction = NULL;
while (!done) {
ret = diaExecuteDialog(diaNetCompatUpdate, -1, 1, UpdateFunction);
switch (ret) {
case NETUPD_BTN_START:
if (guiMsgBox(_l(_STR_CONFIRMATION_SETTINGS_UPDATE), 1, NULL)) {
guiRenderTextScreen(_l(_STR_PLEASE_WAIT));
if ((ret = ethLoadInitModules()) == 0) {
diaSetVisible(diaNetCompatUpdate, NETUPD_BTN_START, 0);
diaSetVisible(diaNetCompatUpdate, NETUPD_BTN_CANCEL, 1);
diaSetVisible(diaNetCompatUpdate, NETUPD_PROGRESS_LBL, 1);
diaSetVisible(diaNetCompatUpdate, NETUPD_PROGRESS_PERC_LBL, 1);
diaSetVisible(diaNetCompatUpdate, NETUPD_PROGRESS, 1);
diaSetEnabled(diaNetCompatUpdate, NETUPD_OPT_UPD_ALL, 0);
diaGetInt(diaNetCompatUpdate, NETUPD_OPT_UPD_ALL, &UpdateAll);
oplUpdateGameCompat(UpdateAll);
UpdateFunction = &guiNetCompatUpdRefresh;
started = 1;
} else {
ethDisplayErrorStatus();
}
}
break;
case UIID_BTN_CANCEL: // If the user pressed the cancel button.
case NETUPD_BTN_CANCEL:
if (started) {
if (guiMsgBox(_l(_STR_CONFIRMATION_CANCEL_UPDATE), 1, NULL)) {
guiRenderTextScreen(_l(_STR_PLEASE_WAIT));
oplAbortUpdateGameCompat();
// The process truly ends when the UI callback gets the update from the worker thread that the process has ended.
}
} else {
done = 1;
started = 0;
}
break;
default:
guiShowNetCompatUpdateResult(ret);
done = 1;
started = 0;
UpdateFunction = NULL;
break;
}
}
}
void guiShowNetCompatUpdateSingle(int id, item_list_t *support, config_set_t *configSet)
{
int ConfigSource, result;
ConfigSource = CONFIG_SOURCE_DEFAULT;
configGetInt(configSet, CONFIG_ITEM_CONFIGSOURCE, &ConfigSource);
if (guiMsgBox(_l(_STR_CONFIRMATION_SETTINGS_UPDATE), 1, NULL)) {
guiRenderTextScreen(_l(_STR_PLEASE_WAIT));
if ((result = ethLoadInitModules()) == 0) {
if ((result = oplUpdateGameCompatSingle(id, support, configSet)) == OPL_COMPAT_UPDATE_STAT_DONE) {
configSetInt(configSet, CONFIG_ITEM_CONFIGSOURCE, CONFIG_SOURCE_DLOAD);
}
guiShowNetCompatUpdateResult(result);
} else {
ethDisplayErrorStatus();
}
}
}
static void guiShowBlockDeviceConfig(void)
{
int ret;
diaSetInt(diaBlockDevicesConfig, CFG_ENABLEFW, gEnableFW);
diaSetInt(diaBlockDevicesConfig, CFG_ENABLEMX4SIO, gEnableMX4SIO);
ret = diaExecuteDialog(diaBlockDevicesConfig, -1, 1, NULL);
if (ret) {
diaGetInt(diaBlockDevicesConfig, CFG_ENABLEFW, &gEnableFW);
diaGetInt(diaBlockDevicesConfig, CFG_ENABLEMX4SIO, &gEnableMX4SIO);
}
}
static int guiUpdater(int modified)
{
int showAutoStartLast;
if (modified) {
diaGetInt(diaConfig, CFG_LASTPLAYED, &showAutoStartLast);
diaSetVisible(diaConfig, CFG_LBL_AUTOSTARTLAST, showAutoStartLast);
diaSetVisible(diaConfig, CFG_AUTOSTARTLAST, showAutoStartLast);
diaGetInt(diaConfig, CFG_BDMMODE, &gBDMStartMode);
diaSetVisible(diaConfig, BLOCKDEVICE_BUTTON, gBDMStartMode);
}
return 0;
}
void guiShowConfig()
{
int value;
// configure the enumerations
const char *selectButtons[] = {_l(_STR_CIRCLE), _l(_STR_CROSS), NULL};
const char *deviceNames[] = {_l(_STR_BDM_GAMES), _l(_STR_NET_GAMES), _l(_STR_HDD_GAMES), NULL};
const char *deviceModes[] = {_l(_STR_OFF), _l(_STR_MANUAL), _l(_STR_AUTO), NULL};
diaSetEnum(diaConfig, CFG_SELECTBUTTON, selectButtons);
diaSetEnum(diaConfig, CFG_DEFDEVICE, deviceNames);
diaSetEnum(diaConfig, CFG_BDMMODE, deviceModes);
diaSetEnum(diaConfig, CFG_HDDMODE, deviceModes);
diaSetEnum(diaConfig, CFG_ETHMODE, deviceModes);
diaSetEnum(diaConfig, CFG_APPMODE, deviceModes);
diaSetInt(diaConfig, CFG_DEBUG, gDisableDebug);
diaSetInt(diaConfig, CFG_PS2LOGO, gPS2Logo);
diaSetInt(diaConfig, CFG_HDDGAMELISTCACHE, gHDDGameListCache);
diaSetString(diaConfig, CFG_EXITTO, gExitPath);
diaSetInt(diaConfig, CFG_ENWRITEOP, gEnableWrite);
diaSetInt(diaConfig, CFG_HDDSPINDOWN, gHDDSpindown);
diaSetString(diaConfig, CFG_BDMPREFIX, gBDMPrefix);
diaSetString(diaConfig, CFG_ETHPREFIX, gETHPrefix);
diaSetInt(diaConfig, CFG_LASTPLAYED, gRememberLastPlayed);
diaSetInt(diaConfig, CFG_AUTOSTARTLAST, gAutoStartLastPlayed);
diaSetVisible(diaConfig, CFG_AUTOSTARTLAST, gRememberLastPlayed);
diaSetVisible(diaConfig, CFG_LBL_AUTOSTARTLAST, gRememberLastPlayed);
diaSetInt(diaConfig, CFG_SELECTBUTTON, gSelectButton == KEY_CIRCLE ? 0 : 1);
diaSetInt(diaConfig, CFG_DEFDEVICE, gDefaultDevice);
diaSetInt(diaConfig, CFG_BDMMODE, gBDMStartMode);
diaSetVisible(diaConfig, BLOCKDEVICE_BUTTON, gBDMStartMode);
diaSetInt(diaConfig, CFG_HDDMODE, gHDDStartMode);
diaSetInt(diaConfig, CFG_ETHMODE, gETHStartMode);
diaSetInt(diaConfig, CFG_APPMODE, gAPPStartMode);
int ret = diaExecuteDialog(diaConfig, -1, 1, &guiUpdater);
if (ret) {
diaGetInt(diaConfig, CFG_DEBUG, &gDisableDebug);
diaGetInt(diaConfig, CFG_PS2LOGO, &gPS2Logo);
diaGetInt(diaConfig, CFG_HDDGAMELISTCACHE, &gHDDGameListCache);
diaGetString(diaConfig, CFG_EXITTO, gExitPath, sizeof(gExitPath));
diaGetInt(diaConfig, CFG_ENWRITEOP, &gEnableWrite);
diaGetInt(diaConfig, CFG_HDDSPINDOWN, &gHDDSpindown);
diaGetString(diaConfig, CFG_BDMPREFIX, gBDMPrefix, sizeof(gBDMPrefix));
diaGetString(diaConfig, CFG_ETHPREFIX, gETHPrefix, sizeof(gETHPrefix));
diaGetInt(diaConfig, CFG_LASTPLAYED, &gRememberLastPlayed);
diaGetInt(diaConfig, CFG_AUTOSTARTLAST, &gAutoStartLastPlayed);
DisableCron = 1; // Disable Auto Start Last Played counter (we don't want to call it right after enable it on GUI)
if (diaGetInt(diaConfig, CFG_SELECTBUTTON, &value))
gSelectButton = value == 0 ? KEY_CIRCLE : KEY_CROSS;
else
gSelectButton = KEY_CIRCLE;
diaGetInt(diaConfig, CFG_DEFDEVICE, &gDefaultDevice);
diaGetInt(diaConfig, CFG_HDDMODE, &gHDDStartMode);
diaGetInt(diaConfig, CFG_ETHMODE, &gETHStartMode);
diaGetInt(diaConfig, CFG_APPMODE, &gAPPStartMode);
if (ret == BLOCKDEVICE_BUTTON)
guiShowBlockDeviceConfig();
applyConfig(-1, -1);
menuReinitMainMenu();
}
}
static int curTheme = -1;
static int guiUIUpdater(int modified)
{
if (modified) {
int temp, x, y;
diaGetInt(diaUIConfig, UICFG_THEME, &temp);
if (temp != curTheme) {
curTheme = temp;
if (temp == 0) {
// Display the default theme's colours.
diaSetItemType(diaUIConfig, UICFG_BGCOL, UI_COLOUR); // Must be correctly set before doing the diaS/GetColor !!
diaSetItemType(diaUIConfig, UICFG_UICOL, UI_COLOUR);
diaSetItemType(diaUIConfig, UICFG_TXTCOL, UI_COLOUR);
diaSetItemType(diaUIConfig, UICFG_SELCOL, UI_COLOUR);
diaSetColor(diaUIConfig, UICFG_BGCOL, gDefaultBgColor);
diaSetColor(diaUIConfig, UICFG_UICOL, gDefaultUITextColor);
diaSetColor(diaUIConfig, UICFG_TXTCOL, gDefaultTextColor);
diaSetColor(diaUIConfig, UICFG_SELCOL, gDefaultSelTextColor);
} else if (temp == thmGetGuiValue()) {
// Display the current theme's colours.
diaSetItemType(diaUIConfig, UICFG_BGCOL, UI_COLOUR);
diaSetItemType(diaUIConfig, UICFG_UICOL, UI_COLOUR);
diaSetItemType(diaUIConfig, UICFG_TXTCOL, UI_COLOUR);
diaSetItemType(diaUIConfig, UICFG_SELCOL, UI_COLOUR);
diaSetColor(diaUIConfig, UICFG_BGCOL, gTheme->bgColor);
diaSetU64Color(diaUIConfig, UICFG_UICOL, gTheme->uiTextColor);
diaSetU64Color(diaUIConfig, UICFG_TXTCOL, gTheme->textColor);
diaSetU64Color(diaUIConfig, UICFG_SELCOL, gTheme->selTextColor);
} else {
// When another theme is highlighted in the list, its colours are not known. Don't show any colours.
diaSetItemType(diaUIConfig, UICFG_BGCOL, UI_SPACER);
diaSetItemType(diaUIConfig, UICFG_UICOL, UI_SPACER);
diaSetItemType(diaUIConfig, UICFG_TXTCOL, UI_SPACER);
diaSetItemType(diaUIConfig, UICFG_SELCOL, UI_SPACER);
}
// The user cannot adjust the current theme's colours.
temp = !temp;
diaSetEnabled(diaUIConfig, UICFG_BGCOL, temp);
diaSetEnabled(diaUIConfig, UICFG_UICOL, temp);
diaSetEnabled(diaUIConfig, UICFG_TXTCOL, temp);
diaSetEnabled(diaUIConfig, UICFG_SELCOL, temp);
diaSetEnabled(diaUIConfig, UICFG_RESETCOL, temp);
}
diaGetInt(diaUIConfig, UICFG_XOFF, &x);
diaGetInt(diaUIConfig, UICFG_YOFF, &y);
if ((x != gXOff) || (y != gYOff)) {
gXOff = x;
gYOff = y;
rmSetDisplayOffset(x, y);
}
diaGetInt(diaUIConfig, UICFG_OVERSCAN, &temp);
if (temp != gOverscan) {
gOverscan = temp;
rmSetOverscan(gOverscan);
guiUpdateScreenScale();
}
diaGetInt(diaUIConfig, UICFG_WIDESCREEN, &temp);
if (temp != gWideScreen) {
gWideScreen = temp;
rmSetAspectRatio((gWideScreen == 0) ? RM_ARATIO_4_3 : RM_ARATIO_16_9);
guiUpdateScreenScale();
}
}
return 0;
}
void guiShowUIConfig(void)
{
int themeID = -1, langID = -1;
curTheme = -1;
showCfgPopup = 0;
guiResetNotifications();
// configure the enumerations
const char *scrollSpeeds[] = {_l(_STR_SLOW), _l(_STR_MEDIUM), _l(_STR_FAST), NULL};
// clang-format off
const char *vmodeNames[] = {_l(_STR_AUTO)
, "PAL 640x512i @50Hz 24bit"
, "NTSC 640x448i @60Hz 24bit"
, "EDTV 640x448p @60Hz 24bit"
, "EDTV 640x512p @50Hz 24bit"
, "VGA 640x480p @60Hz 24bit"
, "PAL 704x576i @50Hz 24bit (HIRES)"
, "NTSC 704x480i @60Hz 24bit (HIRES)"
, "EDTV 704x480p @60Hz 24bit (HIRES)"
, "EDTV 704x576p @50Hz 24bit (HIRES)"
, "HDTV 1280x720p @60Hz 16bit (HIRES)"
, "HDTV 1920x1080i @60Hz 16bit (HIRES)"
, NULL};
// clang-format on
int previousVMode;
reselect_video_mode:
previousVMode = gVMode;
diaSetEnum(diaUIConfig, UICFG_SCROLL, scrollSpeeds);
diaSetEnum(diaUIConfig, UICFG_THEME, (const char **)thmGetGuiList());
diaSetEnum(diaUIConfig, UICFG_LANG, (const char **)lngGetGuiList());
diaSetEnum(diaUIConfig, UICFG_VMODE, vmodeNames);
diaSetInt(diaUIConfig, UICFG_SCROLL, gScrollSpeed);
diaSetInt(diaUIConfig, UICFG_THEME, thmGetGuiValue());
diaSetInt(diaUIConfig, UICFG_LANG, lngGetGuiValue());
diaSetInt(diaUIConfig, UICFG_AUTOSORT, gAutosort);
diaSetInt(diaUIConfig, UICFG_AUTOREFRESH, gAutoRefresh);
diaSetInt(diaUIConfig, UICFG_NOTIFICATIONS, gEnableNotifications);
diaSetInt(diaUIConfig, UICFG_COVERART, gEnableArt);
diaSetInt(diaUIConfig, UICFG_WIDESCREEN, gWideScreen);
diaSetInt(diaUIConfig, UICFG_VMODE, gVMode);
diaSetInt(diaUIConfig, UICFG_XOFF, gXOff);
diaSetInt(diaUIConfig, UICFG_YOFF, gYOff);
diaSetInt(diaUIConfig, UICFG_OVERSCAN, gOverscan);
guiUIUpdater(1);
int ret = diaExecuteDialog(diaUIConfig, -1, 1, guiUIUpdater);
if (ret) {
diaGetInt(diaUIConfig, UICFG_SCROLL, &gScrollSpeed);
diaGetInt(diaUIConfig, UICFG_LANG, &langID);
diaGetInt(diaUIConfig, UICFG_THEME, &themeID);
if (themeID == 0) {
diaGetColor(diaUIConfig, UICFG_BGCOL, gDefaultBgColor);
diaGetColor(diaUIConfig, UICFG_UICOL, gDefaultUITextColor);
diaGetColor(diaUIConfig, UICFG_TXTCOL, gDefaultTextColor);
diaGetColor(diaUIConfig, UICFG_SELCOL, gDefaultSelTextColor);
}
diaGetInt(diaUIConfig, UICFG_AUTOSORT, &gAutosort);
diaGetInt(diaUIConfig, UICFG_AUTOREFRESH, &gAutoRefresh);
diaGetInt(diaUIConfig, UICFG_NOTIFICATIONS, &gEnableNotifications);
diaGetInt(diaUIConfig, UICFG_COVERART, &gEnableArt);
diaGetInt(diaUIConfig, UICFG_WIDESCREEN, &gWideScreen);
diaGetInt(diaUIConfig, UICFG_VMODE, &gVMode);
diaGetInt(diaUIConfig, UICFG_XOFF, &gXOff);
diaGetInt(diaUIConfig, UICFG_YOFF, &gYOff);
diaGetInt(diaUIConfig, UICFG_OVERSCAN, &gOverscan);
if (ret == UICFG_RESETCOL)
setDefaultColors();
applyConfig(themeID, langID);
sfxInit(0);
}
if (previousVMode != gVMode) {
if (guiConfirmVideoMode() == 0) {
// Restore previous video mode, without changing the theme & language settings.
gVMode = previousVMode;
applyConfig(themeID, langID);
goto reselect_video_mode;
}
}
}
static int netConfigUpdater(int modified)
{
int showAdvancedOptions, isNetBIOS, isDHCPEnabled, i;
if (modified) {
diaGetInt(diaNetConfig, NETCFG_SHOW_ADVANCED_OPTS, &showAdvancedOptions);
diaGetInt(diaNetConfig, NETCFG_PS2_IP_ADDR_TYPE, &isDHCPEnabled);
diaGetInt(diaNetConfig, NETCFG_SHARE_ADDR_TYPE, &isNetBIOS);
diaSetVisible(diaNetConfig, NETCFG_SHARE_NB_ADDR, isNetBIOS);
for (i = 0; i < 4; i++) {
diaSetVisible(diaNetConfig, NETCFG_SHARE_IP_ADDR_0 + i, !isNetBIOS);
diaSetEnabled(diaNetConfig, NETCFG_PS2_IP_ADDR_0 + i, !isDHCPEnabled);
diaSetEnabled(diaNetConfig, NETCFG_PS2_NETMASK_0 + i, !isDHCPEnabled);
diaSetEnabled(diaNetConfig, NETCFG_PS2_GATEWAY_0 + i, !isDHCPEnabled);
diaSetEnabled(diaNetConfig, NETCFG_PS2_DNS_0 + i, !isDHCPEnabled);
}
for (i = 0; i < 3; i++)
diaSetVisible(diaNetConfig, NETCFG_SHARE_IP_ADDR_DOT_0 + i, !isNetBIOS);
diaSetEnabled(diaNetConfig, NETCFG_SHARE_PORT, showAdvancedOptions);
diaSetEnabled(diaNetConfig, NETCFG_ETHOPMODE, showAdvancedOptions);
}
return 0;
}
void guiShowNetConfig(void)
{
size_t i;
const char *ethOpModes[] = {_l(_STR_AUTO), _l(_STR_ETH_100MFDX), _l(_STR_ETH_100MHDX), _l(_STR_ETH_10MFDX), _l(_STR_ETH_10MHDX), NULL};
const char *addrConfModes[] = {_l(_STR_ADDR_TYPE_IP), _l(_STR_ADDR_TYPE_NETBIOS), NULL};
const char *ipAddrConfModes[] = {_l(_STR_IP_ADDRESS_TYPE_STATIC), _l(_STR_IP_ADDRESS_TYPE_DHCP), NULL};
diaSetEnum(diaNetConfig, NETCFG_PS2_IP_ADDR_TYPE, ipAddrConfModes);
diaSetEnum(diaNetConfig, NETCFG_SHARE_ADDR_TYPE, addrConfModes);
diaSetEnum(diaNetConfig, NETCFG_ETHOPMODE, ethOpModes);
// upload current values
diaSetInt(diaNetConfig, NETCFG_SHOW_ADVANCED_OPTS, 0);
diaSetEnabled(diaNetConfig, NETCFG_ETHOPMODE, 0);
diaSetEnabled(diaNetConfig, NETCFG_SHARE_PORT, 0);
diaSetInt(diaNetConfig, NETCFG_PS2_IP_ADDR_TYPE, ps2_ip_use_dhcp);
diaSetInt(diaNetConfig, NETCFG_SHARE_ADDR_TYPE, gPCShareAddressIsNetBIOS);
diaSetVisible(diaNetConfig, NETCFG_SHARE_NB_ADDR, gPCShareAddressIsNetBIOS);
diaSetInt(diaNetConfig, NETCFG_SHARE_NB_ADDR, gPCShareAddressIsNetBIOS);
diaSetString(diaNetConfig, NETCFG_SHARE_NB_ADDR, gPCShareNBAddress);
for (i = 0; i < 4; ++i) {
diaSetEnabled(diaNetConfig, NETCFG_PS2_IP_ADDR_0 + i, !ps2_ip_use_dhcp);
diaSetEnabled(diaNetConfig, NETCFG_PS2_NETMASK_0 + i, !ps2_ip_use_dhcp);
diaSetEnabled(diaNetConfig, NETCFG_PS2_GATEWAY_0 + i, !ps2_ip_use_dhcp);
diaSetEnabled(diaNetConfig, NETCFG_PS2_DNS_0 + i, !ps2_ip_use_dhcp);
diaSetVisible(diaNetConfig, NETCFG_SHARE_IP_ADDR_0 + i, !gPCShareAddressIsNetBIOS);
diaSetInt(diaNetConfig, NETCFG_PS2_IP_ADDR_0 + i, ps2_ip[i]);
diaSetInt(diaNetConfig, NETCFG_PS2_NETMASK_0 + i, ps2_netmask[i]);
diaSetInt(diaNetConfig, NETCFG_PS2_GATEWAY_0 + i, ps2_gateway[i]);
diaSetInt(diaNetConfig, NETCFG_PS2_DNS_0 + i, ps2_dns[i]);
diaSetInt(diaNetConfig, NETCFG_SHARE_IP_ADDR_0 + i, pc_ip[i]);
}
for (i = 0; i < 3; ++i)
diaSetVisible(diaNetConfig, NETCFG_SHARE_IP_ADDR_DOT_0 + i, !gPCShareAddressIsNetBIOS);
diaSetInt(diaNetConfig, NETCFG_SHARE_PORT, gPCPort);
diaSetString(diaNetConfig, NETCFG_SHARE_NAME, gPCShareName);
diaSetString(diaNetConfig, NETCFG_SHARE_USERNAME, gPCUserName);
diaSetString(diaNetConfig, NETCFG_SHARE_PASSWORD, gPCPassword);
diaSetInt(diaNetConfig, NETCFG_ETHOPMODE, gETHOpMode);
// Update the spacer item between the OK and reconnect buttons (See dialogs.c).
if (gNetworkStartup == 0) {
diaSetLabel(diaNetConfig, NETCFG_OK, _l(_STR_OK));
diaSetVisible(diaNetConfig, NETCFG_RECONNECT, 1);
} else if (gNetworkStartup >= ERROR_ETH_SMB_CONN) {
diaSetLabel(diaNetConfig, NETCFG_OK, _l(_STR_RECONNECT));
diaSetVisible(diaNetConfig, NETCFG_RECONNECT, 0);
} else {
diaSetLabel(diaNetConfig, NETCFG_OK, _l(_STR_OK));
diaSetVisible(diaNetConfig, NETCFG_RECONNECT, 0);
}
int result = diaExecuteDialog(diaNetConfig, -1, 1, &netConfigUpdater);
if (result) {
// Store values
diaGetInt(diaNetConfig, NETCFG_PS2_IP_ADDR_TYPE, &ps2_ip_use_dhcp);
diaGetInt(diaNetConfig, NETCFG_SHARE_ADDR_TYPE, &gPCShareAddressIsNetBIOS);
diaGetString(diaNetConfig, NETCFG_SHARE_NB_ADDR, gPCShareNBAddress, sizeof(gPCShareNBAddress));
for (i = 0; i < 4; ++i) {
diaGetInt(diaNetConfig, NETCFG_PS2_IP_ADDR_0 + i, &ps2_ip[i]);
diaGetInt(diaNetConfig, NETCFG_PS2_NETMASK_0 + i, &ps2_netmask[i]);
diaGetInt(diaNetConfig, NETCFG_PS2_GATEWAY_0 + i, &ps2_gateway[i]);
diaGetInt(diaNetConfig, NETCFG_PS2_DNS_0 + i, &ps2_dns[i]);
diaGetInt(diaNetConfig, NETCFG_SHARE_IP_ADDR_0 + i, &pc_ip[i]);
}
diaGetInt(diaNetConfig, NETCFG_ETHOPMODE, &gETHOpMode);
diaGetInt(diaNetConfig, NETCFG_SHARE_PORT, &gPCPort);
diaGetString(diaNetConfig, NETCFG_SHARE_NAME, gPCShareName, sizeof(gPCShareName));
diaGetString(diaNetConfig, NETCFG_SHARE_USERNAME, gPCUserName, sizeof(gPCUserName));
diaGetString(diaNetConfig, NETCFG_SHARE_PASSWORD, gPCPassword, sizeof(gPCPassword));
if (result == NETCFG_RECONNECT && gNetworkStartup < ERROR_ETH_SMB_CONN)
gNetworkStartup = ERROR_ETH_SMB_LOGON;
applyConfig(-1, -1);
}
}
void guiShowParentalLockConfig(void)
{
int result;
char password[CONFIG_KEY_VALUE_LEN];
config_set_t *configOPL = configGetByType(CONFIG_OPL);
// Set current values
configGetStrCopy(configOPL, CONFIG_OPL_PARENTAL_LOCK_PWD, password, CONFIG_KEY_VALUE_LEN); // This will return the current password, or a blank string if it is not set.
diaSetString(diaParentalLockConfig, CFG_PARENLOCK_PASSWORD, password);
result = diaExecuteDialog(diaParentalLockConfig, -1, 1, NULL);
if (result) {
diaGetString(diaParentalLockConfig, CFG_PARENLOCK_PASSWORD, password, CONFIG_KEY_VALUE_LEN);
if (strlen(password) > 0) {
if (strncmp(OPL_PARENTAL_LOCK_MASTER_PASS, password, CONFIG_KEY_VALUE_LEN) != 0) {
// Store password
configSetStr(configOPL, CONFIG_OPL_PARENTAL_LOCK_PWD, password);
} else {
// Password not acceptable (i.e. master password entered).
guiMsgBox(_l(_STR_PARENLOCK_INVALID_PASSWORD), 0, NULL);
}
} else {
configRemoveKey(configOPL, CONFIG_OPL_PARENTAL_LOCK_PWD);
guiMsgBox(_l(_STR_PARENLOCK_DISABLE_WARNING), 0, diaParentalLockConfig);
}
menuSetParentalLockCheckState(1);
}
}
static void guiSetAudioSettingsState(void)
{
diaGetInt(diaAudioConfig, CFG_SFX, &gEnableSFX);
diaGetInt(diaAudioConfig, CFG_BOOT_SND, &gEnableBootSND);
diaGetInt(diaAudioConfig, CFG_SFX_VOLUME, &gSFXVolume);
diaGetInt(diaAudioConfig, CFG_BOOT_SND_VOLUME, &gBootSndVolume);
sfxVolume();
}
static int guiAudioUpdater(int modified)
{
if (modified) {
guiSetAudioSettingsState();
}
return 0;
}
void guiShowAudioConfig(void)
{
diaSetInt(diaAudioConfig, CFG_SFX, gEnableSFX);
diaSetInt(diaAudioConfig, CFG_BOOT_SND, gEnableBootSND);
diaSetInt(diaAudioConfig, CFG_SFX_VOLUME, gSFXVolume);
diaSetInt(diaAudioConfig, CFG_BOOT_SND_VOLUME, gBootSndVolume);
diaExecuteDialog(diaAudioConfig, -1, 1, guiAudioUpdater);
}
int guiShowKeyboard(char *value, int maxLength)
{
char tmp[maxLength];
strncpy(tmp, value, maxLength);
int result = diaShowKeyb(tmp, maxLength, 0, NULL);
if (result) {
strncpy(value, tmp, maxLength);
value[maxLength - 1] = '\0';
}
return result;
}
int guiGetOpCompleted(int opid)
{
return gCompletedOps > opid;
}
int guiDeferUpdate(struct gui_update_t *op)
{
WaitSema(gSemaId);
struct gui_update_list_t *up = (struct gui_update_list_t *)malloc(sizeof(struct gui_update_list_t));
up->item = op;
up->next = NULL;
if (!gUpdateList) {
gUpdateList = up;
gUpdateEnd = gUpdateList;
} else {
gUpdateEnd->next = up;
gUpdateEnd = up;
}
SignalSema(gSemaId);
return gScheduledOps++;
}
static void guiHandleOp(struct gui_update_t *item)
{
submenu_list_t *result = NULL;
switch (item->type) {
case GUI_INIT_DONE:
gInitComplete = 1;
break;
case GUI_OP_ADD_MENU:
menuAppendItem(item->menu.menu);
break;
case GUI_OP_APPEND_MENU:
result = submenuAppendItem(item->menu.subMenu, item->submenu.icon_id,
item->submenu.text, item->submenu.id, item->submenu.text_id);
if (!item->menu.menu->submenu) { // first subitem in list
item->menu.menu->submenu = result;
item->menu.menu->current = result;
item->menu.menu->pagestart = result;
} else if (item->submenu.selected) { // remember last played game feature
item->menu.menu->current = result;
item->menu.menu->pagestart = result;
item->menu.menu->remindLast = 1;
// Last Played Auto Start
if ((gAutoStartLastPlayed) && !(KeyPressedOnce))
DisableCron = 0; // Release Auto Start Last Played counter
}
break;
case GUI_OP_SELECT_MENU:
menuSetSelectedItem(item->menu.menu);
screenHandler = &screenHandlers[GUI_SCREEN_MAIN];
break;
case GUI_OP_CLEAR_SUBMENU:
submenuDestroy(item->menu.subMenu);
item->menu.menu->submenu = NULL;
item->menu.menu->current = NULL;
item->menu.menu->pagestart = NULL;
break;
case GUI_OP_SORT:
submenuSort(item->menu.subMenu);
item->menu.menu->submenu = *item->menu.subMenu;
if (!item->menu.menu->remindLast)
item->menu.menu->current = item->menu.menu->submenu;
item->menu.menu->pagestart = item->menu.menu->current;
break;
case GUI_OP_ADD_HINT:
// append the hint list in the menu item
menuAddHint(item->menu.menu, item->hint.text_id, item->hint.icon_id);
break;
default:
LOG("GUI: ??? (%d)\n", item->type);
}
}
static void guiHandleDeferredOps(void)
{
WaitSema(gSemaId);
while (gUpdateList) {
guiHandleOp(gUpdateList->item);
struct gui_update_list_t *td = gUpdateList;
gUpdateList = gUpdateList->next;
free(td);
gCompletedOps++;
}
SignalSema(gSemaId);
gUpdateEnd = NULL;
}
void guiExecDeferredOps(void)
{
// Clears deferred operations list by executing them.
guiHandleDeferredOps();
}
static void guiDrawBusy(int alpha)
{
if (gTheme->loadingIcon) {
GSTEXTURE *texture = thmGetTexture(LOAD0_ICON + (guiFrameId >> 1) % gTheme->loadingIconCount);
if (texture && texture->Mem) {
u64 mycolor = GS_SETREG_RGBA(0x80, 0x80, 0x80, alpha);
rmDrawPixmap(texture, gTheme->loadingIcon->posX, gTheme->loadingIcon->posY, gTheme->loadingIcon->aligned, gTheme->loadingIcon->width, gTheme->loadingIcon->height, gTheme->loadingIcon->scaled, mycolor);
}
}
}
static void guiRenderGreeting(int alpha)
{
u64 mycolor = GS_SETREG_RGBA(0x1C, 0x1C, 0x1C, alpha);
rmDrawRect(0, 0, screenWidth, screenHeight, mycolor);
GSTEXTURE *logo = thmGetTexture(LOGO_PICTURE);
if (logo) {
mycolor = GS_SETREG_RGBA(0x80, 0x80, 0x80, alpha);
rmDrawPixmap(logo, screenWidth >> 1, gTheme->usedHeight >> 1, ALIGN_CENTER, logo->Width, logo->Height, SCALING_RATIO, mycolor);
}
}
static float mix(float a, float b, float t)
{
return a + (b - a) * t;
}
static float fade(float t)
{
return fadetbl[(int)(t * FADE_SIZE)];
}
// The same as mix, but with 8 (2*4) values mixed at once
static void VU0MixVec(VU_VECTOR *a, VU_VECTOR *b, float mix, VU_VECTOR *res)
{
asm volatile(
#if __GNUC__ > 3
"lqc2 $vf1, (%[a])\n" // load the first vector
"lqc2 $vf2, (%[b])\n" // load the second vector
"qmtc2 %[mix], $vf3\n" // move the mix value from reg to VU
"vaddw.x $vf5, $vf0, $vf0\n" // vf5.x = 1
"vsub.x $vf4x, $vf5x, $vf3x\n" // subtract 1 - vf3,x, store the result in vf4.x
"vmulax.xyzw $ACC, $vf1, $vf3x\n" // multiply vf1 by vf3.x, store the result in ACC
"vmaddx.xyzw $vf1, $vf2, $vf4x\n" // multiply vf2 by vf4.x add ACC, store the result in vf1
"sqc2 $vf1, (%[res])\n" // transfer the result in acc to the ee
#else
"lqc2 vf1, (%[a])\n" // load the first vector
"lqc2 vf2, (%[b])\n" // load the second vector
"qmtc2 %[mix], vf3\n" // move the mix value from reg to VU
"vaddw.x vf5, vf00, vf00\n" // vf5.x = 1
"vsub.x vf4x, vf5x, vf3x\n" // subtract 1 - vf3,x, store the result in vf4.x
"vmulax.xyzw ACC, vf1, vf3x\n" // multiply vf1 by vf3.x, store the result in ACC
"vmaddx.xyzw vf1, vf2, vf4x\n" // multiply vf2 by vf4.x add ACC, store the result in vf1
"sqc2 vf1, (%[res])\n" // transfer the result in acc to the ee
#endif
: [res] "+r"(res), "=m"(*res)
: [a] "r"(a), [b] "r"(b), [mix] "r"(mix), "m"(*a), "m"(*b));
}
static float guiCalcPerlin(float x, float y, float z)
{
// Taken from: http://people.opera.com/patrickl/experiments/canvas/plasma/perlin-noise-classical.js
// By Sean McCullough
// Find unit grid cell containing point
int X = floorf(x);
int Y = floorf(y);
int Z = floorf(z);
// Get relative xyz coordinates of point within that cell
x = x - X;
y = y - Y;
z = z - Z;
// Wrap the integer cells at 255 (smaller integer period can be introduced here)
X = X & 255;
Y = Y & 255;
Z = Z & 255;
// Calculate a set of eight hashed gradient indices
int gi000 = pperm[X + pperm[Y + pperm[Z]]] % 12;
int gi001 = pperm[X + pperm[Y + pperm[Z + 1]]] % 12;
int gi010 = pperm[X + pperm[Y + 1 + pperm[Z]]] % 12;
int gi011 = pperm[X + pperm[Y + 1 + pperm[Z + 1]]] % 12;
int gi100 = pperm[X + 1 + pperm[Y + pperm[Z]]] % 12;
int gi101 = pperm[X + 1 + pperm[Y + pperm[Z + 1]]] % 12;
int gi110 = pperm[X + 1 + pperm[Y + 1 + pperm[Z]]] % 12;
int gi111 = pperm[X + 1 + pperm[Y + 1 + pperm[Z + 1]]] % 12;
// The gradients of each corner are now:
// g000 = grad3[gi000];
// g001 = grad3[gi001];
// g010 = grad3[gi010];
// g011 = grad3[gi011];
// g100 = grad3[gi100];
// g101 = grad3[gi101];
// g110 = grad3[gi110];
// g111 = grad3[gi111];
// Calculate noise contributions from each of the eight corners
VU_VECTOR vec;
vec.x = x;
vec.y = y;
vec.z = z;
vec.w = 1;
VU_VECTOR a, b;
// float n000
a.x = Vu0DotProduct(&pgrad3[gi000], &vec);
vec.y -= 1;
// float n010
a.z = Vu0DotProduct(&pgrad3[gi010], &vec);
vec.x -= 1;
// float n110
b.z = Vu0DotProduct(&pgrad3[gi110], &vec);
vec.y += 1;
// float n100
b.x = Vu0DotProduct(&pgrad3[gi100], &vec);
vec.z -= 1;
// float n101
b.y = Vu0DotProduct(&pgrad3[gi101], &vec);
vec.y -= 1;
// float n111
b.w = Vu0DotProduct(&pgrad3[gi111], &vec);
vec.x += 1;
// float n011
a.w = Vu0DotProduct(&pgrad3[gi011], &vec);
vec.y += 1;
// float n001
a.y = Vu0DotProduct(&pgrad3[gi001], &vec);
// Compute the fade curve value for each of x, y, z
float u = fade(x);
float v = fade(y);
float w = fade(z);
// TODO: Low priority... This could be done on VU0 (xyzw for the first 4 mixes)
// The result in sw
// Interpolate along x the contributions from each of the corners
VU_VECTOR rv;
VU0MixVec(&b, &a, u, &rv);
// TODO: The VU0MixVec could as well mix the results (as follows) - might improve performance...
// Interpolate the four results along y
float nxy0 = mix(rv.x, rv.z, v);
float nxy1 = mix(rv.y, rv.w, v);
// Interpolate the two last results along z
float nxyz = mix(nxy0, nxy1, w);
return nxyz;
}
static float dir = 0.02;
static float perz = -100;
static int pery = 0;
static unsigned char curbgColor[3] = {0, 0, 0};
static int cdirection(unsigned char a, unsigned char b)
{
if (a == b)
return 0;
else if (a > b)
return -1;
else
return 1;
}
void guiDrawBGPlasma()
{
int x, y;
// transition the colors
curbgColor[0] += cdirection(curbgColor[0], gTheme->bgColor[0]);
curbgColor[1] += cdirection(curbgColor[1], gTheme->bgColor[1]);
curbgColor[2] += cdirection(curbgColor[2], gTheme->bgColor[2]);
// it's PLASMA_ROWS_PER_FRAME rows a frame to stop being a resource hog
if (pery >= PLASMA_H) {
pery = 0;
perz += dir;
if (perz > 100.0f || perz < -100.0f)
dir = -dir;
}
u32 *buf = gBackgroundTex.Mem + PLASMA_W * pery;
int ymax = pery + PLASMA_ROWS_PER_FRAME;
if (ymax > PLASMA_H)
ymax = PLASMA_H;
for (y = pery; y < ymax; y++) {
for (x = 0; x < PLASMA_W; x++) {
u32 fper = guiCalcPerlin((float)(2 * x) / PLASMA_W, (float)(2 * y) / PLASMA_H, perz) * 0x80 + 0x80;
*buf = GS_SETREG_RGBA(
(u32)(fper * curbgColor[0]) >> 8,
(u32)(fper * curbgColor[1]) >> 8,
(u32)(fper * curbgColor[2]) >> 8,
0x80);
++buf;
}
}
pery = ymax;
rmInvalidateTexture(&gBackgroundTex);
rmDrawPixmap(&gBackgroundTex, 0, 0, ALIGN_NONE, screenWidth, screenHeight, SCALING_NONE, gDefaultCol);
}
int guiDrawIconAndText(int iconId, int textId, int font, int x, int y, u64 color)
{
GSTEXTURE *iconTex = thmGetTexture(iconId);
int w = (iconTex->Width * 20) / iconTex->Height;
int h = 20;
if (iconTex && iconTex->Mem) {
y += h >> 1;
rmDrawPixmap(iconTex, x, y, ALIGN_VCENTER, w, h, SCALING_RATIO, gDefaultCol);
x += rmWideScale(w) + 2;
} else {
// HACK: font is aligned to VCENTER, the default height icon height is 20
y += 10;
}
x = fntRenderString(font, x, y, ALIGN_VCENTER, 0, 0, _l(textId), color);
return x;
}
int guiAlignMenuHints(menu_hint_item_t *hint, int font, int width)
{
int x = screenWidth;
int w;
for (; hint; hint = hint->next) {
GSTEXTURE *iconTex = thmGetTexture(hint->icon_id);
w = (iconTex->Width * 20) / iconTex->Height;
char *text = _l(hint->text_id);
x -= rmWideScale(w) + 2;
x -= rmUnScaleX(fntCalcDimensions(font, text));
if (hint->next != NULL)
x -= width;
}
// align center
x /= 2;
return x;
}
int guiAlignSubMenuHints(int hintCount, int *textID, int *iconID, int font, int width, int align)
{
int x = screenWidth;
int i, w;
for (i = 0; i < hintCount; i++) {
GSTEXTURE *iconTex = thmGetTexture(iconID[i]);
w = (iconTex->Width * 20) / iconTex->Height;
char *text = _l(textID[i]);
x -= rmWideScale(w) + 2;
x -= rmUnScaleX(fntCalcDimensions(font, text));
if (i != (hintCount - 1))
x -= width;
}
if (align == 1) // align center
x /= 2;
if (align == 2) // align right
x -= 20;
return x;
}
void guiDrawSubMenuHints(void)
{
int subMenuHints[2] = {_STR_SELECT, _STR_GAMES_LIST};
int subMenuIcons[2] = {CIRCLE_ICON, CROSS_ICON};
int x = guiAlignSubMenuHints(2, subMenuHints, subMenuIcons, gTheme->fonts[0], 12, 2);
int y = gTheme->usedHeight - 32;
x = guiDrawIconAndText(gSelectButton == KEY_CIRCLE ? subMenuIcons[0] : subMenuIcons[1], subMenuHints[0], gTheme->fonts[0], x, y, gTheme->textColor);
x += 12;
x = guiDrawIconAndText(gSelectButton == KEY_CIRCLE ? subMenuIcons[1] : subMenuIcons[0], subMenuHints[1], gTheme->fonts[0], x, y, gTheme->textColor);
}
static int endIntro = 0; // Break intro loop and start 'Last Played Auto Start' countdown
static void guiDrawOverlays()
{
// are there any pending operations?
int pending = ioHasPendingRequests();
static int busyAlpha = 0x00; // Fully transparant
if (!pending) {
// Fade out
if (busyAlpha > 0x00)
busyAlpha -= 0x02;
} else {
// Fade in
if (busyAlpha < 0x80)
busyAlpha += 0x02;
}
if (busyAlpha > 0x00)
guiDrawBusy(busyAlpha);
#ifdef __DEBUG
char text[20];
int x = screenWidth - 120;
int y = 15;
int yadd = 15;
snprintf(text, sizeof(text), "VRAM:");
fntRenderString(gTheme->fonts[0], x, y, ALIGN_LEFT, 0, 0, text, GS_SETREG_RGBA(0x60, 0x60, 0x60, 0x80));
y += yadd;
snprintf(text, sizeof(text), "%dKiB FIXED", gsGlobal->CurrentPointer / 1024);
fntRenderString(gTheme->fonts[0], x, y, ALIGN_LEFT, 0, 0, text, GS_SETREG_RGBA(0x60, 0x60, 0x60, 0x80));
y += yadd;
snprintf(text, sizeof(text), "%dKiB TEXMAN", ((4 * 1024 * 1024) - gsGlobal->CurrentPointer) / 1024);
fntRenderString(gTheme->fonts[0], x, y, ALIGN_LEFT, 0, 0, text, GS_SETREG_RGBA(0x60, 0x60, 0x60, 0x80));
y += yadd;
y += yadd; // Empty line
if (prevtime != 0) {
clock_t diff = curtime - prevtime;
// Raw FPS value with 2 decimal places
float rawfps = ((100 * CLOCKS_PER_SEC) / diff) / 100.0f;
if (fps == 0.0f)
fps = rawfps;
else
fps = fps * 0.9f + rawfps / 10.0f; // Smooth FPS value
snprintf(text, sizeof(text), "%.1f FPS", fps);
fntRenderString(gTheme->fonts[0], x, y, ALIGN_LEFT, 0, 0, text, GS_SETREG_RGBA(0x60, 0x60, 0x60, 0x80));
y += yadd;
}
#endif
// Last Played Auto Start
if (!pending && DisableCron == 0 && endIntro) {
if (CronStart == 0) {
CronStart = clock() / CLOCKS_PER_SEC;
} else {
char strAutoStartInNSecs[21];
clock_t CronCurrent;
CronCurrent = clock() / CLOCKS_PER_SEC;
RemainSecs = gAutoStartLastPlayed - (CronCurrent - CronStart);
snprintf(strAutoStartInNSecs, sizeof(strAutoStartInNSecs), _l(_STR_AUTO_START_IN_N_SECS), RemainSecs);
fntRenderString(gTheme->fonts[0], screenWidth / 2, screenHeight / 2, ALIGN_CENTER, 0, 0, strAutoStartInNSecs, GS_SETREG_RGBA(0x60, 0x60, 0x60, 0x80));
}
}
// BLURT output
// if (!gDisableDebug)
// fntRenderString(gTheme->fonts[0], 0, screenHeight - 24, ALIGN_NONE, 0, 0, blurttext, GS_SETREG_RGBA(255, 255, 0, 128));
}
static void guiReadPads()
{
if (readPads())
guiInactiveFrames = 0;
else
guiInactiveFrames++;
}
// renders the screen and handles inputs. Also handles screen transitions between numerous
// screen handlers. Fade transition code written by Maximus32
static void guiShow()
{
// is there a transmission effect going on or are
// we in a normal rendering state?
if (screenHandlerTarget) {
u8 alpha;
const u8 transition_frames = 26;
if (transIndex < (transition_frames / 2)) {
// Fade-out old screen
// index: 0..7
// alpha: 1..8 * transition_step
screenHandler->renderScreen();
alpha = fade((float)(transIndex + 1) / (transition_frames / 2)) * 0x80;
} else {
// Fade-in new screen
// index: 8..15
// alpha: 8..1 * transition_step
screenHandlerTarget->renderScreen();
alpha = fade((float)(transition_frames - transIndex) / (transition_frames / 2)) * 0x80;
}
// Overlay the actual "fade"
rmDrawRect(0, 0, screenWidth, screenHeight, GS_SETREG_RGBA(0x00, 0x00, 0x00, alpha));
// Advance the effect
transIndex++;
if (transIndex >= transition_frames) {
screenHandler = screenHandlerTarget;
screenHandlerTarget = NULL;
}
} else
// render with the set screen handler
screenHandler->renderScreen();
}
void guiIntroLoop(void)
{
int greetingAlpha = 0x80;
const int fadeFrameCount = 0x80 / 2;
const int fadeDuration = (fadeFrameCount * 1000) / 55; // Average between 50 and 60 fps
clock_t tFadeDelayEnd = 0;
while (!endIntro) {
guiStartFrame();
if (greetingAlpha < 0x80)
guiShow();
if (greetingAlpha > 0)
guiRenderGreeting(greetingAlpha);
// Initialize boot sound
if (gInitComplete && !tFadeDelayEnd && gEnableBootSND) {
// Start playing sound
sfxPlay(SFX_BOOT);
// Calculate transition delay
tFadeDelayEnd = clock() + (sfxGetSoundDuration(SFX_BOOT) - fadeDuration) * (CLOCKS_PER_SEC / 1000);
}
if (gInitComplete && clock() >= tFadeDelayEnd)
greetingAlpha -= 2;
if (greetingAlpha <= 0)
endIntro = 1;
guiDrawOverlays();
guiHandleDeferredOps();
guiEndFrame();
if (!screenHandlerTarget && screenHandler)
screenHandler->handleInput();
}
}
void guiMainLoop(void)
{
guiResetNotifications();
guiCheckNotifications(1, 1);
while (!gTerminate) {
guiStartFrame();
// Read the pad states to prepare for input processing in the screen handler
guiReadPads();
// handle inputs and render screen
guiShow();
// Render overlaying gui thingies :)
guiDrawOverlays();
if (gEnableNotifications)
guiShowNotifications();
// handle deferred operations
guiHandleDeferredOps();
guiEndFrame();
// if not transiting, handle input
// done here so we can use renderman if needed
if (!screenHandlerTarget && screenHandler)
screenHandler->handleInput();
if (gFrameHook)
gFrameHook();
}
}
void guiSetFrameHook(gui_callback_t cback)
{
gFrameHook = cback;
}
void guiSwitchScreen(int target)
{
sfxPlay(SFX_TRANSITION);
transIndex = 0;
screenHandlerTarget = &screenHandlers[target];
}
struct gui_update_t *guiOpCreate(gui_op_type_t type)
{
struct gui_update_t *op = (struct gui_update_t *)malloc(sizeof(struct gui_update_t));
memset(op, 0, sizeof(struct gui_update_t));
op->type = type;
return op;
}
void guiUpdateScrollSpeed(void)
{
// sanitize the settings
if ((gScrollSpeed < 0) || (gScrollSpeed > 2))
gScrollSpeed = 1;
// update the pad delays for KEY_UP and KEY_DOWN
// default delay is 7
// fast - 100 ms
// medium - 300 ms
// slow - 500 ms
setButtonDelay(KEY_UP, 500 - gScrollSpeed * 200); // 0,1,2 -> 500, 300, 100
setButtonDelay(KEY_DOWN, 500 - gScrollSpeed * 200);
}
void guiUpdateScreenScale(void)
{
fntUpdateAspectRatio();
}
int guiMsgBox(const char *text, int addAccept, struct UIItem *ui)
{
int terminate = 0;
sfxPlay(SFX_MESSAGE);
while (!terminate) {
guiStartFrame();
readPads();
if (getKeyOn(gSelectButton == KEY_CIRCLE ? KEY_CROSS : KEY_CIRCLE))
terminate = 1;
else if (getKeyOn(gSelectButton))
terminate = 2;
if (ui)
diaRenderUI(ui, screenHandler->inMenu, NULL, 0);
else
guiShow();
rmDrawRect(0, 0, screenWidth, screenHeight, gColDarker);
rmDrawLine(50, 75, screenWidth - 50, 75, gColWhite);
rmDrawLine(50, 410, screenWidth - 50, 410, gColWhite);
fntRenderString(gTheme->fonts[0], screenWidth >> 1, gTheme->usedHeight >> 1, ALIGN_CENTER, 0, 0, text, gTheme->textColor);
guiDrawIconAndText(gSelectButton == KEY_CIRCLE ? CROSS_ICON : CIRCLE_ICON, _STR_BACK, gTheme->fonts[0], 500, 417, gTheme->selTextColor);
if (addAccept)
guiDrawIconAndText(gSelectButton == KEY_CIRCLE ? CIRCLE_ICON : CROSS_ICON, _STR_ACCEPT, gTheme->fonts[0], 70, 417, gTheme->selTextColor);
guiEndFrame();
}
if (terminate == 1) {
sfxPlay(SFX_CANCEL);
}
if (terminate == 2) {
sfxPlay(SFX_CONFIRM);
}
return terminate - 1;
}
void guiHandleDeferedIO(int *ptr, const char *message, int type, void *data)
{
ioPutRequest(type, data);
while (*ptr)
guiRenderTextScreen(message);
}
void guiGameHandleDeferedIO(int *ptr, struct UIItem *ui, int type, void *data)
{
ioPutRequest(type, data);
while (*ptr) {
guiStartFrame();
if (ui)
diaRenderUI(ui, screenHandler->inMenu, NULL, 0);
else
guiShow();
guiEndFrame();
}
}
void guiRenderTextScreen(const char *message)
{
guiStartFrame();
guiShow();
rmDrawRect(0, 0, screenWidth, screenHeight, gColDarker);
fntRenderString(gTheme->fonts[0], screenWidth >> 1, gTheme->usedHeight >> 1, ALIGN_CENTER, 0, 0, message, gTheme->textColor);
guiDrawOverlays();
guiEndFrame();
}
void guiWarning(const char *text, int count)
{
guiStartFrame();
guiShow();
rmDrawRect(0, 0, screenWidth, screenHeight, gColDarker);
rmDrawLine(50, 75, screenWidth - 50, 75, gColWhite);
rmDrawLine(50, 410, screenWidth - 50, 410, gColWhite);
fntRenderString(gTheme->fonts[0], screenWidth >> 1, gTheme->usedHeight >> 1, ALIGN_CENTER, screenWidth, screenHeight, text, gTheme->textColor);
guiEndFrame();
delay(count);
}
int guiConfirmVideoMode(void)
{
clock_t timeEnd;
int terminate = 0;
sfxPlay(SFX_MESSAGE);
timeEnd = clock() + OPL_VMODE_CHANGE_CONFIRMATION_TIMEOUT_MS * (CLOCKS_PER_SEC / 1000);
while (!terminate) {
guiStartFrame();
readPads();
if (getKeyOn(gSelectButton == KEY_CIRCLE ? KEY_CROSS : KEY_CIRCLE))
terminate = 1;
else if (getKeyOn(gSelectButton))
terminate = 2;
// If the user fails to respond within the timeout period, deem it as a cancel operation.
if (clock() > timeEnd)
terminate = 1;
guiShow();
rmDrawRect(0, 0, screenWidth, screenHeight, gColDarker);
rmDrawLine(50, 75, screenWidth - 50, 75, gColWhite);
rmDrawLine(50, 410, screenWidth - 50, 410, gColWhite);
fntRenderString(gTheme->fonts[0], screenWidth >> 1, gTheme->usedHeight >> 1, ALIGN_CENTER, 0, 0, _l(_STR_CFM_VMODE_CHG), gTheme->textColor);
guiDrawIconAndText(gSelectButton == KEY_CIRCLE ? CROSS_ICON : CIRCLE_ICON, _STR_BACK, gTheme->fonts[0], 500, 417, gTheme->selTextColor);
guiDrawIconAndText(gSelectButton == KEY_CIRCLE ? CIRCLE_ICON : CROSS_ICON, _STR_ACCEPT, gTheme->fonts[0], 70, 417, gTheme->selTextColor);
guiEndFrame();
}
if (terminate == 1) {
sfxPlay(SFX_CANCEL);
}
if (terminate == 2) {
sfxPlay(SFX_CONFIRM);
}
return terminate - 1;
}
int guiGameShowRemoveSettings(config_set_t *configSet, config_set_t *configGame)
{
int terminate = 0;
char message[256];
sfxPlay(SFX_MESSAGE);
while (!terminate) {
guiStartFrame();
readPads();
if (getKeyOn(gSelectButton == KEY_CIRCLE ? KEY_CROSS : KEY_CIRCLE))
terminate = 1;
else if (getKeyOn(gSelectButton))
terminate = 2;
else if (getKeyOn(KEY_SQUARE))
terminate = 3;
else if (getKeyOn(KEY_TRIANGLE))
terminate = 4;
guiShow();
rmDrawRect(0, 0, screenWidth, screenHeight, gColDarker);
rmDrawLine(50, 75, screenWidth - 50, 75, gColWhite);
rmDrawLine(50, 410, screenWidth - 50, 410, gColWhite);
fntRenderString(gTheme->fonts[0], screenWidth >> 1, gTheme->usedHeight >> 1, ALIGN_CENTER, 0, 0, _l(_STR_GAME_SETTINGS_PROMPT), gTheme->textColor);
guiDrawIconAndText(gSelectButton == KEY_CIRCLE ? CROSS_ICON : CIRCLE_ICON, _STR_BACK, gTheme->fonts[0], 500, 417, gTheme->selTextColor);
guiDrawIconAndText(SQUARE_ICON, _STR_GLOBAL_SETTINGS, gTheme->fonts[0], 213, 417, gTheme->selTextColor);
guiDrawIconAndText(TRIANGLE_ICON, _STR_ALL_SETTINGS, gTheme->fonts[0], 356, 417, gTheme->selTextColor);
guiDrawIconAndText(gSelectButton == KEY_CIRCLE ? CIRCLE_ICON : CROSS_ICON, _STR_PERGAME_SETTINGS, gTheme->fonts[0], 70, 417, gTheme->selTextColor);
guiEndFrame();
}
if (terminate == 1) {
sfxPlay(SFX_CANCEL);
return 0;
} else if (terminate == 2) {
guiGameRemoveSettings(configSet);
snprintf(message, sizeof(message), _l(_STR_GAME_SETTINGS_REMOVED), _l(_STR_PERGAME_SETTINGS));
} else if (terminate == 3) {
guiGameRemoveGlobalSettings(configGame);
snprintf(message, sizeof(message), _l(_STR_GAME_SETTINGS_REMOVED), _l(_STR_GLOBAL_SETTINGS));
} else if (terminate == 4) {
guiGameRemoveSettings(configSet);
guiGameRemoveGlobalSettings(configGame);
snprintf(message, sizeof(message), _l(_STR_GAME_SETTINGS_REMOVED), _l(_STR_ALL_SETTINGS));
}
sfxPlay(SFX_CONFIRM);
guiMsgBox(message, 0, NULL);
return 1;
}
|
881370.c | /*==================================================================*\
| EXIP - Embeddable EXI Processor in C |
|--------------------------------------------------------------------|
| This work is licensed under BSD 3-Clause License |
| The full license terms and conditions are located in LICENSE.txt |
\===================================================================*/
/**
* @file streamEncode.c
* @brief Implements an interface to a higher-level EXI stream encoder - encode basic EXI types
*
* @date Oct 26, 2010
* @author Rumen Kyusakov
* @version 0.5
* @par[Revision] $Id$
*/
#include "streamEncode.h"
#include "streamWrite.h"
#include "stringManipulate.h"
#include "ioUtil.h"
#include <math.h>
errorCode encodeNBitUnsignedInteger(EXIStream* strm, unsigned char n, unsigned int int_val)
{
DEBUG_MSG(INFO, DEBUG_STREAM_IO, (">> %d [0x%X] (%u bits)", int_val, int_val, n));
if(WITH_COMPRESSION(strm->header.opts.enumOpt) == FALSE && GET_ALIGNMENT(strm->header.opts.enumOpt) == BIT_PACKED)
{
return writeNBits(strm, n, int_val);
}
else
{
unsigned int byte_number = n / 8 + (n % 8 != 0);
int tmp_byte_buf;
unsigned int i;
if(strm->buffer.bufLen < strm->context.bufferIndx + byte_number)
{
// The buffer end is reached: there are fewer than nbits bits left in the buffer
// Flush the buffer if possible
errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR;
TRY(writeEncodedEXIChunk(strm));
}
for(i = 0; i < byte_number*8; i += 8)
{
tmp_byte_buf = (int_val >> i) & 0xFF;
strm->buffer.buf[strm->context.bufferIndx] = tmp_byte_buf;
strm->context.bufferIndx++;
}
}
return EXIP_OK;
}
errorCode encodeBoolean(EXIStream* strm, boolean bool_val)
{
//TODO: when pattern facets are available in the schema datatype - handle it differently
DEBUG_MSG(INFO, DEBUG_STREAM_IO, (">> 0x%X (bool)", bool_val));
return encodeNBitUnsignedInteger(strm, 1, bool_val);
}
errorCode encodeUnsignedInteger(EXIStream* strm, UnsignedInteger int_val)
{
errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR;
unsigned int tmp_byte_buf = 0;
DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" Write %lu (unsigned)\n", (long unsigned int)int_val));
do
{
tmp_byte_buf = (unsigned int) (int_val & 0x7F);
int_val = int_val >> 7;
if(int_val)
tmp_byte_buf |= 0x80;
DEBUG_MSG(INFO, DEBUG_STREAM_IO, (">> 0x%.2X", tmp_byte_buf));
TRY(writeNBits(strm, 8, tmp_byte_buf));
}
while(int_val);
return EXIP_OK;
}
errorCode encodeString(EXIStream* strm, const String* string_val)
{
// Assume no Restricted Character Set is defined
//TODO: Handle the case when Restricted Character Set is defined
errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR;
DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" Prepare to write string"));
TRY(encodeUnsignedInteger(strm, (UnsignedInteger)(string_val->length)));
return encodeStringOnly(strm, string_val);
}
errorCode encodeStringOnly(EXIStream* strm, const String* string_val)
{
// Assume no Restricted Character Set is defined
//TODO: Handle the case when Restricted Character Set is defined
errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR;
uint32_t tmp_val = 0;
Index i = 0;
Index readerPosition = 0;
#if DEBUG_STREAM_IO == ON && EXIP_DEBUG_LEVEL == INFO
DEBUG_MSG(INFO, DEBUG_STREAM_IO, ("\n Write string, len %u: ", (unsigned int) string_val->length));
printString(string_val);
DEBUG_MSG(INFO, DEBUG_STREAM_IO, ("\n"));
#endif
for(i = 0; i < string_val->length; i++)
{
tmp_val = readCharFromString(string_val, &readerPosition);
TRY(encodeUnsignedInteger(strm, (UnsignedInteger) tmp_val));
}
return EXIP_OK;
}
errorCode encodeBinary(EXIStream* strm, char* binary_val, Index nbytes)
{
errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR;
Index i = 0;
TRY(encodeUnsignedInteger(strm, (UnsignedInteger) nbytes));
DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" Write %u (binary bytes)\n", (unsigned int) nbytes));
for(i = 0; i < nbytes; i++)
{
TRY(writeNBits(strm, 8, (unsigned int) binary_val[i]));
}
DEBUG_MSG(INFO, DEBUG_STREAM_IO, ("\n"));
return EXIP_OK;
}
errorCode encodeIntegerValue(EXIStream* strm, Integer sint_val)
{
errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR;
UnsignedInteger uval;
unsigned char sign;
if(sint_val >= 0)
{
sign = 0;
uval = (UnsignedInteger) sint_val;
}
else
{
sint_val += 1;
uval = (UnsignedInteger) -sint_val;
sign = 1;
}
DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" Write %ld (signed)", (long int)sint_val));
TRY(writeNextBit(strm, sign));
DEBUG_MSG(INFO, DEBUG_STREAM_IO, ("\n"));
return encodeUnsignedInteger(strm, uval);
}
errorCode encodeDecimalValue(EXIStream* strm, Decimal dec_val)
{
errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR;
boolean sign;
UnsignedInteger integr_part = 0;
UnsignedInteger fract_part_rev = 0;
UnsignedInteger m;
int e = dec_val.exponent;
if(dec_val.mantissa >= 0)
{
sign = FALSE;
integr_part = (UnsignedInteger) dec_val.mantissa;
}
else
{
sign = TRUE;
integr_part = (UnsignedInteger) -dec_val.mantissa;
}
m = integr_part;
TRY(encodeBoolean(strm, sign));
if(dec_val.exponent > 0)
{
while(e)
{
integr_part = integr_part*10;
e--;
}
}
else if(dec_val.exponent < 0)
{
while(e)
{
integr_part = integr_part/10;
e++;
}
}
TRY(encodeUnsignedInteger(strm, integr_part));
e = dec_val.exponent;
while(e < 0)
{
fract_part_rev = fract_part_rev*10 + m%10;
m = m/10;
e++;
}
TRY(encodeUnsignedInteger(strm, fract_part_rev));
return EXIP_OK;
}
errorCode encodeFloatValue(EXIStream* strm, Float fl_val)
{
errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR;
DEBUG_MSG(ERROR, DEBUG_STREAM_IO, (">Float value: %ldE%d\n", (long int)fl_val.mantissa, fl_val.exponent));
TRY(encodeIntegerValue(strm, (Integer) fl_val.mantissa)); //encode mantissa
TRY(encodeIntegerValue(strm, (Integer) fl_val.exponent)); //encode exponent
return EXIP_OK;
}
errorCode encodeDateTimeValue(EXIStream* strm, EXIType dtType, EXIPDateTime dt_val)
{
errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR;
if(dtType == VALUE_TYPE_DATE_TIME || dtType == VALUE_TYPE_DATE || dtType == VALUE_TYPE_YEAR)
{
/* Year component */
TRY(encodeIntegerValue(strm, (Integer) dt_val.dateTime.tm_year - 100));
}
if(dtType == VALUE_TYPE_DATE_TIME || dtType == VALUE_TYPE_DATE || dtType == VALUE_TYPE_MONTH)
{
/* MonthDay component */
unsigned int monDay = 0;
monDay = dt_val.dateTime.tm_mon + 1;
monDay = monDay * 32;
monDay += dt_val.dateTime.tm_mday;
TRY(encodeNBitUnsignedInteger(strm, 9, monDay));
}
if(dtType == VALUE_TYPE_DATE_TIME || dtType == VALUE_TYPE_TIME)
{
/* Time component */
unsigned int timeVal = 0;
timeVal += dt_val.dateTime.tm_hour;
timeVal = timeVal * 64;
timeVal += dt_val.dateTime.tm_min;
timeVal = timeVal * 64;
timeVal += dt_val.dateTime.tm_sec;
TRY(encodeNBitUnsignedInteger(strm, 17, timeVal));
if(IS_PRESENT(dt_val.presenceMask, FRACT_PRESENCE))
{
/* FractionalSecs component */
UnsignedInteger fSecs = 0;
unsigned int tmp;
unsigned int i = 1;
unsigned int j = 0;
tmp = dt_val.fSecs.value;
while(tmp != 0)
{
fSecs = fSecs*i + (tmp % 10);
tmp = tmp / 10;
i = 10;
j++;
}
for(i = 0; i < dt_val.fSecs.offset + 1 - j; j++)
{
fSecs = fSecs*10;
}
TRY(encodeBoolean(strm, TRUE));
TRY(encodeUnsignedInteger(strm, fSecs));
}
else
{
TRY(encodeBoolean(strm, FALSE));
}
}
if(IS_PRESENT(dt_val.presenceMask, TZONE_PRESENCE))
{
// 11-bit Unsigned Integer representing a signed integer offset by 896
unsigned int timeZone = 896;
TRY(encodeBoolean(strm, TRUE));
if(dt_val.TimeZone < -896)
{
timeZone = 0;
DEBUG_MSG(WARNING, DEBUG_STREAM_IO, (">Invalid TimeZone value: %d\n", dt_val.TimeZone));
}
else if(dt_val.TimeZone > 955)
{
timeZone = 955;
DEBUG_MSG(WARNING, DEBUG_STREAM_IO, (">Invalid TimeZone value: %d\n", dt_val.TimeZone));
}
else
timeZone += dt_val.TimeZone;
TRY(encodeNBitUnsignedInteger(strm, 11, timeZone));
}
else
{
TRY(encodeBoolean(strm, FALSE));
}
return EXIP_OK;
}
errorCode writeEventCode(EXIStream* strm, EventCode ec)
{
errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR;
int i;
for(i = 0; i < ec.length; i++)
{
TRY(encodeNBitUnsignedInteger(strm, ec.bits[i], (unsigned int) ec.part[i]));
}
return EXIP_OK;
}
|
312076.c | /*
* Copyright 2005, 2006 PathScale, Inc. All Rights Reserved.
*/
/*
Copyright (C) 2000,2004 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2.1 of the GNU Lesser General Public License
as published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307,
USA.
Contact information: Silicon Graphics, Inc., 1500 Crittenden Lane,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#include "config.h"
#include "libdwarfdefs.h"
#include <stdio.h>
#include <string.h>
#ifdef HAVE_ELFACCESS_H
#include <elfaccess.h>
#endif
#include "pro_incl.h"
#include "pro_section.h"
/*
This function adds another variable name to the
list of variable names for the given Dwarf_P_Debug.
It returns 0 on error, and 1 otherwise.
*/
Dwarf_Unsigned
dwarf_add_varname(Dwarf_P_Debug dbg,
Dwarf_P_Die die, char *var_name, Dwarf_Error * error)
{
return
_dwarf_add_simple_name_entry(dbg, die, var_name,
dwarf_snk_varname, error);
}
|
988305.c | /* origin: OpenBSD /usr/src/lib/libm/src/ld80/e_powl.c */
/*
* Copyright (c) 2008 Stephen L. Moshier <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* powl.c
*
* Power function, long double precision
*
*
* SYNOPSIS:
*
* long double x, y, z, powl();
*
* z = powl( x, y );
*
*
* DESCRIPTION:
*
* Computes x raised to the yth power. Analytically,
*
* x**y = exp( y log(x) ).
*
* Following Cody and Waite, this program uses a lookup table
* of 2**-i/32 and pseudo extended precision arithmetic to
* obtain several extra bits of accuracy in both the logarithm
* and the exponential.
*
*
* ACCURACY:
*
* The relative error of pow(x,y) can be estimated
* by y dl ln(2), where dl is the absolute error of
* the internally computed base 2 logarithm. At the ends
* of the approximation interval the logarithm equal 1/32
* and its relative error is about 1 lsb = 1.1e-19. Hence
* the predicted relative error in the result is 2.3e-21 y .
*
* Relative error:
* arithmetic domain # trials peak rms
*
* IEEE +-1000 40000 2.8e-18 3.7e-19
* .001 < x < 1000, with log(x) uniformly distributed.
* -1000 < y < 1000, y uniformly distributed.
*
* IEEE 0,8700 60000 6.5e-18 1.0e-18
* 0.99 < x < 1.01, 0 < y < 8700, uniformly distributed.
*
*
* ERROR MESSAGES:
*
* message condition value returned
* pow overflow x**y > MAXNUM INFINITY
* pow underflow x**y < 1/MAXNUM 0.0
* pow domain x<0 and y noninteger 0.0
*
*/
#include "libm.h"
#if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
long double powl(long double x, long double y)
{
return pow(x, y);
}
#elif LDBL_MANT_DIG == 64 && LDBL_MAX_EXP == 16384
/* Table size */
# define NXT 32
/* log(1+x) = x - .5x^2 + x^3 * P(z)/Q(z)
* on the domain 2^(-1/32) - 1 <= x <= 2^(1/32) - 1
*/
static const long double P[] = {
8.3319510773868690346226E-4L,
4.9000050881978028599627E-1L,
1.7500123722550302671919E0L,
1.4000100839971580279335E0L,
};
static const long double Q[] = {
/* 1.0000000000000000000000E0L,*/
5.2500282295834889175431E0L,
8.4000598057587009834666E0L,
4.2000302519914740834728E0L,
};
/* A[i] = 2^(-i/32), rounded to IEEE long double precision.
* If i is even, A[i] + B[i/2] gives additional accuracy.
*/
static const long double A[33] = {
1.0000000000000000000000E0L,
9.7857206208770013448287E-1L,
9.5760328069857364691013E-1L,
9.3708381705514995065011E-1L,
9.1700404320467123175367E-1L,
8.9735453750155359320742E-1L,
8.7812608018664974155474E-1L,
8.5930964906123895780165E-1L,
8.4089641525371454301892E-1L,
8.2287773907698242225554E-1L,
8.0524516597462715409607E-1L,
7.8799042255394324325455E-1L,
7.7110541270397041179298E-1L,
7.5458221379671136985669E-1L,
7.3841307296974965571198E-1L,
7.2259040348852331001267E-1L,
7.0710678118654752438189E-1L,
6.9195494098191597746178E-1L,
6.7712777346844636413344E-1L,
6.6261832157987064729696E-1L,
6.4841977732550483296079E-1L,
6.3452547859586661129850E-1L,
6.2092890603674202431705E-1L,
6.0762367999023443907803E-1L,
5.9460355750136053334378E-1L,
5.8186242938878875689693E-1L,
5.6939431737834582684856E-1L,
5.5719337129794626814472E-1L,
5.4525386633262882960438E-1L,
5.3357020033841180906486E-1L,
5.2213689121370692017331E-1L,
5.1094857432705833910408E-1L,
5.0000000000000000000000E-1L,
};
static const long double B[17] = {
0.0000000000000000000000E0L,
2.6176170809902549338711E-20L,
-1.0126791927256478897086E-20L,
1.3438228172316276937655E-21L,
1.2207982955417546912101E-20L,
-6.3084814358060867200133E-21L,
1.3164426894366316434230E-20L,
-1.8527916071632873716786E-20L,
1.8950325588932570796551E-20L,
1.5564775779538780478155E-20L,
6.0859793637556860974380E-21L,
-2.0208749253662532228949E-20L,
1.4966292219224761844552E-20L,
3.3540909728056476875639E-21L,
-8.6987564101742849540743E-22L,
-1.2327176863327626135542E-20L,
0.0000000000000000000000E0L,
};
/* 2^x = 1 + x P(x),
* on the interval -1/32 <= x <= 0
*/
static const long double R[] = {
1.5089970579127659901157E-5L,
1.5402715328927013076125E-4L,
1.3333556028915671091390E-3L,
9.6181291046036762031786E-3L,
5.5504108664798463044015E-2L,
2.4022650695910062854352E-1L,
6.9314718055994530931447E-1L,
};
# define MEXP (NXT * 16384.0L)
/* The following if denormal numbers are supported, else -MEXP: */
# define MNEXP (-NXT * (16384.0L + 64.0L))
/* log2(e) - 1 */
# define LOG2EA 0.44269504088896340735992L
# define F W
# define Fa Wa
# define Fb Wb
# define G W
# define Ga Wa
# define Gb u
# define H W
# define Ha Wb
# define Hb Wb
static const long double MAXLOGL = 1.1356523406294143949492E4L;
static const long double MINLOGL = -1.13994985314888605586758E4L;
static const long double LOGE2L = 6.9314718055994530941723E-1L;
static const long double huge = 0x1p10000L;
/* XXX Prevent gcc from erroneously constant folding this. */
static const volatile long double twom10000 = 0x1p-10000L;
static long double reducl(long double);
static long double powil(long double, int);
long double powl(long double x, long double y)
{
/* double F, Fa, Fb, G, Ga, Gb, H, Ha, Hb */
int i, nflg, iyflg, yoddint;
long e;
volatile long double z = 0;
long double w = 0, W = 0, Wa = 0, Wb = 0, ya = 0, yb = 0, u = 0;
/* make sure no invalid exception is raised by nan comparision */
if (isnan(x))
{
if (!isnan(y) && y == 0.0)
return 1.0;
return x;
}
if (isnan(y))
{
if (x == 1.0)
return 1.0;
return y;
}
if (x == 1.0)
return 1.0; /* 1**y = 1, even if y is nan */
if (x == -1.0 && !isfinite(y))
return 1.0; /* -1**inf = 1 */
if (y == 0.0)
return 1.0; /* x**0 = 1, even if x is nan */
if (y == 1.0)
return x;
if (y >= LDBL_MAX)
{
if (x > 1.0 || x < -1.0)
return INFINITY;
if (x != 0.0)
return 0.0;
}
if (y <= -LDBL_MAX)
{
if (x > 1.0 || x < -1.0)
return 0.0;
if (x != 0.0 || y == -INFINITY)
return INFINITY;
}
if (x >= LDBL_MAX)
{
if (y > 0.0)
return INFINITY;
return 0.0;
}
w = floorl(y);
/* Set iyflg to 1 if y is an integer. */
iyflg = 0;
if (w == y)
iyflg = 1;
/* Test for odd integer y. */
yoddint = 0;
if (iyflg)
{
ya = fabsl(y);
ya = floorl(0.5 * ya);
yb = 0.5 * fabsl(w);
if (ya != yb)
yoddint = 1;
}
if (x <= -LDBL_MAX)
{
if (y > 0.0)
{
if (yoddint)
return -INFINITY;
return INFINITY;
}
if (y < 0.0)
{
if (yoddint)
return -0.0;
return 0.0;
}
}
nflg = 0; /* (x<0)**(odd int) */
if (x <= 0.0)
{
if (x == 0.0)
{
if (y < 0.0)
{
if (signbit(x) && yoddint)
/* (-0.0)**(-odd int) = -inf, divbyzero */
return -1.0 / 0.0;
/* (+-0.0)**(negative) = inf, divbyzero */
return 1.0 / 0.0;
}
if (signbit(x) && yoddint)
return -0.0;
return 0.0;
}
if (iyflg == 0)
return (x - x) / (x - x); /* (x<0)**(non-int) is NaN */
/* (x<0)**(integer) */
if (yoddint)
nflg = 1; /* negate result */
x = -x;
}
/* (+integer)**(integer) */
if (iyflg && floorl(x) == x && fabsl(y) < 32768.0)
{
w = powil(x, (int)y);
return nflg ? -w : w;
}
/* separate significand from exponent */
x = frexpl(x, &i);
e = i;
/* find significand in antilog table A[] */
i = 1;
if (x <= A[17])
i = 17;
if (x <= A[i + 8])
i += 8;
if (x <= A[i + 4])
i += 4;
if (x <= A[i + 2])
i += 2;
if (x >= A[1])
i = -1;
i += 1;
/* Find (x - A[i])/A[i]
* in order to compute log(x/A[i]):
*
* log(x) = log( a x/a ) = log(a) + log(x/a)
*
* log(x/a) = log(1+v), v = x/a - 1 = (x-a)/a
*/
x -= A[i];
x -= B[i / 2];
x /= A[i];
/* rational approximation for log(1+v):
*
* log(1+v) = v - v**2/2 + v**3 P(v) / Q(v)
*/
z = x * x;
w = x * (z * __polevll(x, P, 3) / __p1evll(x, Q, 3));
w = w - 0.5 * z;
/* Convert to base 2 logarithm:
* multiply by log2(e) = 1 + LOG2EA
*/
z = LOG2EA * w;
z += w;
z += LOG2EA * x;
z += x;
/* Compute exponent term of the base 2 logarithm. */
w = -i;
w /= NXT;
w += e;
/* Now base 2 log of x is w + z. */
/* Multiply base 2 log by y, in extended precision. */
/* separate y into large part ya
* and small part yb less than 1/NXT
*/
ya = reducl(y);
yb = y - ya;
/* (w+z)(ya+yb)
* = w*ya + w*yb + z*y
*/
F = z * y + w * yb;
Fa = reducl(F);
Fb = F - Fa;
G = Fa + w * ya;
Ga = reducl(G);
Gb = G - Ga;
H = Fb + Gb;
Ha = reducl(H);
w = (Ga + Ha) * NXT;
/* Test the power of 2 for overflow */
if (w > MEXP)
return huge * huge; /* overflow */
if (w < MNEXP)
return twom10000 * twom10000; /* underflow */
e = w;
Hb = H - Ha;
if (Hb > 0.0)
{
e += 1;
Hb -= 1.0 / NXT; /*0.0625L;*/
}
/* Now the product y * log2(x) = Hb + e/NXT.
*
* Compute base 2 exponential of Hb,
* where -0.0625 <= Hb <= 0.
*/
z = Hb * __polevll(Hb, R, 6); /* z = 2**Hb - 1 */
/* Express e/NXT as an integer plus a negative number of (1/NXT)ths.
* Find lookup table entry for the fractional power of 2.
*/
if (e < 0)
i = 0;
else
i = 1;
i = e / NXT + i;
e = NXT * i - e;
w = A[e];
z = w * z; /* 2**-e * ( 1 + (2**Hb-1) ) */
z = z + w;
z = scalbnl(z, i); /* multiply by integer power of 2 */
if (nflg)
z = -z;
return z;
}
/* Find a multiple of 1/NXT that is within 1/NXT of x. */
static long double reducl(long double x)
{
long double t;
t = x * NXT;
t = floorl(t);
t = t / NXT;
return t;
}
/*
* Positive real raised to integer power, long double precision
*
*
* SYNOPSIS:
*
* long double x, y, powil();
* int n;
*
* y = powil( x, n );
*
*
* DESCRIPTION:
*
* Returns argument x>0 raised to the nth power.
* The routine efficiently decomposes n as a sum of powers of
* two. The desired power is a product of two-to-the-kth
* powers of x. Thus to compute the 32767 power of x requires
* 28 multiplications instead of 32767 multiplications.
*
*
* ACCURACY:
*
* Relative error:
* arithmetic x domain n domain # trials peak rms
* IEEE .001,1000 -1022,1023 50000 4.3e-17 7.8e-18
* IEEE 1,2 -1022,1023 20000 3.9e-17 7.6e-18
* IEEE .99,1.01 0,8700 10000 3.6e-16 7.2e-17
*
* Returns MAXNUM on overflow, zero on underflow.
*/
static long double powil(long double x, int nn)
{
long double ww, y;
long double s;
int n, e, sign, lx;
if (nn == 0)
return 1.0;
if (nn < 0)
{
sign = -1;
n = -nn;
}
else
{
sign = 1;
n = nn;
}
/* Overflow detection */
/* Calculate approximate logarithm of answer */
s = x;
s = frexpl(s, &lx);
e = (lx - 1) * n;
if ((e == 0) || (e > 64) || (e < -64))
{
s = (s - 7.0710678118654752e-1L) / (s + 7.0710678118654752e-1L);
s = (2.9142135623730950L * s - 0.5 + lx) * nn * LOGE2L;
}
else
{
s = LOGE2L * e;
}
if (s > MAXLOGL)
return huge * huge; /* overflow */
if (s < MINLOGL)
return twom10000 * twom10000; /* underflow */
/* Handle tiny denormal answer, but with less accuracy
* since roundoff error in 1.0/x will be amplified.
* The precise demarcation should be the gradual underflow threshold.
*/
if (s < -MAXLOGL + 2.0)
{
x = 1.0 / x;
sign = -sign;
}
/* First bit of the power */
if (n & 1)
y = x;
else
y = 1.0;
ww = x;
n >>= 1;
while (n)
{
ww = ww * ww; /* arg to the 2-to-the-kth power */
if (n & 1) /* if that bit is set, then include in product */
y *= ww;
n >>= 1;
}
if (sign < 0)
y = 1.0 / y;
return y;
}
#elif LDBL_MANT_DIG == 113 && LDBL_MAX_EXP == 16384
// TODO: broken implementation to make things compile
long double powl(long double x, long double y)
{
return pow(x, y);
}
#endif
|
495879.c | /*-
* Copyright (c) 1999 Michael Smith
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: releng/9.3/sys/dev/mlx/mlx_pci.c 254306 2013-08-13 22:05:50Z scottl $");
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/bus.h>
#include <sys/conf.h>
#include <machine/bus.h>
#include <machine/resource.h>
#include <sys/rman.h>
#include <geom/geom_disk.h>
#include <dev/pci/pcireg.h>
#include <dev/pci/pcivar.h>
#include <dev/mlx/mlx_compat.h>
#include <dev/mlx/mlxio.h>
#include <dev/mlx/mlxvar.h>
#include <dev/mlx/mlxreg.h>
static int mlx_pci_probe(device_t dev);
static int mlx_pci_attach(device_t dev);
static device_method_t mlx_methods[] = {
/* Device interface */
DEVMETHOD(device_probe, mlx_pci_probe),
DEVMETHOD(device_attach, mlx_pci_attach),
DEVMETHOD(device_detach, mlx_detach),
DEVMETHOD(device_shutdown, mlx_shutdown),
DEVMETHOD(device_suspend, mlx_suspend),
DEVMETHOD(device_resume, mlx_resume),
DEVMETHOD_END
};
static driver_t mlx_pci_driver = {
"mlx",
mlx_methods,
sizeof(struct mlx_softc)
};
DRIVER_MODULE(mlx, pci, mlx_pci_driver, mlx_devclass, 0, 0);
struct mlx_ident
{
u_int16_t vendor;
u_int16_t device;
u_int16_t subvendor;
u_int16_t subdevice;
int iftype;
char *desc;
} mlx_identifiers[] = {
{0x1069, 0x0001, 0x0000, 0x0000, MLX_IFTYPE_2, "Mylex version 2 RAID interface"},
{0x1069, 0x0002, 0x0000, 0x0000, MLX_IFTYPE_3, "Mylex version 3 RAID interface"},
{0x1069, 0x0010, 0x0000, 0x0000, MLX_IFTYPE_4, "Mylex version 4 RAID interface"},
{0x1011, 0x1065, 0x1069, 0x0020, MLX_IFTYPE_5, "Mylex version 5 RAID interface"},
{0, 0, 0, 0, 0, 0}
};
static int
mlx_pci_probe(device_t dev)
{
struct mlx_ident *m;
debug_called(1);
for (m = mlx_identifiers; m->vendor != 0; m++) {
if ((m->vendor == pci_get_vendor(dev)) &&
(m->device == pci_get_device(dev)) &&
((m->subvendor == 0) || ((m->subvendor == pci_get_subvendor(dev)) &&
(m->subdevice == pci_get_subdevice(dev))))) {
device_set_desc(dev, m->desc);
return(BUS_PROBE_DEFAULT);
}
}
return(ENXIO);
}
static int
mlx_pci_attach(device_t dev)
{
struct mlx_softc *sc;
int i, error;
debug_called(1);
/* force the busmaster enable bit on */
pci_enable_busmaster(dev);
/*
* Initialise softc.
*/
sc = device_get_softc(dev);
bzero(sc, sizeof(*sc));
sc->mlx_dev = dev;
/*
* Work out what sort of adapter this is (we need to know this in order
* to map the appropriate interface resources).
*/
sc->mlx_iftype = 0;
for (i = 0; mlx_identifiers[i].vendor != 0; i++) {
if ((mlx_identifiers[i].vendor == pci_get_vendor(dev)) &&
(mlx_identifiers[i].device == pci_get_device(dev))) {
sc->mlx_iftype = mlx_identifiers[i].iftype;
break;
}
}
if (sc->mlx_iftype == 0) /* shouldn't happen */
return(ENXIO);
/*
* Allocate the PCI register window.
*/
/* type 2/3 adapters have an I/O region we don't prefer at base 0 */
switch(sc->mlx_iftype) {
case MLX_IFTYPE_2:
case MLX_IFTYPE_3:
sc->mlx_mem_type = SYS_RES_MEMORY;
sc->mlx_mem_rid = MLX_CFG_BASE1;
sc->mlx_mem = bus_alloc_resource_any(dev, sc->mlx_mem_type,
&sc->mlx_mem_rid, RF_ACTIVE);
if (sc->mlx_mem == NULL) {
sc->mlx_mem_type = SYS_RES_IOPORT;
sc->mlx_mem_rid = MLX_CFG_BASE0;
sc->mlx_mem = bus_alloc_resource_any(dev, sc->mlx_mem_type,
&sc->mlx_mem_rid, RF_ACTIVE);
}
break;
case MLX_IFTYPE_4:
case MLX_IFTYPE_5:
sc->mlx_mem_type = SYS_RES_MEMORY;
sc->mlx_mem_rid = MLX_CFG_BASE0;
sc->mlx_mem = bus_alloc_resource_any(dev, sc->mlx_mem_type,
&sc->mlx_mem_rid, RF_ACTIVE);
break;
}
if (sc->mlx_mem == NULL) {
device_printf(sc->mlx_dev, "couldn't allocate mailbox window\n");
mlx_free(sc);
return(ENXIO);
}
sc->mlx_btag = rman_get_bustag(sc->mlx_mem);
sc->mlx_bhandle = rman_get_bushandle(sc->mlx_mem);
/*
* Allocate the parent bus DMA tag appropriate for PCI.
*/
error = bus_dma_tag_create(bus_get_dma_tag(dev), /* PCI parent */
1, 0, /* alignment, boundary */
BUS_SPACE_MAXADDR_32BIT, /* lowaddr */
BUS_SPACE_MAXADDR, /* highaddr */
NULL, NULL, /* filter, filterarg */
MAXBSIZE, MLX_NSEG, /* maxsize, nsegments */
BUS_SPACE_MAXSIZE_32BIT, /* maxsegsize */
BUS_DMA_ALLOCNOW, /* flags */
NULL, /* lockfunc */
NULL, /* lockarg */
&sc->mlx_parent_dmat);
if (error != 0) {
device_printf(dev, "can't allocate parent DMA tag\n");
mlx_free(sc);
return(ENOMEM);
}
/*
* Do bus-independant initialisation.
*/
error = mlx_attach(sc);
if (error != 0) {
mlx_free(sc);
return(error);
}
/*
* Start the controller.
*/
mlx_startup(sc);
return(0);
}
|
335730.c | /* hipstopgm.c - read a HIPS file and produce a portable graymap
**
** Copyright (C) 1989 by Jef Poskanzer.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
*/
#include "pgm.h"
struct HIPS_Header {
char* orig_name; /* An indication of the originator of this sequence. */
char* seq_name; /* The sequence name. */
int num_frame; /* The number of frames in this sequence. */
char* orig_date; /* The date the sequence was originated. */
int rows; /* The number of rows in each image, the height. */
int cols; /* The number of columns in each image, the width. */
int bits_per_pixel; /* The number of significant bits per pixel. */
int bit_packing; /* Nonzero if the bits were packed such as to
eliminate any unused bits resulting from a
bits_per_pixel value which was not an even
multiple of eight. */
int pixel_format; /* An indication of the format of each pixel. */
char* seq_history; /* A description of the sequence of transformations
leading up to the current image. */
char* seq_desc; /* A free form description of the contents of the
sequence. */
};
#define HIPS_PFBYTE 0
#define HIPS_PFSHORT 1
#define HIPS_PFINT 2
#define HIPS_PFFLOAT 3
#define HIPS_PFCOMPLEX 4
static void read_hips_header ARGS(( FILE* fd, struct HIPS_Header* hP ));
static void read_line ARGS(( FILE* fd, char* buf, int size ));
int
main( argc, argv )
int argc;
char* argv[];
{
FILE* ifp;
gray* grayrow;
register gray* gP;
int argn, row;
register int col;
int maxval;
int rows, cols;
struct HIPS_Header h;
pgm_init( &argc, argv );
argn = 1;
if ( argn < argc )
{
ifp = pm_openr( argv[argn] );
argn++;
}
else
ifp = stdin;
if ( argn != argc )
pm_usage( "[hipsfile]" );
read_hips_header( ifp, &h );
cols = h.cols;
rows = h.rows * h.num_frame;
switch ( h.pixel_format )
{
case HIPS_PFBYTE:
if ( h.bits_per_pixel != 8 )
pm_error(
"can't handle unusual bits_per_pixel %d", h.bits_per_pixel );
if ( h.bit_packing != 0 )
pm_error( "can't handle bit_packing" );
maxval = 255;
break;
default:
pm_error( "unknown pixel format %d", h.pixel_format );
}
if ( maxval > PGM_MAXMAXVAL )
pm_error(
"bits_per_pixel is too large - try reconfiguring with PGM_BIGGRAYS" );
pgm_writepgminit( stdout, cols, rows, (gray) maxval, 0 );
grayrow = pgm_allocrow( cols );
for ( row = 0; row < rows; row++)
{
for ( col = 0, gP = grayrow; col < cols; col++, gP++ )
{
int ich;
switch ( h.pixel_format )
{
case HIPS_PFBYTE:
ich = getc( ifp );
if ( ich == EOF )
pm_error( "EOF / read error" );
*gP = (gray) ich;
break;
default:
pm_error( "can't happen" );
}
}
pgm_writepgmrow( stdout, grayrow, cols, (gray) maxval, 0 );
}
pm_close( ifp );
pm_close( stdout );
exit( 0 );
}
static void
read_hips_header( fd, hP )
FILE* fd;
struct HIPS_Header* hP;
{
char buf[5000];
/* Read and toss orig_name. */
read_line( fd, buf, 5000 );
/* Read and toss seq_name. */
read_line( fd, buf, 5000 );
/* Read num_frame. */
read_line( fd, buf, 5000 );
hP->num_frame = atoi( buf );
/* Read and toss orig_date. */
read_line( fd, buf, 5000 );
/* Read rows. */
read_line( fd, buf, 5000 );
hP->rows = atoi( buf );
/* Read cols. */
read_line( fd, buf, 5000 );
hP->cols = atoi( buf );
/* Read bits_per_pixel. */
read_line( fd, buf, 5000 );
hP->bits_per_pixel = atoi( buf );
/* Read bit_packing. */
read_line( fd, buf, 5000 );
hP->bit_packing = atoi( buf );
/* Read pixel_format. */
read_line( fd, buf, 5000 );
hP->pixel_format = atoi( buf );
/* Now read and toss lines until we get one with just a period. */
do
{
read_line( fd, buf, 5000 );
}
while ( strcmp( buf, ".\n" ) != 0 );
}
static void
read_line( fd, buf, size )
FILE* fd;
char* buf;
int size;
{
if ( fgets( buf, size, fd ) == NULL )
pm_error( "error reading header" );
}
|
175562.c | #include <yed/plugin.h>
void*
sysclip();
char*
get_sel_text(yed_buffer* buffer);
void
thr_wrap(int n_args, char** args);
struct Params
{
char* str2paste;
char* clip_pref;
};
int
yed_plugin_boot(yed_plugin* self)
{
/*Check for matching YED and plugin version*/
YED_PLUG_VERSION_CHECK();
if (yed_get_var("sys-clip") == NULL)
{
yed_set_var("sys-clip", "xsel");
}
yed_plugin_set_command(self, "y2s", thr_wrap);
return 0;
}
void
thr_wrap(int n_args, char** args)
{
yed_frame* frame;
yed_buffer* buffer;
pthread_t sctr;
int tret;
struct Params* p;
if (!ys->active_frame)
{
yed_cerr("no active frame");
return;
}
frame = ys->active_frame;
if (!frame->buffer)
{
yed_cerr("active frame has no buffer");
return;
}
buffer = frame->buffer;
if (!buffer->has_selection)
{
yed_cerr("nothing is selected");
return;
}
p = (struct Params*)malloc(sizeof(struct Params));
p->str2paste = get_sel_text(frame->buffer);
p->clip_pref = yed_get_var("sys-clip");
tret = pthread_create(&sctr, NULL, sysclip, p);
if (tret != 0)
{
yed_cerr("Failed to create thread");
return;
}
}
void*
sysclip(struct Params* p)
{
char cmd_buff[4096];
FILE* sc_pipe;
snprintf(cmd_buff, sizeof(cmd_buff), "%s",
p->clip_pref);
if ((sc_pipe = popen(cmd_buff, "w")) == NULL)
{
pthread_exit(NULL);
}
fprintf(sc_pipe, "%s", p->str2paste);
pclose(sc_pipe);
/* yed_cprint("Yanked to system clipboard"); */
free(p->str2paste);
free(p);
return (NULL);
}
/* ty kammer */
char*
get_sel_text(yed_buffer* buffer)
{
char nl;
array_t chars;
int r1;
int c1;
int r2;
int c2;
int r;
yed_line* line;
int cstart;
int cend;
int i;
int n;
char* data;
nl = '\n';
chars = array_make(char);
yed_range_sorted_points(&buffer->selection, &r1, &c1, &r2, &c2);
if (buffer->selection.kind == RANGE_LINE)
{
for (r = r1; r <= r2; r += 1)
{
line = yed_buff_get_line(buffer, r);
if (line == NULL)
{
break;
} /* should not happen */
data = (char*)array_data(line->chars);
array_push_n(chars, data, array_len(line->chars));
array_push(chars, nl);
}
}
else
{
for (r = r1; r <= r2; r += 1)
{
line = yed_buff_get_line(buffer, r);
if (line == NULL)
{
break;
} /* should not happen */
if (line->visual_width > 0)
{
cstart = r == r1 ? c1 : 1;
cend = r == r2 ? c2 : line->visual_width + 1;
i = yed_line_col_to_idx(line, cstart);
n = yed_line_col_to_idx(line, cend) - i;
data = array_item(line->chars, i);
array_push_n(chars, data, n);
}
if (r < r2)
{
array_push(chars, nl);
}
}
}
array_zero_term(chars);
return (char*)array_data(chars);
}
|
152224.c | /* $OpenLDAP$ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
*
* Copyright 1998-2018 The OpenLDAP Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
/* Portions Copyright (c) 1995 Regents of the University of Michigan.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that this notice is preserved and that due credit is given
* to the University of Michigan at Ann Arbor. The name of the University
* may not be used to endorse or promote products derived from this
* software without specific prior written permission. This software
* is provided ``as is'' without express or implied warranty.
*/
#include <stdio.h>
#include "portable.h"
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#include <ac/errno.h>
#include <ac/socket.h>
#include <ac/string.h>
#include <ac/time.h>
#include <ac/unistd.h>
#include "lutil.h"
#include "slap.h"
#ifdef LDAP_CONNECTIONLESS
#include "../../libraries/liblber/lber-int.h" /* ber_int_sb_read() */
#endif
#ifdef LDAP_SLAPI
#include "slapi/slapi.h"
#endif
/* protected by connections_mutex */
static ldap_pvt_thread_mutex_t connections_mutex;
static Connection* connections = NULL;
static ldap_pvt_thread_mutex_t conn_nextid_mutex;
static unsigned long conn_nextid = SLAPD_SYNC_SYNCCONN_OFFSET;
static const char conn_lost_str[] = "connection lost";
const char* connection_state2str(int state)
{
switch (state)
{
case SLAP_C_INVALID:
return "!";
case SLAP_C_INACTIVE:
return "|";
case SLAP_C_CLOSING:
return "C";
case SLAP_C_ACTIVE:
return "";
case SLAP_C_BINDING:
return "B";
case SLAP_C_CLIENT:
return "L";
}
return "?";
}
static Connection* connection_get(ber_socket_t s);
typedef struct conn_readinfo
{
Operation* op;
ldap_pvt_thread_start_t* func;
void* arg;
void* ctx;
int nullop;
} conn_readinfo;
static int connection_input(Connection* c, conn_readinfo* cri);
static void connection_close(Connection* c);
static int connection_op_activate(Operation* op);
static void connection_op_queue(Operation* op);
static int connection_resched(Connection* conn);
static void connection_abandon(Connection* conn);
static void connection_destroy(Connection* c);
static ldap_pvt_thread_start_t connection_operation;
/*
* Initialize connection management infrastructure.
*/
int connections_init(void)
{
int i;
assert(connections == NULL);
if (connections != NULL)
{
Debug(LDAP_DEBUG_ANY, "connections_init: already initialized.\n", 0, 0,
0);
return -1;
}
/* should check return of every call */
ldap_pvt_thread_mutex_init(&connections_mutex);
ldap_pvt_thread_mutex_init(&conn_nextid_mutex);
connections = (Connection*)ch_calloc(dtblsize, sizeof(Connection));
if (connections == NULL)
{
Debug(LDAP_DEBUG_ANY,
"connections_init: "
"allocation (%d*%ld) of connection array failed\n",
dtblsize, (long)sizeof(Connection), 0);
return -1;
}
assert(connections[0].c_struct_state == SLAP_C_UNINITIALIZED);
assert(connections[dtblsize - 1].c_struct_state == SLAP_C_UNINITIALIZED);
for (i = 0; i < dtblsize; i++)
connections[i].c_conn_idx = i;
/*
* per entry initialization of the Connection array initialization
* will be done by connection_init()
*/
return 0;
}
/*
* Destroy connection management infrastructure.
*/
int connections_destroy(void)
{
ber_socket_t i;
/* should check return of every call */
if (connections == NULL)
{
Debug(LDAP_DEBUG_ANY, "connections_destroy: nothing to destroy.\n", 0,
0, 0);
return -1;
}
for (i = 0; i < dtblsize; i++)
{
if (connections[i].c_struct_state != SLAP_C_UNINITIALIZED)
{
ber_sockbuf_free(connections[i].c_sb);
ldap_pvt_thread_mutex_destroy(&connections[i].c_mutex);
ldap_pvt_thread_mutex_destroy(&connections[i].c_write1_mutex);
ldap_pvt_thread_mutex_destroy(&connections[i].c_write2_mutex);
ldap_pvt_thread_cond_destroy(&connections[i].c_write1_cv);
ldap_pvt_thread_cond_destroy(&connections[i].c_write2_cv);
#ifdef LDAP_SLAPI
if (slapi_plugins_used)
{
slapi_int_free_object_extensions(SLAPI_X_EXT_CONNECTION,
&connections[i]);
}
#endif
}
}
free(connections);
connections = NULL;
ldap_pvt_thread_mutex_destroy(&connections_mutex);
ldap_pvt_thread_mutex_destroy(&conn_nextid_mutex);
return 0;
}
/*
* shutdown all connections
*/
int connections_shutdown(void)
{
ber_socket_t i;
for (i = 0; i < dtblsize; i++)
{
if (connections[i].c_struct_state != SLAP_C_UNINITIALIZED)
{
ldap_pvt_thread_mutex_lock(&connections[i].c_mutex);
if (connections[i].c_struct_state == SLAP_C_USED)
{
/* give persistent clients a chance to cleanup */
if (connections[i].c_conn_state == SLAP_C_CLIENT)
{
ldap_pvt_thread_pool_submit(&connection_pool,
connections[i].c_clientfunc,
connections[i].c_clientarg);
}
else
{
/* c_mutex is locked */
connection_closing(&connections[i], "slapd shutdown");
connection_close(&connections[i]);
}
}
ldap_pvt_thread_mutex_unlock(&connections[i].c_mutex);
}
}
return 0;
}
/*
* Timeout idle connections.
*/
int connections_timeout_idle(time_t now)
{
int i = 0, writers = 0;
ber_socket_t connindex;
Connection* c;
time_t old;
old = slapd_get_writetime();
for (c = connection_first(&connindex); c != NULL;
c = connection_next(c, &connindex))
{
/* Don't timeout a slow-running request or a persistent
* outbound connection. But if it has a writewaiter, see
* if the waiter has been there too long.
*/
if ((c->c_n_ops_executing && !c->c_writewaiter) ||
c->c_conn_state == SLAP_C_CLIENT)
{
continue;
}
if (global_idletimeout &&
difftime(c->c_activitytime + global_idletimeout, now) < 0)
{
/* close it */
connection_closing(c, "idletimeout");
connection_close(c);
i++;
continue;
}
if (c->c_writewaiter && global_writetimeout)
{
writers = 1;
if (difftime(c->c_activitytime + global_writetimeout, now) < 0)
{
/* close it */
connection_closing(c, "writetimeout");
connection_close(c);
i++;
continue;
}
}
}
connection_done(c);
if (old && !writers)
slapd_clr_writetime(old);
return i;
}
/* Drop all client connections */
void connections_drop()
{
Connection* c;
ber_socket_t connindex;
for (c = connection_first(&connindex); c != NULL;
c = connection_next(c, &connindex))
{
/* Don't close a slow-running request or a persistent
* outbound connection.
*/
if ((c->c_n_ops_executing && !c->c_writewaiter) ||
c->c_conn_state == SLAP_C_CLIENT)
{
continue;
}
connection_closing(c, "dropping");
connection_close(c);
}
connection_done(c);
}
static Connection* connection_get(ber_socket_t s)
{
Connection* c;
Debug(LDAP_DEBUG_ARGS, "connection_get(%ld)\n", (long)s, 0, 0);
assert(connections != NULL);
if (s == AC_SOCKET_INVALID)
return NULL;
assert(s < dtblsize);
c = &connections[s];
if (c != NULL)
{
ldap_pvt_thread_mutex_lock(&c->c_mutex);
assert(c->c_struct_state != SLAP_C_UNINITIALIZED);
if (c->c_struct_state != SLAP_C_USED)
{
/* connection must have been closed due to resched */
Debug(LDAP_DEBUG_CONNS, "connection_get(%d): connection not used\n",
s, 0, 0);
assert(c->c_conn_state == SLAP_C_INVALID);
assert(c->c_sd == AC_SOCKET_INVALID);
ldap_pvt_thread_mutex_unlock(&c->c_mutex);
return NULL;
}
Debug(LDAP_DEBUG_TRACE, "connection_get(%d): got connid=%lu\n", s,
c->c_connid, 0);
c->c_n_get++;
assert(c->c_struct_state == SLAP_C_USED);
assert(c->c_conn_state != SLAP_C_INVALID);
assert(c->c_sd != AC_SOCKET_INVALID);
#ifndef SLAPD_MONITOR
if (global_idletimeout > 0)
#endif /* ! SLAPD_MONITOR */
{
c->c_activitytime = slap_get_time();
}
}
return c;
}
static void connection_return(Connection* c)
{
ldap_pvt_thread_mutex_unlock(&c->c_mutex);
}
Connection* connection_init(
ber_socket_t s, Listener* listener, const char* dnsname,
const char* peername, int flags, slap_ssf_t ssf,
struct berval* authid LDAP_PF_LOCAL_SENDMSG_ARG(struct berval* peerbv))
{
unsigned long id;
Connection* c;
int doinit = 0;
ber_socket_t sfd = SLAP_FD2SOCK(s);
assert(connections != NULL);
assert(listener != NULL);
assert(dnsname != NULL);
assert(peername != NULL);
#ifndef HAVE_TLS
assert(!(flags & CONN_IS_TLS));
#endif
if (s == AC_SOCKET_INVALID)
{
Debug(LDAP_DEBUG_ANY, "connection_init: init of socket %ld invalid.\n",
(long)s, 0, 0);
return NULL;
}
assert(s >= 0);
assert(s < dtblsize);
c = &connections[s];
if (c->c_struct_state == SLAP_C_UNINITIALIZED)
{
doinit = 1;
}
else
{
assert(c->c_struct_state == SLAP_C_UNUSED);
}
if (doinit)
{
c->c_send_ldap_result = slap_send_ldap_result;
c->c_send_search_entry = slap_send_search_entry;
c->c_send_search_reference = slap_send_search_reference;
c->c_send_ldap_extended = slap_send_ldap_extended;
c->c_send_ldap_intermediate = slap_send_ldap_intermediate;
BER_BVZERO(&c->c_authmech);
BER_BVZERO(&c->c_dn);
BER_BVZERO(&c->c_ndn);
c->c_listener = NULL;
BER_BVZERO(&c->c_peer_domain);
BER_BVZERO(&c->c_peer_name);
LDAP_STAILQ_INIT(&c->c_ops);
LDAP_STAILQ_INIT(&c->c_pending_ops);
#ifdef LDAP_X_TXN
c->c_txn = CONN_TXN_INACTIVE;
c->c_txn_backend = NULL;
LDAP_STAILQ_INIT(&c->c_txn_ops);
#endif
BER_BVZERO(&c->c_sasl_bind_mech);
c->c_sasl_done = 0;
c->c_sasl_authctx = NULL;
c->c_sasl_sockctx = NULL;
c->c_sasl_extra = NULL;
c->c_sasl_bindop = NULL;
c->c_sb = ber_sockbuf_alloc();
{
ber_len_t max = sockbuf_max_incoming;
ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max);
}
c->c_currentber = NULL;
/* should check status of thread calls */
ldap_pvt_thread_mutex_init(&c->c_mutex);
ldap_pvt_thread_mutex_init(&c->c_write1_mutex);
ldap_pvt_thread_mutex_init(&c->c_write2_mutex);
ldap_pvt_thread_cond_init(&c->c_write1_cv);
ldap_pvt_thread_cond_init(&c->c_write2_cv);
#ifdef LDAP_SLAPI
if (slapi_plugins_used)
{
slapi_int_create_object_extensions(SLAPI_X_EXT_CONNECTION, c);
}
#endif
}
ldap_pvt_thread_mutex_lock(&c->c_mutex);
assert(BER_BVISNULL(&c->c_authmech));
assert(BER_BVISNULL(&c->c_dn));
assert(BER_BVISNULL(&c->c_ndn));
assert(c->c_listener == NULL);
assert(BER_BVISNULL(&c->c_peer_domain));
assert(BER_BVISNULL(&c->c_peer_name));
assert(LDAP_STAILQ_EMPTY(&c->c_ops));
assert(LDAP_STAILQ_EMPTY(&c->c_pending_ops));
#ifdef LDAP_X_TXN
assert(c->c_txn == CONN_TXN_INACTIVE);
assert(c->c_txn_backend == NULL);
assert(LDAP_STAILQ_EMPTY(&c->c_txn_ops));
#endif
assert(BER_BVISNULL(&c->c_sasl_bind_mech));
assert(c->c_sasl_done == 0);
assert(c->c_sasl_authctx == NULL);
assert(c->c_sasl_sockctx == NULL);
assert(c->c_sasl_extra == NULL);
assert(c->c_sasl_bindop == NULL);
assert(c->c_currentber == NULL);
assert(c->c_writewaiter == 0);
assert(c->c_writers == 0);
c->c_listener = listener;
c->c_sd = s;
if (flags & CONN_IS_CLIENT)
{
c->c_connid = 0;
ldap_pvt_thread_mutex_lock(&connections_mutex);
c->c_conn_state = SLAP_C_CLIENT;
c->c_struct_state = SLAP_C_USED;
ldap_pvt_thread_mutex_unlock(&connections_mutex);
c->c_close_reason = "?"; /* should never be needed */
ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_SET_FD, &sfd);
ldap_pvt_thread_mutex_unlock(&c->c_mutex);
return c;
}
ber_str2bv(dnsname, 0, 1, &c->c_peer_domain);
ber_str2bv(peername, 0, 1, &c->c_peer_name);
c->c_n_ops_received = 0;
c->c_n_ops_executing = 0;
c->c_n_ops_pending = 0;
c->c_n_ops_completed = 0;
c->c_n_get = 0;
c->c_n_read = 0;
c->c_n_write = 0;
/* set to zero until bind, implies LDAP_VERSION3 */
c->c_protocol = 0;
#ifndef SLAPD_MONITOR
if (global_idletimeout > 0)
#endif /* ! SLAPD_MONITOR */
{
c->c_activitytime = c->c_starttime = slap_get_time();
}
#ifdef LDAP_CONNECTIONLESS
c->c_is_udp = 0;
if (flags & CONN_IS_UDP)
{
c->c_is_udp = 1;
#ifdef LDAP_DEBUG
ber_sockbuf_add_io(c->c_sb, &ber_sockbuf_io_debug,
LBER_SBIOD_LEVEL_PROVIDER, (void*)"udp_");
#endif
ber_sockbuf_add_io(c->c_sb, &ber_sockbuf_io_udp,
LBER_SBIOD_LEVEL_PROVIDER, (void*)&sfd);
ber_sockbuf_add_io(c->c_sb, &ber_sockbuf_io_readahead,
LBER_SBIOD_LEVEL_PROVIDER, NULL);
}
else
#endif /* LDAP_CONNECTIONLESS */
#ifdef LDAP_PF_LOCAL
if (flags & CONN_IS_IPC)
{
#ifdef LDAP_DEBUG
ber_sockbuf_add_io(c->c_sb, &ber_sockbuf_io_debug,
LBER_SBIOD_LEVEL_PROVIDER, (void*)"ipc_");
#endif
ber_sockbuf_add_io(c->c_sb, &ber_sockbuf_io_fd,
LBER_SBIOD_LEVEL_PROVIDER, (void*)&sfd);
#ifdef LDAP_PF_LOCAL_SENDMSG
if (!BER_BVISEMPTY(peerbv))
ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_UNGET_BUF, peerbv);
#endif
}
else
#endif /* LDAP_PF_LOCAL */
{
#ifdef LDAP_DEBUG
ber_sockbuf_add_io(c->c_sb, &ber_sockbuf_io_debug,
LBER_SBIOD_LEVEL_PROVIDER, (void*)"tcp_");
#endif
ber_sockbuf_add_io(c->c_sb, &ber_sockbuf_io_tcp,
LBER_SBIOD_LEVEL_PROVIDER, (void*)&sfd);
}
#ifdef LDAP_DEBUG
ber_sockbuf_add_io(c->c_sb, &ber_sockbuf_io_debug, INT_MAX, (void*)"ldap_");
#endif
if (ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_SET_NONBLOCK, c /* non-NULL */) <
0)
{
Debug(LDAP_DEBUG_ANY,
"connection_init(%d, %s): set nonblocking failed\n", s,
c->c_peer_name.bv_val, 0);
}
ldap_pvt_thread_mutex_lock(&conn_nextid_mutex);
id = c->c_connid = conn_nextid++;
ldap_pvt_thread_mutex_unlock(&conn_nextid_mutex);
ldap_pvt_thread_mutex_lock(&connections_mutex);
c->c_conn_state = SLAP_C_INACTIVE;
c->c_struct_state = SLAP_C_USED;
ldap_pvt_thread_mutex_unlock(&connections_mutex);
c->c_close_reason = "?"; /* should never be needed */
c->c_ssf = c->c_transport_ssf = ssf;
c->c_tls_ssf = 0;
#ifdef HAVE_TLS
if (flags & CONN_IS_TLS)
{
c->c_is_tls = 1;
c->c_needs_tls_accept = 1;
}
else
{
c->c_is_tls = 0;
c->c_needs_tls_accept = 0;
}
#endif
slap_sasl_open(c, 0);
slap_sasl_external(c, ssf, authid);
slapd_add_internal(s, 1);
backend_connection_init(c);
ldap_pvt_thread_mutex_unlock(&c->c_mutex);
if (!(flags & CONN_IS_UDP))
Statslog(LDAP_DEBUG_STATS, "conn=%ld fd=%ld ACCEPT from %s (%s)\n", id,
(long)s, peername, listener->sl_name.bv_val, 0);
return c;
}
void connection2anonymous(Connection* c)
{
assert(connections != NULL);
assert(c != NULL);
{
ber_len_t max = sockbuf_max_incoming;
ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max);
}
if (!BER_BVISNULL(&c->c_authmech))
{
ch_free(c->c_authmech.bv_val);
}
BER_BVZERO(&c->c_authmech);
if (!BER_BVISNULL(&c->c_dn))
{
ch_free(c->c_dn.bv_val);
}
BER_BVZERO(&c->c_dn);
if (!BER_BVISNULL(&c->c_ndn))
{
ch_free(c->c_ndn.bv_val);
}
BER_BVZERO(&c->c_ndn);
if (!BER_BVISNULL(&c->c_sasl_authz_dn))
{
ber_memfree_x(c->c_sasl_authz_dn.bv_val, NULL);
}
BER_BVZERO(&c->c_sasl_authz_dn);
c->c_authz_backend = NULL;
}
static void connection_destroy(Connection* c)
{
unsigned long connid;
const char* close_reason;
Sockbuf* sb;
ber_socket_t sd;
assert(connections != NULL);
assert(c != NULL);
assert(c->c_struct_state != SLAP_C_UNUSED);
assert(c->c_conn_state != SLAP_C_INVALID);
assert(LDAP_STAILQ_EMPTY(&c->c_ops));
assert(LDAP_STAILQ_EMPTY(&c->c_pending_ops));
#ifdef LDAP_X_TXN
assert(c->c_txn == CONN_TXN_INACTIVE);
assert(c->c_txn_backend == NULL);
assert(LDAP_STAILQ_EMPTY(&c->c_txn_ops));
#endif
assert(c->c_writewaiter == 0);
assert(c->c_writers == 0);
/* only for stats (print -1 as "%lu" may give unexpected results ;) */
connid = c->c_connid;
close_reason = c->c_close_reason;
ldap_pvt_thread_mutex_lock(&connections_mutex);
c->c_struct_state = SLAP_C_PENDING;
ldap_pvt_thread_mutex_unlock(&connections_mutex);
backend_connection_destroy(c);
c->c_protocol = 0;
c->c_connid = -1;
c->c_activitytime = c->c_starttime = 0;
connection2anonymous(c);
c->c_listener = NULL;
if (c->c_peer_domain.bv_val != NULL)
{
free(c->c_peer_domain.bv_val);
}
BER_BVZERO(&c->c_peer_domain);
if (c->c_peer_name.bv_val != NULL)
{
free(c->c_peer_name.bv_val);
}
BER_BVZERO(&c->c_peer_name);
c->c_sasl_bind_in_progress = 0;
if (c->c_sasl_bind_mech.bv_val != NULL)
{
free(c->c_sasl_bind_mech.bv_val);
}
BER_BVZERO(&c->c_sasl_bind_mech);
slap_sasl_close(c);
if (c->c_currentber != NULL)
{
ber_free(c->c_currentber, 1);
c->c_currentber = NULL;
}
#ifdef LDAP_SLAPI
/* call destructors, then constructors; avoids unnecessary allocation */
if (slapi_plugins_used)
{
slapi_int_clear_object_extensions(SLAPI_X_EXT_CONNECTION, c);
}
#endif
sd = c->c_sd;
c->c_sd = AC_SOCKET_INVALID;
c->c_conn_state = SLAP_C_INVALID;
c->c_struct_state = SLAP_C_UNUSED;
c->c_close_reason = "?"; /* should never be needed */
sb = c->c_sb;
c->c_sb = ber_sockbuf_alloc();
{
ber_len_t max = sockbuf_max_incoming;
ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max);
}
/* c must be fully reset by this point; when we call slapd_remove
* it may get immediately reused by a new connection.
*/
if (sd != AC_SOCKET_INVALID)
{
slapd_remove(sd, sb, 1, 0, 0);
if (close_reason == NULL)
{
Statslog(LDAP_DEBUG_STATS, "conn=%lu fd=%ld closed\n", connid,
(long)sd, 0, 0, 0);
}
else
{
Statslog(LDAP_DEBUG_STATS, "conn=%lu fd=%ld closed (%s)\n", connid,
(long)sd, close_reason, 0, 0);
}
}
}
int connection_valid(Connection* c)
{
/* c_mutex must be locked by caller */
assert(c != NULL);
return c->c_struct_state == SLAP_C_USED &&
c->c_conn_state >= SLAP_C_ACTIVE && c->c_conn_state <= SLAP_C_CLIENT;
}
static void connection_abandon(Connection* c)
{
/* c_mutex must be locked by caller */
Operation *o, *next, op = {0};
Opheader ohdr = {0};
op.o_hdr = &ohdr;
op.o_conn = c;
op.o_connid = c->c_connid;
op.o_tag = LDAP_REQ_ABANDON;
for (o = LDAP_STAILQ_FIRST(&c->c_ops); o; o = next)
{
SlapReply rs = {REP_RESULT};
next = LDAP_STAILQ_NEXT(o, o_next);
/* don't abandon an op twice */
if (o->o_abandon)
continue;
op.orn_msgid = o->o_msgid;
o->o_abandon = 1;
op.o_bd = frontendDB;
frontendDB->be_abandon(&op, &rs);
}
#ifdef LDAP_X_TXN
/* remove operations in pending transaction */
while ((o = LDAP_STAILQ_FIRST(&c->c_txn_ops)) != NULL)
{
LDAP_STAILQ_REMOVE_HEAD(&c->c_txn_ops, o_next);
LDAP_STAILQ_NEXT(o, o_next) = NULL;
slap_op_free(o, NULL);
}
/* clear transaction */
c->c_txn_backend = NULL;
c->c_txn = CONN_TXN_INACTIVE;
#endif
/* remove pending operations */
while ((o = LDAP_STAILQ_FIRST(&c->c_pending_ops)) != NULL)
{
LDAP_STAILQ_REMOVE_HEAD(&c->c_pending_ops, o_next);
LDAP_STAILQ_NEXT(o, o_next) = NULL;
slap_op_free(o, NULL);
}
}
static void connection_wake_writers(Connection* c)
{
/* wake write blocked operations */
ldap_pvt_thread_mutex_lock(&c->c_write1_mutex);
if (c->c_writers > 0)
{
c->c_writers = -c->c_writers;
ldap_pvt_thread_cond_broadcast(&c->c_write1_cv);
ldap_pvt_thread_mutex_unlock(&c->c_write1_mutex);
if (c->c_writewaiter)
{
ldap_pvt_thread_mutex_lock(&c->c_write2_mutex);
ldap_pvt_thread_cond_signal(&c->c_write2_cv);
slapd_clr_write(c->c_sd, 1);
ldap_pvt_thread_mutex_unlock(&c->c_write2_mutex);
}
ldap_pvt_thread_mutex_lock(&c->c_write1_mutex);
while (c->c_writers)
{
ldap_pvt_thread_cond_wait(&c->c_write1_cv, &c->c_write1_mutex);
}
ldap_pvt_thread_mutex_unlock(&c->c_write1_mutex);
}
else
{
ldap_pvt_thread_mutex_unlock(&c->c_write1_mutex);
slapd_clr_write(c->c_sd, 1);
}
}
void connection_closing(Connection* c, const char* why)
{
assert(connections != NULL);
assert(c != NULL);
if (c->c_struct_state != SLAP_C_USED)
return;
assert(c->c_conn_state != SLAP_C_INVALID);
/* c_mutex must be locked by caller */
if (c->c_conn_state != SLAP_C_CLOSING)
{
Debug(LDAP_DEBUG_CONNS,
"connection_closing: readying conn=%lu sd=%d for close\n",
c->c_connid, c->c_sd, 0);
/* update state to closing */
c->c_conn_state = SLAP_C_CLOSING;
c->c_close_reason = why;
/* don't listen on this port anymore */
slapd_clr_read(c->c_sd, 0);
/* abandon active operations */
connection_abandon(c);
/* wake write blocked operations */
connection_wake_writers(c);
}
else if (why == NULL && c->c_close_reason == conn_lost_str)
{
/* Client closed connection after doing Unbind. */
c->c_close_reason = NULL;
}
}
static void connection_close(Connection* c)
{
assert(connections != NULL);
assert(c != NULL);
if (c->c_struct_state != SLAP_C_USED)
return;
assert(c->c_conn_state == SLAP_C_CLOSING);
/* NOTE: c_mutex should be locked by caller */
if (!LDAP_STAILQ_EMPTY(&c->c_ops) || !LDAP_STAILQ_EMPTY(&c->c_pending_ops))
{
Debug(LDAP_DEBUG_CONNS, "connection_close: deferring conn=%lu sd=%d\n",
c->c_connid, c->c_sd, 0);
return;
}
Debug(LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n", c->c_connid,
c->c_sd, 0);
connection_destroy(c);
}
unsigned long connections_nextid(void)
{
unsigned long id;
assert(connections != NULL);
ldap_pvt_thread_mutex_lock(&conn_nextid_mutex);
id = conn_nextid;
ldap_pvt_thread_mutex_unlock(&conn_nextid_mutex);
return id;
}
/*
* Loop through the connections:
*
* for (c = connection_first(&i); c; c = connection_next(c, &i)) ...;
* connection_done(c);
*
* 'i' is the cursor, initialized by connection_first().
* 'c_mutex' is locked in the returned connection. The functions must
* be passed the previous return value so they can unlock it again.
*/
Connection* connection_first(ber_socket_t* index)
{
assert(connections != NULL);
assert(index != NULL);
ldap_pvt_thread_mutex_lock(&connections_mutex);
for (*index = 0; *index < dtblsize; (*index)++)
{
if (connections[*index].c_struct_state != SLAP_C_UNINITIALIZED)
{
break;
}
}
ldap_pvt_thread_mutex_unlock(&connections_mutex);
return connection_next(NULL, index);
}
/* Next connection in loop, see connection_first() */
Connection* connection_next(Connection* c, ber_socket_t* index)
{
assert(connections != NULL);
assert(index != NULL);
assert(*index <= dtblsize);
if (c != NULL)
ldap_pvt_thread_mutex_unlock(&c->c_mutex);
c = NULL;
ldap_pvt_thread_mutex_lock(&connections_mutex);
for (; *index < dtblsize; (*index)++)
{
int c_struct;
if (connections[*index].c_struct_state == SLAP_C_UNINITIALIZED)
{
/* FIXME: accessing c_conn_state without locking c_mutex */
assert(connections[*index].c_conn_state == SLAP_C_INVALID);
continue;
}
if (connections[*index].c_struct_state == SLAP_C_USED)
{
c = &connections[(*index)++];
if (ldap_pvt_thread_mutex_trylock(&c->c_mutex))
{
/* avoid deadlock */
ldap_pvt_thread_mutex_unlock(&connections_mutex);
ldap_pvt_thread_mutex_lock(&c->c_mutex);
ldap_pvt_thread_mutex_lock(&connections_mutex);
if (c->c_struct_state != SLAP_C_USED)
{
ldap_pvt_thread_mutex_unlock(&c->c_mutex);
c = NULL;
continue;
}
}
assert(c->c_conn_state != SLAP_C_INVALID);
break;
}
c_struct = connections[*index].c_struct_state;
if (c_struct == SLAP_C_PENDING)
continue;
assert(c_struct == SLAP_C_UNUSED);
/* FIXME: accessing c_conn_state without locking c_mutex */
assert(connections[*index].c_conn_state == SLAP_C_INVALID);
}
ldap_pvt_thread_mutex_unlock(&connections_mutex);
return c;
}
/* End connection loop, see connection_first() */
void connection_done(Connection* c)
{
assert(connections != NULL);
if (c != NULL)
ldap_pvt_thread_mutex_unlock(&c->c_mutex);
}
/*
* connection_activity - handle the request operation op on connection
* conn. This routine figures out what kind of operation it is and
* calls the appropriate stub to handle it.
*/
#ifdef SLAPD_MONITOR
/* FIXME: returns 0 in case of failure */
#define INCR_OP_INITIATED(index) \
do \
{ \
ldap_pvt_thread_mutex_lock(&op->o_counters->sc_mutex); \
ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated_[(index)], 1); \
ldap_pvt_thread_mutex_unlock(&op->o_counters->sc_mutex); \
} while (0)
#define INCR_OP_COMPLETED(index) \
do \
{ \
ldap_pvt_thread_mutex_lock(&op->o_counters->sc_mutex); \
ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed, 1); \
ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed_[(index)], 1); \
ldap_pvt_thread_mutex_unlock(&op->o_counters->sc_mutex); \
} while (0)
#else /* !SLAPD_MONITOR */
#define INCR_OP_INITIATED(index) \
do \
{ \
} while (0)
#define INCR_OP_COMPLETED(index) \
do \
{ \
ldap_pvt_thread_mutex_lock(&op->o_counters->sc_mutex); \
ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed, 1); \
ldap_pvt_thread_mutex_unlock(&op->o_counters->sc_mutex); \
} while (0)
#endif /* !SLAPD_MONITOR */
/*
* NOTE: keep in sync with enum in slapd.h
*/
static BI_op_func* opfun[] = {do_bind, do_unbind, do_search, do_compare,
do_modify, do_modrdn, do_add, do_delete,
do_abandon, do_extended, NULL};
/* Counters are per-thread, not per-connection.
*/
static void conn_counter_destroy(void* key, void* data)
{
slap_counters_t **prev, *sc;
ldap_pvt_thread_mutex_lock(&slap_counters.sc_mutex);
for (prev = &slap_counters.sc_next, sc = slap_counters.sc_next; sc;
prev = &sc->sc_next, sc = sc->sc_next)
{
if (sc == data)
{
int i;
*prev = sc->sc_next;
/* Copy data to main counter */
ldap_pvt_mp_add(slap_counters.sc_bytes, sc->sc_bytes);
ldap_pvt_mp_add(slap_counters.sc_pdu, sc->sc_pdu);
ldap_pvt_mp_add(slap_counters.sc_entries, sc->sc_entries);
ldap_pvt_mp_add(slap_counters.sc_refs, sc->sc_refs);
ldap_pvt_mp_add(slap_counters.sc_ops_initiated,
sc->sc_ops_initiated);
ldap_pvt_mp_add(slap_counters.sc_ops_completed,
sc->sc_ops_completed);
#ifdef SLAPD_MONITOR
for (i = 0; i < SLAP_OP_LAST; i++)
{
ldap_pvt_mp_add(slap_counters.sc_ops_initiated_[i],
sc->sc_ops_initiated_[i]);
ldap_pvt_mp_add(slap_counters.sc_ops_initiated_[i],
sc->sc_ops_completed_[i]);
}
#endif /* SLAPD_MONITOR */
slap_counters_destroy(sc);
ber_memfree_x(data, NULL);
break;
}
}
ldap_pvt_thread_mutex_unlock(&slap_counters.sc_mutex);
}
static void conn_counter_init(Operation* op, void* ctx)
{
slap_counters_t* sc;
void* vsc = NULL;
if (ldap_pvt_thread_pool_getkey(ctx, (void*)conn_counter_init, &vsc,
NULL) ||
!vsc)
{
vsc = ch_malloc(sizeof(slap_counters_t));
sc = vsc;
slap_counters_init(sc);
ldap_pvt_thread_pool_setkey(ctx, (void*)conn_counter_init, vsc,
conn_counter_destroy, NULL, NULL);
ldap_pvt_thread_mutex_lock(&slap_counters.sc_mutex);
sc->sc_next = slap_counters.sc_next;
slap_counters.sc_next = sc;
ldap_pvt_thread_mutex_unlock(&slap_counters.sc_mutex);
}
op->o_counters = vsc;
}
static void* connection_operation(void* ctx, void* arg_v)
{
int rc = LDAP_OTHER, cancel;
Operation* op = arg_v;
SlapReply rs = {REP_RESULT};
ber_tag_t tag = op->o_tag;
slap_op_t opidx = SLAP_OP_LAST;
Connection* conn = op->o_conn;
void* memctx = NULL;
void* memctx_null = NULL;
ber_len_t memsiz;
conn_counter_init(op, ctx);
ldap_pvt_thread_mutex_lock(&op->o_counters->sc_mutex);
/* FIXME: returns 0 in case of failure */
ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated, 1);
ldap_pvt_thread_mutex_unlock(&op->o_counters->sc_mutex);
op->o_threadctx = ctx;
op->o_tid = ldap_pvt_thread_pool_tid(ctx);
switch (tag)
{
case LDAP_REQ_BIND:
case LDAP_REQ_UNBIND:
case LDAP_REQ_ADD:
case LDAP_REQ_DELETE:
case LDAP_REQ_MODDN:
case LDAP_REQ_MODIFY:
case LDAP_REQ_COMPARE:
case LDAP_REQ_SEARCH:
case LDAP_REQ_ABANDON:
case LDAP_REQ_EXTENDED:
break;
default:
Debug(LDAP_DEBUG_ANY,
"connection_operation: "
"conn %lu unknown LDAP request 0x%lx\n",
conn->c_connid, tag, 0);
op->o_tag = LBER_ERROR;
rs.sr_err = LDAP_PROTOCOL_ERROR;
rs.sr_text = "unknown LDAP request";
send_ldap_disconnect(op, &rs);
rc = SLAPD_DISCONNECT;
goto operations_error;
}
if (conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND)
{
Debug(LDAP_DEBUG_ANY,
"connection_operation: "
"error: SASL bind in progress (tag=%ld).\n",
(long)tag, 0, 0);
send_ldap_error(op, &rs, LDAP_OPERATIONS_ERROR,
"SASL bind in progress");
rc = LDAP_OPERATIONS_ERROR;
goto operations_error;
}
#ifdef LDAP_X_TXN
if ((conn->c_txn == CONN_TXN_SPECIFY) &&
((tag == LDAP_REQ_ADD) || (tag == LDAP_REQ_DELETE) ||
(tag == LDAP_REQ_MODIFY) || (tag == LDAP_REQ_MODRDN)))
{
/* Disable SLAB allocator for all update operations
issued inside of a transaction */
op->o_tmpmemctx = NULL;
op->o_tmpmfuncs = &ch_mfuncs;
}
else
#endif
{
/* We can use Thread-Local storage for most mallocs. We can
* also use TL for ber parsing, but not on Add or Modify.
*/
#if 0
memsiz = ber_len( op->o_ber ) * 64;
if ( SLAP_SLAB_SIZE > memsiz ) memsiz = SLAP_SLAB_SIZE;
#endif
memsiz = SLAP_SLAB_SIZE;
memctx = slap_sl_mem_create(memsiz, SLAP_SLAB_STACK, ctx, 1);
op->o_tmpmemctx = memctx;
op->o_tmpmfuncs = &slap_sl_mfuncs;
if (tag != LDAP_REQ_ADD && tag != LDAP_REQ_MODIFY)
{
/* Note - the ber and its buffer are already allocated from
* regular memory; this only affects subsequent mallocs that
* ber_scanf may invoke.
*/
ber_set_option(op->o_ber, LBER_OPT_BER_MEMCTX, &memctx);
}
}
opidx = slap_req2op(tag);
assert(opidx != SLAP_OP_LAST);
INCR_OP_INITIATED(opidx);
rc = (*(opfun[opidx]))(op, &rs);
operations_error:
if (rc == SLAPD_DISCONNECT)
{
tag = LBER_ERROR;
}
else if (opidx != SLAP_OP_LAST)
{
/* increment completed operations count
* only if operation was initiated
* and rc != SLAPD_DISCONNECT */
INCR_OP_COMPLETED(opidx);
}
ldap_pvt_thread_mutex_lock(&conn->c_mutex);
if (opidx == SLAP_OP_BIND && conn->c_conn_state == SLAP_C_BINDING)
conn->c_conn_state = SLAP_C_ACTIVE;
cancel = op->o_cancel;
if (cancel != SLAP_CANCEL_NONE && cancel != SLAP_CANCEL_DONE)
{
if (cancel == SLAP_CANCEL_REQ)
{
op->o_cancel =
rc == SLAPD_ABANDON ? SLAP_CANCEL_ACK : LDAP_TOO_LATE;
}
do
{
/* Fake a cond_wait with thread_yield, then
* verify the result properly mutex-protected.
*/
ldap_pvt_thread_mutex_unlock(&conn->c_mutex);
do
{
ldap_pvt_thread_yield();
} while ((cancel = op->o_cancel) != SLAP_CANCEL_NONE &&
cancel != SLAP_CANCEL_DONE);
ldap_pvt_thread_mutex_lock(&conn->c_mutex);
} while ((cancel = op->o_cancel) != SLAP_CANCEL_NONE &&
cancel != SLAP_CANCEL_DONE);
}
ber_set_option(op->o_ber, LBER_OPT_BER_MEMCTX, &memctx_null);
LDAP_STAILQ_REMOVE(&conn->c_ops, op, Operation, o_next);
LDAP_STAILQ_NEXT(op, o_next) = NULL;
conn->c_n_ops_executing--;
conn->c_n_ops_completed++;
switch (tag)
{
case LBER_ERROR:
case LDAP_REQ_UNBIND:
/* c_mutex is locked */
connection_closing(
conn, tag == LDAP_REQ_UNBIND ? NULL : "operations error");
break;
}
connection_resched(conn);
ldap_pvt_thread_mutex_unlock(&conn->c_mutex);
slap_op_free(op, ctx);
return NULL;
}
static const Listener dummy_list = {BER_BVC(""), BER_BVC("")};
Connection* connection_client_setup(ber_socket_t s,
ldap_pvt_thread_start_t* func, void* arg)
{
Connection* c;
ber_socket_t sfd = SLAP_SOCKNEW(s);
c = connection_init(sfd, (Listener*)&dummy_list, "", "", CONN_IS_CLIENT, 0,
NULL LDAP_PF_LOCAL_SENDMSG_ARG(NULL));
if (c)
{
c->c_clientfunc = func;
c->c_clientarg = arg;
slapd_add_internal(sfd, 0);
}
return c;
}
void connection_client_enable(Connection* c)
{
slapd_set_read(c->c_sd, 1);
}
void connection_client_stop(Connection* c)
{
Sockbuf* sb;
ber_socket_t s = c->c_sd;
/* get (locked) connection */
c = connection_get(s);
assert(c->c_conn_state == SLAP_C_CLIENT);
c->c_listener = NULL;
c->c_conn_state = SLAP_C_INVALID;
c->c_struct_state = SLAP_C_UNUSED;
c->c_sd = AC_SOCKET_INVALID;
c->c_close_reason = "?"; /* should never be needed */
sb = c->c_sb;
c->c_sb = ber_sockbuf_alloc();
{
ber_len_t max = sockbuf_max_incoming;
ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max);
}
slapd_remove(s, sb, 0, 1, 0);
connection_return(c);
}
static int connection_read(ber_socket_t s, conn_readinfo* cri);
static void* connection_read_thread(void* ctx, void* argv)
{
int rc;
conn_readinfo cri = {NULL, NULL, NULL, NULL, 0};
ber_socket_t s = (long)argv;
/*
* read incoming LDAP requests. If there is more than one,
* the first one is returned with new_op
*/
cri.ctx = ctx;
if ((rc = connection_read(s, &cri)) < 0)
{
Debug(LDAP_DEBUG_CONNS, "connection_read(%d) error\n", s, 0, 0);
return (void*)(long)rc;
}
/* execute a single queued request in the same thread */
if (cri.op && !cri.nullop)
{
rc = (long)connection_operation(ctx, cri.op);
}
else if (cri.func)
{
rc = (long)cri.func(ctx, cri.arg);
}
return (void*)(long)rc;
}
int connection_read_activate(ber_socket_t s)
{
int rc;
/*
* suspend reading on this file descriptor until a connection processing
* thread reads data on it. Otherwise the listener thread will repeatedly
* submit the same event on it to the pool.
*/
rc = slapd_clr_read(s, 0);
if (rc)
return rc;
/* Don't let blocked writers block a pause request */
if (connections[s].c_writewaiter &&
ldap_pvt_thread_pool_pausing(&connection_pool))
connection_wake_writers(&connections[s]);
rc = ldap_pvt_thread_pool_submit(&connection_pool, connection_read_thread,
(void*)(long)s);
if (rc != 0)
{
Debug(LDAP_DEBUG_ANY,
"connection_read_activate(%d): submit failed (%d)\n", s, rc, 0);
}
return rc;
}
static int connection_read(ber_socket_t s, conn_readinfo* cri)
{
int rc = 0;
Connection* c;
assert(connections != NULL);
/* get (locked) connection */
c = connection_get(s);
if (c == NULL)
{
Debug(LDAP_DEBUG_ANY, "connection_read(%ld): no connection!\n", (long)s,
0, 0);
return -1;
}
c->c_n_read++;
if (c->c_conn_state == SLAP_C_CLOSING)
{
Debug(LDAP_DEBUG_CONNS,
"connection_read(%d): closing, ignoring input for id=%lu\n", s,
c->c_connid, 0);
connection_return(c);
return 0;
}
if (c->c_conn_state == SLAP_C_CLIENT)
{
cri->func = c->c_clientfunc;
cri->arg = c->c_clientarg;
/* read should already be cleared */
connection_return(c);
return 0;
}
Debug(LDAP_DEBUG_TRACE,
"connection_read(%d): checking for input on id=%lu\n", s, c->c_connid,
0);
#ifdef HAVE_TLS
if (c->c_is_tls && c->c_needs_tls_accept)
{
rc = ldap_pvt_tls_accept(c->c_sb, slap_tls_ctx);
if (rc < 0)
{
Debug(LDAP_DEBUG_TRACE,
"connection_read(%d): TLS accept failure "
"error=%d id=%lu, closing\n",
s, rc, c->c_connid);
c->c_needs_tls_accept = 0;
/* c_mutex is locked */
connection_closing(c, "TLS negotiation failure");
connection_close(c);
connection_return(c);
return 0;
}
else if (rc == 0)
{
void* ssl;
struct berval authid = BER_BVNULL;
c->c_needs_tls_accept = 0;
/* we need to let SASL know */
ssl = ldap_pvt_tls_sb_ctx(c->c_sb);
c->c_tls_ssf = (slap_ssf_t)ldap_pvt_tls_get_strength(ssl);
if (c->c_tls_ssf > c->c_ssf)
{
c->c_ssf = c->c_tls_ssf;
}
rc = dnX509peerNormalize(ssl, &authid);
if (rc != LDAP_SUCCESS)
{
Debug(LDAP_DEBUG_TRACE,
"connection_read(%d): "
"unable to get TLS client DN, error=%d id=%lu\n",
s, rc, c->c_connid);
}
Statslog(LDAP_DEBUG_STATS,
"conn=%lu fd=%d TLS established tls_ssf=%u ssf=%u\n",
c->c_connid, (int)s, c->c_tls_ssf, c->c_ssf, 0);
slap_sasl_external(c, c->c_tls_ssf, &authid);
if (authid.bv_val)
free(authid.bv_val);
}
else if (rc == 1 &&
ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL))
{ /* need to retry */
slapd_set_write(s, 1);
connection_return(c);
return 0;
}
/* if success and data is ready, fall thru to data input loop */
if (!ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_DATA_READY, NULL))
{
slapd_set_read(s, 1);
connection_return(c);
return 0;
}
}
#endif
#ifdef HAVE_CYRUS_SASL
if (c->c_sasl_layers)
{
/* If previous layer is not removed yet, give up for now */
if (!c->c_sasl_sockctx)
{
slapd_set_read(s, 1);
connection_return(c);
return 0;
}
c->c_sasl_layers = 0;
rc = ldap_pvt_sasl_install(c->c_sb, c->c_sasl_sockctx);
if (rc != LDAP_SUCCESS)
{
Debug(LDAP_DEBUG_TRACE,
"connection_read(%d): SASL install error "
"error=%d id=%lu, closing\n",
s, rc, c->c_connid);
/* c_mutex is locked */
connection_closing(c, "SASL layer install failure");
connection_close(c);
connection_return(c);
return 0;
}
}
#endif
#define CONNECTION_INPUT_LOOP 1
/* #define DATA_READY_LOOP 1 */
do
{
/* How do we do this without getting into a busy loop ? */
rc = connection_input(c, cri);
}
#ifdef DATA_READY_LOOP
while (!rc && ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_DATA_READY, NULL));
#elif defined CONNECTION_INPUT_LOOP
while (!rc);
#else
while (0);
#endif
if (rc < 0)
{
Debug(LDAP_DEBUG_CONNS,
"connection_read(%d): input error=%d id=%lu, closing.\n", s, rc,
c->c_connid);
/* c_mutex is locked */
connection_closing(c, conn_lost_str);
connection_close(c);
connection_return(c);
return 0;
}
if (ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL))
{
slapd_set_write(s, 0);
}
slapd_set_read(s, 1);
connection_return(c);
return 0;
}
static int connection_input(Connection* conn, conn_readinfo* cri)
{
Operation* op;
ber_tag_t tag;
ber_len_t len;
ber_int_t msgid;
BerElement* ber;
int rc;
#ifdef LDAP_CONNECTIONLESS
Sockaddr peeraddr;
char* cdn = NULL;
#endif
char* defer = NULL;
void* ctx;
if (conn->c_currentber == NULL &&
(conn->c_currentber = ber_alloc()) == NULL)
{
Debug(LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0);
return -1;
}
sock_errset(0);
#ifdef LDAP_CONNECTIONLESS
if (conn->c_is_udp)
{
#if defined(LDAP_PF_INET6)
char peername[sizeof(
"IP=[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535")];
char addr[INET6_ADDRSTRLEN];
#else
char peername[sizeof("IP=255.255.255.255:65336")];
char addr[INET_ADDRSTRLEN];
#endif
const char* peeraddr_string = NULL;
len = ber_int_sb_read(conn->c_sb, &peeraddr, sizeof(Sockaddr));
if (len != sizeof(Sockaddr))
return 1;
#if defined(LDAP_PF_INET6)
if (peeraddr.sa_addr.sa_family == AF_INET6)
{
if (IN6_IS_ADDR_V4MAPPED(&peeraddr.sa_in6_addr.sin6_addr))
{
#if defined(HAVE_GETADDRINFO) && defined(HAVE_INET_NTOP)
peeraddr_string =
inet_ntop(AF_INET,
((struct in_addr*)&peeraddr.sa_in6_addr.sin6_addr
.s6_addr[12]),
addr, sizeof(addr));
#else /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
peeraddr_string =
inet_ntoa(*((struct in_addr*)&peeraddr.sa_in6_addr.sin6_addr
.s6_addr[12]));
#endif /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
if (!peeraddr_string)
peeraddr_string = SLAP_STRING_UNKNOWN;
sprintf(peername, "IP=%s:%d", peeraddr_string,
(unsigned)ntohs(peeraddr.sa_in6_addr.sin6_port));
}
else
{
peeraddr_string =
inet_ntop(AF_INET6, &peeraddr.sa_in6_addr.sin6_addr, addr,
sizeof addr);
if (!peeraddr_string)
peeraddr_string = SLAP_STRING_UNKNOWN;
sprintf(peername, "IP=[%s]:%d", peeraddr_string,
(unsigned)ntohs(peeraddr.sa_in6_addr.sin6_port));
}
}
else
#endif
#if defined(HAVE_GETADDRINFO) && defined(HAVE_INET_NTOP)
{
peeraddr_string = inet_ntop(AF_INET, &peeraddr.sa_in_addr.sin_addr,
addr, sizeof(addr));
#else /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
peeraddr_string = inet_ntoa(peeraddr.sa_in_addr.sin_addr);
#endif /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
sprintf(peername, "IP=%s:%d", peeraddr_string,
(unsigned)ntohs(peeraddr.sa_in_addr.sin_port));
}
Statslog(LDAP_DEBUG_STATS,
"conn=%lu UDP request from %s (%s) accepted.\n",
conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0);
}
#endif
tag = ber_get_next(conn->c_sb, &len, conn->c_currentber);
if (tag != LDAP_TAG_MESSAGE)
{
int err = sock_errno();
if (err != EWOULDBLOCK && err != EAGAIN)
{
/* log, close and send error */
Debug(LDAP_DEBUG_TRACE,
"ber_get_next on fd %d failed errno=%d (%s)\n", conn->c_sd,
err, sock_errstr(err));
ber_free(conn->c_currentber, 1);
conn->c_currentber = NULL;
return -2;
}
return 1;
}
ber = conn->c_currentber;
conn->c_currentber = NULL;
if ((tag = ber_get_int(ber, &msgid)) != LDAP_TAG_MSGID)
{
/* log, close and send error */
Debug(LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0, 0);
ber_free(ber, 1);
return -1;
}
if ((tag = ber_peek_tag(ber, &len)) == LBER_ERROR)
{
/* log, close and send error */
Debug(LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0, 0);
ber_free(ber, 1);
return -1;
}
#ifdef LDAP_CONNECTIONLESS
if (conn->c_is_udp)
{
if (tag == LBER_OCTETSTRING)
{
if ((tag = ber_get_stringa(ber, &cdn)) != LBER_ERROR)
tag = ber_peek_tag(ber, &len);
}
if (tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH)
{
Debug(LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0, 0);
ber_free(ber, 1);
return 0;
}
}
#endif
if (tag == LDAP_REQ_BIND)
{
/* immediately abandon all existing operations upon BIND */
connection_abandon(conn);
}
ctx = cri->ctx;
op = slap_op_alloc(ber, msgid, tag, conn->c_n_ops_received++, ctx);
Debug(LDAP_DEBUG_TRACE, "op tag 0x%lx, time %ld\n", tag, (long)op->o_time,
0);
op->o_conn = conn;
/* clear state if the connection is being reused from inactive */
if (conn->c_conn_state == SLAP_C_INACTIVE)
{
memset(&conn->c_pagedresults_state, 0,
sizeof(conn->c_pagedresults_state));
}
op->o_res_ber = NULL;
#ifdef LDAP_CONNECTIONLESS
if (conn->c_is_udp)
{
if (cdn)
{
ber_str2bv(cdn, 0, 1, &op->o_dn);
op->o_protocol = LDAP_VERSION2;
}
op->o_res_ber = ber_alloc_t(LBER_USE_DER);
if (op->o_res_ber == NULL)
return 1;
rc = ber_write(op->o_res_ber, (char*)&peeraddr, sizeof(struct sockaddr),
0);
if (rc != sizeof(struct sockaddr))
{
Debug(LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0);
return 1;
}
if (op->o_protocol == LDAP_VERSION2)
{
rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
if (rc == -1)
{
Debug(LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0);
return rc;
}
}
}
#endif /* LDAP_CONNECTIONLESS */
rc = 0;
/* Don't process requests when the conn is in the middle of a
* Bind, or if it's closing. Also, don't let any single conn
* use up all the available threads, and don't execute if we're
* currently blocked on output. And don't execute if there are
* already pending ops, let them go first. Abandon operations
* get exceptions to some, but not all, cases.
*/
switch (tag)
{
default:
/* Abandon and Unbind are exempt from these checks */
if (conn->c_conn_state == SLAP_C_CLOSING)
{
defer = "closing";
break;
}
else if (conn->c_writewaiter)
{
defer = "awaiting write";
break;
}
else if (conn->c_n_ops_pending)
{
defer = "pending operations";
break;
}
/* FALLTHRU */
case LDAP_REQ_ABANDON:
/* Unbind is exempt from these checks */
if (conn->c_n_ops_executing >= connection_pool_max / 2)
{
defer = "too many executing";
break;
}
else if (conn->c_conn_state == SLAP_C_BINDING)
{
defer = "binding";
break;
}
/* FALLTHRU */
case LDAP_REQ_UNBIND:
break;
}
if (defer)
{
int max = conn->c_dn.bv_len ? slap_conn_max_pending_auth
: slap_conn_max_pending;
Debug(LDAP_DEBUG_ANY,
"connection_input: conn=%lu deferring operation: %s\n",
conn->c_connid, defer, 0);
conn->c_n_ops_pending++;
LDAP_STAILQ_INSERT_TAIL(&conn->c_pending_ops, op, o_next);
rc = (conn->c_n_ops_pending > max) ? -1 : 0;
}
else
{
conn->c_n_ops_executing++;
/*
* The first op will be processed in the same thread context,
* as long as there is only one op total.
* Subsequent ops will be submitted to the pool by
* calling connection_op_activate()
*/
if (cri->op == NULL)
{
/* the first incoming request */
connection_op_queue(op);
cri->op = op;
}
else
{
if (!cri->nullop)
{
cri->nullop = 1;
rc = ldap_pvt_thread_pool_submit(
&connection_pool, connection_operation, (void*)cri->op);
}
connection_op_activate(op);
}
}
#ifdef NO_THREADS
if (conn->c_struct_state != SLAP_C_USED)
{
/* connection must have got closed underneath us */
return 1;
}
#endif
assert(conn->c_struct_state == SLAP_C_USED);
return rc;
}
static int connection_resched(Connection* conn)
{
Operation* op;
if (conn->c_writewaiter)
return 0;
if (conn->c_conn_state == SLAP_C_CLOSING)
{
Debug(LDAP_DEBUG_CONNS,
"connection_resched: "
"attempting closing conn=%lu sd=%d\n",
conn->c_connid, conn->c_sd, 0);
connection_close(conn);
return 0;
}
if (conn->c_conn_state != SLAP_C_ACTIVE)
{
/* other states need different handling */
return 0;
}
while ((op = LDAP_STAILQ_FIRST(&conn->c_pending_ops)) != NULL)
{
if (conn->c_n_ops_executing > connection_pool_max / 2)
break;
LDAP_STAILQ_REMOVE_HEAD(&conn->c_pending_ops, o_next);
LDAP_STAILQ_NEXT(op, o_next) = NULL;
/* pending operations should not be marked for abandonment */
assert(!op->o_abandon);
conn->c_n_ops_pending--;
conn->c_n_ops_executing++;
connection_op_activate(op);
if (conn->c_conn_state == SLAP_C_BINDING)
break;
}
return 0;
}
static void connection_init_log_prefix(Operation* op)
{
if (op->o_connid == (unsigned long)(-1))
{
snprintf(op->o_log_prefix, sizeof(op->o_log_prefix), "conn=-1 op=%lu",
op->o_opid);
}
else
{
snprintf(op->o_log_prefix, sizeof(op->o_log_prefix), "conn=%lu op=%lu",
op->o_connid, op->o_opid);
}
}
static int connection_bind_cleanup_cb(Operation* op, SlapReply* rs)
{
op->o_conn->c_sasl_bindop = NULL;
ch_free(op->o_callback);
op->o_callback = NULL;
return SLAP_CB_CONTINUE;
}
static int connection_bind_cb(Operation* op, SlapReply* rs)
{
ldap_pvt_thread_mutex_lock(&op->o_conn->c_mutex);
op->o_conn->c_sasl_bind_in_progress =
(rs->sr_err == LDAP_SASL_BIND_IN_PROGRESS);
/* Moved here from bind.c due to ITS#4158 */
op->o_conn->c_sasl_bindop = NULL;
if (op->orb_method == LDAP_AUTH_SASL)
{
if (rs->sr_err == LDAP_SUCCESS)
{
ber_dupbv(&op->o_conn->c_dn, &op->orb_edn);
if (!BER_BVISEMPTY(&op->orb_edn))
{
/* edn is always normalized already */
ber_dupbv(&op->o_conn->c_ndn, &op->o_conn->c_dn);
}
op->o_tmpfree(op->orb_edn.bv_val, op->o_tmpmemctx);
BER_BVZERO(&op->orb_edn);
op->o_conn->c_authmech = op->o_conn->c_sasl_bind_mech;
BER_BVZERO(&op->o_conn->c_sasl_bind_mech);
op->o_conn->c_sasl_ssf = op->orb_ssf;
if (op->orb_ssf > op->o_conn->c_ssf)
{
op->o_conn->c_ssf = op->orb_ssf;
}
if (!BER_BVISEMPTY(&op->o_conn->c_dn))
{
ber_len_t max = sockbuf_max_incoming_auth;
ber_sockbuf_ctrl(op->o_conn->c_sb, LBER_SB_OPT_SET_MAX_INCOMING,
&max);
}
/* log authorization identity */
Statslog(LDAP_DEBUG_STATS,
"%s BIND dn=\"%s\" mech=%s sasl_ssf=%d ssf=%d\n",
op->o_log_prefix,
BER_BVISNULL(&op->o_conn->c_dn) ? "<empty>"
: op->o_conn->c_dn.bv_val,
op->o_conn->c_authmech.bv_val, op->orb_ssf,
op->o_conn->c_ssf);
Debug(LDAP_DEBUG_TRACE,
"do_bind: SASL/%s bind: dn=\"%s\" sasl_ssf=%d\n",
op->o_conn->c_authmech.bv_val,
BER_BVISNULL(&op->o_conn->c_dn) ? "<empty>"
: op->o_conn->c_dn.bv_val,
op->orb_ssf);
}
else if (rs->sr_err != LDAP_SASL_BIND_IN_PROGRESS)
{
if (!BER_BVISNULL(&op->o_conn->c_sasl_bind_mech))
{
free(op->o_conn->c_sasl_bind_mech.bv_val);
BER_BVZERO(&op->o_conn->c_sasl_bind_mech);
}
}
}
ldap_pvt_thread_mutex_unlock(&op->o_conn->c_mutex);
ch_free(op->o_callback);
op->o_callback = NULL;
return SLAP_CB_CONTINUE;
}
static void connection_op_queue(Operation* op)
{
ber_tag_t tag = op->o_tag;
if (tag == LDAP_REQ_BIND)
{
slap_callback* sc = ch_calloc(1, sizeof(slap_callback));
sc->sc_response = connection_bind_cb;
sc->sc_cleanup = connection_bind_cleanup_cb;
sc->sc_next = op->o_callback;
op->o_callback = sc;
op->o_conn->c_conn_state = SLAP_C_BINDING;
}
if (!op->o_dn.bv_len)
{
op->o_authz = op->o_conn->c_authz;
if (BER_BVISNULL(&op->o_conn->c_sasl_authz_dn))
{
ber_dupbv(&op->o_dn, &op->o_conn->c_dn);
ber_dupbv(&op->o_ndn, &op->o_conn->c_ndn);
}
else
{
ber_dupbv(&op->o_dn, &op->o_conn->c_sasl_authz_dn);
ber_dupbv(&op->o_ndn, &op->o_conn->c_sasl_authz_dn);
}
}
op->o_authtype = op->o_conn->c_authtype;
ber_dupbv(&op->o_authmech, &op->o_conn->c_authmech);
if (!op->o_protocol)
{
op->o_protocol =
op->o_conn->c_protocol ? op->o_conn->c_protocol : LDAP_VERSION3;
}
if (op->o_conn->c_conn_state == SLAP_C_INACTIVE &&
op->o_protocol > LDAP_VERSION2)
{
op->o_conn->c_conn_state = SLAP_C_ACTIVE;
}
op->o_connid = op->o_conn->c_connid;
connection_init_log_prefix(op);
LDAP_STAILQ_INSERT_TAIL(&op->o_conn->c_ops, op, o_next);
}
static int connection_op_activate(Operation* op)
{
int rc;
connection_op_queue(op);
rc = ldap_pvt_thread_pool_submit(&connection_pool, connection_operation,
(void*)op);
if (rc != 0)
{
Debug(LDAP_DEBUG_ANY,
"connection_op_activate: submit failed (%d) for conn=%lu\n", rc,
op->o_connid, 0);
/* should move op to pending list */
}
return rc;
}
int connection_write(ber_socket_t s)
{
Connection* c;
Operation* op;
assert(connections != NULL);
c = connection_get(s);
if (c == NULL)
{
Debug(LDAP_DEBUG_ANY, "connection_write(%ld): no connection!\n",
(long)s, 0, 0);
return -1;
}
slapd_clr_write(s, 0);
#ifdef HAVE_TLS
if (c->c_is_tls && c->c_needs_tls_accept)
{
connection_return(c);
connection_read_activate(s);
return 0;
}
#endif
c->c_n_write++;
Debug(LDAP_DEBUG_TRACE, "connection_write(%d): waking output for id=%lu\n",
s, c->c_connid, 0);
ldap_pvt_thread_mutex_lock(&c->c_write2_mutex);
ldap_pvt_thread_cond_signal(&c->c_write2_cv);
ldap_pvt_thread_mutex_unlock(&c->c_write2_mutex);
if (ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL))
{
slapd_set_read(s, 1);
}
if (ber_sockbuf_ctrl(c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL))
{
slapd_set_write(s, 1);
}
/* If there are ops pending because of a writewaiter,
* start one up.
*/
while ((op = LDAP_STAILQ_FIRST(&c->c_pending_ops)) != NULL)
{
if (!c->c_writewaiter)
break;
if (c->c_n_ops_executing > connection_pool_max / 2)
break;
LDAP_STAILQ_REMOVE_HEAD(&c->c_pending_ops, o_next);
LDAP_STAILQ_NEXT(op, o_next) = NULL;
/* pending operations should not be marked for abandonment */
assert(!op->o_abandon);
c->c_n_ops_pending--;
c->c_n_ops_executing++;
connection_op_activate(op);
break;
}
connection_return(c);
return 0;
}
#ifdef LDAP_SLAPI
typedef struct conn_fake_extblock
{
void* eb_conn;
void* eb_op;
} conn_fake_extblock;
static void connection_fake_destroy(void* key, void* data)
{
Connection conn = {0};
Operation op = {0};
Opheader ohdr = {0};
conn_fake_extblock* eb = data;
op.o_hdr = &ohdr;
op.o_hdr->oh_extensions = eb->eb_op;
conn.c_extensions = eb->eb_conn;
op.o_conn = &conn;
conn.c_connid = -1;
op.o_connid = -1;
ber_memfree_x(eb, NULL);
slapi_int_free_object_extensions(SLAPI_X_EXT_OPERATION, &op);
slapi_int_free_object_extensions(SLAPI_X_EXT_CONNECTION, &conn);
}
#endif
void connection_fake_init(Connection* conn, OperationBuffer* opbuf, void* ctx)
{
connection_fake_init2(conn, opbuf, ctx, 1);
}
void operation_fake_init(Connection* conn, Operation* op, void* ctx, int newmem)
{
/* set memory context */
op->o_tmpmemctx =
slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx, newmem);
op->o_tmpmfuncs = &slap_sl_mfuncs;
op->o_threadctx = ctx;
op->o_tid = ldap_pvt_thread_pool_tid(ctx);
op->o_counters = &slap_counters;
op->o_conn = conn;
op->o_connid = op->o_conn->c_connid;
connection_init_log_prefix(op);
}
void connection_fake_init2(Connection* conn, OperationBuffer* opbuf, void* ctx,
int newmem)
{
Operation* op = (Operation*)opbuf;
conn->c_connid = -1;
conn->c_conn_idx = -1;
conn->c_send_ldap_result = slap_send_ldap_result;
conn->c_send_search_entry = slap_send_search_entry;
conn->c_send_search_reference = slap_send_search_reference;
conn->c_send_ldap_extended = slap_send_ldap_extended;
conn->c_send_ldap_intermediate = slap_send_ldap_intermediate;
conn->c_listener = (Listener*)&dummy_list;
conn->c_peer_domain = slap_empty_bv;
conn->c_peer_name = slap_empty_bv;
memset(opbuf, 0, sizeof(*opbuf));
op->o_hdr = &opbuf->ob_hdr;
op->o_controls = opbuf->ob_controls;
operation_fake_init(conn, op, ctx, newmem);
#ifdef LDAP_SLAPI
if (slapi_plugins_used)
{
conn_fake_extblock* eb;
void* ebx = NULL;
/* Use thread keys to make sure these eventually get cleaned up */
if (ldap_pvt_thread_pool_getkey(ctx, (void*)connection_fake_init, &ebx,
NULL))
{
eb = ch_malloc(sizeof(*eb));
slapi_int_create_object_extensions(SLAPI_X_EXT_CONNECTION, conn);
slapi_int_create_object_extensions(SLAPI_X_EXT_OPERATION, op);
eb->eb_conn = conn->c_extensions;
eb->eb_op = op->o_hdr->oh_extensions;
ldap_pvt_thread_pool_setkey(ctx, (void*)connection_fake_init, eb,
connection_fake_destroy, NULL, NULL);
}
else
{
eb = ebx;
conn->c_extensions = eb->eb_conn;
op->o_hdr->oh_extensions = eb->eb_op;
}
}
#endif /* LDAP_SLAPI */
slap_op_time(&op->o_time, &op->o_tincr);
}
void connection_assign_nextid(Connection* conn)
{
ldap_pvt_thread_mutex_lock(&conn_nextid_mutex);
conn->c_connid = conn_nextid++;
ldap_pvt_thread_mutex_unlock(&conn_nextid_mutex);
}
|
501133.c | /*
Copyright (C) 1997-2021 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple test of the SDL threading code */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include "SDL.h"
#define NUMTHREADS 10
static SDL_atomic_t time_for_threads_to_die[NUMTHREADS];
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
int SDLCALL
SubThreadFunc(void *data)
{
while (!*(int volatile *) data) {
; /* SDL_Delay(10); *//* do nothing */
}
return 0;
}
int SDLCALL
ThreadFunc(void *data)
{
SDL_Thread *sub_threads[NUMTHREADS];
int flags[NUMTHREADS];
int i;
int tid = (int) (uintptr_t) data;
SDL_Log("Creating Thread %d\n", tid);
for (i = 0; i < NUMTHREADS; i++) {
char name[64];
SDL_snprintf(name, sizeof (name), "Child%d_%d", tid, i);
flags[i] = 0;
sub_threads[i] = SDL_CreateThread(SubThreadFunc, name, &flags[i]);
}
SDL_Log("Thread '%d' waiting for signal\n", tid);
while (SDL_AtomicGet(&time_for_threads_to_die[tid]) != 1) {
; /* do nothing */
}
SDL_Log("Thread '%d' sending signals to subthreads\n", tid);
for (i = 0; i < NUMTHREADS; i++) {
flags[i] = 1;
SDL_WaitThread(sub_threads[i], NULL);
}
SDL_Log("Thread '%d' exiting!\n", tid);
return 0;
}
int
main(int argc, char *argv[])
{
SDL_Thread *threads[NUMTHREADS];
int i;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(0) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
signal(SIGSEGV, SIG_DFL);
for (i = 0; i < NUMTHREADS; i++) {
char name[64];
SDL_snprintf(name, sizeof (name), "Parent%d", i);
SDL_AtomicSet(&time_for_threads_to_die[i], 0);
threads[i] = SDL_CreateThread(ThreadFunc, name, (void*) (uintptr_t) i);
if (threads[i] == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create thread: %s\n", SDL_GetError());
quit(1);
}
}
for (i = 0; i < NUMTHREADS; i++) {
SDL_AtomicSet(&time_for_threads_to_die[i], 1);
}
for (i = 0; i < NUMTHREADS; i++) {
SDL_WaitThread(threads[i], NULL);
}
SDL_Quit();
return (0);
}
|
76143.c | /*
* Copyright © 2009 Corbin Simpson
* Copyright © 2011 Marek Olšák <[email protected]>
* All Rights Reserved.
*
* 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, sub license, 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 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
* NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS, AUTHORS
* AND/OR ITS SUPPLIERS 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.
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*/
/*
* Authors:
* Corbin Simpson <[email protected]>
* Joakim Sindholt <[email protected]>
* Marek Olšák <[email protected]>
*/
#include "radeon_drm_bo.h"
#include "radeon_drm_cs.h"
#include "radeon_drm_public.h"
#include "pipebuffer/pb_bufmgr.h"
#include "util/u_memory.h"
#include <xf86drm.h>
#include <stdio.h>
#ifndef RADEON_INFO_WANT_HYPERZ
#define RADEON_INFO_WANT_HYPERZ 7
#endif
#ifndef RADEON_INFO_WANT_CMASK
#define RADEON_INFO_WANT_CMASK 8
#endif
/* Enable/disable feature access for one command stream.
* If enable == TRUE, return TRUE on success.
* Otherwise, return FALSE.
*
* We basically do the same thing kernel does, because we have to deal
* with multiple contexts (here command streams) backed by one winsys. */
static boolean radeon_set_fd_access(struct radeon_drm_cs *applier,
struct radeon_drm_cs **owner,
pipe_mutex *mutex,
unsigned request, boolean enable)
{
struct drm_radeon_info info = {0};
unsigned value = enable ? 1 : 0;
pipe_mutex_lock(*mutex);
/* Early exit if we are sure the request will fail. */
if (enable) {
if (*owner) {
pipe_mutex_unlock(*mutex);
return FALSE;
}
} else {
if (*owner != applier) {
pipe_mutex_unlock(*mutex);
return FALSE;
}
}
/* Pass through the request to the kernel. */
info.value = (unsigned long)&value;
info.request = request;
if (drmCommandWriteRead(applier->ws->fd, DRM_RADEON_INFO,
&info, sizeof(info)) != 0) {
pipe_mutex_unlock(*mutex);
return FALSE;
}
/* Update the rights in the winsys. */
if (enable) {
if (value) {
*owner = applier;
fprintf(stderr, "radeon: Acquired Hyper-Z.\n");
pipe_mutex_unlock(*mutex);
return TRUE;
}
} else {
*owner = NULL;
fprintf(stderr, "radeon: Released Hyper-Z.\n");
}
pipe_mutex_unlock(*mutex);
return FALSE;
}
/* Helper function to do the ioctls needed for setup and init. */
static void do_ioctls(struct radeon_drm_winsys *winsys)
{
struct drm_radeon_gem_info gem_info = {0};
struct drm_radeon_info info = {0};
int target = 0;
int retval;
drmVersionPtr version;
info.value = (unsigned long)⌖
/* We do things in a specific order here.
*
* DRM version first. We need to be sure we're running on a KMS chipset.
* This is also for some features.
*
* Then, the PCI ID. This is essential and should return usable numbers
* for all Radeons. If this fails, we probably got handed an FD for some
* non-Radeon card.
*
* The GB and Z pipe requests should always succeed, but they might not
* return sensical values for all chipsets, but that's alright because
* the pipe drivers already know that.
*
* The GEM info is actually bogus on the kernel side, as well as our side
* (see radeon_gem_info_ioctl in radeon_gem.c) but that's alright because
* we don't actually use the info for anything yet. */
version = drmGetVersion(winsys->fd);
if (version->version_major != 2 ||
version->version_minor < 3) {
fprintf(stderr, "%s: DRM version is %d.%d.%d but this driver is "
"only compatible with 2.3.x (kernel 2.6.34) and later.\n",
__FUNCTION__,
version->version_major,
version->version_minor,
version->version_patchlevel);
drmFreeVersion(version);
exit(1);
}
winsys->drm_major = version->version_major;
winsys->drm_minor = version->version_minor;
winsys->drm_patchlevel = version->version_patchlevel;
info.request = RADEON_INFO_DEVICE_ID;
retval = drmCommandWriteRead(winsys->fd, DRM_RADEON_INFO, &info, sizeof(info));
if (retval) {
fprintf(stderr, "%s: Failed to get PCI ID, "
"error number %d\n", __FUNCTION__, retval);
exit(1);
}
winsys->pci_id = target;
info.request = RADEON_INFO_NUM_GB_PIPES;
retval = drmCommandWriteRead(winsys->fd, DRM_RADEON_INFO, &info, sizeof(info));
if (retval) {
fprintf(stderr, "%s: Failed to get GB pipe count, "
"error number %d\n", __FUNCTION__, retval);
exit(1);
}
winsys->gb_pipes = target;
info.request = RADEON_INFO_NUM_Z_PIPES;
retval = drmCommandWriteRead(winsys->fd, DRM_RADEON_INFO, &info, sizeof(info));
if (retval) {
fprintf(stderr, "%s: Failed to get Z pipe count, "
"error number %d\n", __FUNCTION__, retval);
exit(1);
}
winsys->z_pipes = target;
retval = drmCommandWriteRead(winsys->fd, DRM_RADEON_GEM_INFO,
&gem_info, sizeof(gem_info));
if (retval) {
fprintf(stderr, "%s: Failed to get MM info, error number %d\n",
__FUNCTION__, retval);
exit(1);
}
winsys->gart_size = gem_info.gart_size;
winsys->vram_size = gem_info.vram_size;
drmFreeVersion(version);
winsys->num_cpus = sysconf(_SC_NPROCESSORS_ONLN);
}
static void radeon_winsys_destroy(struct radeon_winsys *rws)
{
struct radeon_drm_winsys *ws = (struct radeon_drm_winsys*)rws;
pipe_mutex_destroy(ws->hyperz_owner_mutex);
pipe_mutex_destroy(ws->cmask_owner_mutex);
ws->cman->destroy(ws->cman);
ws->kman->destroy(ws->kman);
FREE(rws);
}
static uint32_t radeon_get_value(struct radeon_winsys *rws,
enum radeon_value_id id)
{
struct radeon_drm_winsys *ws = (struct radeon_drm_winsys *)rws;
switch(id) {
case RADEON_VID_PCI_ID:
return ws->pci_id;
case RADEON_VID_R300_GB_PIPES:
return ws->gb_pipes;
case RADEON_VID_R300_Z_PIPES:
return ws->z_pipes;
case RADEON_VID_GART_SIZE:
return ws->gart_size;
case RADEON_VID_VRAM_SIZE:
return ws->vram_size;
case RADEON_VID_DRM_MAJOR:
return ws->drm_major;
case RADEON_VID_DRM_MINOR:
return ws->drm_minor;
case RADEON_VID_DRM_PATCHLEVEL:
return ws->drm_patchlevel;
case RADEON_VID_DRM_2_6_0:
return ws->drm_major*100 + ws->drm_minor >= 206;
case RADEON_VID_DRM_2_8_0:
return ws->drm_major*100 + ws->drm_minor >= 208;
}
return 0;
}
static boolean radeon_cs_request_feature(struct radeon_winsys_cs *rcs,
enum radeon_feature_id fid,
boolean enable)
{
struct radeon_drm_cs *cs = radeon_drm_cs(rcs);
switch (fid) {
case RADEON_FID_HYPERZ_RAM_ACCESS:
if (debug_get_bool_option("RADEON_HYPERZ", FALSE)) {
return radeon_set_fd_access(cs, &cs->ws->hyperz_owner,
&cs->ws->hyperz_owner_mutex,
RADEON_INFO_WANT_HYPERZ, enable);
} else {
return FALSE;
}
case RADEON_FID_CMASK_RAM_ACCESS:
if (debug_get_bool_option("RADEON_CMASK", FALSE)) {
return radeon_set_fd_access(cs, &cs->ws->cmask_owner,
&cs->ws->cmask_owner_mutex,
RADEON_INFO_WANT_CMASK, enable);
} else {
return FALSE;
}
}
return FALSE;
}
struct radeon_winsys *radeon_drm_winsys_create(int fd)
{
struct radeon_drm_winsys *ws = CALLOC_STRUCT(radeon_drm_winsys);
if (!ws) {
return NULL;
}
ws->fd = fd;
do_ioctls(ws);
switch (ws->pci_id) {
#define CHIPSET(pci_id, name, family) case pci_id:
#include "pci_ids/r300_pci_ids.h"
#undef CHIPSET
break;
default:
goto fail;
}
/* Create managers. */
ws->kman = radeon_bomgr_create(ws);
if (!ws->kman)
goto fail;
ws->cman = pb_cache_manager_create(ws->kman, 1000000);
if (!ws->cman)
goto fail;
/* Set functions. */
ws->base.destroy = radeon_winsys_destroy;
ws->base.get_value = radeon_get_value;
ws->base.cs_request_feature = radeon_cs_request_feature;
radeon_bomgr_init_functions(ws);
radeon_drm_cs_init_functions(ws);
pipe_mutex_init(ws->hyperz_owner_mutex);
pipe_mutex_init(ws->cmask_owner_mutex);
return &ws->base;
fail:
if (ws->cman)
ws->cman->destroy(ws->cman);
if (ws->kman)
ws->kman->destroy(ws->kman);
FREE(ws);
return NULL;
}
|
51605.c | /*----------------------------------------------------------------------------
* Name: ulp_man.c
* Purpose: Ultra Low Power Management
* Code and data placed in SRAM3 (see scatter file)
* SRAM3 is active during Ultra Low Power down.
*----------------------------------------------------------------------------*/
#include "RTE_Components.h" // Component selection
#include CMSIS_device_header // Device header
#include "ulp_man.h"
/*----------------------------------------------------------------------------
Support functions
*---------------------------------------------------------------------------*/
static void apSleepUs(uint32_t val_us);
static void apSleep(uint32_t val);
static void apSleepUs(uint32_t val) {
for (uint32_t _i = val; _i > 0; _i--);
}
static void apSleep(uint32_t val) {
apSleepUs(val * 1000UL);
}
/*============================================================================
Ultra Low Power Handling
*============================================================================*/
/*----------------------------------------------------------------------------
Musca Low Power entry function
*----------------------------------------------------------------------------*/
void Musca_ULP_Entry (void)
{
/* MRAM power-off */
#ifndef ULP_NO_MRAM_PWR_OFF
SECURE_SCC->SCC_MRAM_CTRL1 = 0x3fffffffUL; /* MRAM Stop in DirectAccess mode */
SECURE_SCC->SCC_MRAM_CTRL0 |= ( 1UL << 31); /* Activate DirectAccess (DA) mode */
SECURE_SCC->SCC_MRAM_CTRL0 |= (0x0aUL << 8); /* Power gate VDD_18 first */
SECURE_SCC->SCC_MRAM_CTRL0 |= (0x05UL << 8); /* Power gate VDD after 1us */
#endif
/* SRAM power-off */
#ifndef ULP_NO_SRAM_PWR_OFF
SECURE_SCC->SRAM_CTRL = 0xffffffffUL; /* Power down code SRAM cells */
#endif /* We use cells 0..3 to hold code and data during Ultra Low Power down */
/* */
#ifndef ULP_NO_PPU_OFF
CRYPTO_PPU->PWPR = 0x00000000UL; /* Turn off crypto (static) */
RAM0_PPU->PWPR = 0x00000100UL; /* Turn off SRAM0 PPU dynamically */
RAM1_PPU->PWPR = 0x00000100UL; /* Turn off SRAM1 PPU dynamically */
RAM2_PPU->PWPR = 0x00000100UL; /* Turn off SRAM2 PPU dynamically */
// RAM3_PPU->PWPR = 0x00000102UL; /* Turn off SRAM3 PPU dynamically */ /* SRAM3 used as ULP RAM */
#endif
/* */
#ifndef ULP_NO_BBGEN
SECURE_SCC->CLK_CTRL_SEL |= ( 1UL << 4); /* BBGen Switch to Fast clk for CP boot */
SECURE_SCC->SPARE_CTRL0 = 0x000000c7UL; /* BBBGen Voltage VBBP and VBBN */
SECURE_SCC->CLK_CTRL_ENABLE |= ( 1UL << 11); /* Enable BBGen Clock */
apSleep(10UL); /* Wait for CP settle */
SECURE_SCC->CLK_CTRL_SEL &= ~( 1UL << 4); /* Switch back to Slow clock because fast clock will stop */
#endif
/* Switch main clock to clock selected for ULP mode */
#ifndef ULP_NO_CLK_SWITCH_TO_X32K
SECURE_SCC->CLK_CTRL_SEL &= ~(1UL << 0); /* ctrl_sel_pre_mux_clk set to X32K */
SECURE_SCC->CLK_CTRL_SEL |= (1UL << 2); /* ctrl_sel_main_mux_clk set to pre_mux_clk */
while ((SECURE_SCC->CLK_STATUS & (1U << 0)) != (1U << 0)) __NOP();
SECURE_SYSCTRL->SYSCLK_DIV = 0UL; /* FCLKDIV set to div by 1 (optional) */
SECURE_SCC->PLL_CTRL_PLL0_CLK |= ((1UL << 31) | /* Switch off LP_PLL */
(1UL << 30) ); /* Switch off INT_PLL */
#endif
/* turn OFF CPU1 */
#ifndef ULP_NO_CPU1_OFF
SECURE_SYSCTRL->CPUWAIT = 0x00000002U; /* CPU1 Shall wait at Boot stage */
CPU1CORE_PPU->PWPR = 0x00000100U; /* Turn off CPU1 PPU dynamically */
#endif
}
/*----------------------------------------------------------------------------
Musca Low Power exit function
*----------------------------------------------------------------------------*/
void Musca_ULP_Exit (void)
{
#ifndef ULP_NO_CLK_SWITCH_TO_X32K
SECURE_SCC->PLL_CTRL_PLL0_CLK &= ~(1U << 31); /* Power-ON and enable LP_PLL */
while ((SECURE_SCC->CLK_STATUS & (1U << 1)) != (1U << 1)) __NOP();
SECURE_SYSCTRL->SYSCLK_DIV = 3U; /* Div by 4 (set back) */
SECURE_SCC->CLK_CTRL_SEL &= ~(1U << 12); /* ctrl_pll_mux_clk_sel set to LP PLL */
SECURE_SCC->CLK_CTRL_SEL &= ~(1U << 2); /* ctrl_sel_main_mux_clk set to pll0_clk */
while ((SECURE_SCC->CLK_STATUS & (1U << 0)) != (1U << 0)) __NOP();
#endif
#ifndef ULP_NO_BBGEN
SECURE_SCC->SPARE_CTRL0 = 0x00000000UL; /* BBGen Power-OFF */
#endif
#ifndef ULP_NO_PPU_OFF
CPU0CORE_PPU->PWPR = 0x00000108UL; /* Turn ON CORE PPU */
RAM0_PPU->PWPR = 0x00000108UL; /* Turn on SRAM1 PPU dynamically */
RAM1_PPU->PWPR = 0x00000108UL; /* Turn on SRAM2 PPU dynamically */
RAM2_PPU->PWPR = 0x00000108UL; /* Turn on SRAM3 PPU dynamically */
RAM3_PPU->PWPR = 0x00000108UL; /* Turn on SRAM0 PPU dynamically */
SYS_PPU->PWPR = 0x00000108UL; /* Turn on BASE PPU dynamically */
CRYPTO_PPU->PWPR = 0x00000108UL; /* Turn on Crypto PPU dynamically */
#endif
#ifndef ULP_NO_SRAM_PWR_OFF
SECURE_SCC->SRAM_CTRL = 0x00000000UL; /* Code SRAM Cells Power-ON */
#endif
#ifndef ULP_NO_MRAM_PWR_OFF
SECURE_SCC->SCC_MRAM_CTRL0 &= ~(0x5UL << 8); /* Power ON MRAM VDD after VDD Core */
apSleep(5UL); /* Wait for 5us */
SECURE_SCC->SCC_MRAM_CTRL0 &= ~(0xaUL << 8); /* Power gate VDD_18 first 1us after stop mode */
SECURE_SCC->SCC_MRAM_CTRL0 &= ~( 1UL << 31); /* Disabling DA will make the FSM take MRAM through init phase */
#endif
}
|
526675.c | #include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include "test_defs.h"
#include "unittest_suite_lib.h"
int main (int argc, char *argv[])
{
char *xmldir;
if (argc == 2) {
xmldir = argv[1];
} else {
xmldir = NULL;
}
/* Run test suites */
suite_lib(xmldir);
return 0;
}
|
766427.c | /*
************************************************
username : smmehrab
fullname : s.m.mehrabul islam
email : [email protected]
institute : university of dhaka, bangladesh
session : 2017-2018
************************************************
*/
#include<stdio.h>
int main()
{
int t,r,c,ans=0,cs=0;
scanf("%d",&t);
while(t--)
{
ans=0;
scanf("%d %d",&r,&c);
if(r+1<=8 && c+2<=8 ) ans++;
if(r-1>0 && c+2<=8 ) ans++;
if(r+1<=8 && c-2>0 ) ans++;
if(r-1>0 && c-2>0 ) ans++;
if(c+1<=8 && r+2<=8 ) ans++;
if(c-1>0 && r+2<=8 ) ans++;
if(c+1<=8 && r-2>0 ) ans++;
if(c-1>0 && r-2>0 ) ans++;
printf("Case %d: %d\n",++cs, ans);
}
return 0;
}
|
875385.c | #if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) {
return TRUE;
}
#endif // defined(_WIN32) |
741361.c | /*
Copyright (C) 2014 Parrot SA
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Parrot nor the names
of its contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
/**
* @file ARSTREAM_TCPReader_LinuxTb.c
* @brief Testbench for the Drone2-like reader submodule
* @date 07/10/2013
* @author [email protected]
*/
/*
* System Headers
*/
#include <pthread.h>
/*
* ARSDK Headers
*/
#include <libARSAL/ARSAL_Print.h>
#include "../../Common/TCPReader/ARSTREAM_TCPReader.h"
#include "../../Common/Logger/ARSTREAM_Logger.h"
/*
* Macros
*/
#define __TAG__ "TCPREADER_LINUX_TB"
#define REPORT_DELAY_MS (500)
/*
* Types
*/
typedef struct {
int argc;
char **argv;
} ARSTREAM_TCPReader_LinuxTb_Args_t;
/*
* Globals
*/
/*
* Internal functions declarations
*/
/**
* @brief Thread entry point for the testbench
* @param params An ARSTREAM_Sender_LinuxTb_Args_t pointer, casted to void *
* @return the main error code, casted as a void *
*/
void* tbMain (void *params);
/**
* @brief Thread entry point for the report thread
* @param params Unused (put NULL)
* @return Unused ((void *)0)
*/
void *reportMain (void *params);
/*
* Internal functions implementation
*/
void* tbMain (void *params)
{
int retVal = 0;
ARSTREAM_TCPReader_LinuxTb_Args_t *args = (ARSTREAM_TCPReader_LinuxTb_Args_t *)params;
retVal = ARSTREAM_TCPReader_Main (args->argc, args->argv);
return (void *)(intptr_t)retVal;
}
void* reportMain (void *params)
{
/* Avoid unused warnings */
params = params;
ARSTREAM_Logger_t *logger = ARSTREAM_Logger_NewWithDefaultName ();
ARSTREAM_Logger_Log (logger, "Mean time between frames (ms)");
ARSAL_PRINT (ARSAL_PRINT_WARNING, __TAG__, "Mean time between frames (ms)");
while (1)
{
int dt = ARSTREAM_TCPReader_GetMeanTimeBetweenFrames ();
ARSAL_PRINT (ARSAL_PRINT_WARNING, __TAG__, "%4d", dt);
ARSTREAM_Logger_Log (logger, "%4d", dt);
usleep (1000 * REPORT_DELAY_MS);
}
ARSTREAM_Logger_Delete (&logger);
return (void *)0;
}
/*
* Implementation
*/
int main (int argc, char *argv[])
{
pthread_t tbThread;
pthread_t reportThread;
ARSTREAM_TCPReader_LinuxTb_Args_t args = {argc, argv};
int retVal;
pthread_create (&tbThread, NULL, tbMain, &args);
pthread_create (&reportThread, NULL, reportMain, NULL);
pthread_join (reportThread, NULL);
pthread_join (tbThread, (void **)&retVal);
return retVal;
}
|
160359.c | ////////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2021 Tarek Sherif
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
// Uses XLib and EWMH
// - https://tronche.com/gui/x/xlib/
// - https://specifications.freedesktop.org/wm-spec/1.3/index.html
///////////////////////////////////////////////////////////////////
#define SOGL_IMPLEMENTATION_X11
#include "../../../lib/simple-opengl-loader.h"
#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include "../../shared/constants.h"
#include "../../shared/data.h"
#include "../../shared/platform-interface.h"
#include "../../shared/debug.h"
#include "linux-audio.h"
#include "linux-gamepad.h"
#define NET_WM_STATE_REMOVE 0
#define NET_WM_STATE_ADD 1
static Linux_Gamepad gamepad;
typedef GLXContext (*glXCreateContextAttribsARBFUNC)(Display* display, GLXFBConfig framebufferConfig, GLXContext shareContext, Bool direct, const int32_t* contextAttribs);
typedef void (*glXSwapIntervalEXTFUNC)(Display* display, GLXDrawable window, int32_t interval);
int xErrorHandler(Display* display, XErrorEvent* event) {
platform_userMessage("An Xlib error occurred.");
return 0;
}
int64_t nsFromTimeSpec(struct timespec timeSpec) {
return timeSpec.tv_sec * 1000000000ll + timeSpec.tv_nsec;
}
int32_t main(int32_t argc, char const *argv[]) {
int32_t exitStatus = 1;
struct stat assetsStat = { 0 };
int statResult = stat("./assets", &assetsStat);
if (statResult == -1 || !S_ISDIR(assetsStat.st_mode)) {
platform_userMessage("Asset directory not found.\nDid you move the game executable without moving the assets?");
goto EXIT_NO_ALLOCATIONS;
}
XSetErrorHandler(xErrorHandler);
/////////////////////////
// Connect to X server
/////////////////////////
Display* display = XOpenDisplay(NULL);
if (display == NULL) {
DEBUG_LOG("Failed to open X connection.");
platform_userMessage("Failed to create window.");
goto EXIT_ERROR_HANDLER;
}
//////////////////////////////////////////////////////
// Find framebuffer configuration that satisfies
// OpenGL requirements. Have to do this here,
// so we can create window with that configuration.
//////////////////////////////////////////////////////
int32_t fbcCount = 0;
GLXFBConfig *fbcList = glXChooseFBConfig(display, DefaultScreen(display), (int32_t[]) {
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_DOUBLEBUFFER, True,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
None
}, &fbcCount);
if (!fbcList) {
DEBUG_LOG("No framebuffer config found.");
platform_userMessage("Failed to load OpenGL.");
goto EXIT_DISPLAY;
}
// Find fbc with most samples but at most 4
int32_t fbcIndex = 0;
int32_t bestSamples = 0;
int32_t samples = 0;
glXGetFBConfigAttrib(display, fbcList[0], GLX_SAMPLES, &samples);
for (int32_t i = 1; i < fbcCount; ++i) {
glXGetFBConfigAttrib(display, fbcList[i], GLX_SAMPLES, &samples);
if (samples <= SPACE_SHOOTER_MSAA_SAMPLES && samples > bestSamples) {
bestSamples = samples;
fbcIndex = i;
}
}
GLXFBConfig framebufferConfig = fbcList[fbcIndex];
XVisualInfo *visualInfo = glXGetVisualFromFBConfig(display, framebufferConfig);
XFree(fbcList);
if (!visualInfo) {
DEBUG_LOG("No visual info found.");
platform_userMessage("Failed to load OpenGL.");
goto EXIT_DISPLAY;
}
///////////////////
// Create window
///////////////////
// NOTE(Tarek): border pixel is required in case depth doesn't match parent depth.
// See: https://tronche.com/gui/x/xlib/window/attributes/border.html
Window rootWindow = XRootWindow(display, visualInfo->screen);
Colormap colorMap = XCreateColormap(display, rootWindow, visualInfo->visual, AllocNone);
Window window = XCreateWindow(
display,
rootWindow,
20, 20,
SPACE_SHOOTER_DEFAULT_WINDOWED_WIDTH, SPACE_SHOOTER_DEFAULT_WINDOWED_HEIGHT,
0,
visualInfo->depth,
InputOutput,
visualInfo->visual,
CWColormap | CWEventMask | CWBorderPixel,
&(XSetWindowAttributes) {
.colormap = colorMap,
.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask,
.border_pixel = 0
}
);
XStoreName(display, window, "space-shooter.c (Linux)");
XFree(visualInfo);
/////////////////
// Hide cursor
/////////////////
char hiddenCursorData = 0;
XColor hiddenCursorColor = { 0 };
Pixmap hiddenCursorPixmap = XCreatePixmapFromBitmapData(display, window, &hiddenCursorData, 1, 1, 1, 0, 1);
Cursor hiddenCursor = XCreatePixmapCursor(display, hiddenCursorPixmap, hiddenCursorPixmap, &hiddenCursorColor, &hiddenCursorColor, 0, 0);
XDefineCursor(display, window, hiddenCursor);
XFreeCursor(display, hiddenCursor);
XFreePixmap(display, hiddenCursorPixmap);
///////////////////////////
// Create OpenGL context
///////////////////////////
glXCreateContextAttribsARBFUNC glXCreateContextAttribsARB = (glXCreateContextAttribsARBFUNC) glXGetProcAddress((const GLubyte *) "glXCreateContextAttribsARB");
glXSwapIntervalEXTFUNC glXSwapIntervalEXT = (glXSwapIntervalEXTFUNC) glXGetProcAddress((const GLubyte *) "glXSwapIntervalEXT");
if (!glXCreateContextAttribsARB) {
DEBUG_LOG("Failed to load GLX extension functions.");
platform_userMessage("Failed to load OpenGL.");
goto EXIT_WINDOW;
}
GLXContext gl = glXCreateContextAttribsARB(display, framebufferConfig, NULL, True, (int32_t []) {
GLX_CONTEXT_MAJOR_VERSION_ARB, SOGL_MAJOR_VERSION,
GLX_CONTEXT_MINOR_VERSION_ARB, SOGL_MINOR_VERSION,
GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
None
});
if (!gl) {
DEBUG_LOG("Unable create OpenGL context.");
platform_userMessage("Failed to load OpenGL.");
goto EXIT_WINDOW;
}
glXMakeCurrent(display, window, gl);
if (glXSwapIntervalEXT) {
glXSwapIntervalEXT(display, window, 1);
}
if (!sogl_loadOpenGL()) {
const char **failures = sogl_getFailures();
while (*failures) {
char debugMessage[256];
snprintf(debugMessage, 256, "SOGL: Failed to load function %s", *failures);
DEBUG_LOG(debugMessage);
failures++;
}
}
/////////////////////////////////
// Set up window manager events
/////////////////////////////////
Atom NET_WM_STATE = XInternAtom(display, "_NET_WM_STATE", False);
Atom NET_WM_STATE_FULLSCREEN = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", False);
Atom WM_DELETE_WINDOW = XInternAtom(display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display, window, &WM_DELETE_WINDOW, 1);
XEvent fullscreenEvent = {
.xclient = {
.type = ClientMessage,
.window = window,
.message_type = NET_WM_STATE,
.format = 32,
.data = {
.l = {
NET_WM_STATE_ADD,
NET_WM_STATE_FULLSCREEN,
0,
1,
0
}
}
}
};
XEvent windowedEvent = {
.xclient = {
.type = ClientMessage,
.window = window,
.message_type = NET_WM_STATE,
.format = 32,
.data = {
.l = {
NET_WM_STATE_REMOVE,
NET_WM_STATE_FULLSCREEN,
0,
1,
0
}
}
}
};
// Start in fullscreen
XSendEvent(display, rootWindow, False, SubstructureNotifyMask | SubstructureRedirectMask, &fullscreenEvent);
////////////////////
// Display window
////////////////////
XMapWindow(display, window);
/////////////////////
// Initialize audio
/////////////////////
if (!linux_initAudio()) {
platform_userMessage("Failed to initialize audio.");
}
/////////////////////
// Start game
/////////////////////
linux_detectGamepad();
if (!game_init()) {
goto EXIT_GAME;
}
struct {
bool left;
bool right;
bool up;
bool down;
} keyboardDirections = { 0 };
struct {
bool toggleFullscreen;
bool quit;
bool lastToggleFullscreen;
bool lastQuit;
} systemInput = { 0 };
XEvent event = { 0 };
XWindowAttributes xWinAtt = { 0 };
struct timespec timeSpec = { 0 };
clock_gettime(CLOCK_MONOTONIC, &timeSpec);
int64_t lastTime = nsFromTimeSpec(timeSpec);
int64_t gamePadPollTime = 0;
bool fullscreen = true;
bool running = true;
while (running) {
while (XCheckTypedWindowEvent(display, window, ClientMessage, &event) == True) {
if (event.xclient.data.l[0] == WM_DELETE_WINDOW) {
running = false;
}
}
while (XCheckTypedWindowEvent(display, window, Expose, &event) == True) {
XGetWindowAttributes(display, window, &xWinAtt);
game_resize(xWinAtt.width, xWinAtt.height);
}
while (XCheckWindowEvent(display, window, KeyPressMask | KeyReleaseMask, &event) == True) {
bool down = event.type == KeyPress;
KeySym key = XLookupKeysym(&event.xkey, 0);
switch (key) {
case XK_Left: keyboardDirections.left = down; break;
case XK_Right: keyboardDirections.right = down; break;
case XK_Down: keyboardDirections.down = down; break;
case XK_Up: keyboardDirections.up = down; break;
case XK_space: gamepad.aButton = down; break;
case XK_Escape: gamepad.backButton = down; break;
case XK_f: gamepad.startButton = down; break;
}
if (keyboardDirections.left) {
gamepad.stickX = -1.0f;
} else if (keyboardDirections.right) {
gamepad.stickX = 1.0f;
} else {
gamepad.stickX = 0.0f;
}
if (keyboardDirections.down) {
gamepad.stickY = -1.0f;
} else if (keyboardDirections.up) {
gamepad.stickY = 1.0f;
} else {
gamepad.stickY = 0.0f;
}
gamepad.keyboard = true;
}
linux_updateGamepad(&gamepad);
systemInput.toggleFullscreen = gamepad.startButton;
if (systemInput.toggleFullscreen && !systemInput.lastToggleFullscreen) {
if (fullscreen) {
XSendEvent(display, rootWindow, False, SubstructureNotifyMask | SubstructureRedirectMask, &windowedEvent);
} else {
XSendEvent(display, rootWindow, False, SubstructureNotifyMask | SubstructureRedirectMask, &fullscreenEvent);
}
fullscreen = !fullscreen;
}
systemInput.lastToggleFullscreen = systemInput.toggleFullscreen;
systemInput.quit = gamepad.backButton;
if (systemInput.quit && !systemInput.lastQuit) {
running = false;
}
systemInput.lastQuit = systemInput.quit;
clock_gettime(CLOCK_MONOTONIC, &timeSpec);
int64_t time = nsFromTimeSpec(timeSpec);
int64_t elapsedTime = time - lastTime;
// Sleep if at least 1ms less than frame min
if (SPACE_SHOOTER_MIN_FRAME_TIME_NS - elapsedTime > 1000000) {
struct timespec sleepTime = {
.tv_nsec = SPACE_SHOOTER_MIN_FRAME_TIME_NS - elapsedTime
};
nanosleep(&sleepTime, NULL);
clock_gettime(CLOCK_MONOTONIC, &timeSpec);
time = nsFromTimeSpec(timeSpec);
elapsedTime = time - lastTime;
}
gamePadPollTime += elapsedTime;
if (gamePadPollTime > SPACE_SHOOTER_GAMEPAD_POLL_TIME_NS) {
linux_detectGamepad();
gamePadPollTime = 0;
}
game_update(elapsedTime / 1000000.0f);
game_draw();
glXSwapBuffers(display, window);
lastTime = time;
};
EXIT_GAME:
linux_closeGamepad();
linux_closeAudio();
game_close(); // NOTE(Tarek): After closeAudio so audio buffers don't get freed while playing.
glXMakeCurrent(display, None, NULL);
glXDestroyContext(display, gl);
EXIT_WINDOW:
XDestroyWindow(display, window);
XFreeColormap(display, colorMap);
EXIT_DISPLAY:
XCloseDisplay(display);
EXIT_ERROR_HANDLER:
XSetErrorHandler(NULL);
EXIT_NO_ALLOCATIONS:
return exitStatus;
}
void platform_getInput(Game_Input* input) {
input->lastShoot = input->shoot;
input->velocity[0] = gamepad.stickX;
input->velocity[1] = gamepad.stickY;
input->shoot = gamepad.aButton;
input->keyboard = gamepad.keyboard;
}
void platform_debugLog(const char* message) {
int32_t length = 0;
while(message[length]) {
++length;
}
write(STDERR_FILENO, message, length);
write(STDERR_FILENO, "\n", 1);
}
void platform_userMessage(const char* message) {
platform_debugLog(message);
}
bool platform_loadFile(const char* fileName, Data_Buffer* buffer, bool nullTerminate) {
int32_t fd = open(fileName, O_RDONLY);
uint8_t* data = 0;
if (fd == -1) {
DEBUG_LOG("platform_loadFile: Failed to open file.");
goto ERROR_NO_RESOURCES;
}
int32_t size = lseek(fd, 0, SEEK_END);
int32_t allocation = size;
if (nullTerminate) {
allocation += 1;
}
if (size == -1) {
DEBUG_LOG("platform_loadFile: Failed to get file size.");
goto ERROR_FILE_OPENED;
}
if (lseek(fd, 0, SEEK_SET) == -1) {
DEBUG_LOG("platform_loadFile: Failed to reset file cursor.");
goto ERROR_FILE_OPENED;
}
data = (uint8_t*) malloc(allocation);
if (!data) {
DEBUG_LOG("platform_loadFile: Failed to allocate data.");
goto ERROR_FILE_OPENED;
}
if (read(fd, data, size) == -1) {
DEBUG_LOG("platform_loadFile: Failed to read data.");
goto ERROR_DATA_ALLOCATED;
}
if (nullTerminate) {
data[allocation - 1] = 0;
}
buffer->data = data;
buffer->size = allocation;
close(fd);
return true;
ERROR_DATA_ALLOCATED:
free(data);
ERROR_FILE_OPENED:
close(fd);
ERROR_NO_RESOURCES:
return false;
}
|
648314.c | /*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) Hans Alblas PE1AYX <[email protected]>
* Copyright (C) 2004, 05 Ralf Baechle DL5RB <[email protected]>
* Copyright (C) 2004, 05 Thomas Osterried DL9SAU <[email protected]>
*/
#include <linux/module.h>
#include <linux/bitops.h>
#include <asm/uaccess.h>
#include <linux/crc16.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/major.h>
#include <linux/init.h>
#include <linux/rtnetlink.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>
#include <linux/jiffies.h>
#include <linux/compat.h>
#include <net/ax25.h>
#define AX_MTU 236
/* SLIP/KISS protocol characters. */
#define END 0300 /* indicates end of frame */
#define ESC 0333 /* indicates byte stuffing */
#define ESC_END 0334 /* ESC ESC_END means END 'data' */
#define ESC_ESC 0335 /* ESC ESC_ESC means ESC 'data' */
struct mkiss {
struct tty_struct *tty; /* ptr to TTY structure */
struct net_device *dev; /* easy for intr handling */
/* These are pointers to the malloc()ed frame buffers. */
spinlock_t buflock;/* lock for rbuf and xbuf */
unsigned char *rbuff; /* receiver buffer */
int rcount; /* received chars counter */
unsigned char *xbuff; /* transmitter buffer */
unsigned char *xhead; /* pointer to next byte to XMIT */
int xleft; /* bytes left in XMIT queue */
/* Detailed SLIP statistics. */
int mtu; /* Our mtu (to spot changes!) */
int buffsize; /* Max buffers sizes */
unsigned long flags; /* Flag values/ mode etc */
/* long req'd: used by set_bit --RR */
#define AXF_INUSE 0 /* Channel in use */
#define AXF_ESCAPE 1 /* ESC received */
#define AXF_ERROR 2 /* Parity, etc. error */
#define AXF_KEEPTEST 3 /* Keepalive test flag */
#define AXF_OUTWAIT 4 /* is outpacket was flag */
int mode;
int crcmode; /* MW: for FlexNet, SMACK etc. */
int crcauto; /* CRC auto mode */
#define CRC_MODE_NONE 0
#define CRC_MODE_FLEX 1
#define CRC_MODE_SMACK 2
#define CRC_MODE_FLEX_TEST 3
#define CRC_MODE_SMACK_TEST 4
atomic_t refcnt;
struct semaphore dead_sem;
};
/*---------------------------------------------------------------------------*/
static const unsigned short crc_flex_table[] = {
0x0f87, 0x1e0e, 0x2c95, 0x3d1c, 0x49a3, 0x582a, 0x6ab1, 0x7b38,
0x83cf, 0x9246, 0xa0dd, 0xb154, 0xc5eb, 0xd462, 0xe6f9, 0xf770,
0x1f06, 0x0e8f, 0x3c14, 0x2d9d, 0x5922, 0x48ab, 0x7a30, 0x6bb9,
0x934e, 0x82c7, 0xb05c, 0xa1d5, 0xd56a, 0xc4e3, 0xf678, 0xe7f1,
0x2e85, 0x3f0c, 0x0d97, 0x1c1e, 0x68a1, 0x7928, 0x4bb3, 0x5a3a,
0xa2cd, 0xb344, 0x81df, 0x9056, 0xe4e9, 0xf560, 0xc7fb, 0xd672,
0x3e04, 0x2f8d, 0x1d16, 0x0c9f, 0x7820, 0x69a9, 0x5b32, 0x4abb,
0xb24c, 0xa3c5, 0x915e, 0x80d7, 0xf468, 0xe5e1, 0xd77a, 0xc6f3,
0x4d83, 0x5c0a, 0x6e91, 0x7f18, 0x0ba7, 0x1a2e, 0x28b5, 0x393c,
0xc1cb, 0xd042, 0xe2d9, 0xf350, 0x87ef, 0x9666, 0xa4fd, 0xb574,
0x5d02, 0x4c8b, 0x7e10, 0x6f99, 0x1b26, 0x0aaf, 0x3834, 0x29bd,
0xd14a, 0xc0c3, 0xf258, 0xe3d1, 0x976e, 0x86e7, 0xb47c, 0xa5f5,
0x6c81, 0x7d08, 0x4f93, 0x5e1a, 0x2aa5, 0x3b2c, 0x09b7, 0x183e,
0xe0c9, 0xf140, 0xc3db, 0xd252, 0xa6ed, 0xb764, 0x85ff, 0x9476,
0x7c00, 0x6d89, 0x5f12, 0x4e9b, 0x3a24, 0x2bad, 0x1936, 0x08bf,
0xf048, 0xe1c1, 0xd35a, 0xc2d3, 0xb66c, 0xa7e5, 0x957e, 0x84f7,
0x8b8f, 0x9a06, 0xa89d, 0xb914, 0xcdab, 0xdc22, 0xeeb9, 0xff30,
0x07c7, 0x164e, 0x24d5, 0x355c, 0x41e3, 0x506a, 0x62f1, 0x7378,
0x9b0e, 0x8a87, 0xb81c, 0xa995, 0xdd2a, 0xcca3, 0xfe38, 0xefb1,
0x1746, 0x06cf, 0x3454, 0x25dd, 0x5162, 0x40eb, 0x7270, 0x63f9,
0xaa8d, 0xbb04, 0x899f, 0x9816, 0xeca9, 0xfd20, 0xcfbb, 0xde32,
0x26c5, 0x374c, 0x05d7, 0x145e, 0x60e1, 0x7168, 0x43f3, 0x527a,
0xba0c, 0xab85, 0x991e, 0x8897, 0xfc28, 0xeda1, 0xdf3a, 0xceb3,
0x3644, 0x27cd, 0x1556, 0x04df, 0x7060, 0x61e9, 0x5372, 0x42fb,
0xc98b, 0xd802, 0xea99, 0xfb10, 0x8faf, 0x9e26, 0xacbd, 0xbd34,
0x45c3, 0x544a, 0x66d1, 0x7758, 0x03e7, 0x126e, 0x20f5, 0x317c,
0xd90a, 0xc883, 0xfa18, 0xeb91, 0x9f2e, 0x8ea7, 0xbc3c, 0xadb5,
0x5542, 0x44cb, 0x7650, 0x67d9, 0x1366, 0x02ef, 0x3074, 0x21fd,
0xe889, 0xf900, 0xcb9b, 0xda12, 0xaead, 0xbf24, 0x8dbf, 0x9c36,
0x64c1, 0x7548, 0x47d3, 0x565a, 0x22e5, 0x336c, 0x01f7, 0x107e,
0xf808, 0xe981, 0xdb1a, 0xca93, 0xbe2c, 0xafa5, 0x9d3e, 0x8cb7,
0x7440, 0x65c9, 0x5752, 0x46db, 0x3264, 0x23ed, 0x1176, 0x00ff
};
static unsigned short calc_crc_flex(unsigned char *cp, int size)
{
unsigned short crc = 0xffff;
while (size--)
crc = (crc << 8) ^ crc_flex_table[((crc >> 8) ^ *cp++) & 0xff];
return crc;
}
static int check_crc_flex(unsigned char *cp, int size)
{
unsigned short crc = 0xffff;
if (size < 3)
return -1;
while (size--)
crc = (crc << 8) ^ crc_flex_table[((crc >> 8) ^ *cp++) & 0xff];
if ((crc & 0xffff) != 0x7070)
return -1;
return 0;
}
static int check_crc_16(unsigned char *cp, int size)
{
unsigned short crc = 0x0000;
if (size < 3)
return -1;
crc = crc16(0, cp, size);
if (crc != 0x0000)
return -1;
return 0;
}
/*
* Standard encapsulation
*/
static int kiss_esc(unsigned char *s, unsigned char *d, int len)
{
unsigned char *ptr = d;
unsigned char c;
/*
* Send an initial END character to flush out any data that may have
* accumulated in the receiver due to line noise.
*/
*ptr++ = END;
while (len-- > 0) {
switch (c = *s++) {
case END:
*ptr++ = ESC;
*ptr++ = ESC_END;
break;
case ESC:
*ptr++ = ESC;
*ptr++ = ESC_ESC;
break;
default:
*ptr++ = c;
break;
}
}
*ptr++ = END;
return ptr - d;
}
/*
* MW:
* OK its ugly, but tell me a better solution without copying the
* packet to a temporary buffer :-)
*/
static int kiss_esc_crc(unsigned char *s, unsigned char *d, unsigned short crc,
int len)
{
unsigned char *ptr = d;
unsigned char c=0;
*ptr++ = END;
while (len > 0) {
if (len > 2)
c = *s++;
else if (len > 1)
c = crc >> 8;
else if (len > 0)
c = crc & 0xff;
len--;
switch (c) {
case END:
*ptr++ = ESC;
*ptr++ = ESC_END;
break;
case ESC:
*ptr++ = ESC;
*ptr++ = ESC_ESC;
break;
default:
*ptr++ = c;
break;
}
}
*ptr++ = END;
return ptr - d;
}
/* Send one completely decapsulated AX.25 packet to the AX.25 layer. */
static void ax_bump(struct mkiss *ax)
{
struct sk_buff *skb;
int count;
spin_lock_bh(&ax->buflock);
if (ax->rbuff[0] > 0x0f) {
if (ax->rbuff[0] & 0x80) {
if (check_crc_16(ax->rbuff, ax->rcount) < 0) {
ax->dev->stats.rx_errors++;
spin_unlock_bh(&ax->buflock);
return;
}
if (ax->crcmode != CRC_MODE_SMACK && ax->crcauto) {
printk(KERN_INFO
"mkiss: %s: Switching to crc-smack\n",
ax->dev->name);
ax->crcmode = CRC_MODE_SMACK;
}
ax->rcount -= 2;
*ax->rbuff &= ~0x80;
} else if (ax->rbuff[0] & 0x20) {
if (check_crc_flex(ax->rbuff, ax->rcount) < 0) {
ax->dev->stats.rx_errors++;
spin_unlock_bh(&ax->buflock);
return;
}
if (ax->crcmode != CRC_MODE_FLEX && ax->crcauto) {
printk(KERN_INFO
"mkiss: %s: Switching to crc-flexnet\n",
ax->dev->name);
ax->crcmode = CRC_MODE_FLEX;
}
ax->rcount -= 2;
/*
* dl9sau bugfix: the trailling two bytes flexnet crc
* will not be passed to the kernel. thus we have to
* correct the kissparm signature, because it indicates
* a crc but there's none
*/
*ax->rbuff &= ~0x20;
}
}
count = ax->rcount;
if ((skb = dev_alloc_skb(count)) == NULL) {
printk(KERN_ERR "mkiss: %s: memory squeeze, dropping packet.\n",
ax->dev->name);
ax->dev->stats.rx_dropped++;
spin_unlock_bh(&ax->buflock);
return;
}
memcpy(skb_put(skb,count), ax->rbuff, count);
skb->protocol = ax25_type_trans(skb, ax->dev);
netif_rx(skb);
ax->dev->stats.rx_packets++;
ax->dev->stats.rx_bytes += count;
spin_unlock_bh(&ax->buflock);
}
static void kiss_unesc(struct mkiss *ax, unsigned char s)
{
switch (s) {
case END:
/* drop keeptest bit = VSV */
if (test_bit(AXF_KEEPTEST, &ax->flags))
clear_bit(AXF_KEEPTEST, &ax->flags);
if (!test_and_clear_bit(AXF_ERROR, &ax->flags) && (ax->rcount > 2))
ax_bump(ax);
clear_bit(AXF_ESCAPE, &ax->flags);
ax->rcount = 0;
return;
case ESC:
set_bit(AXF_ESCAPE, &ax->flags);
return;
case ESC_ESC:
if (test_and_clear_bit(AXF_ESCAPE, &ax->flags))
s = ESC;
break;
case ESC_END:
if (test_and_clear_bit(AXF_ESCAPE, &ax->flags))
s = END;
break;
}
spin_lock_bh(&ax->buflock);
if (!test_bit(AXF_ERROR, &ax->flags)) {
if (ax->rcount < ax->buffsize) {
ax->rbuff[ax->rcount++] = s;
spin_unlock_bh(&ax->buflock);
return;
}
ax->dev->stats.rx_over_errors++;
set_bit(AXF_ERROR, &ax->flags);
}
spin_unlock_bh(&ax->buflock);
}
static int ax_set_mac_address(struct net_device *dev, void *addr)
{
struct sockaddr_ax25 *sa = addr;
netif_tx_lock_bh(dev);
netif_addr_lock(dev);
memcpy(dev->dev_addr, &sa->sax25_call, AX25_ADDR_LEN);
netif_addr_unlock(dev);
netif_tx_unlock_bh(dev);
return 0;
}
/*---------------------------------------------------------------------------*/
static void ax_changedmtu(struct mkiss *ax)
{
struct net_device *dev = ax->dev;
unsigned char *xbuff, *rbuff, *oxbuff, *orbuff;
int len;
len = dev->mtu * 2;
/*
* allow for arrival of larger UDP packets, even if we say not to
* also fixes a bug in which SunOS sends 512-byte packets even with
* an MSS of 128
*/
if (len < 576 * 2)
len = 576 * 2;
xbuff = kmalloc(len + 4, GFP_ATOMIC);
rbuff = kmalloc(len + 4, GFP_ATOMIC);
if (xbuff == NULL || rbuff == NULL) {
printk(KERN_ERR "mkiss: %s: unable to grow ax25 buffers, "
"MTU change cancelled.\n",
ax->dev->name);
dev->mtu = ax->mtu;
kfree(xbuff);
kfree(rbuff);
return;
}
spin_lock_bh(&ax->buflock);
oxbuff = ax->xbuff;
ax->xbuff = xbuff;
orbuff = ax->rbuff;
ax->rbuff = rbuff;
if (ax->xleft) {
if (ax->xleft <= len) {
memcpy(ax->xbuff, ax->xhead, ax->xleft);
} else {
ax->xleft = 0;
dev->stats.tx_dropped++;
}
}
ax->xhead = ax->xbuff;
if (ax->rcount) {
if (ax->rcount <= len) {
memcpy(ax->rbuff, orbuff, ax->rcount);
} else {
ax->rcount = 0;
dev->stats.rx_over_errors++;
set_bit(AXF_ERROR, &ax->flags);
}
}
ax->mtu = dev->mtu + 73;
ax->buffsize = len;
spin_unlock_bh(&ax->buflock);
kfree(oxbuff);
kfree(orbuff);
}
/* Encapsulate one AX.25 packet and stuff into a TTY queue. */
static void ax_encaps(struct net_device *dev, unsigned char *icp, int len)
{
struct mkiss *ax = netdev_priv(dev);
unsigned char *p;
int actual, count;
if (ax->mtu != ax->dev->mtu + 73) /* Someone has been ifconfigging */
ax_changedmtu(ax);
if (len > ax->mtu) { /* Sigh, shouldn't occur BUT ... */
len = ax->mtu;
printk(KERN_ERR "mkiss: %s: truncating oversized transmit packet!\n", ax->dev->name);
dev->stats.tx_dropped++;
netif_start_queue(dev);
return;
}
p = icp;
spin_lock_bh(&ax->buflock);
if ((*p & 0x0f) != 0) {
/* Configuration Command (kissparms(1).
* Protocol spec says: never append CRC.
* This fixes a very old bug in the linux
* kiss driver. -- dl9sau */
switch (*p & 0xff) {
case 0x85:
/* command from userspace especially for us,
* not for delivery to the tnc */
if (len > 1) {
int cmd = (p[1] & 0xff);
switch(cmd) {
case 3:
ax->crcmode = CRC_MODE_SMACK;
break;
case 2:
ax->crcmode = CRC_MODE_FLEX;
break;
case 1:
ax->crcmode = CRC_MODE_NONE;
break;
case 0:
default:
ax->crcmode = CRC_MODE_SMACK_TEST;
cmd = 0;
}
ax->crcauto = (cmd ? 0 : 1);
printk(KERN_INFO "mkiss: %s: crc mode %s %d\n", ax->dev->name, (len) ? "set to" : "is", cmd);
}
spin_unlock_bh(&ax->buflock);
netif_start_queue(dev);
return;
default:
count = kiss_esc(p, ax->xbuff, len);
}
} else {
unsigned short crc;
switch (ax->crcmode) {
case CRC_MODE_SMACK_TEST:
ax->crcmode = CRC_MODE_FLEX_TEST;
printk(KERN_INFO "mkiss: %s: Trying crc-smack\n", ax->dev->name);
// fall through
case CRC_MODE_SMACK:
*p |= 0x80;
crc = swab16(crc16(0, p, len));
count = kiss_esc_crc(p, ax->xbuff, crc, len+2);
break;
case CRC_MODE_FLEX_TEST:
ax->crcmode = CRC_MODE_NONE;
printk(KERN_INFO "mkiss: %s: Trying crc-flexnet\n", ax->dev->name);
// fall through
case CRC_MODE_FLEX:
*p |= 0x20;
crc = calc_crc_flex(p, len);
count = kiss_esc_crc(p, ax->xbuff, crc, len+2);
break;
default:
count = kiss_esc(p, ax->xbuff, len);
}
}
spin_unlock_bh(&ax->buflock);
set_bit(TTY_DO_WRITE_WAKEUP, &ax->tty->flags);
actual = ax->tty->ops->write(ax->tty, ax->xbuff, count);
dev->stats.tx_packets++;
dev->stats.tx_bytes += actual;
ax->dev->trans_start = jiffies;
ax->xleft = count - actual;
ax->xhead = ax->xbuff + actual;
}
/* Encapsulate an AX.25 packet and kick it into a TTY queue. */
static netdev_tx_t ax_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct mkiss *ax = netdev_priv(dev);
if (skb->protocol == htons(ETH_P_IP))
return ax25_ip_xmit(skb);
if (!netif_running(dev)) {
printk(KERN_ERR "mkiss: %s: xmit call when iface is down\n", dev->name);
return NETDEV_TX_BUSY;
}
if (netif_queue_stopped(dev)) {
/*
* May be we must check transmitter timeout here ?
* 14 Oct 1994 Dmitry Gorodchanin.
*/
if (time_before(jiffies, dev->trans_start + 20 * HZ)) {
/* 20 sec timeout not reached */
return NETDEV_TX_BUSY;
}
printk(KERN_ERR "mkiss: %s: transmit timed out, %s?\n", dev->name,
(tty_chars_in_buffer(ax->tty) || ax->xleft) ?
"bad line quality" : "driver error");
ax->xleft = 0;
clear_bit(TTY_DO_WRITE_WAKEUP, &ax->tty->flags);
netif_start_queue(dev);
}
/* We were not busy, so we are now... :-) */
netif_stop_queue(dev);
ax_encaps(dev, skb->data, skb->len);
kfree_skb(skb);
return NETDEV_TX_OK;
}
static int ax_open_dev(struct net_device *dev)
{
struct mkiss *ax = netdev_priv(dev);
if (ax->tty == NULL)
return -ENODEV;
return 0;
}
/* Open the low-level part of the AX25 channel. Easy! */
static int ax_open(struct net_device *dev)
{
struct mkiss *ax = netdev_priv(dev);
unsigned long len;
if (ax->tty == NULL)
return -ENODEV;
/*
* Allocate the frame buffers:
*
* rbuff Receive buffer.
* xbuff Transmit buffer.
*/
len = dev->mtu * 2;
/*
* allow for arrival of larger UDP packets, even if we say not to
* also fixes a bug in which SunOS sends 512-byte packets even with
* an MSS of 128
*/
if (len < 576 * 2)
len = 576 * 2;
if ((ax->rbuff = kmalloc(len + 4, GFP_KERNEL)) == NULL)
goto norbuff;
if ((ax->xbuff = kmalloc(len + 4, GFP_KERNEL)) == NULL)
goto noxbuff;
ax->mtu = dev->mtu + 73;
ax->buffsize = len;
ax->rcount = 0;
ax->xleft = 0;
ax->flags &= (1 << AXF_INUSE); /* Clear ESCAPE & ERROR flags */
spin_lock_init(&ax->buflock);
return 0;
noxbuff:
kfree(ax->rbuff);
norbuff:
return -ENOMEM;
}
/* Close the low-level part of the AX25 channel. Easy! */
static int ax_close(struct net_device *dev)
{
struct mkiss *ax = netdev_priv(dev);
if (ax->tty)
clear_bit(TTY_DO_WRITE_WAKEUP, &ax->tty->flags);
netif_stop_queue(dev);
return 0;
}
static const struct net_device_ops ax_netdev_ops = {
.ndo_open = ax_open_dev,
.ndo_stop = ax_close,
.ndo_start_xmit = ax_xmit,
.ndo_set_mac_address = ax_set_mac_address,
};
static void ax_setup(struct net_device *dev)
{
/* Finish setting up the DEVICE info. */
dev->mtu = AX_MTU;
dev->hard_header_len = 0;
dev->addr_len = 0;
dev->type = ARPHRD_AX25;
dev->tx_queue_len = 10;
dev->header_ops = &ax25_header_ops;
dev->netdev_ops = &ax_netdev_ops;
memcpy(dev->broadcast, &ax25_bcast, AX25_ADDR_LEN);
memcpy(dev->dev_addr, &ax25_defaddr, AX25_ADDR_LEN);
dev->flags = IFF_BROADCAST | IFF_MULTICAST;
}
/*
* We have a potential race on dereferencing tty->disc_data, because the tty
* layer provides no locking at all - thus one cpu could be running
* sixpack_receive_buf while another calls sixpack_close, which zeroes
* tty->disc_data and frees the memory that sixpack_receive_buf is using. The
* best way to fix this is to use a rwlock in the tty struct, but for now we
* use a single global rwlock for all ttys in ppp line discipline.
*/
static DEFINE_RWLOCK(disc_data_lock);
static struct mkiss *mkiss_get(struct tty_struct *tty)
{
struct mkiss *ax;
read_lock(&disc_data_lock);
ax = tty->disc_data;
if (ax)
atomic_inc(&ax->refcnt);
read_unlock(&disc_data_lock);
return ax;
}
static void mkiss_put(struct mkiss *ax)
{
if (atomic_dec_and_test(&ax->refcnt))
up(&ax->dead_sem);
}
static int crc_force = 0; /* Can be overridden with insmod */
static int mkiss_open(struct tty_struct *tty)
{
struct net_device *dev;
struct mkiss *ax;
int err;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (tty->ops->write == NULL)
return -EOPNOTSUPP;
dev = alloc_netdev(sizeof(struct mkiss), "ax%d", NET_NAME_UNKNOWN,
ax_setup);
if (!dev) {
err = -ENOMEM;
goto out;
}
ax = netdev_priv(dev);
ax->dev = dev;
spin_lock_init(&ax->buflock);
atomic_set(&ax->refcnt, 1);
sema_init(&ax->dead_sem, 0);
ax->tty = tty;
tty->disc_data = ax;
tty->receive_room = 65535;
tty_driver_flush_buffer(tty);
/* Restore default settings */
dev->type = ARPHRD_AX25;
/* Perform the low-level AX25 initialization. */
err = ax_open(ax->dev);
if (err)
goto out_free_netdev;
err = register_netdev(dev);
if (err)
goto out_free_buffers;
/* after register_netdev() - because else printk smashes the kernel */
switch (crc_force) {
case 3:
ax->crcmode = CRC_MODE_SMACK;
printk(KERN_INFO "mkiss: %s: crc mode smack forced.\n",
ax->dev->name);
break;
case 2:
ax->crcmode = CRC_MODE_FLEX;
printk(KERN_INFO "mkiss: %s: crc mode flexnet forced.\n",
ax->dev->name);
break;
case 1:
ax->crcmode = CRC_MODE_NONE;
printk(KERN_INFO "mkiss: %s: crc mode disabled.\n",
ax->dev->name);
break;
case 0:
/* fall through */
default:
crc_force = 0;
printk(KERN_INFO "mkiss: %s: crc mode is auto.\n",
ax->dev->name);
ax->crcmode = CRC_MODE_SMACK_TEST;
}
ax->crcauto = (crc_force ? 0 : 1);
netif_start_queue(dev);
/* Done. We have linked the TTY line to a channel. */
return 0;
out_free_buffers:
kfree(ax->rbuff);
kfree(ax->xbuff);
out_free_netdev:
free_netdev(dev);
out:
return err;
}
static void mkiss_close(struct tty_struct *tty)
{
struct mkiss *ax;
write_lock_bh(&disc_data_lock);
ax = tty->disc_data;
tty->disc_data = NULL;
write_unlock_bh(&disc_data_lock);
if (!ax)
return;
/*
* We have now ensured that nobody can start using ap from now on, but
* we have to wait for all existing users to finish.
*/
if (!atomic_dec_and_test(&ax->refcnt))
down(&ax->dead_sem);
/*
* Halt the transmit queue so that a new transmit cannot scribble
* on our buffers
*/
netif_stop_queue(ax->dev);
/* Free all AX25 frame buffers. */
kfree(ax->rbuff);
kfree(ax->xbuff);
ax->tty = NULL;
unregister_netdev(ax->dev);
}
/* Perform I/O control on an active ax25 channel. */
static int mkiss_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct mkiss *ax = mkiss_get(tty);
struct net_device *dev;
unsigned int tmp, err;
/* First make sure we're connected. */
if (ax == NULL)
return -ENXIO;
dev = ax->dev;
switch (cmd) {
case SIOCGIFNAME:
err = copy_to_user((void __user *) arg, ax->dev->name,
strlen(ax->dev->name) + 1) ? -EFAULT : 0;
break;
case SIOCGIFENCAP:
err = put_user(4, (int __user *) arg);
break;
case SIOCSIFENCAP:
if (get_user(tmp, (int __user *) arg)) {
err = -EFAULT;
break;
}
ax->mode = tmp;
dev->addr_len = AX25_ADDR_LEN;
dev->hard_header_len = AX25_KISS_HEADER_LEN +
AX25_MAX_HEADER_LEN + 3;
dev->type = ARPHRD_AX25;
err = 0;
break;
case SIOCSIFHWADDR: {
char addr[AX25_ADDR_LEN];
if (copy_from_user(&addr,
(void __user *) arg, AX25_ADDR_LEN)) {
err = -EFAULT;
break;
}
netif_tx_lock_bh(dev);
memcpy(dev->dev_addr, addr, AX25_ADDR_LEN);
netif_tx_unlock_bh(dev);
err = 0;
break;
}
default:
err = -ENOIOCTLCMD;
}
mkiss_put(ax);
return err;
}
#ifdef CONFIG_COMPAT
static long mkiss_compat_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCGIFNAME:
case SIOCGIFENCAP:
case SIOCSIFENCAP:
case SIOCSIFHWADDR:
return mkiss_ioctl(tty, file, cmd,
(unsigned long)compat_ptr(arg));
}
return -ENOIOCTLCMD;
}
#endif
/*
* Handle the 'receiver data ready' interrupt.
* This function is called by the 'tty_io' module in the kernel when
* a block of data has been received, which can now be decapsulated
* and sent on to the AX.25 layer for further processing.
*/
static void mkiss_receive_buf(struct tty_struct *tty, const unsigned char *cp,
char *fp, int count)
{
struct mkiss *ax = mkiss_get(tty);
if (!ax)
return;
/*
* Argh! mtu change time! - costs us the packet part received
* at the change
*/
if (ax->mtu != ax->dev->mtu + 73)
ax_changedmtu(ax);
/* Read the characters out of the buffer */
while (count--) {
if (fp != NULL && *fp++) {
if (!test_and_set_bit(AXF_ERROR, &ax->flags))
ax->dev->stats.rx_errors++;
cp++;
continue;
}
kiss_unesc(ax, *cp++);
}
mkiss_put(ax);
tty_unthrottle(tty);
}
/*
* Called by the driver when there's room for more data. If we have
* more packets to send, we send them here.
*/
static void mkiss_write_wakeup(struct tty_struct *tty)
{
struct mkiss *ax = mkiss_get(tty);
int actual;
if (!ax)
return;
if (ax->xleft <= 0) {
/* Now serial buffer is almost free & we can start
* transmission of another packet
*/
clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
netif_wake_queue(ax->dev);
goto out;
}
actual = tty->ops->write(tty, ax->xhead, ax->xleft);
ax->xleft -= actual;
ax->xhead += actual;
out:
mkiss_put(ax);
}
static struct tty_ldisc_ops ax_ldisc = {
.owner = THIS_MODULE,
.magic = TTY_LDISC_MAGIC,
.name = "mkiss",
.open = mkiss_open,
.close = mkiss_close,
.ioctl = mkiss_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = mkiss_compat_ioctl,
#endif
.receive_buf = mkiss_receive_buf,
.write_wakeup = mkiss_write_wakeup
};
static const char banner[] __initconst = KERN_INFO \
"mkiss: AX.25 Multikiss, Hans Albas PE1AYX\n";
static const char msg_regfail[] __initconst = KERN_ERR \
"mkiss: can't register line discipline (err = %d)\n";
static int __init mkiss_init_driver(void)
{
int status;
printk(banner);
status = tty_register_ldisc(N_AX25, &ax_ldisc);
if (status != 0)
printk(msg_regfail, status);
return status;
}
static const char msg_unregfail[] = KERN_ERR \
"mkiss: can't unregister line discipline (err = %d)\n";
static void __exit mkiss_exit_driver(void)
{
int ret;
if ((ret = tty_unregister_ldisc(N_AX25)))
printk(msg_unregfail, ret);
}
MODULE_AUTHOR("Ralf Baechle DL5RB <[email protected]>");
MODULE_DESCRIPTION("KISS driver for AX.25 over TTYs");
module_param(crc_force, int, 0);
MODULE_PARM_DESC(crc_force, "crc [0 = auto | 1 = none | 2 = flexnet | 3 = smack]");
MODULE_LICENSE("GPL");
MODULE_ALIAS_LDISC(N_AX25);
module_init(mkiss_init_driver);
module_exit(mkiss_exit_driver);
|
408146.c |
/* $Id: fpm_sockets.c,v 1.20.2.1 2008/12/13 03:21:18 anight Exp $ */
/* (c) 2007,2008 Andrei Nigmatulin */
#include "fpm_config.h"
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#include <sys/types.h>
#include <sys/stat.h> /* for chmod(2) */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include "zlog.h"
#include "fpm_arrays.h"
#include "fpm_sockets.h"
#include "fpm_worker_pool.h"
#include "fpm_unix.h"
#include "fpm_str.h"
#include "fpm_env.h"
#include "fpm_cleanup.h"
#include "fpm_scoreboard.h"
struct listening_socket_s {
int refcount;
int sock;
int type;
char *key;
};
static struct fpm_array_s sockets_list;
enum { FPM_GET_USE_SOCKET = 1, FPM_STORE_SOCKET = 2, FPM_STORE_USE_SOCKET = 3 };
static void fpm_sockets_cleanup(int which, void *arg) /* {{{ */
{
unsigned i;
char *env_value = 0;
int p = 0;
struct listening_socket_s *ls = sockets_list.data;
for (i = 0; i < sockets_list.used; i++, ls++) {
if (which != FPM_CLEANUP_PARENT_EXEC) {
close(ls->sock);
} else { /* on PARENT EXEC we want socket fds to be inherited through environment variable */
char fd[32];
sprintf(fd, "%d", ls->sock);
env_value = realloc(env_value, p + (p ? 1 : 0) + strlen(ls->key) + 1 + strlen(fd) + 1);
p += sprintf(env_value + p, "%s%s=%s", p ? "," : "", ls->key, fd);
}
if (which == FPM_CLEANUP_PARENT_EXIT_MAIN) {
if (ls->type == FPM_AF_UNIX) {
unlink(ls->key);
}
}
free(ls->key);
}
if (env_value) {
setenv("FPM_SOCKETS", env_value, 1);
free(env_value);
}
fpm_array_free(&sockets_list);
}
/* }}} */
static void *fpm_get_in_addr(struct sockaddr *sa) /* {{{ */
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
/* }}} */
static int fpm_get_in_port(struct sockaddr *sa) /* {{{ */
{
if (sa->sa_family == AF_INET) {
return ntohs(((struct sockaddr_in*)sa)->sin_port);
}
return ntohs(((struct sockaddr_in6*)sa)->sin6_port);
}
/* }}} */
static int fpm_sockets_hash_op(int sock, struct sockaddr *sa, char *key, int type, int op) /* {{{ */
{
if (key == NULL) {
switch (type) {
case FPM_AF_INET : {
key = alloca(INET6_ADDRSTRLEN+10);
inet_ntop(sa->sa_family, fpm_get_in_addr(sa), key, INET6_ADDRSTRLEN);
sprintf(key+strlen(key), ":%d", fpm_get_in_port(sa));
break;
}
case FPM_AF_UNIX : {
struct sockaddr_un *sa_un = (struct sockaddr_un *) sa;
key = alloca(strlen(sa_un->sun_path) + 1);
strcpy(key, sa_un->sun_path);
break;
}
default :
return -1;
}
}
switch (op) {
case FPM_GET_USE_SOCKET :
{
unsigned i;
struct listening_socket_s *ls = sockets_list.data;
for (i = 0; i < sockets_list.used; i++, ls++) {
if (!strcmp(ls->key, key)) {
++ls->refcount;
return ls->sock;
}
}
break;
}
case FPM_STORE_SOCKET : /* inherited socket */
case FPM_STORE_USE_SOCKET : /* just created */
{
struct listening_socket_s *ls;
ls = fpm_array_push(&sockets_list);
if (!ls) {
break;
}
if (op == FPM_STORE_SOCKET) {
ls->refcount = 0;
} else {
ls->refcount = 1;
}
ls->type = type;
ls->sock = sock;
ls->key = strdup(key);
return 0;
}
}
return -1;
}
/* }}} */
static int fpm_sockets_new_listening_socket(struct fpm_worker_pool_s *wp, struct sockaddr *sa, int socklen) /* {{{ */
{
int flags = 1;
int sock;
mode_t saved_umask = 0;
sock = socket(sa->sa_family, SOCK_STREAM, 0);
if (0 > sock) {
zlog(ZLOG_SYSERROR, "failed to create new listening socket: socket()");
return -1;
}
if (0 > setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags))) {
zlog(ZLOG_WARNING, "failed to change socket attribute");
}
if (wp->listen_address_domain == FPM_AF_UNIX) {
if (fpm_socket_unix_test_connect((struct sockaddr_un *)sa, socklen) == 0) {
zlog(ZLOG_ERROR, "An another FPM instance seems to already listen on %s", ((struct sockaddr_un *) sa)->sun_path);
close(sock);
return -1;
}
unlink( ((struct sockaddr_un *) sa)->sun_path);
saved_umask = umask(0777 ^ wp->socket_mode);
}
if (0 > bind(sock, sa, socklen)) {
zlog(ZLOG_SYSERROR, "unable to bind listening socket for address '%s'", wp->config->listen_address);
if (wp->listen_address_domain == FPM_AF_UNIX) {
umask(saved_umask);
}
close(sock);
return -1;
}
if (wp->listen_address_domain == FPM_AF_UNIX) {
char *path = ((struct sockaddr_un *) sa)->sun_path;
umask(saved_umask);
if (0 > fpm_unix_set_socket_premissions(wp, path)) {
close(sock);
return -1;
}
}
if (0 > listen(sock, wp->config->listen_backlog)) {
zlog(ZLOG_SYSERROR, "failed to listen to address '%s'", wp->config->listen_address);
close(sock);
return -1;
}
return sock;
}
/* }}} */
static int fpm_sockets_get_listening_socket(struct fpm_worker_pool_s *wp, struct sockaddr *sa, int socklen) /* {{{ */
{
int sock;
sock = fpm_sockets_hash_op(0, sa, 0, wp->listen_address_domain, FPM_GET_USE_SOCKET);
if (sock >= 0) {
return sock;
}
sock = fpm_sockets_new_listening_socket(wp, sa, socklen);
fpm_sockets_hash_op(sock, sa, 0, wp->listen_address_domain, FPM_STORE_USE_SOCKET);
return sock;
}
/* }}} */
enum fpm_address_domain fpm_sockets_domain_from_address(char *address) /* {{{ */
{
if (strchr(address, ':')) {
return FPM_AF_INET;
}
if (strlen(address) == strspn(address, "0123456789")) {
return FPM_AF_INET;
}
return FPM_AF_UNIX;
}
/* }}} */
static int fpm_socket_af_inet_listening_socket(struct fpm_worker_pool_s *wp) /* {{{ */
{
struct addrinfo hints, *servinfo, *p;
char *dup_address = strdup(wp->config->listen_address);
char *port_str = strrchr(dup_address, ':');
char *addr = NULL;
char tmpbuf[INET6_ADDRSTRLEN];
int addr_len;
int port = 0;
int sock = -1;
int status;
if (port_str) { /* this is host:port pair */
*port_str++ = '\0';
port = atoi(port_str);
addr = dup_address;
} else if (strlen(dup_address) == strspn(dup_address, "0123456789")) { /* this is port */
port = atoi(dup_address);
port_str = dup_address;
/* IPv6 catch-all + IPv4-mapped */
addr = "::";
}
if (port == 0) {
zlog(ZLOG_ERROR, "invalid port value '%s'", port_str);
return -1;
}
/* strip brackets from address for getaddrinfo */
addr_len = strlen(addr);
if (addr[0] == '[' && addr[addr_len - 1] == ']') {
addr[addr_len - 1] = '\0';
addr++;
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(addr, port_str, &hints, &servinfo)) != 0) {
zlog(ZLOG_ERROR, "getaddrinfo: %s\n", gai_strerror(status));
free(dup_address);
return -1;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
inet_ntop(p->ai_family, fpm_get_in_addr(p->ai_addr), tmpbuf, INET6_ADDRSTRLEN);
if (sock < 0) {
if ((sock = fpm_sockets_get_listening_socket(wp, p->ai_addr, p->ai_addrlen)) != -1) {
zlog(ZLOG_DEBUG, "Found address for %s, socket opened on %s", addr, tmpbuf);
}
} else {
zlog(ZLOG_WARNING, "Found multiple addresses for %s, %s ignored", addr, tmpbuf);
}
}
free(dup_address);
freeaddrinfo(servinfo);
return sock;
}
/* }}} */
static int fpm_socket_af_unix_listening_socket(struct fpm_worker_pool_s *wp) /* {{{ */
{
struct sockaddr_un sa_un;
memset(&sa_un, 0, sizeof(sa_un));
strlcpy(sa_un.sun_path, wp->config->listen_address, sizeof(sa_un.sun_path));
sa_un.sun_family = AF_UNIX;
return fpm_sockets_get_listening_socket(wp, (struct sockaddr *) &sa_un, sizeof(struct sockaddr_un));
}
/* }}} */
int fpm_sockets_init_main() /* {{{ */
{
unsigned i, lq_len;
struct fpm_worker_pool_s *wp;
char *inherited = getenv("FPM_SOCKETS");
struct listening_socket_s *ls;
if (0 == fpm_array_init(&sockets_list, sizeof(struct listening_socket_s), 10)) {
return -1;
}
/* import inherited sockets */
while (inherited && *inherited) {
char *comma = strchr(inherited, ',');
int type, fd_no;
char *eq;
if (comma) {
*comma = '\0';
}
eq = strchr(inherited, '=');
if (eq) {
*eq = '\0';
fd_no = atoi(eq + 1);
type = fpm_sockets_domain_from_address(inherited);
zlog(ZLOG_NOTICE, "using inherited socket fd=%d, \"%s\"", fd_no, inherited);
fpm_sockets_hash_op(fd_no, 0, inherited, type, FPM_STORE_SOCKET);
}
if (comma) {
inherited = comma + 1;
} else {
inherited = 0;
}
}
/* create all required sockets */
for (wp = fpm_worker_all_pools; wp; wp = wp->next) {
switch (wp->listen_address_domain) {
case FPM_AF_INET :
wp->listening_socket = fpm_socket_af_inet_listening_socket(wp);
break;
case FPM_AF_UNIX :
if (0 > fpm_unix_resolve_socket_premissions(wp)) {
return -1;
}
wp->listening_socket = fpm_socket_af_unix_listening_socket(wp);
break;
}
if (wp->listening_socket == -1) {
return -1;
}
if (wp->listen_address_domain == FPM_AF_INET && fpm_socket_get_listening_queue(wp->listening_socket, NULL, &lq_len) >= 0) {
fpm_scoreboard_update(-1, -1, -1, (int)lq_len, -1, -1, 0, FPM_SCOREBOARD_ACTION_SET, wp->scoreboard);
}
}
/* close unused sockets that was inherited */
ls = sockets_list.data;
for (i = 0; i < sockets_list.used; ) {
if (ls->refcount == 0) {
close(ls->sock);
if (ls->type == FPM_AF_UNIX) {
unlink(ls->key);
}
free(ls->key);
fpm_array_item_remove(&sockets_list, i);
} else {
++i;
++ls;
}
}
if (0 > fpm_cleanup_add(FPM_CLEANUP_ALL, fpm_sockets_cleanup, 0)) {
return -1;
}
return 0;
}
/* }}} */
#if HAVE_FPM_LQ
#ifdef HAVE_LQ_TCP_INFO
#include <netinet/tcp.h>
int fpm_socket_get_listening_queue(int sock, unsigned *cur_lq, unsigned *max_lq)
{
struct tcp_info info;
socklen_t len = sizeof(info);
if (0 > getsockopt(sock, IPPROTO_TCP, TCP_INFO, &info, &len)) {
zlog(ZLOG_SYSERROR, "failed to retrieve TCP_INFO for socket");
return -1;
}
#if defined(__FreeBSD__) || defined(__NetBSD__)
if (info.__tcpi_sacked == 0) {
return -1;
}
if (cur_lq) {
*cur_lq = info.__tcpi_unacked;
}
if (max_lq) {
*max_lq = info.__tcpi_sacked;
}
#else
/* kernel >= 2.6.24 return non-zero here, that means operation is supported */
if (info.tcpi_sacked == 0) {
return -1;
}
if (cur_lq) {
*cur_lq = info.tcpi_unacked;
}
if (max_lq) {
*max_lq = info.tcpi_sacked;
}
#endif
return 0;
}
#endif
#ifdef HAVE_LQ_SO_LISTENQ
int fpm_socket_get_listening_queue(int sock, unsigned *cur_lq, unsigned *max_lq)
{
int val;
socklen_t len = sizeof(val);
if (cur_lq) {
if (0 > getsockopt(sock, SOL_SOCKET, SO_LISTENQLEN, &val, &len)) {
return -1;
}
*cur_lq = val;
}
if (max_lq) {
if (0 > getsockopt(sock, SOL_SOCKET, SO_LISTENQLIMIT, &val, &len)) {
return -1;
}
*max_lq = val;
}
return 0;
}
#endif
#else
int fpm_socket_get_listening_queue(int sock, unsigned *cur_lq, unsigned *max_lq)
{
return -1;
}
#endif
int fpm_socket_unix_test_connect(struct sockaddr_un *sock, size_t socklen) /* {{{ */
{
int fd;
if (!sock || sock->sun_family != AF_UNIX) {
return -1;
}
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
return -1;
}
if (connect(fd, (struct sockaddr *)sock, socklen) == -1) {
close(fd);
return -1;
}
close(fd);
return 0;
}
/* }}} */
|
181597.c | #include <memory.h>
#include "md5.h"
unsigned char PADDING[]={0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
void MD5Init(MD5_CTX *context)
{
context->count[0] = 0;
context->count[1] = 0;
context->state[0] = 0x67452301;
context->state[1] = 0xEFCDAB89;
context->state[2] = 0x98BADCFE;
context->state[3] = 0x10325476;
}
void MD5Update(MD5_CTX *context,unsigned char *input,unsigned int inputlen)
{
unsigned int i = 0,index = 0,partlen = 0;
index = (context->count[0] >> 3) & 0x3F;
partlen = 64 - index;
context->count[0] += inputlen << 3;
if(context->count[0] < (inputlen << 3))
context->count[1]++;
context->count[1] += inputlen >> 29;
if(inputlen >= partlen)
{
memcpy(&context->buffer[index],input,partlen);
MD5Transform(context->state,context->buffer);
for(i = partlen;i+64 <= inputlen;i+=64)
MD5Transform(context->state,&input[i]);
index = 0;
}
else
{
i = 0;
}
memcpy(&context->buffer[index],&input[i],inputlen-i);
}
void MD5Final(MD5_CTX *context,unsigned char digest[16])
{
unsigned int index = 0,padlen = 0;
unsigned char bits[8];
index = (context->count[0] >> 3) & 0x3F;
padlen = (index < 56)?(56-index):(120-index);
MD5Encode(bits,context->count,8);
MD5Update(context,PADDING,padlen);
MD5Update(context,bits,8);
MD5Encode(digest,context->state,16);
}
void MD5Encode(unsigned char *output,unsigned int *input,unsigned int len)
{
unsigned int i = 0,j = 0;
while(j < len)
{
output[j] = input[i] & 0xFF;
output[j+1] = (input[i] >> 8) & 0xFF;
output[j+2] = (input[i] >> 16) & 0xFF;
output[j+3] = (input[i] >> 24) & 0xFF;
i++;
j+=4;
}
}
void MD5Decode(unsigned int *output,unsigned char *input,unsigned int len)
{
unsigned int i = 0,j = 0;
while(j < len)
{
output[i] = (input[j]) |
(input[j+1] << 8) |
(input[j+2] << 16) |
(input[j+3] << 24);
i++;
j+=4;
}
}
void MD5Transform(unsigned int state[4],unsigned char block[64])
{
unsigned int a = state[0];
unsigned int b = state[1];
unsigned int c = state[2];
unsigned int d = state[3];
unsigned int x[64];
MD5Decode(x,block,64);
FF(a, b, c, d, x[ 0], 7, 0xd76aa478); /* 1 */
FF(d, a, b, c, x[ 1], 12, 0xe8c7b756); /* 2 */
FF(c, d, a, b, x[ 2], 17, 0x242070db); /* 3 */
FF(b, c, d, a, x[ 3], 22, 0xc1bdceee); /* 4 */
FF(a, b, c, d, x[ 4], 7, 0xf57c0faf); /* 5 */
FF(d, a, b, c, x[ 5], 12, 0x4787c62a); /* 6 */
FF(c, d, a, b, x[ 6], 17, 0xa8304613); /* 7 */
FF(b, c, d, a, x[ 7], 22, 0xfd469501); /* 8 */
FF(a, b, c, d, x[ 8], 7, 0x698098d8); /* 9 */
FF(d, a, b, c, x[ 9], 12, 0x8b44f7af); /* 10 */
FF(c, d, a, b, x[10], 17, 0xffff5bb1); /* 11 */
FF(b, c, d, a, x[11], 22, 0x895cd7be); /* 12 */
FF(a, b, c, d, x[12], 7, 0x6b901122); /* 13 */
FF(d, a, b, c, x[13], 12, 0xfd987193); /* 14 */
FF(c, d, a, b, x[14], 17, 0xa679438e); /* 15 */
FF(b, c, d, a, x[15], 22, 0x49b40821); /* 16 */
/* Round 2 */
GG(a, b, c, d, x[ 1], 5, 0xf61e2562); /* 17 */
GG(d, a, b, c, x[ 6], 9, 0xc040b340); /* 18 */
GG(c, d, a, b, x[11], 14, 0x265e5a51); /* 19 */
GG(b, c, d, a, x[ 0], 20, 0xe9b6c7aa); /* 20 */
GG(a, b, c, d, x[ 5], 5, 0xd62f105d); /* 21 */
GG(d, a, b, c, x[10], 9, 0x2441453); /* 22 */
GG(c, d, a, b, x[15], 14, 0xd8a1e681); /* 23 */
GG(b, c, d, a, x[ 4], 20, 0xe7d3fbc8); /* 24 */
GG(a, b, c, d, x[ 9], 5, 0x21e1cde6); /* 25 */
GG(d, a, b, c, x[14], 9, 0xc33707d6); /* 26 */
GG(c, d, a, b, x[ 3], 14, 0xf4d50d87); /* 27 */
GG(b, c, d, a, x[ 8], 20, 0x455a14ed); /* 28 */
GG(a, b, c, d, x[13], 5, 0xa9e3e905); /* 29 */
GG(d, a, b, c, x[ 2], 9, 0xfcefa3f8); /* 30 */
GG(c, d, a, b, x[ 7], 14, 0x676f02d9); /* 31 */
GG(b, c, d, a, x[12], 20, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH(a, b, c, d, x[ 5], 4, 0xfffa3942); /* 33 */
HH(d, a, b, c, x[ 8], 11, 0x8771f681); /* 34 */
HH(c, d, a, b, x[11], 16, 0x6d9d6122); /* 35 */
HH(b, c, d, a, x[14], 23, 0xfde5380c); /* 36 */
HH(a, b, c, d, x[ 1], 4, 0xa4beea44); /* 37 */
HH(d, a, b, c, x[ 4], 11, 0x4bdecfa9); /* 38 */
HH(c, d, a, b, x[ 7], 16, 0xf6bb4b60); /* 39 */
HH(b, c, d, a, x[10], 23, 0xbebfbc70); /* 40 */
HH(a, b, c, d, x[13], 4, 0x289b7ec6); /* 41 */
HH(d, a, b, c, x[ 0], 11, 0xeaa127fa); /* 42 */
HH(c, d, a, b, x[ 3], 16, 0xd4ef3085); /* 43 */
HH(b, c, d, a, x[ 6], 23, 0x4881d05); /* 44 */
HH(a, b, c, d, x[ 9], 4, 0xd9d4d039); /* 45 */
HH(d, a, b, c, x[12], 11, 0xe6db99e5); /* 46 */
HH(c, d, a, b, x[15], 16, 0x1fa27cf8); /* 47 */
HH(b, c, d, a, x[ 2], 23, 0xc4ac5665); /* 48 */
/* Round 4 */
II(a, b, c, d, x[ 0], 6, 0xf4292244); /* 49 */
II(d, a, b, c, x[ 7], 10, 0x432aff97); /* 50 */
II(c, d, a, b, x[14], 15, 0xab9423a7); /* 51 */
II(b, c, d, a, x[ 5], 21, 0xfc93a039); /* 52 */
II(a, b, c, d, x[12], 6, 0x655b59c3); /* 53 */
II(d, a, b, c, x[ 3], 10, 0x8f0ccc92); /* 54 */
II(c, d, a, b, x[10], 15, 0xffeff47d); /* 55 */
II(b, c, d, a, x[ 1], 21, 0x85845dd1); /* 56 */
II(a, b, c, d, x[ 8], 6, 0x6fa87e4f); /* 57 */
II(d, a, b, c, x[15], 10, 0xfe2ce6e0); /* 58 */
II(c, d, a, b, x[ 6], 15, 0xa3014314); /* 59 */
II(b, c, d, a, x[13], 21, 0x4e0811a1); /* 60 */
II(a, b, c, d, x[ 4], 6, 0xf7537e82); /* 61 */
II(d, a, b, c, x[11], 10, 0xbd3af235); /* 62 */
II(c, d, a, b, x[ 2], 15, 0x2ad7d2bb); /* 63 */
II(b, c, d, a, x[ 9], 21, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
|
96405.c | #include "tp7.h"
/*!\author Lilian Naretto <[email protected]>
\date 15 novembre 2019
\file tp7.c
\brief tp7
\version 0.1 premier jet*/
void tri_insertion(int tableau[N]){
int i, j;
int valeur;
for (i = 1; i < N; i++) {
valeur = tableau[i];
for (j = i; j > 0 && tableau[j - 1] > valeur; j--) {
tableau[j]=tableau[j-1];
}
tableau[j] = valeur;
}
}
int* copiersoustableau(int* src, int debut, int fin){
int taille=fin-debut+1;
int* dest=malloc(taille*sizeof(int));
for (int i = 0; i <= fin - debut + 1; ++i)
{
dest[i] = src[debut+i];
}
return dest;
}
void fusion(int* tab1, int taille1, int* tab2,int taille2, int* tabRes){
int taille=taille1+taille2;
int k=0;
int debut1=0;
int debut2=0;
for (int i = 0; i < taille; i++)
{
if (debut2>=taille2)
{
tabRes[k++]=tab1[debut1++];
}
else if (debut1>=taille1)
{
tabRes[k++]=tab2[debut2++];
} else{
if (tab1[debut1]<=tab2[debut2])
{
tabRes[k++]=tab1[debut1++];
}
else
{
tabRes[k++]=tab2[debut2++];
}
}
}
}
void triFusion(int* tab, int taille){
int taille2 = taille / 2;
int taille3 = taille - taille2;
if (taille >= 2)
{
int *tab1=copiersoustableau(tab, 0, taille3-1);
int *tab2=copiersoustableau(tab, taille3, taille-1);
triFusion(tab1, taille3);
triFusion(tab2, taille2);
fusion(tab1, taille3, tab2, taille2, tab);
}
}
void minMaxTableau(int* tab, int taille, int* min,int* max){
*min = tab[0];
*max = tab[0];
for (int i = 1; i < taille; ++i)
{
if (tab[i] > *max)
{
*max = tab[i];
}else if (tab[i] < *min)
{
*min = tab[i];
}
}
}
void histogramme(int* tab, int taille, int* histo, int tailleH, int min){
for (int i = 0; i < taille; ++i)
{
histo[tab[i]-min]++;
}
}
void triDenombrement(int* tab, int taille){
int* min=malloc(1*sizeof(int));
int* max=malloc(1*sizeof(int));
minMaxTableau(tab, taille, min, max);
int tailleH = *max - *min +1;
int histo[tailleH] ;
for (int i = 0; i < tailleH; ++i)
{
histo[i] = 0;
}
histogramme(tab, taille, histo, tailleH, *min);
int l = 0;
for (int i = 0; i < tailleH; ++i)
{
for (int v = 0; v < histo[i]; ++v)
{
tab[l] = i+*min;
l++;
}
}
}
/*! \fn int main(int argc, char** argv)
\param argc nombre d'arguments en entrée
\param argv valeur des arguments en entrée
\brief sert de menu pour choisir les tries voulus*/
int main(int argc, char** argv){
int i,question;
int k[N],b[N];
printf("k[N] = [");
for ( i = 0; i < N; i++)
{
k[i]=rand()%20;
printf("%d,",k[i]);
}
printf("]\n");
printf("b[N] = [");
for ( i = 0; i < N; i++)
{
b[i]=rand()%20;
printf("%d,",b[i]);
}
printf("]\n");
printf("tri insertion = 1\n");
printf("tri fusion = 2\n");
printf("tri dénombrement = 3\n");
printf("choisis le type de tri : ");
scanf("%d",&question);
if (question > 3 || question < 0)
{
printf("mauvais numero\n");
}
else
{
switch (question)
{
case 1:
tri_insertion(k);
printf("k[N] = [");
for ( i = 0; i < N; i++)
{
printf("%d,",k[i]);
}
printf("]\n");
return 0;
break;
case 2:
triFusion(b,N);
printf("b[N] = [");
for ( i = 0; i < N; i++)
{
printf("%d,",b[i]);
}
printf("]\n");
return 0;
break;
case 3:
triDenombrement(b,N);
printf("b[N] = [");
for ( i = 0; i < N; i++)
{
printf("%d,",b[i]);
}
printf("]\n");
return 0;
break;
default:
break;
}
}
} |
786161.c | /* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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.
*/
/**
* Unit test for jerry-ext/args.
*/
#include <string.h>
#include "jerryscript.h"
#include "jerryscript-ext/arg.h"
#include "test-common.h"
static const jerry_char_t test_source[] = TEST_STRING_LITERAL (
"var arg1 = true;"
"var arg2 = 10.5;"
"var arg3 = 'abc';"
"var arg4 = function foo() {};"
"test_validator1(arg1, arg2, arg3, arg4);"
"arg1 = new Boolean(true);"
"arg3 = new String('abc');"
"test_validator1(arg1, arg2, arg3);"
"test_validator1(arg1, arg2, '');"
"arg2 = new Number(10.5);"
"test_validator1(arg1, arg2, arg3);"
"test_validator1(arg1, 10.5, 'abcdef');"
"test_validator3(arg1, arg1);"
"test_validator3(arg1);"
"test_validator3();"
"test_validator3(undefined, undefined);"
"var obj_a = new MyObjectA();"
"var obj_b = new MyObjectB();"
"test_validator2.call(obj_a, 5);"
"test_validator2.call(obj_b, 5);"
"test_validator2.call(obj_a, 1);"
"var obj1 = {prop1:true, prop2:'1.5'};"
"test_validator_prop1(obj1);"
"test_validator_prop2(obj1);"
"test_validator_prop2();"
"var obj2 = {prop1:true};"
"Object.defineProperty(obj2, 'prop2', {"
" get: function() { throw new TypeError('prop2 error') }"
"});"
"test_validator_prop3(obj2);"
"test_validator_int1(-1000, 1000, 128, -1000, 1000, -127,"
" -1000, 4294967297, 65536, -2200000000, 4294967297, -2147483647);"
"test_validator_int2(-1.5, -1.5, -1.5, 1.5, 1.5, 1.5, Infinity, -Infinity, 300.5, 300.5);"
"test_validator_int3(NaN);"
"var arr = [1, 2];"
"test_validator_array1(arr);"
"test_validator_array1();"
"test_validator_array2(arr);"
"test_validator_restore(false, 3.0);"
"test_validator_restore(3.0, false);"
);
static const jerry_object_native_info_t thing_a_info =
{
.free_cb = NULL
};
static const jerry_object_native_info_t thing_b_info =
{
.free_cb = NULL
};
typedef struct
{
int x;
} my_type_a_t;
typedef struct
{
bool x;
} my_type_b_t;
static my_type_a_t my_thing_a;
static my_type_b_t my_thing_b;
static int validator1_count = 0;
static int validator2_count = 0;
static int validator3_count = 0;
static int validator_int_count = 0;
static int validator_prop_count = 0;
static int validator_array_count = 0;
static int validator_restore_count = 0;
/**
* The handler should have following arguments:
* this: Ignore.
* arg1: Bool.
* arg2: Number. It must be strict primitive number.
* arg3: String.
* arg4: function. It is an optional argument.
*
*/
static jerry_value_t
test_validator1_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
bool arg1;
double arg2 = 0.0;
char arg3[5] = "1234";
jerry_value_t arg4 = jerry_create_undefined ();
jerryx_arg_t mapping[] =
{
/* ignore this */
jerryx_arg_ignore (),
/* 1st argument should be boolean */
jerryx_arg_boolean (&arg1, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
/* 2nd argument should be strict number */
jerryx_arg_number (&arg2, JERRYX_ARG_NO_COERCE, JERRYX_ARG_REQUIRED),
/* 3th argument should be string */
jerryx_arg_string (arg3, 5, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
/* 4th argument should be function, and it is optional */
jerryx_arg_function (&arg4, JERRYX_ARG_OPTIONAL)
};
jerry_value_t is_ok = jerryx_arg_transform_this_and_args (this_val,
args_p,
args_cnt,
mapping,
ARRAY_SIZE (mapping));
if (validator1_count == 0)
{
TEST_ASSERT (!jerry_value_is_error (is_ok));
TEST_ASSERT (arg1);
TEST_ASSERT (arg2 == 10.5);
TEST_ASSERT (strcmp (arg3, "abc") == 0);
TEST_ASSERT (jerry_value_is_function (arg4));
}
else if (validator1_count == 1)
{
TEST_ASSERT (!jerry_value_is_error (is_ok));
TEST_ASSERT (arg1);
TEST_ASSERT (arg2 == 10.5);
TEST_ASSERT (strcmp (arg3, "abc") == 0);
TEST_ASSERT (jerry_value_is_undefined (arg4));
}
else if (validator1_count == 2)
{
TEST_ASSERT (!jerry_value_is_error (is_ok));
TEST_ASSERT (arg1);
TEST_ASSERT (arg2 == 10.5);
TEST_ASSERT (strcmp (arg3, "") == 0);
TEST_ASSERT (jerry_value_is_undefined (arg4));
}
else
{
TEST_ASSERT (jerry_value_is_error (is_ok));
}
jerry_release_value (is_ok);
jerry_release_value (arg4);
validator1_count++;
return jerry_create_undefined ();
} /* test_validator1_handler */
/**
* The JS argument should be number, whose value is equal with the extra_info .
*/
static jerry_value_t
my_custom_transform (jerryx_arg_js_iterator_t *js_arg_iter_p, /**< available JS args */
const jerryx_arg_t *c_arg_p) /**< the native arg */
{
jerry_value_t js_arg = jerryx_arg_js_iterator_pop (js_arg_iter_p);
jerry_value_t to_number = jerry_value_to_number (js_arg);
if (jerry_value_is_error (to_number))
{
jerry_release_value (to_number);
return jerry_create_error (JERRY_ERROR_TYPE,
(jerry_char_t *) "It can not be converted to a number.");
}
int expected_num = (int) c_arg_p->extra_info;
int get_num = (int) jerry_get_number_value (to_number);
if (get_num != expected_num)
{
return jerry_create_error (JERRY_ERROR_TYPE,
(jerry_char_t *) "Number value is not expected.");
}
return jerry_create_undefined ();
} /* my_custom_transform */
/**
* The handler should have following arguments:
* this: with native pointer whose type is bind_a_info.
* arg1: should pass the custom tranform function.
*/
static jerry_value_t
test_validator2_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
my_type_a_t *thing_p;
jerryx_arg_t mapping[] =
{
/* this should has native pointer, whose type is thing_a_info */
jerryx_arg_native_pointer ((void **) &thing_p, &thing_a_info, JERRYX_ARG_REQUIRED),
/* custom tranform function */
jerryx_arg_custom (NULL, 5, my_custom_transform)
};
jerry_value_t is_ok = jerryx_arg_transform_this_and_args (this_val,
args_p,
args_cnt,
mapping,
ARRAY_SIZE (mapping));
if (validator2_count == 0)
{
TEST_ASSERT (!jerry_value_is_error (is_ok));
TEST_ASSERT (thing_p == &my_thing_a);
TEST_ASSERT (thing_p->x == 1);
}
else
{
TEST_ASSERT (jerry_value_is_error (is_ok));
}
jerry_release_value (is_ok);
validator2_count++;
return jerry_create_undefined ();
} /* test_validator2_handler */
/**
* The handler should have following arguments:
* arg1: Bool. It is an optional argument.
*
*/
static jerry_value_t
test_validator3_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
bool arg1 = false;
bool arg2 = false;
jerryx_arg_t mapping[] =
{
/* ignore this */
jerryx_arg_ignore (),
/* 1th argument should be boolean, and it is optional */
jerryx_arg_boolean (&arg1, JERRYX_ARG_COERCE, JERRYX_ARG_OPTIONAL),
/* 2nd argument should be boolean, and it is optional */
jerryx_arg_boolean (&arg2, JERRYX_ARG_COERCE, JERRYX_ARG_OPTIONAL),
};
jerry_value_t is_ok = jerryx_arg_transform_this_and_args (this_val,
args_p,
args_cnt,
mapping,
ARRAY_SIZE (mapping));
if (validator3_count == 0)
{
TEST_ASSERT (!jerry_value_is_error (is_ok));
TEST_ASSERT (arg1);
TEST_ASSERT (arg2);
}
else if (validator3_count == 1)
{
TEST_ASSERT (!jerry_value_is_error (is_ok));
TEST_ASSERT (arg1);
/* arg2 must be unchanged */
TEST_ASSERT (!arg2);
}
else if (validator3_count == 2)
{
TEST_ASSERT (!jerry_value_is_error (is_ok));
/* arg1 must be unchanged */
TEST_ASSERT (!arg1);
/* arg2 must be unchanged */
TEST_ASSERT (!arg2);
}
else if (validator3_count == 3)
{
TEST_ASSERT (!jerry_value_is_error (is_ok));
/* arg1 must be unchanged */
TEST_ASSERT (!arg1);
/* arg2 must be unchanged */
TEST_ASSERT (!arg2);
}
jerry_release_value (is_ok);
validator3_count++;
return jerry_create_undefined ();
} /* test_validator3_handler */
/**
* Calling jerryx_arg_transform_object_properties directly.
*/
static jerry_value_t
test_validator_prop1_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
JERRY_UNUSED (this_val);
JERRY_UNUSED (args_cnt);
bool native1 = false;
double native2 = 0;
double native3 = 3;
const char *name_p[] = {"prop1", "prop2", "prop3"};
jerryx_arg_t mapping[] =
{
jerryx_arg_boolean (&native1, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_number (&native2, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_number (&native3, JERRYX_ARG_COERCE, JERRYX_ARG_OPTIONAL)
};
jerry_value_t is_ok = jerryx_arg_transform_object_properties (args_p[0],
(const jerry_char_t **) name_p,
ARRAY_SIZE (name_p),
mapping,
ARRAY_SIZE (mapping));
TEST_ASSERT (!jerry_value_is_error (is_ok));
TEST_ASSERT (native1);
TEST_ASSERT (native2 == 1.5);
TEST_ASSERT (native3 == 3);
validator_prop_count++;
return jerry_create_undefined ();
} /* test_validator_prop1_handler */
/**
* Calling jerryx_arg_transform_object_properties indirectly by
* using jerryx_arg_object_properties.
*/
static jerry_value_t
test_validator_prop2_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
JERRY_UNUSED (this_val);
bool native1 = false;
double native2 = 0;
double native3 = 3;
jerryx_arg_object_props_t prop_info;
const char *name_p[] = { "prop1", "prop2", "prop3" };
jerryx_arg_t prop_mapping[] =
{
jerryx_arg_boolean (&native1, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_number (&native2, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_number (&native3, JERRYX_ARG_COERCE, JERRYX_ARG_OPTIONAL)
};
prop_info.name_p = (const jerry_char_t **) name_p;
prop_info.name_cnt = 3;
prop_info.c_arg_p = prop_mapping;
prop_info.c_arg_cnt = 3;
jerryx_arg_t mapping[] =
{
jerryx_arg_object_properties (&prop_info, JERRYX_ARG_OPTIONAL),
};
jerry_value_t is_ok = jerryx_arg_transform_args (args_p, args_cnt, mapping, ARRAY_SIZE (mapping));
TEST_ASSERT (!jerry_value_is_error (is_ok));
if (validator_prop_count == 1)
{
TEST_ASSERT (native1);
TEST_ASSERT (native2 == 1.5);
TEST_ASSERT (native3 == 3);
}
validator_prop_count++;
return jerry_create_undefined ();
} /* test_validator_prop2_handler */
static jerry_value_t
test_validator_prop3_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
JERRY_UNUSED (this_val);
JERRY_UNUSED (args_cnt);
bool native1 = false;
bool native2 = true;
const char *name_p[] = { "prop1", "prop2" };
jerryx_arg_t mapping[] =
{
jerryx_arg_boolean (&native1, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_boolean (&native2, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
};
jerry_value_t is_ok = jerryx_arg_transform_object_properties (args_p[0],
(const jerry_char_t **) name_p,
ARRAY_SIZE (name_p),
mapping,
ARRAY_SIZE (mapping));
TEST_ASSERT (jerry_value_is_error (is_ok));
TEST_ASSERT (!native1);
TEST_ASSERT (native2);
validator_prop_count++;
jerry_release_value (is_ok);
return jerry_create_undefined ();
} /* test_validator_prop3_handler */
/*
* args_p[0-2] are uint8, args_p[3-5] are int8, args_p[6-8] are uint32, args_p[9-11] are int32.
*/
static jerry_value_t
test_validator_int1_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
JERRY_UNUSED (this_val);
uint8_t num0, num1, num2;
int8_t num3, num4, num5;
uint32_t num6, num7, num8;
int32_t num9, num10, num11;
jerryx_arg_t mapping[] =
{
jerryx_arg_uint8 (&num0, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_uint8 (&num1, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_uint8 (&num2, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num3, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num4, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num5, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_uint32 (&num6, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_uint32 (&num7, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_uint32 (&num8, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int32 (&num9, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int32 (&num10, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int32 (&num11, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED)
};
jerry_value_t is_ok = jerryx_arg_transform_args (args_p,
args_cnt,
mapping,
ARRAY_SIZE (mapping));
TEST_ASSERT (!jerry_value_is_error (is_ok));
TEST_ASSERT (num0 == 0);
TEST_ASSERT (num1 == 255);
TEST_ASSERT (num2 == 128);
TEST_ASSERT (num3 == -128);
TEST_ASSERT (num4 == 127);
TEST_ASSERT (num5 == -127);
TEST_ASSERT (num6 == 0);
TEST_ASSERT (num7 == 4294967295);
TEST_ASSERT (num8 == 65536);
TEST_ASSERT (num9 == -2147483648);
TEST_ASSERT (num10 == 2147483647);
TEST_ASSERT (num11 == -2147483647);
jerry_release_value (is_ok);
validator_int_count++;
return jerry_create_undefined ();
} /* test_validator_int1_handler */
static jerry_value_t
test_validator_int2_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
JERRY_UNUSED (this_val);
int8_t num0, num1, num2, num3, num4, num5, num6, num7, num8, num9;
num8 = 123;
num9 = 123;
jerryx_arg_t mapping[] =
{
jerryx_arg_int8 (&num0, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num1, JERRYX_ARG_FLOOR, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num2, JERRYX_ARG_CEIL, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num3, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num4, JERRYX_ARG_FLOOR, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num5, JERRYX_ARG_CEIL, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num6, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num7, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num8, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_int8 (&num9, JERRYX_ARG_ROUND, JERRYX_ARG_NO_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
};
jerry_value_t is_ok = jerryx_arg_transform_args (args_p,
args_cnt,
mapping,
ARRAY_SIZE (mapping));
TEST_ASSERT (jerry_value_is_error (is_ok));
TEST_ASSERT (num0 == -2);
TEST_ASSERT (num1 == -2);
TEST_ASSERT (num2 == -1);
TEST_ASSERT (num3 == 2);
TEST_ASSERT (num4 == 1);
TEST_ASSERT (num5 == 2);
TEST_ASSERT (num6 == 127);
TEST_ASSERT (num7 == -128);
TEST_ASSERT (num8 == 127);
TEST_ASSERT (num9 == 123);
jerry_release_value (is_ok);
validator_int_count++;
return jerry_create_undefined ();
} /* test_validator_int2_handler */
static jerry_value_t
test_validator_int3_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
JERRY_UNUSED (this_val);
int8_t num0;
jerryx_arg_t mapping[] =
{
jerryx_arg_int8 (&num0, JERRYX_ARG_ROUND, JERRYX_ARG_CLAMP, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
};
jerry_value_t is_ok = jerryx_arg_transform_args (args_p,
args_cnt,
mapping,
ARRAY_SIZE (mapping));
TEST_ASSERT (jerry_value_is_error (is_ok));
jerry_release_value (is_ok);
validator_int_count++;
return jerry_create_undefined ();
} /* test_validator_int3_handler */
static jerry_value_t
test_validator_array1_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
JERRY_UNUSED (this_val);
double native1 = 0;
double native2 = 0;
double native3 = 0;
jerryx_arg_array_items_t arr_info;
jerryx_arg_t item_mapping[] =
{
jerryx_arg_number (&native1, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_number (&native2, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_number (&native3, JERRYX_ARG_COERCE, JERRYX_ARG_OPTIONAL)
};
arr_info.c_arg_p = item_mapping;
arr_info.c_arg_cnt = 3;
jerryx_arg_t mapping[] =
{
jerryx_arg_array (&arr_info, JERRYX_ARG_OPTIONAL),
};
jerry_value_t is_ok = jerryx_arg_transform_args (args_p, args_cnt, mapping, ARRAY_SIZE (mapping));
TEST_ASSERT (!jerry_value_is_error (is_ok));
if (validator_array_count == 0)
{
TEST_ASSERT (native1 == 1);
TEST_ASSERT (native2 == 2);
TEST_ASSERT (native3 == 0);
}
validator_array_count++;
return jerry_create_undefined ();
} /* test_validator_array1_handler */
static jerry_value_t
test_validator_array2_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
JERRY_UNUSED (this_val);
JERRY_UNUSED (args_cnt);
double native1 = 0;
bool native2 = false;
jerryx_arg_t item_mapping[] =
{
jerryx_arg_number (&native1, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
jerryx_arg_boolean (&native2, JERRYX_ARG_NO_COERCE, JERRYX_ARG_REQUIRED)
};
jerry_value_t is_ok = jerryx_arg_transform_array (args_p[0], item_mapping, ARRAY_SIZE (item_mapping));
TEST_ASSERT (jerry_value_is_error (is_ok));
TEST_ASSERT (native1 == 1);
TEST_ASSERT (!native2);
validator_array_count++;
jerry_release_value (is_ok);
return jerry_create_undefined ();
} /* test_validator_array2_handler */
/**
* This validator is designed to test the
* jerryx_arg_js_iterator_restore function. We'll introduce a union
* type to hold a bool or double and a transform function that will
* look for this type. Then, we'll call the handler with two
* parameters, one bool and one double and see if we correctly build
* the union types for each parameter. To check that the code protects
* against backing up too far, when the check for the double fails,
* we'll "restore" the stack three times; this shouldn't break
* anything.
*/
/*
* This enumeration type specifies the kind of thing held in the union.
*/
typedef enum
{
DOUBLE_VALUE,
BOOL_VALUE
} union_type_t;
/*
* This struct holds either a boolean or double in a union and has a
* second field that describes the type held in the union.
*/
typedef struct
{
union_type_t type_of_value;
union
{
double double_field;
bool bool_field;
} value;
} double_or_bool_t;
/**
* This creates a jerryx_arg_t that can be used like any
* of the installed functions, like jerryx_arg_bool().
*/
#define jerryx_arg_double_or_bool_t(value_ptr, coerce_or_not, optional_or_not, last_parameter) \
jerryx_arg_custom (value_ptr, \
(uintptr_t)&((uintptr_t []){(uintptr_t)coerce_or_not, \
(uintptr_t)optional_or_not, \
(uintptr_t)last_parameter}), \
jerry_arg_to_double_or_bool_t)
/*
* This function is the argument validator used in the above macro called
* jerryx_arg_double_or_bool. It calls jerryx_arg_js_iterator_restore()
* more times than it should to ensure that calling that function too
* often doesn't cause an error.
*/
static jerry_value_t
jerry_arg_to_double_or_bool_t (jerryx_arg_js_iterator_t *js_arg_iter_p,
const jerryx_arg_t *c_arg_p)
{
/* c_arg_p has two fields: dest, which is a pointer to the data that
* gets filled in, and extra_info, which contains the flags used to
* control coercion and optional-ness, respectively. For this test,
* we added an extra flag that tells us that we're working on the
* last parameter; when we know it's the last parameter, we'll "restore"
* the stack more times than there are actual stack values to ensure
* that the restore function doesn't produce an error. */
double_or_bool_t *destination = c_arg_p->dest;
uintptr_t *extra_info = (uintptr_t *) (c_arg_p->extra_info);
jerryx_arg_t conversion_function;
jerry_value_t conversion_result;
jerry_value_t restore_result;
bool last_parameter = (extra_info[2] == 1);
validator_restore_count++;
conversion_function = jerryx_arg_number ((double *) (&(destination->value.double_field)),
(jerryx_arg_coerce_t) extra_info[0],
JERRYX_ARG_OPTIONAL);
conversion_result = conversion_function.func (js_arg_iter_p, &conversion_function);
if (!jerry_value_is_error (conversion_result))
{
if (last_parameter)
{
/* The stack is only two parameters high, but we want to ensure that
* excessive calls will not result in aberrant behavior... */
jerryx_arg_js_iterator_restore (js_arg_iter_p);
jerryx_arg_js_iterator_restore (js_arg_iter_p);
jerryx_arg_js_iterator_restore (js_arg_iter_p);
restore_result = jerryx_arg_js_iterator_restore (js_arg_iter_p);
TEST_ASSERT (jerry_value_is_undefined (restore_result));
}
destination->type_of_value = DOUBLE_VALUE;
return conversion_result;
}
jerryx_arg_js_iterator_restore (js_arg_iter_p);
conversion_function = jerryx_arg_boolean ((bool *) (&(destination->value.bool_field)),
(jerryx_arg_coerce_t) extra_info[0],
(jerryx_arg_optional_t) extra_info[1]);
jerry_release_value (conversion_result);
conversion_result = conversion_function.func (js_arg_iter_p, &conversion_function);
if (!jerry_value_is_error (conversion_result))
{
if (last_parameter)
{
/* The stack is only two parameters high, but we want to ensure that
* excessive calls will not result in aberrant behavior... */
jerryx_arg_js_iterator_restore (js_arg_iter_p);
jerryx_arg_js_iterator_restore (js_arg_iter_p);
jerryx_arg_js_iterator_restore (js_arg_iter_p);
restore_result = jerryx_arg_js_iterator_restore (js_arg_iter_p);
TEST_ASSERT (jerry_value_is_undefined (restore_result));
}
destination->type_of_value = BOOL_VALUE;
return conversion_result;
}
/* Fall through indicates that whatever they gave us, it wasn't
* one of the types we were expecting... */
jerry_release_value (conversion_result);
return jerry_create_error (JERRY_ERROR_TYPE,
(const jerry_char_t *) "double_or_bool-type error.");
} /* jerry_arg_to_double_or_bool_t */
/**
* This validator expects two parameters, one a bool and one a double -- the
* order doesn't matter (so we'll call it twice with the orders reversed).
*/
static jerry_value_t
test_validator_restore_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
JERRY_UNUSED (this_val);
double_or_bool_t arg1;
double_or_bool_t arg2;
jerryx_arg_t item_mapping[] =
{
jerryx_arg_double_or_bool_t (&arg1, JERRYX_ARG_NO_COERCE, JERRYX_ARG_REQUIRED, 0),
jerryx_arg_double_or_bool_t (&arg2, JERRYX_ARG_NO_COERCE, JERRYX_ARG_REQUIRED, 1)
};
jerry_value_t is_ok = jerryx_arg_transform_args (args_p, args_cnt, item_mapping, ARRAY_SIZE (item_mapping));
TEST_ASSERT (!jerry_value_is_error (is_ok));
/* We are going to call this with [false, 3.0] and [3.0, false] parameters... */
bool arg1_is_false = (arg1.type_of_value == BOOL_VALUE && arg1.value.bool_field == false);
bool arg1_is_three = (arg1.type_of_value == DOUBLE_VALUE && arg1.value.double_field == 3.0);
bool arg2_is_false = (arg2.type_of_value == BOOL_VALUE && arg2.value.bool_field == false);
bool arg2_is_three = (arg2.type_of_value == DOUBLE_VALUE && arg2.value.double_field == 3.0);
TEST_ASSERT ((arg1_is_false && arg2_is_three) || (arg1_is_three && arg2_is_false));
jerry_release_value (is_ok);
return jerry_create_undefined ();
} /* test_validator_restore_handler */
static void
test_utf8_string (void)
{
/* test string: 'str: {DESERET CAPITAL LETTER LONG I}' */
jerry_value_t str = jerry_create_string ((jerry_char_t *) "\x73\x74\x72\x3a \xed\xa0\x81\xed\xb0\x80");
char expect_utf8_buf[] = "\x73\x74\x72\x3a \xf0\x90\x90\x80";
size_t buf_len = sizeof (expect_utf8_buf) - 1;
JERRY_VLA (char, buf, buf_len + 1);
jerryx_arg_t mapping[] =
{
jerryx_arg_utf8_string (buf, (uint32_t) buf_len + 1, JERRYX_ARG_COERCE, JERRYX_ARG_REQUIRED),
};
jerry_value_t is_ok = jerryx_arg_transform_args (&str,
1,
mapping,
ARRAY_SIZE (mapping));
TEST_ASSERT (!jerry_value_is_error (is_ok));
TEST_ASSERT (!strcmp (buf, expect_utf8_buf));
jerry_release_value (str);
} /* test_utf8_string */
static jerry_value_t
create_object_a_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
JERRY_UNUSED (args_p);
JERRY_UNUSED (args_cnt);
TEST_ASSERT (jerry_value_is_object (this_val));
my_thing_a.x = 1;
jerry_set_object_native_pointer (this_val,
&my_thing_a,
&thing_a_info);
return jerry_create_boolean (true);
} /* create_object_a_handler */
static jerry_value_t
create_object_b_handler (const jerry_value_t func_obj_val, /**< function object */
const jerry_value_t this_val, /**< this value */
const jerry_value_t args_p[], /**< arguments list */
const jerry_length_t args_cnt) /**< arguments length */
{
JERRY_UNUSED (func_obj_val);
JERRY_UNUSED (args_p);
JERRY_UNUSED (args_cnt);
TEST_ASSERT (jerry_value_is_object (this_val));
my_thing_b.x = false;
jerry_set_object_native_pointer (this_val,
&my_thing_b,
&thing_b_info);
return jerry_create_boolean (true);
} /* create_object_b_handler */
/**
* Register a JavaScript function in the global object.
*/
static void
register_js_function (const char *name_p, /**< name of the function */
jerry_external_handler_t handler_p) /**< function callback */
{
jerry_value_t global_obj_val = jerry_get_global_object ();
jerry_value_t function_val = jerry_create_external_function (handler_p);
jerry_value_t function_name_val = jerry_create_string ((const jerry_char_t *) name_p);
jerry_value_t result_val = jerry_set_property (global_obj_val, function_name_val, function_val);
jerry_release_value (function_name_val);
jerry_release_value (function_val);
jerry_release_value (global_obj_val);
jerry_release_value (result_val);
} /* register_js_function */
int
main (void)
{
jerry_init (JERRY_INIT_EMPTY);
test_utf8_string ();
register_js_function ("test_validator1", test_validator1_handler);
register_js_function ("test_validator2", test_validator2_handler);
register_js_function ("test_validator3", test_validator3_handler);
register_js_function ("test_validator_int1", test_validator_int1_handler);
register_js_function ("test_validator_int2", test_validator_int2_handler);
register_js_function ("test_validator_int3", test_validator_int3_handler);
register_js_function ("MyObjectA", create_object_a_handler);
register_js_function ("MyObjectB", create_object_b_handler);
register_js_function ("test_validator_prop1", test_validator_prop1_handler);
register_js_function ("test_validator_prop2", test_validator_prop2_handler);
register_js_function ("test_validator_prop3", test_validator_prop3_handler);
register_js_function ("test_validator_array1", test_validator_array1_handler);
register_js_function ("test_validator_array2", test_validator_array2_handler);
register_js_function ("test_validator_restore", test_validator_restore_handler);
jerry_value_t parsed_code_val = jerry_parse (NULL,
0,
test_source,
sizeof (test_source) - 1,
JERRY_PARSE_NO_OPTS);
TEST_ASSERT (!jerry_value_is_error (parsed_code_val));
jerry_value_t res = jerry_run (parsed_code_val);
TEST_ASSERT (!jerry_value_is_error (res));
TEST_ASSERT (validator1_count == 5);
TEST_ASSERT (validator2_count == 3);
TEST_ASSERT (validator_prop_count == 4);
TEST_ASSERT (validator_int_count == 3);
TEST_ASSERT (validator_array_count == 3);
TEST_ASSERT (validator_restore_count == 4);
jerry_release_value (res);
jerry_release_value (parsed_code_val);
jerry_cleanup ();
} /* main */
|
729923.c | #include <stdlib.h>
#include "grib2.h"
#include "gridtemplates.h"
g2int getgridindex(g2int number)
/*!$$$ SUBPROGRAM DOCUMENTATION BLOCK
! . . . .
! SUBPROGRAM: getgridindex
! PRGMMR: Gilbert ORG: W/NP11 DATE: 2001-06-28
!
! ABSTRACT: This function returns the index of specified Grid
! Definition Template 3.NN (NN=number) in array templates.
!
! PROGRAM HISTORY LOG:
! 2001-06-28 Gilbert
! 2007-08-16 Vuong - Added GDT 3.204 Curvilinear Orthogonal Grid
!
! USAGE: index=getgridindex(number)
! INPUT ARGUMENT LIST:
! number - NN, indicating the number of the Grid Definition
! Template 3.NN that is being requested.
!
! RETURNS: Index of GDT 3.NN in array templates, if template exists.
! = -1, otherwise.
!
! REMARKS: None
!
! ATTRIBUTES:
! LANGUAGE: C
! MACHINE: IBM SP
!
!$$$*/
{
g2int j,getgridindex=-1;
for (j=0;j<MAXGRIDTEMP;j++) {
if (number == templatesgrid[j].template_num) {
getgridindex=j;
return(getgridindex);
}
}
return(getgridindex);
}
template *getgridtemplate(g2int number)
/*!$$$ SUBPROGRAM DOCUMENTATION BLOCK
! . . . .
! SUBPROGRAM: getgridtemplate
! PRGMMR: Gilbert ORG: W/NP11 DATE: 2000-05-09
!
! ABSTRACT: This subroutine returns grid template information for a
! specified Grid Definition Template 3.NN.
! The number of entries in the template is returned along with a map
! of the number of octets occupied by each entry. Also, a flag is
! returned to indicate whether the template would need to be extended.
!
! PROGRAM HISTORY LOG:
! 2000-05-09 Gilbert
! 2007-08-16 Vuong - Added GDT 3.204 Curvilinear Orthogonal Grid
!
! USAGE: template *getgridtemplate(number)
! INPUT ARGUMENT LIST:
! number - NN, indicating the number of the Grid Definition
! Template 3.NN that is being requested.
!
! RETURN VALUE:
! - Pointer to the returned template struct.
! Returns NULL pointer, if template not found.
!
! REMARKS: None
!
! ATTRIBUTES:
! LANGUAGE: C
! MACHINE: IBM SP
!
!$$$*/
{
g2int index;
template *new;
index=getgridindex(number);
if (index != -1) {
new=(template *)malloc(sizeof(template));
new->type=3;
new->num=templatesgrid[index].template_num;
new->maplen=templatesgrid[index].mapgridlen;
new->needext=templatesgrid[index].needext;
new->map=(g2int *)templatesgrid[index].mapgrid;
new->extlen=0;
new->ext=0; //NULL
return(new);
}
else {
printf("getgridtemplate: GDT Template 3.%d not defined.\n",(int)number);
return(0); //NULL
}
return(0); //NULL
}
template *extgridtemplate(g2int number,g2int *list)
/*!$$$ SUBPROGRAM DOCUMENTATION BLOCK
! . . . .
! SUBPROGRAM: extgridtemplate
! PRGMMR: Gilbert ORG: W/NP11 DATE: 2000-05-09
!
! ABSTRACT: This subroutine generates the remaining octet map for a
! given Grid Definition Template, if required. Some Templates can
! vary depending on data values given in an earlier part of the
! Template, and it is necessary to know some of the earlier entry
! values to generate the full octet map of the Template.
!
! PROGRAM HISTORY LOG:
! 2000-05-09 Gilbert
!
! USAGE: CALL extgridtemplate(number,list)
! INPUT ARGUMENT LIST:
! number - NN, indicating the number of the Grid Definition
! Template 3.NN that is being requested.
! list() - The list of values for each entry in
! the Grid Definition Template.
!
! RETURN VALUE:
! - Pointer to the returned template struct.
! Returns NULL pointer, if template not found.
!
! ATTRIBUTES:
! LANGUAGE: C
! MACHINE: IBM SP
!
!$$$*/
{
template *new;
g2int index,i;
index=getgridindex(number);
if (index == -1) return(0);
new=getgridtemplate(number);
if ( ! new->needext ) return(new);
if ( number == 120 ) {
new->extlen=list[1]*2;
new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
for (i=0;i<new->extlen;i++) {
if ( i%2 == 0 ) {
new->ext[i]=2;
}
else {
new->ext[i]=-2;
}
}
}
else if ( number == 1000 ) {
new->extlen=list[19];
new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
for (i=0;i<new->extlen;i++) {
new->ext[i]=4;
}
}
else if ( number == 1200 ) {
new->extlen=list[15];
new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
for (i=0;i<new->extlen;i++) {
new->ext[i]=4;
}
}
return(new);
}
|
321283.c | #include <kernel/system.h>
#include <kernel/printf.h>
#include <kernel/module.h>
#include <kernel/logging.h>
#include <kernel/types.h>
#include "../lib/termemu.c"
static unsigned short * textmemptr = (unsigned short *)0xB8000;
static void placech(unsigned char c, int x, int y, int attr) {
unsigned short *where;
unsigned att = attr << 8;
where = textmemptr + (y * 80 + x);
*where = c | att;
}
static char vga_to_ansi[] = {
0, 4, 2, 6, 1, 5, 3, 7,
8,12,10,14, 9,13,11,15
};
static int current_fg = 0x07;
static int current_bg = 0x10;
static int cur_x = 0;
static int cur_y = 0;
term_state_t * ansi_state = NULL;
static int write_string(char * s) {
int written = 0;
while (*s) {
switch (*s) {
case '\n':
cur_x = 0;
cur_y++;
break;
case '\b':
if (cur_x > 0) cur_x--;
placech(' ', cur_x, cur_y, (vga_to_ansi[current_fg] & 0xF) | (vga_to_ansi[current_bg] << 4));
break;
default:
placech(*s, cur_x, cur_y, (vga_to_ansi[current_fg] & 0xF) | (vga_to_ansi[current_bg] << 4));
cur_x++;
break;
}
if (cur_x == 80) {
cur_x = 0;
cur_y++;
}
if (cur_y == 25) {
memmove(textmemptr, (textmemptr + 80), sizeof(unsigned short) * 80 * 24);
memset(textmemptr + 80 * 24, 0x00, 80 * sizeof(unsigned short));
cur_y = 24;
}
s++;
written++;
}
return written;
}
static void term_write(char c) {
char foo[] = {c,0};
write_string(foo);
}
static uint32_t vga_write(fs_node_t * node, uint64_t offset, uint32_t size, uint8_t *buffer) {
/* XXX do some terminal processing like we did in the old days */
size_t i = 0;
while (*buffer && i < size) {
ansi_put(ansi_state, *buffer);
buffer++;
i++;
}
return i;
}
static fs_node_t _vga_fnode = {
.name = "vga_log",
.write = vga_write,
};
static void term_scroll(int how_much) {
for (int i = 0; i < how_much; ++i) {
memmove(textmemptr, (textmemptr + 80), sizeof(unsigned short) * 80 * 24);
memset(textmemptr + 80 * 24, 0x00, 80 * sizeof(unsigned short));
}
}
static void term_set_cell(int x, int y, uint32_t c) {
placech(c, x, y, (vga_to_ansi[current_fg] & 0xF) | (vga_to_ansi[current_bg] << 4));
}
static void term_set_csr(int x, int y) {
cur_x = x;
cur_y = y;
}
static int term_get_csr_x() {
return cur_x;
}
static int term_get_csr_y() {
return cur_y;
}
static void term_set_csr_show(int on) {
return;
}
static void term_set_colors(uint32_t fg, uint32_t bg) {
current_fg = fg;
current_bg = bg;
}
static void term_redraw_cursor() {
return;
}
static void input_buffer_stuff(char * str) {
return;
}
static void set_title(char * c) {
/* Do nothing */
}
static void term_clear(int i) {
memset(textmemptr, 0x00, sizeof(unsigned short) * 80 * 25);
}
int unsupported_int(void) { return 0; }
void unsupported(int x, int y, char * data) { }
term_callbacks_t term_callbacks = {
term_write,
term_set_colors,
term_set_csr,
term_get_csr_x,
term_get_csr_y,
term_set_cell,
term_clear,
term_scroll,
term_redraw_cursor,
input_buffer_stuff,
set_title,
unsupported,
unsupported_int,
unsupported_int,
term_set_csr_show,
NULL,
};
static int vgadbg_init(void) {
memset(textmemptr, 0x00, sizeof(unsigned short) * 80 * 25);
ansi_state = ansi_init(ansi_state, 80, 25, &term_callbacks);
debug_file = &_vga_fnode;
debug_level = 1;
write_string("VGA Debug Logging is enabled.\n");
return 0;
}
static int vgadbg_fini(void) {
return 0;
}
MODULE_DEF(vgalog, vgadbg_init, vgadbg_fini);
|
620956.c | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file aia_storage_config.c
* @brief Implements platform-specific Storage functions which are not inlined
* in
* @c aia_storage_config.h.
*/
#include <storage/aia_storage_config.h>
#include <aia_config.h>
#include <aiaalertmanager/aia_alert_constants.h>
#include <aiacore/aia_volume_constants.h>
#include <errno.h>
#include <stdio.h>
const char* g_aiaClientId;
const char* g_aiaAwsAccountId;
const char* g_aiaStorageFolder;
#ifdef AIA_LOAD_VOLUME
uint8_t AiaLoadVolume()
{
/* TODO: ADSER-1741 Provide an actual reference implementation of persisting
* device volume. */
return AIA_DEFAULT_VOLUME;
}
#endif
#define AIA_SHARED_SECRET_STORAGE_KEY "AiaSharedSecretStorageKey"
bool AiaStoreSecret( const uint8_t* sharedSecret, size_t size )
{
return AiaStoreBlob( AIA_SHARED_SECRET_STORAGE_KEY, sharedSecret, size );
}
bool AiaLoadSecret( uint8_t* sharedSecret, size_t size )
{
return AiaLoadBlob( AIA_SHARED_SECRET_STORAGE_KEY, sharedSecret, size );
}
/** If using the provided sample storage implementation, this is the filename
* format of persistent storage files that the SDK will read/write from/to. */
static const char* PERSISTENT_STORAGE_FILE_PATH_FORMAT = "%s/%s_%s_%s.dat";
bool AiaStoreBlob( const char* key, const uint8_t* blob, size_t size )
{
int numCharsRequired =
snprintf( NULL, 0, PERSISTENT_STORAGE_FILE_PATH_FORMAT,
g_aiaStorageFolder, g_aiaAwsAccountId, g_aiaClientId, key );
if( numCharsRequired < 0 )
{
AiaLogError( "snprintf failed, ret=%d", numCharsRequired );
return false;
}
char filePath[ numCharsRequired + 1 ];
if( snprintf( filePath, numCharsRequired + 1,
PERSISTENT_STORAGE_FILE_PATH_FORMAT, g_aiaStorageFolder,
g_aiaAwsAccountId, g_aiaClientId, key ) < 0 )
{
AiaLogError( "snprintf failed" );
return false;
}
FILE* file = fopen( filePath, "wb" );
if( !file )
{
AiaLogError( "fopen failed: %s", strerror( errno ) );
return false;
}
if( fwrite( blob, 1, size, file ) < size )
{
AiaLogError( "Failed to store full blob, key=%s", key );
fclose( file );
return false;
}
if( fclose( file ) != 0 )
{
AiaLogWarn( "fclose failed" );
}
return true;
}
bool AiaLoadBlob( const char* key, const uint8_t* blob, size_t size )
{
if( !key )
{
AiaLogError( "Null key" );
return false;
}
if( !blob )
{
AiaLogError( "Null blob" );
return false;
}
int numCharsRequired =
snprintf( NULL, 0, PERSISTENT_STORAGE_FILE_PATH_FORMAT,
g_aiaStorageFolder, g_aiaAwsAccountId, g_aiaClientId, key );
if( numCharsRequired < 0 )
{
AiaLogError( "snprintf failed, ret=%d", numCharsRequired );
return false;
}
char filePath[ numCharsRequired + 1 ];
if( snprintf( filePath, numCharsRequired + 1,
PERSISTENT_STORAGE_FILE_PATH_FORMAT, g_aiaStorageFolder,
g_aiaAwsAccountId, g_aiaClientId, key ) < 0 )
{
AiaLogError( "snprintf failed" );
return false;
}
FILE* file = fopen( filePath, "rb" );
if( !file )
{
AiaLogError( "fopen failed: %s", strerror( errno ) );
return false;
}
rewind( file );
if( fread( (uint8_t*)blob, 1, size, file ) < size )
{
AiaLogError( "Failed to read full blob, key=%s, size=%zu", key, size );
fclose( file );
return false;
}
if( fclose( file ) != 0 )
{
AiaLogWarn( "fclose failed" );
}
return true;
}
bool AiaBlobExists( const char* key )
{
if( !key )
{
AiaLogError( "Null key" );
return false;
}
int numCharsRequired =
snprintf( NULL, 0, PERSISTENT_STORAGE_FILE_PATH_FORMAT,
g_aiaStorageFolder, g_aiaAwsAccountId, g_aiaClientId, key );
if( numCharsRequired < 0 )
{
AiaLogError( "snprintf failed, ret=%d", numCharsRequired );
return false;
}
char filePath[ numCharsRequired + 1 ];
if( snprintf( filePath, numCharsRequired + 1,
PERSISTENT_STORAGE_FILE_PATH_FORMAT, g_aiaStorageFolder,
g_aiaAwsAccountId, g_aiaClientId, key ) < 0 )
{
AiaLogError( "snprintf failed" );
return false;
}
FILE* file = fopen( filePath, "r" );
if( file )
{
fclose( file );
return true;
}
else
{
return false;
}
}
size_t AiaGetBlobSize( const char* key )
{
if( !key )
{
AiaLogError( "Null key" );
return 0;
}
int numCharsRequired =
snprintf( NULL, 0, PERSISTENT_STORAGE_FILE_PATH_FORMAT,
g_aiaStorageFolder, g_aiaAwsAccountId, g_aiaClientId, key );
if( numCharsRequired < 0 )
{
AiaLogError( "snprintf failed, ret=%d", numCharsRequired );
return 0;
}
char filePath[ numCharsRequired + 1 ];
if( snprintf( filePath, numCharsRequired + 1,
PERSISTENT_STORAGE_FILE_PATH_FORMAT, g_aiaStorageFolder,
g_aiaAwsAccountId, g_aiaClientId, key ) < 0 )
{
AiaLogError( "snprintf failed" );
return 0;
}
FILE* file = fopen( filePath, "rb" );
if( !file )
{
AiaLogError( "fopen failed: %s", strerror( errno ) );
return 0;
}
if( fseek( file, 0, SEEK_END ) < 0 )
{
AiaLogError( "fseek failed" );
fclose( file );
return 0;
}
size_t fileSize = (size_t)ftell( file );
if( fclose( file ) != 0 )
{
AiaLogWarn( "fclose failed" );
}
return fileSize;
}
#define AIA_ALL_ALERTS_STORAGE_KEY_V0 "AiaAllAlertsStorageKey"
bool AiaStoreAlert( const char* alertToken, size_t alertTokenLen,
AiaTimepointSeconds_t scheduledTime,
AiaDurationMs_t duration, uint8_t alertType )
{
if( !alertToken )
{
AiaLogError( "Null alertToken" );
return false;
}
if( alertTokenLen != AIA_ALERT_TOKEN_CHARS )
{
AiaLogError( "Invalid alert token length" );
return false;
}
size_t allAlertsBytes = AiaGetAlertsSize();
size_t alertsBytesWithNewAlert =
allAlertsBytes + AIA_SIZE_OF_ALERT_IN_BYTES;
size_t startingOffset = allAlertsBytes;
size_t bytePosition;
bool updatingExistingAlert = false;
/**
* Load all alerts from persistent storage. Allocated additional space
* for a new alert though in case the token we are trying to insert does
* not exist in persistent storage yet.
*/
uint8_t* allAlertsBuffer = AiaCalloc( 1, alertsBytesWithNewAlert );
if( !allAlertsBuffer )
{
AiaLogError( "AiaCalloc failed, bytes=%zu.", alertsBytesWithNewAlert );
return false;
}
if( !AiaLoadAlerts( allAlertsBuffer, allAlertsBytes ) )
{
AiaLogError( "AiaLoadBlob failed" );
AiaFree( allAlertsBuffer );
return false;
}
/** Go through the tokens to find the first empty or matching one */
for( bytePosition = 0; bytePosition < alertsBytesWithNewAlert;
bytePosition += AIA_SIZE_OF_ALERT_IN_BYTES )
{
startingOffset = bytePosition;
if( '\0' == allAlertsBuffer[ bytePosition ] )
{
/** Found an empty token */
break;
}
else
{
/** Check if this token matches with what we are trying to insert */
if( !strncmp( (const char*)allAlertsBuffer + bytePosition,
alertToken, alertTokenLen ) )
{
updatingExistingAlert = true;
break;
}
}
}
/* Check if we have reached the alerts storage limit */
if( startingOffset == alertsBytesWithNewAlert )
{
AiaLogError(
"AiaStoreAlert failed: Maximum number of local alerts to store "
"reached." );
AiaFree( allAlertsBuffer );
return false;
}
/** Write the new alert token */
uint8_t* newAlertOffset = allAlertsBuffer + startingOffset;
memcpy( newAlertOffset, alertToken, alertTokenLen );
/** Write the other fields: scheduledTime, duration, alertType */
bytePosition = alertTokenLen;
for( size_t i = 0; i < sizeof( AiaTimepointSeconds_t );
++i, bytePosition++ )
{
newAlertOffset[ bytePosition ] = ( scheduledTime >> ( i * 8 ) );
}
for( size_t i = 0; i < sizeof( AiaDurationMs_t ); ++i, bytePosition++ )
{
newAlertOffset[ bytePosition ] = ( duration >> ( i * 8 ) );
}
for( size_t i = 0; i < sizeof( uint8_t ); ++i, bytePosition++ )
{
newAlertOffset[ bytePosition ] = ( alertType >> ( i * 8 ) );
}
/** Store the new blob in persistent storage */
size_t storeSize =
( updatingExistingAlert ? allAlertsBytes : alertsBytesWithNewAlert );
/** Store the new blob in persistent storage */
if( !AiaStoreBlob( AIA_ALL_ALERTS_STORAGE_KEY_V0, allAlertsBuffer,
storeSize ) )
{
AiaLogError( "AiaStoreBlob failed" );
AiaFree( allAlertsBuffer );
return false;
}
AiaFree( allAlertsBuffer );
return true;
}
bool AiaDeleteAlert( const char* alertToken, size_t alertTokenLen )
{
if( !alertToken )
{
AiaLogError( "Null alertToken" );
return false;
}
if( alertTokenLen != AIA_ALERT_TOKEN_CHARS )
{
AiaLogError( "Invalid alert token length" );
return false;
}
size_t allAlertsBytes = AiaGetAlertsSize();
size_t bytePosition;
bool deletingExistingAlert = false;
/**
* Load all alerts from persistent storage.
*/
uint8_t* allAlertsBuffer = AiaCalloc( 1, allAlertsBytes );
if( !allAlertsBuffer )
{
AiaLogError( "AiaCalloc failed, bytes=%zu.", allAlertsBytes );
return false;
}
if( !AiaLoadAlerts( allAlertsBuffer, allAlertsBytes ) )
{
AiaLogError( "AiaLoadBlob failed" );
AiaFree( allAlertsBuffer );
return false;
}
/** Go through the tokens to find the first empty or matching one */
for( bytePosition = 0; bytePosition < allAlertsBytes;
bytePosition += AIA_SIZE_OF_ALERT_IN_BYTES )
{
if( '\0' == allAlertsBuffer[ bytePosition ] )
{
/** Found an empty token */
break;
}
else
{
/** Check if this token matches with what we are trying to delete */
if( !strncmp( (const char*)allAlertsBuffer + bytePosition,
alertToken, alertTokenLen ) )
{
uint8_t* moveDst = allAlertsBuffer + bytePosition;
uint8_t* moveSrc =
allAlertsBuffer + bytePosition + AIA_SIZE_OF_ALERT_IN_BYTES;
size_t moveBytes =
allAlertsBytes -
( bytePosition + AIA_SIZE_OF_ALERT_IN_BYTES );
memmove( moveDst, moveSrc, moveBytes );
deletingExistingAlert = true;
break;
}
}
}
/** Store the new blob in persistent storage */
size_t storeSize =
( deletingExistingAlert ? allAlertsBytes - AIA_SIZE_OF_ALERT_IN_BYTES
: allAlertsBytes );
/** Store the new blob */
if( !AiaStoreBlob( AIA_ALL_ALERTS_STORAGE_KEY_V0, allAlertsBuffer,
storeSize ) )
{
AiaLogError( "AiaStoreBlob failed" );
AiaFree( allAlertsBuffer );
return false;
}
AiaFree( allAlertsBuffer );
return true;
}
bool AiaLoadAlert( char* alertToken, size_t alertTokenLen,
AiaTimepointSeconds_t* scheduledTime,
AiaDurationMs_t* duration, uint8_t* alertType,
const uint8_t* allAlertsBuffer )
{
if( !alertToken )
{
AiaLogError( "Null alertToken" );
return false;
}
if( !scheduledTime )
{
AiaLogError( "Null scheduledTime" );
return false;
}
if( !duration )
{
AiaLogError( "Null duration" );
return false;
}
if( !alertType )
{
AiaLogError( "Null alertType" );
return false;
}
if( !allAlertsBuffer )
{
AiaLogError( "Null allAlertsBuffer" );
return false;
}
if( alertTokenLen != AIA_ALERT_TOKEN_CHARS )
{
AiaLogError( "Invalid alert token length" );
return false;
}
size_t bytePosition = 0;
*scheduledTime = 0;
*duration = 0;
*alertType = 0;
memcpy( alertToken, allAlertsBuffer, alertTokenLen );
bytePosition += alertTokenLen;
for( size_t i = 0; i < sizeof( AiaTimepointSeconds_t );
++i, ++bytePosition )
{
*scheduledTime |= (unsigned)allAlertsBuffer[ bytePosition ]
<< ( i * 8 );
}
for( size_t i = 0; i < sizeof( AiaDurationMs_t ); ++i, ++bytePosition )
{
*duration |= (unsigned)allAlertsBuffer[ bytePosition ] << ( i * 8 );
}
for( size_t i = 0; i < sizeof( uint8_t ); ++i, ++bytePosition )
{
*alertType |= (unsigned)allAlertsBuffer[ bytePosition ] << ( i * 8 );
}
return true;
}
bool AiaLoadAlerts( uint8_t* allAlerts, size_t size )
{
if( !AiaAlertsBlobExists() )
{
if( size != 0 )
{
AiaLogError( "Alerts blob with size %zu does not exist", size );
return false;
}
else
{
return true;
}
}
else
{
return AiaLoadBlob( AIA_ALL_ALERTS_STORAGE_KEY_V0, allAlerts, size );
}
}
size_t AiaGetAlertsSize()
{
return AiaGetBlobSize( AIA_ALL_ALERTS_STORAGE_KEY_V0 );
}
bool AiaAlertsBlobExists()
{
return AiaBlobExists( AIA_ALL_ALERTS_STORAGE_KEY_V0 );
}
|
146797.c | // SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0
/******************************************************************************
*
* Module Name: dswload - Dispatcher first pass namespace load callbacks
*
* Copyright (C) 2000 - 2019, Intel Corp.
*
*****************************************************************************/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acparser.h"
#include "amlcode.h"
#include "acdispat.h"
#include "acinterp.h"
#include "acnamesp.h"
#ifdef ACPI_ASL_COMPILER
#include "acdisasm.h"
#endif
#define _COMPONENT ACPI_DISPATCHER
ACPI_MODULE_NAME("dswload")
/*******************************************************************************
*
* FUNCTION: acpi_ds_init_callbacks
*
* PARAMETERS: walk_state - Current state of the parse tree walk
* pass_number - 1, 2, or 3
*
* RETURN: Status
*
* DESCRIPTION: Init walk state callbacks
*
******************************************************************************/
acpi_status
acpi_ds_init_callbacks(struct acpi_walk_state *walk_state, u32 pass_number)
{
switch (pass_number) {
case 0:
/* Parse only - caller will setup callbacks */
walk_state->parse_flags = ACPI_PARSE_LOAD_PASS1 |
ACPI_PARSE_DELETE_TREE | ACPI_PARSE_DISASSEMBLE;
walk_state->descending_callback = NULL;
walk_state->ascending_callback = NULL;
break;
case 1:
/* Load pass 1 */
walk_state->parse_flags = ACPI_PARSE_LOAD_PASS1 |
ACPI_PARSE_DELETE_TREE;
walk_state->descending_callback = acpi_ds_load1_begin_op;
walk_state->ascending_callback = acpi_ds_load1_end_op;
break;
case 2:
/* Load pass 2 */
walk_state->parse_flags = ACPI_PARSE_LOAD_PASS1 |
ACPI_PARSE_DELETE_TREE;
walk_state->descending_callback = acpi_ds_load2_begin_op;
walk_state->ascending_callback = acpi_ds_load2_end_op;
break;
case 3:
/* Execution pass */
walk_state->parse_flags |= ACPI_PARSE_EXECUTE |
ACPI_PARSE_DELETE_TREE;
walk_state->descending_callback = acpi_ds_exec_begin_op;
walk_state->ascending_callback = acpi_ds_exec_end_op;
break;
default:
return (AE_BAD_PARAMETER);
}
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_load1_begin_op
*
* PARAMETERS: walk_state - Current state of the parse tree walk
* out_op - Where to return op if a new one is created
*
* RETURN: Status
*
* DESCRIPTION: Descending callback used during the loading of ACPI tables.
*
******************************************************************************/
acpi_status
acpi_ds_load1_begin_op(struct acpi_walk_state *walk_state,
union acpi_parse_object **out_op)
{
union acpi_parse_object *op;
struct acpi_namespace_node *node;
acpi_status status;
acpi_object_type object_type;
char *path;
u32 flags;
ACPI_FUNCTION_TRACE_PTR(ds_load1_begin_op, walk_state->op);
op = walk_state->op;
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH, "Op=%p State=%p\n", op,
walk_state));
/* We are only interested in opcodes that have an associated name */
if (op) {
if (!(walk_state->op_info->flags & AML_NAMED)) {
*out_op = op;
return_ACPI_STATUS(AE_OK);
}
/* Check if this object has already been installed in the namespace */
if (op->common.node) {
*out_op = op;
return_ACPI_STATUS(AE_OK);
}
}
path = acpi_ps_get_next_namestring(&walk_state->parser_state);
/* Map the raw opcode into an internal object type */
object_type = walk_state->op_info->object_type;
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"State=%p Op=%p [%s]\n", walk_state, op,
acpi_ut_get_type_name(object_type)));
switch (walk_state->opcode) {
case AML_SCOPE_OP:
/*
* The target name of the Scope() operator must exist at this point so
* that we can actually open the scope to enter new names underneath it.
* Allow search-to-root for single namesegs.
*/
status =
acpi_ns_lookup(walk_state->scope_info, path, object_type,
ACPI_IMODE_EXECUTE, ACPI_NS_SEARCH_PARENT,
walk_state, &(node));
#ifdef ACPI_ASL_COMPILER
if (status == AE_NOT_FOUND) {
/*
* Table disassembly:
* Target of Scope() not found. Generate an External for it, and
* insert the name into the namespace.
*/
acpi_dm_add_op_to_external_list(op, path,
ACPI_TYPE_DEVICE, 0, 0);
status =
acpi_ns_lookup(walk_state->scope_info, path,
object_type, ACPI_IMODE_LOAD_PASS1,
ACPI_NS_SEARCH_PARENT, walk_state,
&node);
}
#endif
if (ACPI_FAILURE(status)) {
ACPI_ERROR_NAMESPACE(walk_state->scope_info, path,
status);
return_ACPI_STATUS(status);
}
/*
* Check to make sure that the target is
* one of the opcodes that actually opens a scope
*/
switch (node->type) {
case ACPI_TYPE_ANY:
case ACPI_TYPE_LOCAL_SCOPE: /* Scope */
case ACPI_TYPE_DEVICE:
case ACPI_TYPE_POWER:
case ACPI_TYPE_PROCESSOR:
case ACPI_TYPE_THERMAL:
/* These are acceptable types */
break;
case ACPI_TYPE_INTEGER:
case ACPI_TYPE_STRING:
case ACPI_TYPE_BUFFER:
/*
* These types we will allow, but we will change the type.
* This enables some existing code of the form:
*
* Name (DEB, 0)
* Scope (DEB) { ... }
*
* Note: silently change the type here. On the second pass,
* we will report a warning
*/
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Type override - [%4.4s] had invalid type (%s) "
"for Scope operator, changed to type ANY\n",
acpi_ut_get_node_name(node),
acpi_ut_get_type_name(node->type)));
node->type = ACPI_TYPE_ANY;
walk_state->scope_info->common.value = ACPI_TYPE_ANY;
break;
case ACPI_TYPE_METHOD:
/*
* Allow scope change to root during execution of module-level
* code. Root is typed METHOD during this time.
*/
if ((node == acpi_gbl_root_node) &&
(walk_state->
parse_flags & ACPI_PARSE_MODULE_LEVEL)) {
break;
}
/*lint -fallthrough */
default:
/* All other types are an error */
ACPI_ERROR((AE_INFO,
"Invalid type (%s) for target of "
"Scope operator [%4.4s] (Cannot override)",
acpi_ut_get_type_name(node->type),
acpi_ut_get_node_name(node)));
return_ACPI_STATUS(AE_AML_OPERAND_TYPE);
}
break;
default:
/*
* For all other named opcodes, we will enter the name into
* the namespace.
*
* Setup the search flags.
* Since we are entering a name into the namespace, we do not want to
* enable the search-to-root upsearch.
*
* There are only two conditions where it is acceptable that the name
* already exists:
* 1) the Scope() operator can reopen a scoping object that was
* previously defined (Scope, Method, Device, etc.)
* 2) Whenever we are parsing a deferred opcode (op_region, Buffer,
* buffer_field, or Package), the name of the object is already
* in the namespace.
*/
if (walk_state->deferred_node) {
/* This name is already in the namespace, get the node */
node = walk_state->deferred_node;
status = AE_OK;
break;
}
/*
* If we are executing a method, do not create any namespace objects
* during the load phase, only during execution.
*/
if (walk_state->method_node) {
node = NULL;
status = AE_OK;
break;
}
flags = ACPI_NS_NO_UPSEARCH;
if ((walk_state->opcode != AML_SCOPE_OP) &&
(!(walk_state->parse_flags & ACPI_PARSE_DEFERRED_OP))) {
if (walk_state->namespace_override) {
flags |= ACPI_NS_OVERRIDE_IF_FOUND;
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"[%s] Override allowed\n",
acpi_ut_get_type_name
(object_type)));
} else {
flags |= ACPI_NS_ERROR_IF_FOUND;
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"[%s] Cannot already exist\n",
acpi_ut_get_type_name
(object_type)));
}
} else {
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"[%s] Both Find or Create allowed\n",
acpi_ut_get_type_name(object_type)));
}
/*
* Enter the named type into the internal namespace. We enter the name
* as we go downward in the parse tree. Any necessary subobjects that
* involve arguments to the opcode must be created as we go back up the
* parse tree later.
*/
status =
acpi_ns_lookup(walk_state->scope_info, path, object_type,
ACPI_IMODE_LOAD_PASS1, flags, walk_state,
&node);
if (ACPI_FAILURE(status)) {
if (status == AE_ALREADY_EXISTS) {
/* The name already exists in this scope */
if (node->flags & ANOBJ_IS_EXTERNAL) {
/*
* Allow one create on an object or segment that was
* previously declared External
*/
node->flags &= ~ANOBJ_IS_EXTERNAL;
node->type = (u8) object_type;
/* Just retyped a node, probably will need to open a scope */
if (acpi_ns_opens_scope(object_type)) {
status =
acpi_ds_scope_stack_push
(node, object_type,
walk_state);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS
(status);
}
}
status = AE_OK;
}
}
if (ACPI_FAILURE(status)) {
ACPI_ERROR_NAMESPACE(walk_state->scope_info,
path, status);
return_ACPI_STATUS(status);
}
}
break;
}
/* Common exit */
if (!op) {
/* Create a new op */
op = acpi_ps_alloc_op(walk_state->opcode, walk_state->aml);
if (!op) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
}
/* Initialize the op */
#ifdef ACPI_CONSTANT_EVAL_ONLY
op->named.path = path;
#endif
if (node) {
/*
* Put the Node in the "op" object that the parser uses, so we
* can get it again quickly when this scope is closed
*/
op->common.node = node;
op->named.name = node->name.integer;
}
acpi_ps_append_arg(acpi_ps_get_parent_scope(&walk_state->parser_state),
op);
*out_op = op;
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_load1_end_op
*
* PARAMETERS: walk_state - Current state of the parse tree walk
*
* RETURN: Status
*
* DESCRIPTION: Ascending callback used during the loading of the namespace,
* both control methods and everything else.
*
******************************************************************************/
acpi_status acpi_ds_load1_end_op(struct acpi_walk_state *walk_state)
{
union acpi_parse_object *op;
acpi_object_type object_type;
acpi_status status = AE_OK;
#ifdef ACPI_ASL_COMPILER
u8 param_count;
#endif
ACPI_FUNCTION_TRACE(ds_load1_end_op);
op = walk_state->op;
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH, "Op=%p State=%p\n", op,
walk_state));
/* We are only interested in opcodes that have an associated name */
if (!(walk_state->op_info->flags & (AML_NAMED | AML_FIELD))) {
return_ACPI_STATUS(AE_OK);
}
/* Get the object type to determine if we should pop the scope */
object_type = walk_state->op_info->object_type;
if (walk_state->op_info->flags & AML_FIELD) {
/*
* If we are executing a method, do not create any namespace objects
* during the load phase, only during execution.
*/
if (!walk_state->method_node) {
if (walk_state->opcode == AML_FIELD_OP ||
walk_state->opcode == AML_BANK_FIELD_OP ||
walk_state->opcode == AML_INDEX_FIELD_OP) {
status =
acpi_ds_init_field_objects(op, walk_state);
}
}
return_ACPI_STATUS(status);
}
/*
* If we are executing a method, do not create any namespace objects
* during the load phase, only during execution.
*/
if (!walk_state->method_node) {
if (op->common.aml_opcode == AML_REGION_OP) {
status =
acpi_ex_create_region(op->named.data,
op->named.length,
(acpi_adr_space_type)
((op->common.value.arg)->
common.value.integer),
walk_state);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
} else if (op->common.aml_opcode == AML_DATA_REGION_OP) {
status =
acpi_ex_create_region(op->named.data,
op->named.length,
ACPI_ADR_SPACE_DATA_TABLE,
walk_state);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
}
}
if (op->common.aml_opcode == AML_NAME_OP) {
/* For Name opcode, get the object type from the argument */
if (op->common.value.arg) {
object_type = (acpi_ps_get_opcode_info((op->common.
value.arg)->
common.
aml_opcode))->
object_type;
/* Set node type if we have a namespace node */
if (op->common.node) {
op->common.node->type = (u8) object_type;
}
}
}
#ifdef ACPI_ASL_COMPILER
/*
* For external opcode, get the object type from the argument and
* get the parameter count from the argument's next.
*/
if (acpi_gbl_disasm_flag &&
op->common.node && op->common.aml_opcode == AML_EXTERNAL_OP) {
/*
* Note, if this external is not a method
* Op->Common.Value.Arg->Common.Next->Common.Value.Integer == 0
* Therefore, param_count will be 0.
*/
param_count =
(u8)op->common.value.arg->common.next->common.value.integer;
object_type = (u8)op->common.value.arg->common.value.integer;
op->common.node->flags |= ANOBJ_IS_EXTERNAL;
op->common.node->type = (u8)object_type;
acpi_dm_create_subobject_for_external((u8)object_type,
&op->common.node,
param_count);
/*
* Add the external to the external list because we may be
* emitting code based off of the items within the external list.
*/
acpi_dm_add_op_to_external_list(op, op->named.path,
(u8)object_type, param_count,
ACPI_EXT_ORIGIN_FROM_OPCODE |
ACPI_EXT_RESOLVED_REFERENCE);
}
#endif
/*
* If we are executing a method, do not create any namespace objects
* during the load phase, only during execution.
*/
if (!walk_state->method_node) {
if (op->common.aml_opcode == AML_METHOD_OP) {
/*
* method_op pkg_length name_string method_flags term_list
*
* Note: We must create the method node/object pair as soon as we
* see the method declaration. This allows later pass1 parsing
* of invocations of the method (need to know the number of
* arguments.)
*/
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"LOADING-Method: State=%p Op=%p NamedObj=%p\n",
walk_state, op, op->named.node));
if (!acpi_ns_get_attached_object(op->named.node)) {
walk_state->operands[0] =
ACPI_CAST_PTR(void, op->named.node);
walk_state->num_operands = 1;
status =
acpi_ds_create_operands(walk_state,
op->common.value.
arg);
if (ACPI_SUCCESS(status)) {
status =
acpi_ex_create_method(op->named.
data,
op->named.
length,
walk_state);
}
walk_state->operands[0] = NULL;
walk_state->num_operands = 0;
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
}
}
}
/* Pop the scope stack (only if loading a table) */
if (!walk_state->method_node &&
op->common.aml_opcode != AML_EXTERNAL_OP &&
acpi_ns_opens_scope(object_type)) {
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"(%s): Popping scope for Op %p\n",
acpi_ut_get_type_name(object_type), op));
status = acpi_ds_scope_stack_pop(walk_state);
}
return_ACPI_STATUS(status);
}
|
211774.c | /*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/params.h>
#include <openssl/core_names.h>
#include <openssl/dh.h>
#include "crypto/evp.h"
#include "internal/provider.h"
#include "evp_local.h"
#if !defined(FIPS_MODE)
int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type)
{
int ret = -1; /* Assume the worst */
const EVP_CIPHER *cipher = c->cipher;
/*
* For legacy implementations, we detect custom AlgorithmIdentifier
* parameter handling by checking if the function pointer
* cipher->set_asn1_parameters is set. We know that this pointer
* is NULL for provided implementations.
*
* Otherwise, for any implementation, we check the flag
* EVP_CIPH_FLAG_CUSTOM_ASN1. If it isn't set, we apply
* default AI parameter extraction.
*
* Otherwise, for provided implementations, we convert |type| to
* a DER encoded blob and pass to the implementation in OSSL_PARAM
* form.
*
* If none of the above applies, this operation is unsupported.
*/
if (cipher->set_asn1_parameters != NULL) {
ret = cipher->set_asn1_parameters(c, type);
} else if ((EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_CUSTOM_ASN1) == 0) {
switch (EVP_CIPHER_mode(cipher)) {
case EVP_CIPH_WRAP_MODE:
if (EVP_CIPHER_is_a(cipher, SN_id_smime_alg_CMS3DESwrap))
ASN1_TYPE_set(type, V_ASN1_NULL, NULL);
ret = 1;
break;
case EVP_CIPH_GCM_MODE:
case EVP_CIPH_CCM_MODE:
case EVP_CIPH_XTS_MODE:
case EVP_CIPH_OCB_MODE:
ret = -2;
break;
default:
ret = EVP_CIPHER_set_asn1_iv(c, type);
}
} else if (cipher->prov != NULL) {
OSSL_PARAM params[3], *p = params;
unsigned char *der = NULL, *derp;
/*
* We make two passes, the first to get the appropriate buffer size,
* and the second to get the actual value.
*/
*p++ = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_ALG_ID,
NULL, 0);
*p = OSSL_PARAM_construct_end();
if (!EVP_CIPHER_CTX_get_params(c, params))
goto err;
/* ... but, we should get a return size too! */
if (OSSL_PARAM_modified(params)
&& params[0].return_size != 0
&& (der = OPENSSL_malloc(params[0].return_size)) != NULL) {
params[0].data = der;
params[0].data_size = params[0].return_size;
OSSL_PARAM_set_all_unmodified(params);
derp = der;
if (EVP_CIPHER_CTX_get_params(c, params)
&& OSSL_PARAM_modified(params)
&& d2i_ASN1_TYPE(&type, (const unsigned char **)&derp,
params[0].return_size) != NULL) {
ret = 1;
}
OPENSSL_free(der);
}
} else {
ret = -2;
}
err:
if (ret == -2)
EVPerr(EVP_F_EVP_CIPHER_PARAM_TO_ASN1, ASN1_R_UNSUPPORTED_CIPHER);
else if (ret <= 0)
EVPerr(EVP_F_EVP_CIPHER_PARAM_TO_ASN1, EVP_R_CIPHER_PARAMETER_ERROR);
if (ret < -1)
ret = -1;
return ret;
}
int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type)
{
int ret = -1; /* Assume the worst */
const EVP_CIPHER *cipher = c->cipher;
/*
* For legacy implementations, we detect custom AlgorithmIdentifier
* parameter handling by checking if there the function pointer
* cipher->get_asn1_parameters is set. We know that this pointer
* is NULL for provided implementations.
*
* Otherwise, for any implementation, we check the flag
* EVP_CIPH_FLAG_CUSTOM_ASN1. If it isn't set, we apply
* default AI parameter creation.
*
* Otherwise, for provided implementations, we get the AI parameter
* in DER encoded form from the implementation by requesting the
* appropriate OSSL_PARAM and converting the result to a ASN1_TYPE.
*
* If none of the above applies, this operation is unsupported.
*/
if (cipher->get_asn1_parameters != NULL) {
ret = cipher->get_asn1_parameters(c, type);
} else if ((EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_CUSTOM_ASN1) == 0) {
switch (EVP_CIPHER_mode(cipher)) {
case EVP_CIPH_WRAP_MODE:
ret = 1;
break;
case EVP_CIPH_GCM_MODE:
case EVP_CIPH_CCM_MODE:
case EVP_CIPH_XTS_MODE:
case EVP_CIPH_OCB_MODE:
ret = -2;
break;
default:
ret = EVP_CIPHER_get_asn1_iv(c, type);
}
} else if (cipher->prov != NULL) {
OSSL_PARAM params[3], *p = params;
unsigned char *der = NULL;
int derl = -1;
if ((derl = i2d_ASN1_TYPE(type, &der)) >= 0) {
*p++ =
OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_ALG_ID,
der, (size_t)derl);
*p = OSSL_PARAM_construct_end();
if (EVP_CIPHER_CTX_set_params(c, params))
ret = 1;
OPENSSL_free(der);
}
} else {
ret = -2;
}
if (ret == -2)
EVPerr(EVP_F_EVP_CIPHER_ASN1_TO_PARAM, EVP_R_UNSUPPORTED_CIPHER);
else if (ret <= 0)
EVPerr(EVP_F_EVP_CIPHER_ASN1_TO_PARAM, EVP_R_CIPHER_PARAMETER_ERROR);
if (ret < -1)
ret = -1;
return ret;
}
int EVP_CIPHER_get_asn1_iv(EVP_CIPHER_CTX *ctx, ASN1_TYPE *type)
{
int i = 0;
unsigned int l;
if (type != NULL) {
unsigned char iv[EVP_MAX_IV_LENGTH];
l = EVP_CIPHER_CTX_iv_length(ctx);
if (!ossl_assert(l <= sizeof(iv)))
return -1;
i = ASN1_TYPE_get_octetstring(type, iv, l);
if (i != (int)l)
return -1;
if (!EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1))
return -1;
}
return i;
}
int EVP_CIPHER_set_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type)
{
int i = 0;
unsigned int j;
unsigned char *oiv = NULL;
if (type != NULL) {
oiv = (unsigned char *)EVP_CIPHER_CTX_original_iv(c);
j = EVP_CIPHER_CTX_iv_length(c);
OPENSSL_assert(j <= sizeof(c->iv));
i = ASN1_TYPE_set_octetstring(type, oiv, j);
}
return i;
}
#endif /* !defined(FIPS_MODE) */
/* Convert the various cipher NIDs and dummies to a proper OID NID */
int EVP_CIPHER_type(const EVP_CIPHER *ctx)
{
int nid;
nid = EVP_CIPHER_nid(ctx);
switch (nid) {
case NID_rc2_cbc:
case NID_rc2_64_cbc:
case NID_rc2_40_cbc:
return NID_rc2_cbc;
case NID_rc4:
case NID_rc4_40:
return NID_rc4;
case NID_aes_128_cfb128:
case NID_aes_128_cfb8:
case NID_aes_128_cfb1:
return NID_aes_128_cfb128;
case NID_aes_192_cfb128:
case NID_aes_192_cfb8:
case NID_aes_192_cfb1:
return NID_aes_192_cfb128;
case NID_aes_256_cfb128:
case NID_aes_256_cfb8:
case NID_aes_256_cfb1:
return NID_aes_256_cfb128;
case NID_des_cfb64:
case NID_des_cfb8:
case NID_des_cfb1:
return NID_des_cfb64;
case NID_des_ede3_cfb64:
case NID_des_ede3_cfb8:
case NID_des_ede3_cfb1:
return NID_des_cfb64;
default:
#ifdef FIPS_MODE
return NID_undef;
#else
{
/* Check it has an OID and it is valid */
ASN1_OBJECT *otmp = OBJ_nid2obj(nid);
if (OBJ_get0_data(otmp) == NULL)
nid = NID_undef;
ASN1_OBJECT_free(otmp);
return nid;
}
#endif
}
}
int evp_cipher_cache_constants(EVP_CIPHER *cipher)
{
int ok;
size_t ivlen = 0;
size_t blksz = 0;
size_t keylen = 0;
unsigned int mode = 0;
unsigned long flags = 0;
OSSL_PARAM params[6];
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_BLOCK_SIZE, &blksz);
params[1] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_IVLEN, &ivlen);
params[2] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &keylen);
params[3] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_MODE, &mode);
params[4] = OSSL_PARAM_construct_ulong(OSSL_CIPHER_PARAM_FLAGS, &flags);
params[5] = OSSL_PARAM_construct_end();
ok = evp_do_ciph_getparams(cipher, params);
if (ok) {
/* Provided implementations may have a custom cipher_cipher */
if (cipher->prov != NULL && cipher->ccipher != NULL)
flags |= EVP_CIPH_FLAG_CUSTOM_CIPHER;
cipher->block_size = blksz;
cipher->iv_len = ivlen;
cipher->key_len = keylen;
cipher->flags = flags | mode;
}
return ok;
}
int EVP_CIPHER_block_size(const EVP_CIPHER *cipher)
{
return cipher->block_size;
}
int EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *ctx)
{
return EVP_CIPHER_block_size(ctx->cipher);
}
int EVP_CIPHER_impl_ctx_size(const EVP_CIPHER *e)
{
return e->ctx_size;
}
int EVP_Cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, unsigned int inl)
{
if (ctx->cipher->prov != NULL) {
/*
* If the provided implementation has a ccipher function, we use it,
* and translate its return value like this: 0 => -1, 1 => outlen
*
* Otherwise, we call the cupdate function if in != NULL, or cfinal
* if in == NULL. Regardless of which, we return what we got.
*/
int ret = -1;
size_t outl = 0;
size_t blocksize = EVP_CIPHER_CTX_block_size(ctx);
if (ctx->cipher->ccipher != NULL)
ret = ctx->cipher->ccipher(ctx->provctx, out, &outl,
inl + (blocksize == 1 ? 0 : blocksize),
in, (size_t)inl)
? (int)outl : -1;
else if (in != NULL)
ret = ctx->cipher->cupdate(ctx->provctx, out, &outl,
inl + (blocksize == 1 ? 0 : blocksize),
in, (size_t)inl);
else
ret = ctx->cipher->cfinal(ctx->provctx, out, &outl,
blocksize == 1 ? 0 : blocksize);
return ret;
}
return ctx->cipher->do_cipher(ctx, out, in, inl);
}
const EVP_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx)
{
return ctx->cipher;
}
int EVP_CIPHER_CTX_encrypting(const EVP_CIPHER_CTX *ctx)
{
return ctx->encrypt;
}
unsigned long EVP_CIPHER_flags(const EVP_CIPHER *cipher)
{
return cipher->flags;
}
void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx)
{
return ctx->app_data;
}
void EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *ctx, void *data)
{
ctx->app_data = data;
}
void *EVP_CIPHER_CTX_get_cipher_data(const EVP_CIPHER_CTX *ctx)
{
return ctx->cipher_data;
}
void *EVP_CIPHER_CTX_set_cipher_data(EVP_CIPHER_CTX *ctx, void *cipher_data)
{
void *old_cipher_data;
old_cipher_data = ctx->cipher_data;
ctx->cipher_data = cipher_data;
return old_cipher_data;
}
int EVP_CIPHER_iv_length(const EVP_CIPHER *cipher)
{
return cipher->iv_len;
}
int EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *ctx)
{
int rv, len = EVP_CIPHER_iv_length(ctx->cipher);
size_t v = len;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_IVLEN, &v);
rv = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
if (rv == EVP_CTRL_RET_UNSUPPORTED)
goto legacy;
return rv != 0 ? (int)v : -1;
/* TODO (3.0) Remove legacy support */
legacy:
if ((EVP_CIPHER_flags(ctx->cipher) & EVP_CIPH_CUSTOM_IV_LENGTH) != 0) {
rv = EVP_CIPHER_CTX_ctrl((EVP_CIPHER_CTX *)ctx, EVP_CTRL_GET_IVLEN,
0, &len);
return (rv == 1) ? len : -1;
}
return len;
}
int EVP_CIPHER_CTX_tag_length(const EVP_CIPHER_CTX *ctx)
{
int ret;
size_t v = 0;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_TAGLEN, &v);
ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
return ret == 1 ? (int)v : 0;
}
const unsigned char *EVP_CIPHER_CTX_original_iv(const EVP_CIPHER_CTX *ctx)
{
int ok;
const unsigned char *v = ctx->oiv;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
params[0] =
OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_IV,
(void **)&v, sizeof(ctx->oiv));
ok = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
return ok != 0 ? v : NULL;
}
/*
* OSSL_PARAM_OCTET_PTR gets us the pointer to the running IV in the provider
*/
const unsigned char *EVP_CIPHER_CTX_iv(const EVP_CIPHER_CTX *ctx)
{
int ok;
const unsigned char *v = ctx->iv;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
params[0] =
OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_IV, (void **)&v,
sizeof(ctx->iv));
ok = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
return ok != 0 ? v : NULL;
}
unsigned char *EVP_CIPHER_CTX_iv_noconst(EVP_CIPHER_CTX *ctx)
{
int ok;
unsigned char *v = ctx->iv;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
params[0] =
OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_IV, (void **)&v,
sizeof(ctx->iv));
ok = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
return ok != 0 ? v : NULL;
}
unsigned char *EVP_CIPHER_CTX_buf_noconst(EVP_CIPHER_CTX *ctx)
{
return ctx->buf;
}
int EVP_CIPHER_CTX_num(const EVP_CIPHER_CTX *ctx)
{
int ok;
unsigned int v = (unsigned int)ctx->num;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_NUM, &v);
ok = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
return ok != 0 ? (int)v : EVP_CTRL_RET_UNSUPPORTED;
}
int EVP_CIPHER_CTX_set_num(EVP_CIPHER_CTX *ctx, int num)
{
int ok;
unsigned int n = (unsigned int)num;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_NUM, &n);
ok = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->provctx, params);
if (ok != 0)
ctx->num = (int)n;
return ok != 0;
}
int EVP_CIPHER_key_length(const EVP_CIPHER *cipher)
{
return cipher->key_len;
}
int EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *ctx)
{
int ok;
size_t v = ctx->key_len;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &v);
ok = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
return ok != 0 ? (int)v : EVP_CTRL_RET_UNSUPPORTED;
}
int EVP_CIPHER_nid(const EVP_CIPHER *cipher)
{
return cipher->nid;
}
int EVP_CIPHER_CTX_nid(const EVP_CIPHER_CTX *ctx)
{
return ctx->cipher->nid;
}
int EVP_CIPHER_is_a(const EVP_CIPHER *cipher, const char *name)
{
if (cipher->prov != NULL)
return evp_is_a(cipher->prov, cipher->name_id, NULL, name);
return evp_is_a(NULL, 0, EVP_CIPHER_name(cipher), name);
}
int EVP_CIPHER_number(const EVP_CIPHER *cipher)
{
return cipher->name_id;
}
const char *EVP_CIPHER_name(const EVP_CIPHER *cipher)
{
if (cipher->prov != NULL)
return evp_first_name(cipher->prov, cipher->name_id);
#ifndef FIPS_MODE
return OBJ_nid2sn(EVP_CIPHER_nid(cipher));
#else
return NULL;
#endif
}
void EVP_CIPHER_names_do_all(const EVP_CIPHER *cipher,
void (*fn)(const char *name, void *data),
void *data)
{
if (cipher->prov != NULL)
evp_names_do_all(cipher->prov, cipher->name_id, fn, data);
}
const OSSL_PROVIDER *EVP_CIPHER_provider(const EVP_CIPHER *cipher)
{
return cipher->prov;
}
int EVP_CIPHER_mode(const EVP_CIPHER *cipher)
{
return EVP_CIPHER_flags(cipher) & EVP_CIPH_MODE;
}
int EVP_MD_is_a(const EVP_MD *md, const char *name)
{
if (md->prov != NULL)
return evp_is_a(md->prov, md->name_id, NULL, name);
return evp_is_a(NULL, 0, EVP_MD_name(md), name);
}
int EVP_MD_number(const EVP_MD *md)
{
return md->name_id;
}
const char *EVP_MD_name(const EVP_MD *md)
{
if (md->prov != NULL)
return evp_first_name(md->prov, md->name_id);
#ifndef FIPS_MODE
return OBJ_nid2sn(EVP_MD_nid(md));
#else
return NULL;
#endif
}
void EVP_MD_names_do_all(const EVP_MD *md,
void (*fn)(const char *name, void *data),
void *data)
{
if (md->prov != NULL)
evp_names_do_all(md->prov, md->name_id, fn, data);
}
const OSSL_PROVIDER *EVP_MD_provider(const EVP_MD *md)
{
return md->prov;
}
int EVP_MD_block_size(const EVP_MD *md)
{
int ok;
size_t v = md->block_size;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
if (md == NULL) {
EVPerr(EVP_F_EVP_MD_BLOCK_SIZE, EVP_R_MESSAGE_DIGEST_IS_NULL);
return -1;
}
params[0] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_BLOCK_SIZE, &v);
ok = evp_do_md_getparams(md, params);
return ok != 0 ? (int)v : -1;
}
int EVP_MD_type(const EVP_MD *md)
{
return md->type;
}
int EVP_MD_pkey_type(const EVP_MD *md)
{
return md->pkey_type;
}
int EVP_MD_size(const EVP_MD *md)
{
int ok;
size_t v = md->md_size;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
if (md == NULL) {
EVPerr(EVP_F_EVP_MD_SIZE, EVP_R_MESSAGE_DIGEST_IS_NULL);
return -1;
}
params[0] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_SIZE, &v);
ok = evp_do_md_getparams(md, params);
return ok != 0 ? (int)v : -1;
}
unsigned long EVP_MD_flags(const EVP_MD *md)
{
int ok;
unsigned long v = md->flags;
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
params[0] = OSSL_PARAM_construct_ulong(OSSL_CIPHER_PARAM_FLAGS, &v);
ok = evp_do_md_getparams(md, params);
return ok != 0 ? v : 0;
}
EVP_MD *EVP_MD_meth_new(int md_type, int pkey_type)
{
EVP_MD *md = evp_md_new();
if (md != NULL) {
md->type = md_type;
md->pkey_type = pkey_type;
}
return md;
}
EVP_MD *EVP_MD_meth_dup(const EVP_MD *md)
{
EVP_MD *to = NULL;
/*
* Non-legacy EVP_MDs can't be duplicated like this.
* Use EVP_MD_up_ref() instead.
*/
if (md->prov != NULL)
return NULL;
if ((to = EVP_MD_meth_new(md->type, md->pkey_type)) != NULL) {
CRYPTO_RWLOCK *lock = to->lock;
memcpy(to, md, sizeof(*to));
to->lock = lock;
}
return to;
}
void EVP_MD_meth_free(EVP_MD *md)
{
EVP_MD_free(md);
}
int EVP_MD_meth_set_input_blocksize(EVP_MD *md, int blocksize)
{
if (md->block_size != 0)
return 0;
md->block_size = blocksize;
return 1;
}
int EVP_MD_meth_set_result_size(EVP_MD *md, int resultsize)
{
if (md->md_size != 0)
return 0;
md->md_size = resultsize;
return 1;
}
int EVP_MD_meth_set_app_datasize(EVP_MD *md, int datasize)
{
if (md->ctx_size != 0)
return 0;
md->ctx_size = datasize;
return 1;
}
int EVP_MD_meth_set_flags(EVP_MD *md, unsigned long flags)
{
if (md->flags != 0)
return 0;
md->flags = flags;
return 1;
}
int EVP_MD_meth_set_init(EVP_MD *md, int (*init)(EVP_MD_CTX *ctx))
{
if (md->init != NULL)
return 0;
md->init = init;
return 1;
}
int EVP_MD_meth_set_update(EVP_MD *md, int (*update)(EVP_MD_CTX *ctx,
const void *data,
size_t count))
{
if (md->update != NULL)
return 0;
md->update = update;
return 1;
}
int EVP_MD_meth_set_final(EVP_MD *md, int (*final)(EVP_MD_CTX *ctx,
unsigned char *md))
{
if (md->final != NULL)
return 0;
md->final = final;
return 1;
}
int EVP_MD_meth_set_copy(EVP_MD *md, int (*copy)(EVP_MD_CTX *to,
const EVP_MD_CTX *from))
{
if (md->copy != NULL)
return 0;
md->copy = copy;
return 1;
}
int EVP_MD_meth_set_cleanup(EVP_MD *md, int (*cleanup)(EVP_MD_CTX *ctx))
{
if (md->cleanup != NULL)
return 0;
md->cleanup = cleanup;
return 1;
}
int EVP_MD_meth_set_ctrl(EVP_MD *md, int (*ctrl)(EVP_MD_CTX *ctx, int cmd,
int p1, void *p2))
{
if (md->md_ctrl != NULL)
return 0;
md->md_ctrl = ctrl;
return 1;
}
int EVP_MD_meth_get_input_blocksize(const EVP_MD *md)
{
return md->block_size;
}
int EVP_MD_meth_get_result_size(const EVP_MD *md)
{
return md->md_size;
}
int EVP_MD_meth_get_app_datasize(const EVP_MD *md)
{
return md->ctx_size;
}
unsigned long EVP_MD_meth_get_flags(const EVP_MD *md)
{
return md->flags;
}
int (*EVP_MD_meth_get_init(const EVP_MD *md))(EVP_MD_CTX *ctx)
{
return md->init;
}
int (*EVP_MD_meth_get_update(const EVP_MD *md))(EVP_MD_CTX *ctx,
const void *data,
size_t count)
{
return md->update;
}
int (*EVP_MD_meth_get_final(const EVP_MD *md))(EVP_MD_CTX *ctx,
unsigned char *md)
{
return md->final;
}
int (*EVP_MD_meth_get_copy(const EVP_MD *md))(EVP_MD_CTX *to,
const EVP_MD_CTX *from)
{
return md->copy;
}
int (*EVP_MD_meth_get_cleanup(const EVP_MD *md))(EVP_MD_CTX *ctx)
{
return md->cleanup;
}
int (*EVP_MD_meth_get_ctrl(const EVP_MD *md))(EVP_MD_CTX *ctx, int cmd,
int p1, void *p2)
{
return md->md_ctrl;
}
const EVP_MD *EVP_MD_CTX_md(const EVP_MD_CTX *ctx)
{
if (ctx == NULL)
return NULL;
return ctx->reqdigest;
}
EVP_PKEY_CTX *EVP_MD_CTX_pkey_ctx(const EVP_MD_CTX *ctx)
{
return ctx->pctx;
}
#if !defined(FIPS_MODE)
/* TODO(3.0): EVP_DigestSign* not yet supported in FIPS module */
void EVP_MD_CTX_set_pkey_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pctx)
{
/*
* it's reasonable to set NULL pctx (a.k.a clear the ctx->pctx), so
* we have to deal with the cleanup job here.
*/
if (!EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX))
EVP_PKEY_CTX_free(ctx->pctx);
ctx->pctx = pctx;
if (pctx != NULL) {
/* make sure pctx is not freed when destroying EVP_MD_CTX */
EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX);
} else {
EVP_MD_CTX_clear_flags(ctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX);
}
}
#endif /* !defined(FIPS_MODE) */
void *EVP_MD_CTX_md_data(const EVP_MD_CTX *ctx)
{
return ctx->md_data;
}
int (*EVP_MD_CTX_update_fn(EVP_MD_CTX *ctx))(EVP_MD_CTX *ctx,
const void *data, size_t count)
{
return ctx->update;
}
void EVP_MD_CTX_set_update_fn(EVP_MD_CTX *ctx,
int (*update) (EVP_MD_CTX *ctx,
const void *data, size_t count))
{
ctx->update = update;
}
void EVP_MD_CTX_set_flags(EVP_MD_CTX *ctx, int flags)
{
ctx->flags |= flags;
}
void EVP_MD_CTX_clear_flags(EVP_MD_CTX *ctx, int flags)
{
ctx->flags &= ~flags;
}
int EVP_MD_CTX_test_flags(const EVP_MD_CTX *ctx, int flags)
{
return (ctx->flags & flags);
}
void EVP_CIPHER_CTX_set_flags(EVP_CIPHER_CTX *ctx, int flags)
{
ctx->flags |= flags;
}
void EVP_CIPHER_CTX_clear_flags(EVP_CIPHER_CTX *ctx, int flags)
{
ctx->flags &= ~flags;
}
int EVP_CIPHER_CTX_test_flags(const EVP_CIPHER_CTX *ctx, int flags)
{
return (ctx->flags & flags);
}
int EVP_str2ctrl(int (*cb)(void *ctx, int cmd, void *buf, size_t buflen),
void *ctx, int cmd, const char *value)
{
size_t len;
len = strlen(value);
if (len > INT_MAX)
return -1;
return cb(ctx, cmd, (void *)value, len);
}
int EVP_hex2ctrl(int (*cb)(void *ctx, int cmd, void *buf, size_t buflen),
void *ctx, int cmd, const char *hex)
{
unsigned char *bin;
long binlen;
int rv = -1;
bin = OPENSSL_hexstr2buf(hex, &binlen);
if (bin == NULL)
return 0;
if (binlen <= INT_MAX)
rv = cb(ctx, cmd, bin, binlen);
OPENSSL_free(bin);
return rv;
}
|
299870.c | /******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#include "_hypre_parcsr_ls.h"
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESCreate
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESCreate( MPI_Comm comm, HYPRE_Solver *solver )
{
hypre_FlexGMRESFunctions * fgmres_functions;
if (!solver)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
fgmres_functions =
hypre_FlexGMRESFunctionsCreate(
hypre_ParKrylovCAlloc, hypre_ParKrylovFree, hypre_ParKrylovCommInfo,
hypre_ParKrylovCreateVector,
hypre_ParKrylovCreateVectorArray,
hypre_ParKrylovDestroyVector, hypre_ParKrylovMatvecCreate,
hypre_ParKrylovMatvec, hypre_ParKrylovMatvecDestroy,
hypre_ParKrylovInnerProd, hypre_ParKrylovCopyVector,
hypre_ParKrylovClearVector,
hypre_ParKrylovScaleVector, hypre_ParKrylovAxpy,
hypre_ParKrylovIdentitySetup, hypre_ParKrylovIdentity );
*solver = ( (HYPRE_Solver) hypre_FlexGMRESCreate( fgmres_functions ) );
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESDestroy
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESDestroy( HYPRE_Solver solver )
{
return( hypre_FlexGMRESDestroy( (void *) solver ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESSetup
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESSetup( HYPRE_Solver solver,
HYPRE_ParCSRMatrix A,
HYPRE_ParVector b,
HYPRE_ParVector x )
{
return( HYPRE_FlexGMRESSetup( solver,
(HYPRE_Matrix) A,
(HYPRE_Vector) b,
(HYPRE_Vector) x ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESSolve
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESSolve( HYPRE_Solver solver,
HYPRE_ParCSRMatrix A,
HYPRE_ParVector b,
HYPRE_ParVector x )
{
return( HYPRE_FlexGMRESSolve( solver,
(HYPRE_Matrix) A,
(HYPRE_Vector) b,
(HYPRE_Vector) x ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESSetKDim
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESSetKDim( HYPRE_Solver solver,
HYPRE_Int k_dim )
{
return( HYPRE_FlexGMRESSetKDim( solver, k_dim ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESSetTol
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESSetTol( HYPRE_Solver solver,
HYPRE_Real tol )
{
return( HYPRE_FlexGMRESSetTol( solver, tol ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESSetAbsoluteTol
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESSetAbsoluteTol( HYPRE_Solver solver,
HYPRE_Real a_tol )
{
return( HYPRE_FlexGMRESSetAbsoluteTol( solver, a_tol ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESSetMinIter
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESSetMinIter( HYPRE_Solver solver,
HYPRE_Int min_iter )
{
return( HYPRE_FlexGMRESSetMinIter( solver, min_iter ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESSetMaxIter
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESSetMaxIter( HYPRE_Solver solver,
HYPRE_Int max_iter )
{
return( HYPRE_FlexGMRESSetMaxIter( solver, max_iter ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESSetPrecond
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESSetPrecond( HYPRE_Solver solver,
HYPRE_PtrToParSolverFcn precond,
HYPRE_PtrToParSolverFcn precond_setup,
HYPRE_Solver precond_solver )
{
return( HYPRE_FlexGMRESSetPrecond( solver,
(HYPRE_PtrToSolverFcn) precond,
(HYPRE_PtrToSolverFcn) precond_setup,
precond_solver ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESGetPrecond
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESGetPrecond( HYPRE_Solver solver,
HYPRE_Solver *precond_data_ptr )
{
return( HYPRE_FlexGMRESGetPrecond( solver, precond_data_ptr ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESSetLogging
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESSetLogging( HYPRE_Solver solver,
HYPRE_Int logging)
{
return( HYPRE_FlexGMRESSetLogging( solver, logging ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESSetPrintLevel
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESSetPrintLevel( HYPRE_Solver solver,
HYPRE_Int print_level)
{
return( HYPRE_FlexGMRESSetPrintLevel( solver, print_level ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESGetNumIterations
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESGetNumIterations( HYPRE_Solver solver,
HYPRE_Int *num_iterations )
{
return( HYPRE_FlexGMRESGetNumIterations( solver, num_iterations ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESGetFinalRelativeResidualNorm
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESGetFinalRelativeResidualNorm( HYPRE_Solver solver,
HYPRE_Real *norm )
{
return( HYPRE_FlexGMRESGetFinalRelativeResidualNorm( solver, norm ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESGetResidual
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRFlexGMRESGetResidual( HYPRE_Solver solver,
HYPRE_ParVector *residual)
{
return( HYPRE_FlexGMRESGetResidual( solver, (void *) residual ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRFlexGMRESSetModifyPC
*--------------------------------------------------------------------------*/
HYPRE_Int HYPRE_ParCSRFlexGMRESSetModifyPC( HYPRE_Solver solver,
HYPRE_PtrToModifyPCFcn modify_pc)
{
return ( HYPRE_FlexGMRESSetModifyPC( solver,
(HYPRE_PtrToModifyPCFcn) modify_pc));
}
|
539739.c | /* NOCW */
#include <stdio.h>
#ifdef _OSD_POSIX
#ifndef CHARSET_EBCDIC
#define CHARSET_EBCDIC 1
#endif
#endif
#ifdef CHARSET_EBCDIC
#include <openssl/ebcdic.h>
#endif
#include <openssl/crypto.h>
/* This version of crypt has been developed from my MIT compatible
* DES library.
* Eric Young ([email protected])
*/
/* Modification by Jens Kupferschmidt (Cu)
* I have included directive PARA for shared memory computers.
* I have included a directive LONGCRYPT to using this routine to cipher
* passwords with more then 8 bytes like HP-UX 10.x it used. The MAXPLEN
* definition is the maximum of length of password and can changed. I have
* defined 24.
*/
#include "des_locl.h"
/* Added more values to handle illegal salt values the way normal
* crypt() implementations do. The patch was sent by
* Bjorn Gronvall <[email protected]>
*/
static unsigned const char con_salt[128]={
0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,
0xDA,0xDB,0xDC,0xDD,0xDE,0xDF,0xE0,0xE1,
0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,
0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,
0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,
0xFA,0xFB,0xFC,0xFD,0xFE,0xFF,0x00,0x01,
0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,
0x0A,0x0B,0x05,0x06,0x07,0x08,0x09,0x0A,
0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,
0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,
0x1B,0x1C,0x1D,0x1E,0x1F,0x20,0x21,0x22,
0x23,0x24,0x25,0x20,0x21,0x22,0x23,0x24,
0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,
0x2D,0x2E,0x2F,0x30,0x31,0x32,0x33,0x34,
0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,
0x3D,0x3E,0x3F,0x40,0x41,0x42,0x43,0x44,
};
static unsigned const char cov_2char[64]={
0x2E,0x2F,0x30,0x31,0x32,0x33,0x34,0x35,
0x36,0x37,0x38,0x39,0x41,0x42,0x43,0x44,
0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,
0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54,
0x55,0x56,0x57,0x58,0x59,0x5A,0x61,0x62,
0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,
0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,
0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A
};
char *DES_crypt(const char *buf, const char *salt)
{
static char buff[14];
#ifndef CHARSET_EBCDIC
return(DES_fcrypt(buf,salt,buff));
#else
char e_salt[2+1];
char e_buf[32+1]; /* replace 32 by 8 ? */
char *ret;
/* Copy at most 2 chars of salt */
if ((e_salt[0] = salt[0]) != '\0')
e_salt[1] = salt[1];
/* Copy at most 32 chars of password */
strncpy (e_buf, buf, sizeof(e_buf));
/* Make sure we have a delimiter */
e_salt[sizeof(e_salt)-1] = e_buf[sizeof(e_buf)-1] = '\0';
/* Convert the e_salt to ASCII, as that's what DES_fcrypt works on */
ebcdic2ascii(e_salt, e_salt, sizeof e_salt);
/* Convert the cleartext password to ASCII */
ebcdic2ascii(e_buf, e_buf, sizeof e_buf);
/* Encrypt it (from/to ASCII) */
ret = DES_fcrypt(e_buf,e_salt,buff);
/* Convert the result back to EBCDIC */
ascii2ebcdic(ret, ret, strlen(ret));
return ret;
#endif
}
char *DES_fcrypt(const char *buf, const char *salt, char *ret)
{
unsigned int i,j,x,y;
DES_LONG Eswap0,Eswap1;
DES_LONG out[2],ll;
DES_cblock key;
DES_key_schedule ks;
unsigned char bb[9];
unsigned char *b=bb;
unsigned char c,u;
/* eay 25/08/92
* If you call crypt("pwd","*") as often happens when you
* have * as the pwd field in /etc/passwd, the function
* returns *\0XXXXXXXXX
* The \0 makes the string look like * so the pwd "*" would
* crypt to "*". This was found when replacing the crypt in
* our shared libraries. People found that the disabled
* accounts effectively had no passwd :-(. */
#ifndef CHARSET_EBCDIC
x=ret[0]=((salt[0] == '\0')?'A':salt[0]);
Eswap0=con_salt[x]<<2;
x=ret[1]=((salt[1] == '\0')?'A':salt[1]);
Eswap1=con_salt[x]<<6;
#else
x=ret[0]=((salt[0] == '\0')?os_toascii['A']:salt[0]);
Eswap0=con_salt[x]<<2;
x=ret[1]=((salt[1] == '\0')?os_toascii['A']:salt[1]);
Eswap1=con_salt[x]<<6;
#endif
/* EAY
r=strlen(buf);
r=(r+7)/8;
*/
for (i=0; i<8; i++)
{
c= *(buf++);
if (!c) break;
key[i]=(c<<1);
}
for (; i<8; i++)
key[i]=0;
DES_set_key_unchecked(&key,&ks);
fcrypt_body(&(out[0]),&ks,Eswap0,Eswap1);
ll=out[0]; l2c(ll,b);
ll=out[1]; l2c(ll,b);
y=0;
u=0x80;
bb[8]=0;
for (i=2; i<13; i++)
{
c=0;
for (j=0; j<6; j++)
{
c<<=1;
if (bb[y] & u) c|=1;
u>>=1;
if (!u)
{
y++;
u=0x80;
}
}
ret[i]=cov_2char[c];
}
ret[13]='\0';
return(ret);
}
|
236032.c | /******************************************************************************
* The MIT License
*
* Copyright (c) 2010 Perry Hung.
* Copyright (c) 2011 LeafLabs, LLC.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*****************************************************************************/
/**
* @file libmaple/stm32f1/rcc.c
* @brief STM32F1 RCC.
*/
#include <libmaple/rcc.h>
#include <libmaple/libmaple.h>
#include <libmaple/bitband.h>
#include "rcc_private.h"
#define APB1 RCC_APB1
#define APB2 RCC_APB2
#define AHB RCC_AHB
/* Device descriptor table, maps rcc_clk_id onto bus and enable/reset
* register bit numbers. */
const struct rcc_dev_info rcc_dev_table[] = {
[RCC_GPIOA] = { .clk_domain = APB2, .line_num = 2 },
[RCC_GPIOB] = { .clk_domain = APB2, .line_num = 3 },
[RCC_GPIOC] = { .clk_domain = APB2, .line_num = 4 },
[RCC_GPIOD] = { .clk_domain = APB2, .line_num = 5 },
[RCC_AFIO] = { .clk_domain = APB2, .line_num = 0 },
[RCC_ADC1] = { .clk_domain = APB2, .line_num = 9 },
[RCC_ADC2] = { .clk_domain = APB2, .line_num = 10 },
[RCC_ADC3] = { .clk_domain = APB2, .line_num = 15 },
[RCC_USART1] = { .clk_domain = APB2, .line_num = 14 },
[RCC_USART2] = { .clk_domain = APB1, .line_num = 17 },
[RCC_USART3] = { .clk_domain = APB1, .line_num = 18 },
[RCC_TIMER1] = { .clk_domain = APB2, .line_num = 11 },
[RCC_TIMER2] = { .clk_domain = APB1, .line_num = 0 },
[RCC_TIMER3] = { .clk_domain = APB1, .line_num = 1 },
[RCC_TIMER4] = { .clk_domain = APB1, .line_num = 2 },
[RCC_SPI1] = { .clk_domain = APB2, .line_num = 12 },
[RCC_SPI2] = { .clk_domain = APB1, .line_num = 14 },
[RCC_DMA1] = { .clk_domain = AHB, .line_num = 0 },
[RCC_PWR] = { .clk_domain = APB1, .line_num = 28},
[RCC_BKP] = { .clk_domain = APB1, .line_num = 27},
[RCC_I2C1] = { .clk_domain = APB1, .line_num = 21 },
[RCC_I2C2] = { .clk_domain = APB1, .line_num = 22 },
[RCC_CRC] = { .clk_domain = AHB, .line_num = 6},
[RCC_FLITF] = { .clk_domain = AHB, .line_num = 4},
[RCC_SRAM] = { .clk_domain = AHB, .line_num = 2},
[RCC_USB] = { .clk_domain = APB1, .line_num = 23},
#if defined(STM32_HIGH_DENSITY) || defined(STM32_XL_DENSITY)
[RCC_GPIOE] = { .clk_domain = APB2, .line_num = 6 },
[RCC_GPIOF] = { .clk_domain = APB2, .line_num = 7 },
[RCC_GPIOG] = { .clk_domain = APB2, .line_num = 8 },
[RCC_UART4] = { .clk_domain = APB1, .line_num = 19 },
[RCC_UART5] = { .clk_domain = APB1, .line_num = 20 },
[RCC_TIMER5] = { .clk_domain = APB1, .line_num = 3 },
[RCC_TIMER6] = { .clk_domain = APB1, .line_num = 4 },
[RCC_TIMER7] = { .clk_domain = APB1, .line_num = 5 },
[RCC_TIMER8] = { .clk_domain = APB2, .line_num = 13 },
[RCC_FSMC] = { .clk_domain = AHB, .line_num = 8 },
[RCC_DAC] = { .clk_domain = APB1, .line_num = 29 },
[RCC_DMA2] = { .clk_domain = AHB, .line_num = 1 },
[RCC_SDIO] = { .clk_domain = AHB, .line_num = 10 },
[RCC_SPI3] = { .clk_domain = APB1, .line_num = 15 },
#endif
#ifdef STM32_XL_DENSITY
[RCC_TIMER9] = { .clk_domain = APB2, .line_num = 19 },
[RCC_TIMER10] = { .clk_domain = APB2, .line_num = 20 },
[RCC_TIMER11] = { .clk_domain = APB2, .line_num = 21 },
[RCC_TIMER12] = { .clk_domain = APB1, .line_num = 6 },
[RCC_TIMER13] = { .clk_domain = APB1, .line_num = 7 },
[RCC_TIMER14] = { .clk_domain = APB1, .line_num = 8 },
#endif
};
__deprecated
void rcc_clk_init(rcc_sysclk_src sysclk_src,
rcc_pllsrc pll_src,
rcc_pll_multiplier pll_mul) {
/* Assume that we're going to clock the chip off the PLL, fed by
* the HSE */
ASSERT(sysclk_src == RCC_CLKSRC_PLL &&
pll_src == RCC_PLLSRC_HSE);
RCC_BASE->CFGR = pll_src | pll_mul;
/* Turn on, and wait for, HSE. */
rcc_turn_on_clk(RCC_CLK_HSE);
while (!rcc_is_clk_ready(RCC_CLK_HSE))
;
/* Do the same for the main PLL. */
rcc_turn_on_clk(RCC_CLK_PLL);
while(!rcc_is_clk_ready(RCC_CLK_PLL))
;
/* Finally, switch over to the PLL. */
rcc_switch_sysclk(RCC_CLKSRC_PLL);
}
/* pll_cfg->data must point to a valid struct stm32f1_rcc_pll_data. */
void rcc_configure_pll(rcc_pll_cfg *pll_cfg) {
stm32f1_rcc_pll_data *data = pll_cfg->data;
rcc_pll_multiplier pll_mul = data->pll_mul;
uint32 cfgr;
/* Check that the PLL is disabled. */
ASSERT_FAULT(!rcc_is_clk_on(RCC_CLK_PLL));
cfgr = RCC_BASE->CFGR;
cfgr &= ~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLMUL);
cfgr |= pll_cfg->pllsrc | pll_mul;
RCC_BASE->CFGR = cfgr;
}
void rcc_clk_enable(rcc_clk_id id) {
static __io uint32* enable_regs[] = {
[APB1] = &RCC_BASE->APB1ENR,
[APB2] = &RCC_BASE->APB2ENR,
[AHB] = &RCC_BASE->AHBENR,
};
rcc_do_clk_enable(enable_regs, id);
}
void rcc_reset_dev(rcc_clk_id id) {
static __io uint32* reset_regs[] = {
[APB1] = &RCC_BASE->APB1RSTR,
[APB2] = &RCC_BASE->APB2RSTR,
};
rcc_do_reset_dev(reset_regs, id);
}
void rcc_set_prescaler(rcc_prescaler prescaler, uint32 divider) {
static const uint32 masks[] = {
[RCC_PRESCALER_AHB] = RCC_CFGR_HPRE,
[RCC_PRESCALER_APB1] = RCC_CFGR_PPRE1,
[RCC_PRESCALER_APB2] = RCC_CFGR_PPRE2,
[RCC_PRESCALER_USB] = RCC_CFGR_USBPRE,
[RCC_PRESCALER_ADC] = RCC_CFGR_ADCPRE,
};
rcc_do_set_prescaler(masks, prescaler, divider);
}
|
657258.c | /*===-- X86DisassemblerDecoder.c - Disassembler decoder ------------*- C -*-===*
*
* The LLVM Compiler Infrastructure
*
* This file is distributed under the University of Illinois Open Source
* License. See LICENSE.TXT for details.
*
*===----------------------------------------------------------------------===*
*
* This file is part of the X86 Disassembler.
* It contains the implementation of the instruction decoder.
* Documentation for the disassembler can be found in X86Disassembler.h.
*
*===----------------------------------------------------------------------===*/
#include <stdarg.h> /* for va_*() */
#include <stdio.h> /* for vsnprintf() */
#include <stdlib.h> /* for exit() */
#include <string.h> /* for memset() */
#include "X86DisassemblerDecoder.h"
#include "X86GenDisassemblerTables.inc"
#define TRUE 1
#define FALSE 0
typedef int8_t bool;
#ifndef NDEBUG
#define debug(s) do { x86DisassemblerDebug(__FILE__, __LINE__, s); } while (0)
#else
#define debug(s) do { } while (0)
#endif
/*
* contextForAttrs - Client for the instruction context table. Takes a set of
* attributes and returns the appropriate decode context.
*
* @param attrMask - Attributes, from the enumeration attributeBits.
* @return - The InstructionContext to use when looking up an
* an instruction with these attributes.
*/
static InstructionContext contextForAttrs(uint8_t attrMask) {
return CONTEXTS_SYM[attrMask];
}
/*
* modRMRequired - Reads the appropriate instruction table to determine whether
* the ModR/M byte is required to decode a particular instruction.
*
* @param type - The opcode type (i.e., how many bytes it has).
* @param insnContext - The context for the instruction, as returned by
* contextForAttrs.
* @param opcode - The last byte of the instruction's opcode, not counting
* ModR/M extensions and escapes.
* @return - TRUE if the ModR/M byte is required, FALSE otherwise.
*/
static int modRMRequired(OpcodeType type,
InstructionContext insnContext,
uint8_t opcode) {
const struct ContextDecision* decision = 0;
switch (type) {
case ONEBYTE:
decision = &ONEBYTE_SYM;
break;
case TWOBYTE:
decision = &TWOBYTE_SYM;
break;
case THREEBYTE_38:
decision = &THREEBYTE38_SYM;
break;
case THREEBYTE_3A:
decision = &THREEBYTE3A_SYM;
break;
case THREEBYTE_A6:
decision = &THREEBYTEA6_SYM;
break;
case THREEBYTE_A7:
decision = &THREEBYTEA7_SYM;
break;
}
return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].
modrm_type != MODRM_ONEENTRY;
}
/*
* decode - Reads the appropriate instruction table to obtain the unique ID of
* an instruction.
*
* @param type - See modRMRequired().
* @param insnContext - See modRMRequired().
* @param opcode - See modRMRequired().
* @param modRM - The ModR/M byte if required, or any value if not.
* @return - The UID of the instruction, or 0 on failure.
*/
static InstrUID decode(OpcodeType type,
InstructionContext insnContext,
uint8_t opcode,
uint8_t modRM) {
const struct ModRMDecision* dec = 0;
switch (type) {
case ONEBYTE:
dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
break;
case TWOBYTE:
dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
break;
case THREEBYTE_38:
dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
break;
case THREEBYTE_3A:
dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
break;
case THREEBYTE_A6:
dec = &THREEBYTEA6_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
break;
case THREEBYTE_A7:
dec = &THREEBYTEA7_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
break;
}
switch (dec->modrm_type) {
default:
debug("Corrupt table! Unknown modrm_type");
return 0;
case MODRM_ONEENTRY:
return modRMTable[dec->instructionIDs];
case MODRM_SPLITRM:
if (modFromModRM(modRM) == 0x3)
return modRMTable[dec->instructionIDs+1];
return modRMTable[dec->instructionIDs];
case MODRM_SPLITREG:
if (modFromModRM(modRM) == 0x3)
return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)+8];
return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
case MODRM_SPLITMISC:
if (modFromModRM(modRM) == 0x3)
return modRMTable[dec->instructionIDs+(modRM & 0x3f)+8];
return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
case MODRM_FULL:
return modRMTable[dec->instructionIDs+modRM];
}
}
/*
* specifierForUID - Given a UID, returns the name and operand specification for
* that instruction.
*
* @param uid - The unique ID for the instruction. This should be returned by
* decode(); specifierForUID will not check bounds.
* @return - A pointer to the specification for that instruction.
*/
static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
return &INSTRUCTIONS_SYM[uid];
}
/*
* consumeByte - Uses the reader function provided by the user to consume one
* byte from the instruction's memory and advance the cursor.
*
* @param insn - The instruction with the reader function to use. The cursor
* for this instruction is advanced.
* @param byte - A pointer to a pre-allocated memory buffer to be populated
* with the data read.
* @return - 0 if the read was successful; nonzero otherwise.
*/
static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
if (!ret)
++(insn->readerCursor);
return ret;
}
/*
* lookAtByte - Like consumeByte, but does not advance the cursor.
*
* @param insn - See consumeByte().
* @param byte - See consumeByte().
* @return - See consumeByte().
*/
static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
return insn->reader(insn->readerArg, byte, insn->readerCursor);
}
static void unconsumeByte(struct InternalInstruction* insn) {
insn->readerCursor--;
}
#define CONSUME_FUNC(name, type) \
static int name(struct InternalInstruction* insn, type* ptr) { \
type combined = 0; \
unsigned offset; \
for (offset = 0; offset < sizeof(type); ++offset) { \
uint8_t byte; \
int ret = insn->reader(insn->readerArg, \
&byte, \
insn->readerCursor + offset); \
if (ret) \
return ret; \
combined = combined | ((uint64_t)byte << (offset * 8)); \
} \
*ptr = combined; \
insn->readerCursor += sizeof(type); \
return 0; \
}
/*
* consume* - Use the reader function provided by the user to consume data
* values of various sizes from the instruction's memory and advance the
* cursor appropriately. These readers perform endian conversion.
*
* @param insn - See consumeByte().
* @param ptr - A pointer to a pre-allocated memory of appropriate size to
* be populated with the data read.
* @return - See consumeByte().
*/
CONSUME_FUNC(consumeInt8, int8_t)
CONSUME_FUNC(consumeInt16, int16_t)
CONSUME_FUNC(consumeInt32, int32_t)
CONSUME_FUNC(consumeUInt16, uint16_t)
CONSUME_FUNC(consumeUInt32, uint32_t)
CONSUME_FUNC(consumeUInt64, uint64_t)
/*
* dbgprintf - Uses the logging function provided by the user to log a single
* message, typically without a carriage-return.
*
* @param insn - The instruction containing the logging function.
* @param format - See printf().
* @param ... - See printf().
*/
static void dbgprintf(struct InternalInstruction* insn,
const char* format,
...) {
char buffer[256];
va_list ap;
if (!insn->dlog)
return;
va_start(ap, format);
(void)vsnprintf(buffer, sizeof(buffer), format, ap);
va_end(ap);
insn->dlog(insn->dlogArg, buffer);
return;
}
/*
* setPrefixPresent - Marks that a particular prefix is present at a particular
* location.
*
* @param insn - The instruction to be marked as having the prefix.
* @param prefix - The prefix that is present.
* @param location - The location where the prefix is located (in the address
* space of the instruction's reader).
*/
static void setPrefixPresent(struct InternalInstruction* insn,
uint8_t prefix,
uint64_t location)
{
insn->prefixPresent[prefix] = 1;
insn->prefixLocations[prefix] = location;
}
/*
* isPrefixAtLocation - Queries an instruction to determine whether a prefix is
* present at a given location.
*
* @param insn - The instruction to be queried.
* @param prefix - The prefix.
* @param location - The location to query.
* @return - Whether the prefix is at that location.
*/
static BOOL isPrefixAtLocation(struct InternalInstruction* insn,
uint8_t prefix,
uint64_t location)
{
if (insn->prefixPresent[prefix] == 1 &&
insn->prefixLocations[prefix] == location)
return TRUE;
else
return FALSE;
}
/*
* readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
* instruction as having them. Also sets the instruction's default operand,
* address, and other relevant data sizes to report operands correctly.
*
* @param insn - The instruction whose prefixes are to be read.
* @return - 0 if the instruction could be read until the end of the prefix
* bytes, and no prefixes conflicted; nonzero otherwise.
*/
static int readPrefixes(struct InternalInstruction* insn) {
BOOL isPrefix = TRUE;
BOOL prefixGroups[4] = { FALSE };
uint64_t prefixLocation;
uint8_t byte = 0;
BOOL hasAdSize = FALSE;
BOOL hasOpSize = FALSE;
dbgprintf(insn, "readPrefixes()");
while (isPrefix) {
prefixLocation = insn->readerCursor;
if (consumeByte(insn, &byte))
return -1;
/*
* If the first byte is a LOCK prefix break and let it be disassembled
* as a lock "instruction", by creating an <MCInst #xxxx LOCK_PREFIX>.
* FIXME there is currently no way to get the disassembler to print the
* lock prefix if it is not the first byte.
*/
if (insn->readerCursor - 1 == insn->startLocation && byte == 0xf0)
break;
switch (byte) {
case 0xf0: /* LOCK */
case 0xf2: /* REPNE/REPNZ */
case 0xf3: /* REP or REPE/REPZ */
if (prefixGroups[0])
dbgprintf(insn, "Redundant Group 1 prefix");
prefixGroups[0] = TRUE;
setPrefixPresent(insn, byte, prefixLocation);
break;
case 0x2e: /* CS segment override -OR- Branch not taken */
case 0x36: /* SS segment override -OR- Branch taken */
case 0x3e: /* DS segment override */
case 0x26: /* ES segment override */
case 0x64: /* FS segment override */
case 0x65: /* GS segment override */
switch (byte) {
case 0x2e:
insn->segmentOverride = SEG_OVERRIDE_CS;
break;
case 0x36:
insn->segmentOverride = SEG_OVERRIDE_SS;
break;
case 0x3e:
insn->segmentOverride = SEG_OVERRIDE_DS;
break;
case 0x26:
insn->segmentOverride = SEG_OVERRIDE_ES;
break;
case 0x64:
insn->segmentOverride = SEG_OVERRIDE_FS;
break;
case 0x65:
insn->segmentOverride = SEG_OVERRIDE_GS;
break;
default:
debug("Unhandled override");
return -1;
}
if (prefixGroups[1])
dbgprintf(insn, "Redundant Group 2 prefix");
prefixGroups[1] = TRUE;
setPrefixPresent(insn, byte, prefixLocation);
break;
case 0x66: /* Operand-size override */
if (prefixGroups[2])
dbgprintf(insn, "Redundant Group 3 prefix");
prefixGroups[2] = TRUE;
hasOpSize = TRUE;
setPrefixPresent(insn, byte, prefixLocation);
break;
case 0x67: /* Address-size override */
if (prefixGroups[3])
dbgprintf(insn, "Redundant Group 4 prefix");
prefixGroups[3] = TRUE;
hasAdSize = TRUE;
setPrefixPresent(insn, byte, prefixLocation);
break;
default: /* Not a prefix byte */
isPrefix = FALSE;
break;
}
if (isPrefix)
dbgprintf(insn, "Found prefix 0x%hhx", byte);
}
insn->vexSize = 0;
if (byte == 0xc4) {
uint8_t byte1;
if (lookAtByte(insn, &byte1)) {
dbgprintf(insn, "Couldn't read second byte of VEX");
return -1;
}
if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
insn->vexSize = 3;
insn->necessaryPrefixLocation = insn->readerCursor - 1;
}
else {
unconsumeByte(insn);
insn->necessaryPrefixLocation = insn->readerCursor - 1;
}
if (insn->vexSize == 3) {
insn->vexPrefix[0] = byte;
consumeByte(insn, &insn->vexPrefix[1]);
consumeByte(insn, &insn->vexPrefix[2]);
/* We simulate the REX prefix for simplicity's sake */
if (insn->mode == MODE_64BIT) {
insn->rexPrefix = 0x40
| (wFromVEX3of3(insn->vexPrefix[2]) << 3)
| (rFromVEX2of3(insn->vexPrefix[1]) << 2)
| (xFromVEX2of3(insn->vexPrefix[1]) << 1)
| (bFromVEX2of3(insn->vexPrefix[1]) << 0);
}
switch (ppFromVEX3of3(insn->vexPrefix[2]))
{
default:
break;
case VEX_PREFIX_66:
hasOpSize = TRUE;
break;
}
dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1], insn->vexPrefix[2]);
}
}
else if (byte == 0xc5) {
uint8_t byte1;
if (lookAtByte(insn, &byte1)) {
dbgprintf(insn, "Couldn't read second byte of VEX");
return -1;
}
if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
insn->vexSize = 2;
}
else {
unconsumeByte(insn);
}
if (insn->vexSize == 2) {
insn->vexPrefix[0] = byte;
consumeByte(insn, &insn->vexPrefix[1]);
if (insn->mode == MODE_64BIT) {
insn->rexPrefix = 0x40
| (rFromVEX2of2(insn->vexPrefix[1]) << 2);
}
switch (ppFromVEX2of2(insn->vexPrefix[1]))
{
default:
break;
case VEX_PREFIX_66:
hasOpSize = TRUE;
break;
}
dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1]);
}
}
else {
if (insn->mode == MODE_64BIT) {
if ((byte & 0xf0) == 0x40) {
uint8_t opcodeByte;
if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
dbgprintf(insn, "Redundant REX prefix");
return -1;
}
insn->rexPrefix = byte;
insn->necessaryPrefixLocation = insn->readerCursor - 2;
dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
} else {
unconsumeByte(insn);
insn->necessaryPrefixLocation = insn->readerCursor - 1;
}
} else {
unconsumeByte(insn);
insn->necessaryPrefixLocation = insn->readerCursor - 1;
}
}
if (insn->mode == MODE_16BIT) {
insn->registerSize = (hasOpSize ? 4 : 2);
insn->addressSize = (hasAdSize ? 4 : 2);
insn->displacementSize = (hasAdSize ? 4 : 2);
insn->immediateSize = (hasOpSize ? 4 : 2);
} else if (insn->mode == MODE_32BIT) {
insn->registerSize = (hasOpSize ? 2 : 4);
insn->addressSize = (hasAdSize ? 2 : 4);
insn->displacementSize = (hasAdSize ? 2 : 4);
insn->immediateSize = (hasOpSize ? 2 : 4);
} else if (insn->mode == MODE_64BIT) {
if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
insn->registerSize = 8;
insn->addressSize = (hasAdSize ? 4 : 8);
insn->displacementSize = 4;
insn->immediateSize = 4;
} else if (insn->rexPrefix) {
insn->registerSize = (hasOpSize ? 2 : 4);
insn->addressSize = (hasAdSize ? 4 : 8);
insn->displacementSize = (hasOpSize ? 2 : 4);
insn->immediateSize = (hasOpSize ? 2 : 4);
} else {
insn->registerSize = (hasOpSize ? 2 : 4);
insn->addressSize = (hasAdSize ? 4 : 8);
insn->displacementSize = (hasOpSize ? 2 : 4);
insn->immediateSize = (hasOpSize ? 2 : 4);
}
}
return 0;
}
/*
* readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
* extended or escape opcodes).
*
* @param insn - The instruction whose opcode is to be read.
* @return - 0 if the opcode could be read successfully; nonzero otherwise.
*/
static int readOpcode(struct InternalInstruction* insn) {
/* Determine the length of the primary opcode */
uint8_t current;
dbgprintf(insn, "readOpcode()");
insn->opcodeType = ONEBYTE;
if (insn->vexSize == 3)
{
switch (mmmmmFromVEX2of3(insn->vexPrefix[1]))
{
default:
dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)", mmmmmFromVEX2of3(insn->vexPrefix[1]));
return -1;
case 0:
break;
case VEX_LOB_0F:
insn->twoByteEscape = 0x0f;
insn->opcodeType = TWOBYTE;
return consumeByte(insn, &insn->opcode);
case VEX_LOB_0F38:
insn->twoByteEscape = 0x0f;
insn->threeByteEscape = 0x38;
insn->opcodeType = THREEBYTE_38;
return consumeByte(insn, &insn->opcode);
case VEX_LOB_0F3A:
insn->twoByteEscape = 0x0f;
insn->threeByteEscape = 0x3a;
insn->opcodeType = THREEBYTE_3A;
return consumeByte(insn, &insn->opcode);
}
}
else if (insn->vexSize == 2)
{
insn->twoByteEscape = 0x0f;
insn->opcodeType = TWOBYTE;
return consumeByte(insn, &insn->opcode);
}
if (consumeByte(insn, ¤t))
return -1;
if (current == 0x0f) {
dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
insn->twoByteEscape = current;
if (consumeByte(insn, ¤t))
return -1;
if (current == 0x38) {
dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
insn->threeByteEscape = current;
if (consumeByte(insn, ¤t))
return -1;
insn->opcodeType = THREEBYTE_38;
} else if (current == 0x3a) {
dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
insn->threeByteEscape = current;
if (consumeByte(insn, ¤t))
return -1;
insn->opcodeType = THREEBYTE_3A;
} else if (current == 0xa6) {
dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
insn->threeByteEscape = current;
if (consumeByte(insn, ¤t))
return -1;
insn->opcodeType = THREEBYTE_A6;
} else if (current == 0xa7) {
dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
insn->threeByteEscape = current;
if (consumeByte(insn, ¤t))
return -1;
insn->opcodeType = THREEBYTE_A7;
} else {
dbgprintf(insn, "Didn't find a three-byte escape prefix");
insn->opcodeType = TWOBYTE;
}
}
/*
* At this point we have consumed the full opcode.
* Anything we consume from here on must be unconsumed.
*/
insn->opcode = current;
return 0;
}
static int readModRM(struct InternalInstruction* insn);
/*
* getIDWithAttrMask - Determines the ID of an instruction, consuming
* the ModR/M byte as appropriate for extended and escape opcodes,
* and using a supplied attribute mask.
*
* @param instructionID - A pointer whose target is filled in with the ID of the
* instruction.
* @param insn - The instruction whose ID is to be determined.
* @param attrMask - The attribute mask to search.
* @return - 0 if the ModR/M could be read when needed or was not
* needed; nonzero otherwise.
*/
static int getIDWithAttrMask(uint16_t* instructionID,
struct InternalInstruction* insn,
uint8_t attrMask) {
BOOL hasModRMExtension;
uint8_t instructionClass;
instructionClass = contextForAttrs(attrMask);
hasModRMExtension = modRMRequired(insn->opcodeType,
instructionClass,
insn->opcode);
if (hasModRMExtension) {
if (readModRM(insn))
return -1;
*instructionID = decode(insn->opcodeType,
instructionClass,
insn->opcode,
insn->modRM);
} else {
*instructionID = decode(insn->opcodeType,
instructionClass,
insn->opcode,
0);
}
return 0;
}
/*
* is16BitEquivalent - Determines whether two instruction names refer to
* equivalent instructions but one is 16-bit whereas the other is not.
*
* @param orig - The instruction that is not 16-bit
* @param equiv - The instruction that is 16-bit
*/
static BOOL is16BitEquivalent(const char* orig, const char* equiv) {
off_t i;
for (i = 0;; i++) {
if (orig[i] == '\0' && equiv[i] == '\0')
return TRUE;
if (orig[i] == '\0' || equiv[i] == '\0')
return FALSE;
if (orig[i] != equiv[i]) {
if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
continue;
if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
continue;
if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
continue;
return FALSE;
}
}
}
/*
* getID - Determines the ID of an instruction, consuming the ModR/M byte as
* appropriate for extended and escape opcodes. Determines the attributes and
* context for the instruction before doing so.
*
* @param insn - The instruction whose ID is to be determined.
* @return - 0 if the ModR/M could be read when needed or was not needed;
* nonzero otherwise.
*/
static int getID(struct InternalInstruction* insn, const void *miiArg) {
uint8_t attrMask;
uint16_t instructionID;
dbgprintf(insn, "getID()");
attrMask = ATTR_NONE;
if (insn->mode == MODE_64BIT)
attrMask |= ATTR_64BIT;
if (insn->vexSize) {
attrMask |= ATTR_VEX;
if (insn->vexSize == 3) {
switch (ppFromVEX3of3(insn->vexPrefix[2])) {
case VEX_PREFIX_66:
attrMask |= ATTR_OPSIZE;
break;
case VEX_PREFIX_F3:
attrMask |= ATTR_XS;
break;
case VEX_PREFIX_F2:
attrMask |= ATTR_XD;
break;
}
if (lFromVEX3of3(insn->vexPrefix[2]))
attrMask |= ATTR_VEXL;
}
else if (insn->vexSize == 2) {
switch (ppFromVEX2of2(insn->vexPrefix[1])) {
case VEX_PREFIX_66:
attrMask |= ATTR_OPSIZE;
break;
case VEX_PREFIX_F3:
attrMask |= ATTR_XS;
break;
case VEX_PREFIX_F2:
attrMask |= ATTR_XD;
break;
}
if (lFromVEX2of2(insn->vexPrefix[1]))
attrMask |= ATTR_VEXL;
}
else {
return -1;
}
}
else {
if (isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
attrMask |= ATTR_OPSIZE;
else if (isPrefixAtLocation(insn, 0x67, insn->necessaryPrefixLocation))
attrMask |= ATTR_ADSIZE;
else if (isPrefixAtLocation(insn, 0xf3, insn->necessaryPrefixLocation))
attrMask |= ATTR_XS;
else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
attrMask |= ATTR_XD;
}
if (insn->rexPrefix & 0x08)
attrMask |= ATTR_REXW;
if (getIDWithAttrMask(&instructionID, insn, attrMask))
return -1;
/* The following clauses compensate for limitations of the tables. */
if ((attrMask & ATTR_VEXL) && (attrMask & ATTR_REXW) &&
!(attrMask & ATTR_OPSIZE)) {
/*
* Some VEX instructions ignore the L-bit, but use the W-bit. Normally L-bit
* has precedence since there are no L-bit with W-bit entries in the tables.
* So if the L-bit isn't significant we should use the W-bit instead.
* We only need to do this if the instruction doesn't specify OpSize since
* there is a VEX_L_W_OPSIZE table.
*/
const struct InstructionSpecifier *spec;
uint16_t instructionIDWithWBit;
const struct InstructionSpecifier *specWithWBit;
spec = specifierForUID(instructionID);
if (getIDWithAttrMask(&instructionIDWithWBit,
insn,
(attrMask & (~ATTR_VEXL)) | ATTR_REXW)) {
insn->instructionID = instructionID;
insn->spec = spec;
return 0;
}
specWithWBit = specifierForUID(instructionIDWithWBit);
if (instructionID != instructionIDWithWBit) {
insn->instructionID = instructionIDWithWBit;
insn->spec = specWithWBit;
} else {
insn->instructionID = instructionID;
insn->spec = spec;
}
return 0;
}
if (insn->prefixPresent[0x66] && !(attrMask & ATTR_OPSIZE)) {
/*
* The instruction tables make no distinction between instructions that
* allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
* particular spot (i.e., many MMX operations). In general we're
* conservative, but in the specific case where OpSize is present but not
* in the right place we check if there's a 16-bit operation.
*/
const struct InstructionSpecifier *spec;
uint16_t instructionIDWithOpsize;
const char *specName, *specWithOpSizeName;
spec = specifierForUID(instructionID);
if (getIDWithAttrMask(&instructionIDWithOpsize,
insn,
attrMask | ATTR_OPSIZE)) {
/*
* ModRM required with OpSize but not present; give up and return version
* without OpSize set
*/
insn->instructionID = instructionID;
insn->spec = spec;
return 0;
}
specName = x86DisassemblerGetInstrName(instructionID, miiArg);
specWithOpSizeName =
x86DisassemblerGetInstrName(instructionIDWithOpsize, miiArg);
if (is16BitEquivalent(specName, specWithOpSizeName)) {
insn->instructionID = instructionIDWithOpsize;
insn->spec = specifierForUID(instructionIDWithOpsize);
} else {
insn->instructionID = instructionID;
insn->spec = spec;
}
return 0;
}
if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
insn->rexPrefix & 0x01) {
/*
* NOOP shouldn't decode as NOOP if REX.b is set. Instead
* it should decode as XCHG %r8, %eax.
*/
const struct InstructionSpecifier *spec;
uint16_t instructionIDWithNewOpcode;
const struct InstructionSpecifier *specWithNewOpcode;
spec = specifierForUID(instructionID);
/* Borrow opcode from one of the other XCHGar opcodes */
insn->opcode = 0x91;
if (getIDWithAttrMask(&instructionIDWithNewOpcode,
insn,
attrMask)) {
insn->opcode = 0x90;
insn->instructionID = instructionID;
insn->spec = spec;
return 0;
}
specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
/* Change back */
insn->opcode = 0x90;
insn->instructionID = instructionIDWithNewOpcode;
insn->spec = specWithNewOpcode;
return 0;
}
insn->instructionID = instructionID;
insn->spec = specifierForUID(insn->instructionID);
return 0;
}
/*
* readSIB - Consumes the SIB byte to determine addressing information for an
* instruction.
*
* @param insn - The instruction whose SIB byte is to be read.
* @return - 0 if the SIB byte was successfully read; nonzero otherwise.
*/
static int readSIB(struct InternalInstruction* insn) {
SIBIndex sibIndexBase = 0;
SIBBase sibBaseBase = 0;
uint8_t index, base;
dbgprintf(insn, "readSIB()");
if (insn->consumedSIB)
return 0;
insn->consumedSIB = TRUE;
switch (insn->addressSize) {
case 2:
dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
return -1;
break;
case 4:
sibIndexBase = SIB_INDEX_EAX;
sibBaseBase = SIB_BASE_EAX;
break;
case 8:
sibIndexBase = SIB_INDEX_RAX;
sibBaseBase = SIB_BASE_RAX;
break;
}
if (consumeByte(insn, &insn->sib))
return -1;
index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
switch (index) {
case 0x4:
insn->sibIndex = SIB_INDEX_NONE;
break;
default:
insn->sibIndex = (SIBIndex)(sibIndexBase + index);
if (insn->sibIndex == SIB_INDEX_sib ||
insn->sibIndex == SIB_INDEX_sib64)
insn->sibIndex = SIB_INDEX_NONE;
break;
}
switch (scaleFromSIB(insn->sib)) {
case 0:
insn->sibScale = 1;
break;
case 1:
insn->sibScale = 2;
break;
case 2:
insn->sibScale = 4;
break;
case 3:
insn->sibScale = 8;
break;
}
base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
switch (base) {
case 0x5:
switch (modFromModRM(insn->modRM)) {
case 0x0:
insn->eaDisplacement = EA_DISP_32;
insn->sibBase = SIB_BASE_NONE;
break;
case 0x1:
insn->eaDisplacement = EA_DISP_8;
insn->sibBase = (insn->addressSize == 4 ?
SIB_BASE_EBP : SIB_BASE_RBP);
break;
case 0x2:
insn->eaDisplacement = EA_DISP_32;
insn->sibBase = (insn->addressSize == 4 ?
SIB_BASE_EBP : SIB_BASE_RBP);
break;
case 0x3:
debug("Cannot have Mod = 0b11 and a SIB byte");
return -1;
}
break;
default:
insn->sibBase = (SIBBase)(sibBaseBase + base);
break;
}
return 0;
}
/*
* readDisplacement - Consumes the displacement of an instruction.
*
* @param insn - The instruction whose displacement is to be read.
* @return - 0 if the displacement byte was successfully read; nonzero
* otherwise.
*/
static int readDisplacement(struct InternalInstruction* insn) {
int8_t d8;
int16_t d16;
int32_t d32;
dbgprintf(insn, "readDisplacement()");
if (insn->consumedDisplacement)
return 0;
insn->consumedDisplacement = TRUE;
insn->displacementOffset = insn->readerCursor - insn->startLocation;
switch (insn->eaDisplacement) {
case EA_DISP_NONE:
insn->consumedDisplacement = FALSE;
break;
case EA_DISP_8:
if (consumeInt8(insn, &d8))
return -1;
insn->displacement = d8;
break;
case EA_DISP_16:
if (consumeInt16(insn, &d16))
return -1;
insn->displacement = d16;
break;
case EA_DISP_32:
if (consumeInt32(insn, &d32))
return -1;
insn->displacement = d32;
break;
}
insn->consumedDisplacement = TRUE;
return 0;
}
/*
* readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
* displacement) for an instruction and interprets it.
*
* @param insn - The instruction whose addressing information is to be read.
* @return - 0 if the information was successfully read; nonzero otherwise.
*/
static int readModRM(struct InternalInstruction* insn) {
uint8_t mod, rm, reg;
dbgprintf(insn, "readModRM()");
if (insn->consumedModRM)
return 0;
if (consumeByte(insn, &insn->modRM))
return -1;
insn->consumedModRM = TRUE;
mod = modFromModRM(insn->modRM);
rm = rmFromModRM(insn->modRM);
reg = regFromModRM(insn->modRM);
/*
* This goes by insn->registerSize to pick the correct register, which messes
* up if we're using (say) XMM or 8-bit register operands. That gets fixed in
* fixupReg().
*/
switch (insn->registerSize) {
case 2:
insn->regBase = MODRM_REG_AX;
insn->eaRegBase = EA_REG_AX;
break;
case 4:
insn->regBase = MODRM_REG_EAX;
insn->eaRegBase = EA_REG_EAX;
break;
case 8:
insn->regBase = MODRM_REG_RAX;
insn->eaRegBase = EA_REG_RAX;
break;
}
reg |= rFromREX(insn->rexPrefix) << 3;
rm |= bFromREX(insn->rexPrefix) << 3;
insn->reg = (Reg)(insn->regBase + reg);
switch (insn->addressSize) {
case 2:
insn->eaBaseBase = EA_BASE_BX_SI;
switch (mod) {
case 0x0:
if (rm == 0x6) {
insn->eaBase = EA_BASE_NONE;
insn->eaDisplacement = EA_DISP_16;
if (readDisplacement(insn))
return -1;
} else {
insn->eaBase = (EABase)(insn->eaBaseBase + rm);
insn->eaDisplacement = EA_DISP_NONE;
}
break;
case 0x1:
insn->eaBase = (EABase)(insn->eaBaseBase + rm);
insn->eaDisplacement = EA_DISP_8;
if (readDisplacement(insn))
return -1;
break;
case 0x2:
insn->eaBase = (EABase)(insn->eaBaseBase + rm);
insn->eaDisplacement = EA_DISP_16;
if (readDisplacement(insn))
return -1;
break;
case 0x3:
insn->eaBase = (EABase)(insn->eaRegBase + rm);
if (readDisplacement(insn))
return -1;
break;
}
break;
case 4:
case 8:
insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
switch (mod) {
case 0x0:
insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
switch (rm) {
case 0x4:
case 0xc: /* in case REXW.b is set */
insn->eaBase = (insn->addressSize == 4 ?
EA_BASE_sib : EA_BASE_sib64);
readSIB(insn);
if (readDisplacement(insn))
return -1;
break;
case 0x5:
insn->eaBase = EA_BASE_NONE;
insn->eaDisplacement = EA_DISP_32;
if (readDisplacement(insn))
return -1;
break;
default:
insn->eaBase = (EABase)(insn->eaBaseBase + rm);
break;
}
break;
case 0x1:
case 0x2:
insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
switch (rm) {
case 0x4:
case 0xc: /* in case REXW.b is set */
insn->eaBase = EA_BASE_sib;
readSIB(insn);
if (readDisplacement(insn))
return -1;
break;
default:
insn->eaBase = (EABase)(insn->eaBaseBase + rm);
if (readDisplacement(insn))
return -1;
break;
}
break;
case 0x3:
insn->eaDisplacement = EA_DISP_NONE;
insn->eaBase = (EABase)(insn->eaRegBase + rm);
break;
}
break;
} /* switch (insn->addressSize) */
return 0;
}
#define GENERIC_FIXUP_FUNC(name, base, prefix) \
static uint8_t name(struct InternalInstruction *insn, \
OperandType type, \
uint8_t index, \
uint8_t *valid) { \
*valid = 1; \
switch (type) { \
default: \
debug("Unhandled register type"); \
*valid = 0; \
return 0; \
case TYPE_Rv: \
return base + index; \
case TYPE_R8: \
if (insn->rexPrefix && \
index >= 4 && index <= 7) { \
return prefix##_SPL + (index - 4); \
} else { \
return prefix##_AL + index; \
} \
case TYPE_R16: \
return prefix##_AX + index; \
case TYPE_R32: \
return prefix##_EAX + index; \
case TYPE_R64: \
return prefix##_RAX + index; \
case TYPE_XMM256: \
return prefix##_YMM0 + index; \
case TYPE_XMM128: \
case TYPE_XMM64: \
case TYPE_XMM32: \
case TYPE_XMM: \
return prefix##_XMM0 + index; \
case TYPE_MM64: \
case TYPE_MM32: \
case TYPE_MM: \
if (index > 7) \
*valid = 0; \
return prefix##_MM0 + index; \
case TYPE_SEGMENTREG: \
if (index > 5) \
*valid = 0; \
return prefix##_ES + index; \
case TYPE_DEBUGREG: \
if (index > 7) \
*valid = 0; \
return prefix##_DR0 + index; \
case TYPE_CONTROLREG: \
if (index > 8) \
*valid = 0; \
return prefix##_CR0 + index; \
} \
}
/*
* fixup*Value - Consults an operand type to determine the meaning of the
* reg or R/M field. If the operand is an XMM operand, for example, an
* operand would be XMM0 instead of AX, which readModRM() would otherwise
* misinterpret it as.
*
* @param insn - The instruction containing the operand.
* @param type - The operand type.
* @param index - The existing value of the field as reported by readModRM().
* @param valid - The address of a uint8_t. The target is set to 1 if the
* field is valid for the register class; 0 if not.
* @return - The proper value.
*/
GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG)
GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG)
/*
* fixupReg - Consults an operand specifier to determine which of the
* fixup*Value functions to use in correcting readModRM()'ss interpretation.
*
* @param insn - See fixup*Value().
* @param op - The operand specifier.
* @return - 0 if fixup was successful; -1 if the register returned was
* invalid for its class.
*/
static int fixupReg(struct InternalInstruction *insn,
const struct OperandSpecifier *op) {
uint8_t valid;
dbgprintf(insn, "fixupReg()");
switch ((OperandEncoding)op->encoding) {
default:
debug("Expected a REG or R/M encoding in fixupReg");
return -1;
case ENCODING_VVVV:
insn->vvvv = (Reg)fixupRegValue(insn,
(OperandType)op->type,
insn->vvvv,
&valid);
if (!valid)
return -1;
break;
case ENCODING_REG:
insn->reg = (Reg)fixupRegValue(insn,
(OperandType)op->type,
insn->reg - insn->regBase,
&valid);
if (!valid)
return -1;
break;
case ENCODING_RM:
if (insn->eaBase >= insn->eaRegBase) {
insn->eaBase = (EABase)fixupRMValue(insn,
(OperandType)op->type,
insn->eaBase - insn->eaRegBase,
&valid);
if (!valid)
return -1;
}
break;
}
return 0;
}
/*
* readOpcodeModifier - Reads an operand from the opcode field of an
* instruction. Handles AddRegFrm instructions.
*
* @param insn - The instruction whose opcode field is to be read.
* @param inModRM - Indicates that the opcode field is to be read from the
* ModR/M extension; useful for escape opcodes
* @return - 0 on success; nonzero otherwise.
*/
static int readOpcodeModifier(struct InternalInstruction* insn) {
dbgprintf(insn, "readOpcodeModifier()");
if (insn->consumedOpcodeModifier)
return 0;
insn->consumedOpcodeModifier = TRUE;
switch (insn->spec->modifierType) {
default:
debug("Unknown modifier type.");
return -1;
case MODIFIER_NONE:
debug("No modifier but an operand expects one.");
return -1;
case MODIFIER_OPCODE:
insn->opcodeModifier = insn->opcode - insn->spec->modifierBase;
return 0;
case MODIFIER_MODRM:
insn->opcodeModifier = insn->modRM - insn->spec->modifierBase;
return 0;
}
}
/*
* readOpcodeRegister - Reads an operand from the opcode field of an
* instruction and interprets it appropriately given the operand width.
* Handles AddRegFrm instructions.
*
* @param insn - See readOpcodeModifier().
* @param size - The width (in bytes) of the register being specified.
* 1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
* RAX.
* @return - 0 on success; nonzero otherwise.
*/
static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
dbgprintf(insn, "readOpcodeRegister()");
if (readOpcodeModifier(insn))
return -1;
if (size == 0)
size = insn->registerSize;
switch (size) {
case 1:
insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
| insn->opcodeModifier));
if (insn->rexPrefix &&
insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
insn->opcodeRegister < MODRM_REG_AL + 0x8) {
insn->opcodeRegister = (Reg)(MODRM_REG_SPL
+ (insn->opcodeRegister - MODRM_REG_AL - 4));
}
break;
case 2:
insn->opcodeRegister = (Reg)(MODRM_REG_AX
+ ((bFromREX(insn->rexPrefix) << 3)
| insn->opcodeModifier));
break;
case 4:
insn->opcodeRegister = (Reg)(MODRM_REG_EAX
+ ((bFromREX(insn->rexPrefix) << 3)
| insn->opcodeModifier));
break;
case 8:
insn->opcodeRegister = (Reg)(MODRM_REG_RAX
+ ((bFromREX(insn->rexPrefix) << 3)
| insn->opcodeModifier));
break;
}
return 0;
}
/*
* readImmediate - Consumes an immediate operand from an instruction, given the
* desired operand size.
*
* @param insn - The instruction whose operand is to be read.
* @param size - The width (in bytes) of the operand.
* @return - 0 if the immediate was successfully consumed; nonzero
* otherwise.
*/
static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
uint8_t imm8;
uint16_t imm16;
uint32_t imm32;
uint64_t imm64;
dbgprintf(insn, "readImmediate()");
if (insn->numImmediatesConsumed == 2) {
debug("Already consumed two immediates");
return -1;
}
if (size == 0)
size = insn->immediateSize;
else
insn->immediateSize = size;
insn->immediateOffset = insn->readerCursor - insn->startLocation;
switch (size) {
case 1:
if (consumeByte(insn, &imm8))
return -1;
insn->immediates[insn->numImmediatesConsumed] = imm8;
break;
case 2:
if (consumeUInt16(insn, &imm16))
return -1;
insn->immediates[insn->numImmediatesConsumed] = imm16;
break;
case 4:
if (consumeUInt32(insn, &imm32))
return -1;
insn->immediates[insn->numImmediatesConsumed] = imm32;
break;
case 8:
if (consumeUInt64(insn, &imm64))
return -1;
insn->immediates[insn->numImmediatesConsumed] = imm64;
break;
}
insn->numImmediatesConsumed++;
return 0;
}
/*
* readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
*
* @param insn - The instruction whose operand is to be read.
* @return - 0 if the vvvv was successfully consumed; nonzero
* otherwise.
*/
static int readVVVV(struct InternalInstruction* insn) {
dbgprintf(insn, "readVVVV()");
if (insn->vexSize == 3)
insn->vvvv = vvvvFromVEX3of3(insn->vexPrefix[2]);
else if (insn->vexSize == 2)
insn->vvvv = vvvvFromVEX2of2(insn->vexPrefix[1]);
else
return -1;
if (insn->mode != MODE_64BIT)
insn->vvvv &= 0x7;
return 0;
}
/*
* readOperands - Consults the specifier for an instruction and consumes all
* operands for that instruction, interpreting them as it goes.
*
* @param insn - The instruction whose operands are to be read and interpreted.
* @return - 0 if all operands could be read; nonzero otherwise.
*/
static int readOperands(struct InternalInstruction* insn) {
int index;
int hasVVVV, needVVVV;
int sawRegImm = 0;
dbgprintf(insn, "readOperands()");
/* If non-zero vvvv specified, need to make sure one of the operands
uses it. */
hasVVVV = !readVVVV(insn);
needVVVV = hasVVVV && (insn->vvvv != 0);
for (index = 0; index < X86_MAX_OPERANDS; ++index) {
switch (x86OperandSets[insn->spec->operands][index].encoding) {
case ENCODING_NONE:
break;
case ENCODING_REG:
case ENCODING_RM:
if (readModRM(insn))
return -1;
if (fixupReg(insn, &x86OperandSets[insn->spec->operands][index]))
return -1;
break;
case ENCODING_CB:
case ENCODING_CW:
case ENCODING_CD:
case ENCODING_CP:
case ENCODING_CO:
case ENCODING_CT:
dbgprintf(insn, "We currently don't hande code-offset encodings");
return -1;
case ENCODING_IB:
if (sawRegImm) {
/* Saw a register immediate so don't read again and instead split the
previous immediate. FIXME: This is a hack. */
insn->immediates[insn->numImmediatesConsumed] =
insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
++insn->numImmediatesConsumed;
break;
}
if (readImmediate(insn, 1))
return -1;
if (x86OperandSets[insn->spec->operands][index].type == TYPE_IMM3 &&
insn->immediates[insn->numImmediatesConsumed - 1] > 7)
return -1;
if (x86OperandSets[insn->spec->operands][index].type == TYPE_IMM5 &&
insn->immediates[insn->numImmediatesConsumed - 1] > 31)
return -1;
if (x86OperandSets[insn->spec->operands][index].type == TYPE_XMM128 ||
x86OperandSets[insn->spec->operands][index].type == TYPE_XMM256)
sawRegImm = 1;
break;
case ENCODING_IW:
if (readImmediate(insn, 2))
return -1;
break;
case ENCODING_ID:
if (readImmediate(insn, 4))
return -1;
break;
case ENCODING_IO:
if (readImmediate(insn, 8))
return -1;
break;
case ENCODING_Iv:
if (readImmediate(insn, insn->immediateSize))
return -1;
break;
case ENCODING_Ia:
if (readImmediate(insn, insn->addressSize))
return -1;
break;
case ENCODING_RB:
if (readOpcodeRegister(insn, 1))
return -1;
break;
case ENCODING_RW:
if (readOpcodeRegister(insn, 2))
return -1;
break;
case ENCODING_RD:
if (readOpcodeRegister(insn, 4))
return -1;
break;
case ENCODING_RO:
if (readOpcodeRegister(insn, 8))
return -1;
break;
case ENCODING_Rv:
if (readOpcodeRegister(insn, 0))
return -1;
break;
case ENCODING_I:
if (readOpcodeModifier(insn))
return -1;
break;
case ENCODING_VVVV:
needVVVV = 0; /* Mark that we have found a VVVV operand. */
if (!hasVVVV)
return -1;
if (fixupReg(insn, &x86OperandSets[insn->spec->operands][index]))
return -1;
break;
case ENCODING_DUP:
break;
default:
dbgprintf(insn, "Encountered an operand with an unknown encoding.");
return -1;
}
}
/* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
if (needVVVV) return -1;
return 0;
}
/*
* decodeInstruction - Reads and interprets a full instruction provided by the
* user.
*
* @param insn - A pointer to the instruction to be populated. Must be
* pre-allocated.
* @param reader - The function to be used to read the instruction's bytes.
* @param readerArg - A generic argument to be passed to the reader to store
* any internal state.
* @param logger - If non-NULL, the function to be used to write log messages
* and warnings.
* @param loggerArg - A generic argument to be passed to the logger to store
* any internal state.
* @param startLoc - The address (in the reader's address space) of the first
* byte in the instruction.
* @param mode - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
* decode the instruction in.
* @return - 0 if the instruction's memory could be read; nonzero if
* not.
*/
int decodeInstruction(struct InternalInstruction* insn,
byteReader_t reader,
const void* readerArg,
dlog_t logger,
void* loggerArg,
const void* miiArg,
uint64_t startLoc,
DisassemblerMode mode) {
memset(insn, 0, sizeof(struct InternalInstruction));
insn->reader = reader;
insn->readerArg = readerArg;
insn->dlog = logger;
insn->dlogArg = loggerArg;
insn->startLocation = startLoc;
insn->readerCursor = startLoc;
insn->mode = mode;
insn->numImmediatesConsumed = 0;
if (readPrefixes(insn) ||
readOpcode(insn) ||
getID(insn, miiArg) ||
insn->instructionID == 0 ||
readOperands(insn))
return -1;
insn->operands = &x86OperandSets[insn->spec->operands][0];
insn->length = insn->readerCursor - insn->startLocation;
dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
startLoc, insn->readerCursor, insn->length);
if (insn->length > 15)
dbgprintf(insn, "Instruction exceeds 15-byte limit");
return 0;
}
|
158553.c | /*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| Copyright (c) Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andi Gutmans <[email protected]> |
| Zeev Suraski <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "zend.h"
#include "zend_API.h"
#include "zend_compile.h"
#include "zend_execute.h"
#include "zend_inheritance.h"
#include "zend_interfaces.h"
#include "zend_smart_str.h"
#include "zend_operators.h"
#include "zend_exceptions.h"
static void add_dependency_obligation(zend_class_entry *ce, zend_class_entry *dependency_ce);
static void add_compatibility_obligation(
zend_class_entry *ce, const zend_function *child_fn, zend_class_entry *child_scope,
const zend_function *parent_fn, zend_class_entry *parent_scope);
static void add_property_compatibility_obligation(
zend_class_entry *ce, const zend_property_info *child_prop,
const zend_property_info *parent_prop);
static void zend_type_copy_ctor(zend_type *type, zend_bool persistent) {
if (ZEND_TYPE_HAS_LIST(*type)) {
zend_type_list *old_list = ZEND_TYPE_LIST(*type);
size_t size = ZEND_TYPE_LIST_SIZE(old_list->num_types);
zend_type_list *new_list = ZEND_TYPE_USES_ARENA(*type)
? zend_arena_alloc(&CG(arena), size) : pemalloc(size, persistent);
memcpy(new_list, old_list, ZEND_TYPE_LIST_SIZE(old_list->num_types));
ZEND_TYPE_SET_PTR(*type, new_list);
zend_type *list_type;
ZEND_TYPE_LIST_FOREACH(new_list, list_type) {
ZEND_ASSERT(ZEND_TYPE_HAS_NAME(*list_type));
zend_string_addref(ZEND_TYPE_NAME(*list_type));
} ZEND_TYPE_LIST_FOREACH_END();
} else if (ZEND_TYPE_HAS_NAME(*type)) {
zend_string_addref(ZEND_TYPE_NAME(*type));
}
}
static zend_property_info *zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */
{
zend_property_info* new_property_info = pemalloc(sizeof(zend_property_info), 1);
memcpy(new_property_info, property_info, sizeof(zend_property_info));
zend_string_addref(new_property_info->name);
zend_type_copy_ctor(&new_property_info->type, /* persistent */ 1);
return new_property_info;
}
/* }}} */
static zend_function *zend_duplicate_internal_function(zend_function *func, zend_class_entry *ce) /* {{{ */
{
zend_function *new_function;
if (UNEXPECTED(ce->type & ZEND_INTERNAL_CLASS)) {
new_function = pemalloc(sizeof(zend_internal_function), 1);
memcpy(new_function, func, sizeof(zend_internal_function));
} else {
new_function = zend_arena_alloc(&CG(arena), sizeof(zend_internal_function));
memcpy(new_function, func, sizeof(zend_internal_function));
new_function->common.fn_flags |= ZEND_ACC_ARENA_ALLOCATED;
}
if (EXPECTED(new_function->common.function_name)) {
zend_string_addref(new_function->common.function_name);
}
return new_function;
}
/* }}} */
static zend_function *zend_duplicate_user_function(zend_function *func) /* {{{ */
{
zend_function *new_function;
new_function = zend_arena_alloc(&CG(arena), sizeof(zend_op_array));
memcpy(new_function, func, sizeof(zend_op_array));
if (CG(compiler_options) & ZEND_COMPILE_PRELOAD) {
ZEND_ASSERT(new_function->op_array.fn_flags & ZEND_ACC_PRELOADED);
ZEND_MAP_PTR_NEW(new_function->op_array.static_variables_ptr);
} else {
ZEND_MAP_PTR_INIT(new_function->op_array.static_variables_ptr, &new_function->op_array.static_variables);
}
HashTable *static_properties_ptr = ZEND_MAP_PTR_GET(func->op_array.static_variables_ptr);
if (static_properties_ptr) {
/* See: Zend/tests/method_static_var.phpt */
ZEND_MAP_PTR_SET(new_function->op_array.static_variables_ptr, static_properties_ptr);
GC_TRY_ADDREF(static_properties_ptr);
} else {
GC_TRY_ADDREF(new_function->op_array.static_variables);
}
return new_function;
}
/* }}} */
static zend_always_inline zend_function *zend_duplicate_function(zend_function *func, zend_class_entry *ce, zend_bool is_interface) /* {{{ */
{
if (UNEXPECTED(func->type == ZEND_INTERNAL_FUNCTION)) {
return zend_duplicate_internal_function(func, ce);
} else {
if (func->op_array.refcount) {
(*func->op_array.refcount)++;
}
if (EXPECTED(func->op_array.function_name)) {
zend_string_addref(func->op_array.function_name);
}
if (is_interface
|| EXPECTED(!func->op_array.static_variables)) {
/* reuse the same op_array structure */
return func;
}
return zend_duplicate_user_function(func);
}
}
/* }}} */
static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */
{
zend_class_entry *parent = ce->parent;
ZEND_ASSERT(parent != NULL);
/* You cannot change create_object */
ce->create_object = parent->create_object;
/* Inherit special functions if needed */
if (EXPECTED(!ce->get_iterator)) {
ce->get_iterator = parent->get_iterator;
}
if (EXPECTED(!ce->__get)) {
ce->__get = parent->__get;
}
if (EXPECTED(!ce->__set)) {
ce->__set = parent->__set;
}
if (EXPECTED(!ce->__unset)) {
ce->__unset = parent->__unset;
}
if (EXPECTED(!ce->__isset)) {
ce->__isset = parent->__isset;
}
if (EXPECTED(!ce->__call)) {
ce->__call = parent->__call;
}
if (EXPECTED(!ce->__callstatic)) {
ce->__callstatic = parent->__callstatic;
}
if (EXPECTED(!ce->__tostring)) {
ce->__tostring = parent->__tostring;
}
if (EXPECTED(!ce->clone)) {
ce->clone = parent->clone;
}
if (EXPECTED(!ce->__serialize)) {
ce->__serialize = parent->__serialize;
}
if (EXPECTED(!ce->__unserialize)) {
ce->__unserialize = parent->__unserialize;
}
if (EXPECTED(!ce->serialize)) {
ce->serialize = parent->serialize;
}
if (EXPECTED(!ce->unserialize)) {
ce->unserialize = parent->unserialize;
}
if (!ce->destructor) {
ce->destructor = parent->destructor;
}
if (EXPECTED(!ce->__debugInfo)) {
ce->__debugInfo = parent->__debugInfo;
}
if (ce->constructor) {
if (parent->constructor && UNEXPECTED(parent->constructor->common.fn_flags & ZEND_ACC_FINAL)) {
zend_error_noreturn(E_ERROR, "Cannot override final %s::%s() with %s::%s()",
ZSTR_VAL(parent->name), ZSTR_VAL(parent->constructor->common.function_name),
ZSTR_VAL(ce->name), ZSTR_VAL(ce->constructor->common.function_name));
}
return;
}
ce->constructor = parent->constructor;
}
/* }}} */
char *zend_visibility_string(uint32_t fn_flags) /* {{{ */
{
if (fn_flags & ZEND_ACC_PUBLIC) {
return "public";
} else if (fn_flags & ZEND_ACC_PRIVATE) {
return "private";
} else {
ZEND_ASSERT(fn_flags & ZEND_ACC_PROTECTED);
return "protected";
}
}
/* }}} */
static zend_string *resolve_class_name(zend_class_entry *scope, zend_string *name) {
ZEND_ASSERT(scope);
if (zend_string_equals_literal_ci(name, "parent") && scope->parent) {
if (scope->ce_flags & ZEND_ACC_RESOLVED_PARENT) {
return scope->parent->name;
} else {
return scope->parent_name;
}
} else if (zend_string_equals_literal_ci(name, "self")) {
return scope->name;
} else {
return name;
}
}
static zend_bool class_visible(zend_class_entry *ce) {
if (ce->type == ZEND_INTERNAL_CLASS) {
return !(CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES);
} else {
ZEND_ASSERT(ce->type == ZEND_USER_CLASS);
return !(CG(compiler_options) & ZEND_COMPILE_IGNORE_OTHER_FILES)
|| ce->info.user.filename == CG(compiled_filename);
}
}
static zend_class_entry *lookup_class(
zend_class_entry *scope, zend_string *name, zend_bool register_unresolved) {
uint32_t flags = ZEND_FETCH_CLASS_ALLOW_UNLINKED | ZEND_FETCH_CLASS_NO_AUTOLOAD;
zend_class_entry *ce = zend_lookup_class_ex(name, NULL, flags);
if (!CG(in_compilation)) {
if (ce) {
return ce;
}
if (register_unresolved) {
/* We'll autoload this class and process delayed variance obligations later. */
if (!CG(delayed_autoloads)) {
ALLOC_HASHTABLE(CG(delayed_autoloads));
zend_hash_init(CG(delayed_autoloads), 0, NULL, NULL, 0);
}
zend_hash_add_empty_element(CG(delayed_autoloads), name);
}
} else {
if (ce && class_visible(ce)) {
return ce;
}
/* The current class may not be registered yet, so check for it explicitly. */
if (zend_string_equals_ci(scope->name, name)) {
return scope;
}
}
return NULL;
}
/* Instanceof that's safe to use on unlinked classes. */
static zend_bool unlinked_instanceof(zend_class_entry *ce1, zend_class_entry *ce2) {
if (ce1 == ce2) {
return 1;
}
if (ce1->ce_flags & ZEND_ACC_LINKED) {
return instanceof_function(ce1, ce2);
}
if (ce1->parent) {
zend_class_entry *parent_ce;
if (ce1->ce_flags & ZEND_ACC_RESOLVED_PARENT) {
parent_ce = ce1->parent;
} else {
parent_ce = zend_lookup_class_ex(ce1->parent_name, NULL,
ZEND_FETCH_CLASS_ALLOW_UNLINKED | ZEND_FETCH_CLASS_NO_AUTOLOAD);
}
/* It's not sufficient to only check the parent chain itself, as need to do a full
* recursive instanceof in case the parent interfaces haven't been copied yet. */
if (parent_ce && unlinked_instanceof(parent_ce, ce2)) {
return 1;
}
}
if (ce1->num_interfaces) {
uint32_t i;
if (ce1->ce_flags & ZEND_ACC_RESOLVED_INTERFACES) {
/* Unlike the normal instanceof_function(), we have to perform a recursive
* check here, as the parent interfaces might not have been fully copied yet. */
for (i = 0; i < ce1->num_interfaces; i++) {
if (unlinked_instanceof(ce1->interfaces[i], ce2)) {
return 1;
}
}
} else {
for (i = 0; i < ce1->num_interfaces; i++) {
zend_class_entry *ce = zend_lookup_class_ex(
ce1->interface_names[i].name, ce1->interface_names[i].lc_name,
ZEND_FETCH_CLASS_ALLOW_UNLINKED | ZEND_FETCH_CLASS_NO_AUTOLOAD);
if (ce && unlinked_instanceof(ce, ce2)) {
return 1;
}
}
}
}
return 0;
}
static zend_bool zend_type_contains_traversable(zend_type type) {
zend_type *single_type;
ZEND_TYPE_FOREACH(type, single_type) {
if (ZEND_TYPE_HAS_NAME(*single_type)
&& zend_string_equals_literal_ci(ZEND_TYPE_NAME(*single_type), "Traversable")) {
return 1;
}
} ZEND_TYPE_FOREACH_END();
return 0;
}
static zend_bool zend_type_permits_self(
zend_type type, zend_class_entry *scope, zend_class_entry *self) {
if (ZEND_TYPE_FULL_MASK(type) & MAY_BE_OBJECT) {
return 1;
}
/* Any types that may satisfy self must have already been loaded at this point
* (as a parent or interface), so we never need to register delayed variance obligations
* for this case. */
zend_type *single_type;
ZEND_TYPE_FOREACH(type, single_type) {
if (ZEND_TYPE_HAS_NAME(*single_type)) {
zend_string *name = resolve_class_name(scope, ZEND_TYPE_NAME(*single_type));
zend_class_entry *ce = lookup_class(self, name, /* register_unresolved */ 0);
if (ce && unlinked_instanceof(self, ce)) {
return 1;
}
}
} ZEND_TYPE_FOREACH_END();
return 0;
}
/* Unresolved means that class declarations that are currently not available are needed to
* determine whether the inheritance is valid or not. At runtime UNRESOLVED should be treated
* as an ERROR. */
typedef enum {
INHERITANCE_UNRESOLVED = -1,
INHERITANCE_ERROR = 0,
INHERITANCE_SUCCESS = 1,
} inheritance_status;
static inheritance_status zend_perform_covariant_class_type_check(
zend_class_entry *fe_scope, zend_string *fe_class_name, zend_class_entry *fe_ce,
zend_class_entry *proto_scope, zend_type proto_type,
zend_bool register_unresolved) {
zend_bool have_unresolved = 0;
if (ZEND_TYPE_FULL_MASK(proto_type) & MAY_BE_OBJECT) {
/* Currently, any class name would be allowed here. We still perform a class lookup
* for forward-compatibility reasons, as we may have named types in the future that
* are not classes (such as enums or typedefs). */
if (!fe_ce) fe_ce = lookup_class(fe_scope, fe_class_name, register_unresolved);
if (!fe_ce) {
have_unresolved = 1;
} else {
return INHERITANCE_SUCCESS;
}
}
if (ZEND_TYPE_FULL_MASK(proto_type) & MAY_BE_ITERABLE) {
if (!fe_ce) fe_ce = lookup_class(fe_scope, fe_class_name, register_unresolved);
if (!fe_ce) {
have_unresolved = 1;
} else if (unlinked_instanceof(fe_ce, zend_ce_traversable)) {
return INHERITANCE_SUCCESS;
}
}
zend_type *single_type;
ZEND_TYPE_FOREACH(proto_type, single_type) {
zend_class_entry *proto_ce;
if (ZEND_TYPE_HAS_NAME(*single_type)) {
zend_string *proto_class_name =
resolve_class_name(proto_scope, ZEND_TYPE_NAME(*single_type));
if (zend_string_equals_ci(fe_class_name, proto_class_name)) {
return INHERITANCE_SUCCESS;
}
if (!fe_ce) fe_ce = lookup_class(fe_scope, fe_class_name, register_unresolved);
proto_ce =
lookup_class(proto_scope, proto_class_name, register_unresolved);
} else if (ZEND_TYPE_HAS_CE(*single_type)) {
if (!fe_ce) fe_ce = lookup_class(fe_scope, fe_class_name, register_unresolved);
proto_ce = ZEND_TYPE_CE(*single_type);
} else {
continue;
}
if (!fe_ce || !proto_ce) {
have_unresolved = 1;
} else if (unlinked_instanceof(fe_ce, proto_ce)) {
return INHERITANCE_SUCCESS;
}
} ZEND_TYPE_FOREACH_END();
return have_unresolved ? INHERITANCE_UNRESOLVED : INHERITANCE_ERROR;
}
static inheritance_status zend_perform_covariant_type_check(
zend_class_entry *fe_scope, zend_type fe_type,
zend_class_entry *proto_scope, zend_type proto_type) /* {{{ */
{
ZEND_ASSERT(ZEND_TYPE_IS_SET(fe_type) && ZEND_TYPE_IS_SET(proto_type));
/* Builtin types may be removed, but not added */
uint32_t fe_type_mask = ZEND_TYPE_PURE_MASK(fe_type);
uint32_t proto_type_mask = ZEND_TYPE_PURE_MASK(proto_type);
uint32_t added_types = fe_type_mask & ~proto_type_mask;
if (added_types) {
// TODO: Make "iterable" an alias of "array|Traversable" instead,
// so these special cases will be handled automatically.
if ((added_types & MAY_BE_ITERABLE)
&& (proto_type_mask & MAY_BE_ARRAY)
&& zend_type_contains_traversable(proto_type)) {
/* Replacing array|Traversable with iterable is okay */
added_types &= ~MAY_BE_ITERABLE;
}
if ((added_types & MAY_BE_ARRAY) && (proto_type_mask & MAY_BE_ITERABLE)) {
/* Replacing iterable with array is okay */
added_types &= ~MAY_BE_ARRAY;
}
if ((added_types & MAY_BE_STATIC)
&& zend_type_permits_self(proto_type, proto_scope, fe_scope)) {
/* Replacing type that accepts self with static is okay */
added_types &= ~MAY_BE_STATIC;
}
if (added_types) {
/* Otherwise adding new types is illegal */
return INHERITANCE_ERROR;
}
}
zend_type *single_type;
zend_bool all_success = 1;
/* First try to check whether we can succeed without resolving anything */
ZEND_TYPE_FOREACH(fe_type, single_type) {
inheritance_status status;
if (ZEND_TYPE_HAS_NAME(*single_type)) {
zend_string *fe_class_name =
resolve_class_name(fe_scope, ZEND_TYPE_NAME(*single_type));
status = zend_perform_covariant_class_type_check(
fe_scope, fe_class_name, NULL,
proto_scope, proto_type, /* register_unresolved */ 0);
} else if (ZEND_TYPE_HAS_CE(*single_type)) {
zend_class_entry *fe_ce = ZEND_TYPE_CE(*single_type);
status = zend_perform_covariant_class_type_check(
fe_scope, fe_ce->name, fe_ce,
proto_scope, proto_type, /* register_unresolved */ 0);
} else {
continue;
}
if (status == INHERITANCE_ERROR) {
return INHERITANCE_ERROR;
}
if (status != INHERITANCE_SUCCESS) {
all_success = 0;
}
} ZEND_TYPE_FOREACH_END();
/* All individual checks succeeded, overall success */
if (all_success) {
return INHERITANCE_SUCCESS;
}
/* Register all classes that may have to be resolved */
ZEND_TYPE_FOREACH(fe_type, single_type) {
if (ZEND_TYPE_HAS_NAME(*single_type)) {
zend_string *fe_class_name =
resolve_class_name(fe_scope, ZEND_TYPE_NAME(*single_type));
zend_perform_covariant_class_type_check(
fe_scope, fe_class_name, NULL,
proto_scope, proto_type, /* register_unresolved */ 1);
} else if (ZEND_TYPE_HAS_CE(*single_type)) {
zend_class_entry *fe_ce = ZEND_TYPE_CE(*single_type);
zend_perform_covariant_class_type_check(
fe_scope, fe_ce->name, fe_ce,
proto_scope, proto_type, /* register_unresolved */ 1);
}
} ZEND_TYPE_FOREACH_END();
return INHERITANCE_UNRESOLVED;
}
/* }}} */
static inheritance_status zend_do_perform_arg_type_hint_check(
zend_class_entry *fe_scope, zend_arg_info *fe_arg_info,
zend_class_entry *proto_scope, zend_arg_info *proto_arg_info) /* {{{ */
{
if (!ZEND_TYPE_IS_SET(fe_arg_info->type) || ZEND_TYPE_PURE_MASK(fe_arg_info->type) == MAY_BE_ANY) {
/* Child with no type or mixed type is always compatible */
return INHERITANCE_SUCCESS;
}
if (!ZEND_TYPE_IS_SET(proto_arg_info->type)) {
/* Child defines a type, but parent doesn't, violates LSP */
return INHERITANCE_ERROR;
}
/* Contravariant type check is performed as a covariant type check with swapped
* argument order. */
return zend_perform_covariant_type_check(
proto_scope, proto_arg_info->type, fe_scope, fe_arg_info->type);
}
/* }}} */
/* For trait methods, fe_scope/proto_scope may differ from fe/proto->common.scope,
* as self will refer to the self of the class the trait is used in, not the trait
* the method was declared in. */
static inheritance_status zend_do_perform_implementation_check(
const zend_function *fe, zend_class_entry *fe_scope,
const zend_function *proto, zend_class_entry *proto_scope) /* {{{ */
{
uint32_t i, num_args, proto_num_args, fe_num_args;
inheritance_status status, local_status;
zend_bool proto_is_variadic, fe_is_variadic;
/* Checks for constructors only if they are declared in an interface,
* or explicitly marked as abstract
*/
ZEND_ASSERT(!((fe->common.fn_flags & ZEND_ACC_CTOR)
&& ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0
&& (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)));
/* If the prototype method is private and not abstract, we do not enforce a signature.
* private abstract methods can only occur in traits. */
ZEND_ASSERT(!(proto->common.fn_flags & ZEND_ACC_PRIVATE)
|| (proto->common.fn_flags & ZEND_ACC_ABSTRACT));
/* The number of required arguments cannot increase. */
if (proto->common.required_num_args < fe->common.required_num_args) {
return INHERITANCE_ERROR;
}
/* by-ref constraints on return values are covariant */
if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)
&& !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) {
return INHERITANCE_ERROR;
}
proto_is_variadic = (proto->common.fn_flags & ZEND_ACC_VARIADIC) != 0;
fe_is_variadic = (fe->common.fn_flags & ZEND_ACC_VARIADIC) != 0;
/* A variadic function cannot become non-variadic */
if (proto_is_variadic && !fe_is_variadic) {
return INHERITANCE_ERROR;
}
/* The variadic argument is not included in the stored argument count. */
proto_num_args = proto->common.num_args + proto_is_variadic;
fe_num_args = fe->common.num_args + fe_is_variadic;
num_args = MAX(proto_num_args, fe_num_args);
status = INHERITANCE_SUCCESS;
for (i = 0; i < num_args; i++) {
zend_arg_info *proto_arg_info =
i < proto_num_args ? &proto->common.arg_info[i] :
proto_is_variadic ? &proto->common.arg_info[proto_num_args - 1] : NULL;
zend_arg_info *fe_arg_info =
i < fe_num_args ? &fe->common.arg_info[i] :
fe_is_variadic ? &fe->common.arg_info[fe_num_args - 1] : NULL;
if (!proto_arg_info) {
/* A new (optional) argument has been added, which is fine. */
continue;
}
if (!fe_arg_info) {
/* An argument has been removed. This is considered illegal, because arity checks
* work based on a model where passing more than the declared number of parameters
* to a function is an error. */
return INHERITANCE_ERROR;
}
local_status = zend_do_perform_arg_type_hint_check(
fe_scope, fe_arg_info, proto_scope, proto_arg_info);
if (UNEXPECTED(local_status != INHERITANCE_SUCCESS)) {
if (UNEXPECTED(local_status == INHERITANCE_ERROR)) {
return INHERITANCE_ERROR;
}
ZEND_ASSERT(local_status == INHERITANCE_UNRESOLVED);
status = INHERITANCE_UNRESOLVED;
}
/* by-ref constraints on arguments are invariant */
if (ZEND_ARG_SEND_MODE(fe_arg_info) != ZEND_ARG_SEND_MODE(proto_arg_info)) {
return INHERITANCE_ERROR;
}
}
/* Check return type compatibility, but only if the prototype already specifies
* a return type. Adding a new return type is always valid. */
if (proto->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE) {
/* Removing a return type is not valid. */
if (!(fe->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE)) {
return INHERITANCE_ERROR;
}
local_status = zend_perform_covariant_type_check(
fe_scope, fe->common.arg_info[-1].type,
proto_scope, proto->common.arg_info[-1].type);
if (UNEXPECTED(local_status != INHERITANCE_SUCCESS)) {
if (UNEXPECTED(local_status == INHERITANCE_ERROR)) {
return INHERITANCE_ERROR;
}
ZEND_ASSERT(local_status == INHERITANCE_UNRESOLVED);
status = INHERITANCE_UNRESOLVED;
}
}
return status;
}
/* }}} */
static ZEND_COLD void zend_append_type_hint(
smart_str *str, zend_class_entry *scope, zend_arg_info *arg_info, bool return_hint) /* {{{ */
{
if (ZEND_TYPE_IS_SET(arg_info->type)) {
zend_string *type_str = zend_type_to_string_resolved(arg_info->type, scope);
smart_str_append(str, type_str);
zend_string_release(type_str);
if (!return_hint) {
smart_str_appendc(str, ' ');
}
}
}
/* }}} */
static ZEND_COLD zend_string *zend_get_function_declaration(
const zend_function *fptr, zend_class_entry *scope) /* {{{ */
{
smart_str str = {0};
if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) {
smart_str_appends(&str, "& ");
}
if (fptr->common.scope) {
/* cut off on NULL byte ... class@anonymous */
smart_str_appendl(&str, ZSTR_VAL(fptr->common.scope->name), strlen(ZSTR_VAL(fptr->common.scope->name)));
smart_str_appends(&str, "::");
}
smart_str_append(&str, fptr->common.function_name);
smart_str_appendc(&str, '(');
if (fptr->common.arg_info) {
uint32_t i, num_args, required;
zend_arg_info *arg_info = fptr->common.arg_info;
required = fptr->common.required_num_args;
num_args = fptr->common.num_args;
if (fptr->common.fn_flags & ZEND_ACC_VARIADIC) {
num_args++;
}
for (i = 0; i < num_args;) {
zend_append_type_hint(&str, scope, arg_info, 0);
if (ZEND_ARG_SEND_MODE(arg_info)) {
smart_str_appendc(&str, '&');
}
if (ZEND_ARG_IS_VARIADIC(arg_info)) {
smart_str_appends(&str, "...");
}
smart_str_appendc(&str, '$');
if (fptr->type == ZEND_INTERNAL_FUNCTION) {
smart_str_appends(&str, ((zend_internal_arg_info*)arg_info)->name);
} else {
smart_str_appendl(&str, ZSTR_VAL(arg_info->name), ZSTR_LEN(arg_info->name));
}
if (i >= required && !ZEND_ARG_IS_VARIADIC(arg_info)) {
smart_str_appends(&str, " = ");
if (fptr->type == ZEND_INTERNAL_FUNCTION) {
if (((zend_internal_arg_info*)arg_info)->default_value) {
smart_str_appends(&str, ((zend_internal_arg_info*)arg_info)->default_value);
} else {
smart_str_appends(&str, "<default>");
}
} else {
zend_op *precv = NULL;
{
uint32_t idx = i;
zend_op *op = fptr->op_array.opcodes;
zend_op *end = op + fptr->op_array.last;
++idx;
while (op < end) {
if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT)
&& op->op1.num == (zend_ulong)idx)
{
precv = op;
}
++op;
}
}
if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) {
zval *zv = RT_CONSTANT(precv, precv->op2);
if (Z_TYPE_P(zv) == IS_FALSE) {
smart_str_appends(&str, "false");
} else if (Z_TYPE_P(zv) == IS_TRUE) {
smart_str_appends(&str, "true");
} else if (Z_TYPE_P(zv) == IS_NULL) {
smart_str_appends(&str, "null");
} else if (Z_TYPE_P(zv) == IS_STRING) {
smart_str_appendc(&str, '\'');
smart_str_appendl(&str, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10));
if (Z_STRLEN_P(zv) > 10) {
smart_str_appends(&str, "...");
}
smart_str_appendc(&str, '\'');
} else if (Z_TYPE_P(zv) == IS_ARRAY) {
if (zend_hash_num_elements(Z_ARRVAL_P(zv)) == 0) {
smart_str_appends(&str, "[]");
} else {
smart_str_appends(&str, "[...]");
}
} else if (Z_TYPE_P(zv) == IS_CONSTANT_AST) {
zend_ast *ast = Z_ASTVAL_P(zv);
if (ast->kind == ZEND_AST_CONSTANT) {
smart_str_append(&str, zend_ast_get_constant_name(ast));
} else {
smart_str_appends(&str, "<expression>");
}
} else {
zend_string *tmp_zv_str;
zend_string *zv_str = zval_get_tmp_string(zv, &tmp_zv_str);
smart_str_append(&str, zv_str);
zend_tmp_string_release(tmp_zv_str);
}
}
}
}
if (++i < num_args) {
smart_str_appends(&str, ", ");
}
arg_info++;
}
}
smart_str_appendc(&str, ')');
if (fptr->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE) {
smart_str_appends(&str, ": ");
zend_append_type_hint(&str, scope, fptr->common.arg_info - 1, 1);
}
smart_str_0(&str);
return str.s;
}
/* }}} */
static zend_always_inline uint32_t func_lineno(const zend_function *fn) {
return fn->common.type == ZEND_USER_FUNCTION ? fn->op_array.line_start : 0;
}
static void ZEND_COLD emit_incompatible_method_error(
const zend_function *child, zend_class_entry *child_scope,
const zend_function *parent, zend_class_entry *parent_scope,
inheritance_status status) {
zend_string *parent_prototype = zend_get_function_declaration(parent, parent_scope);
zend_string *child_prototype = zend_get_function_declaration(child, child_scope);
if (status == INHERITANCE_UNRESOLVED) {
/* Fetch the first unresolved class from registered autoloads */
zend_string *unresolved_class = NULL;
ZEND_HASH_FOREACH_STR_KEY(CG(delayed_autoloads), unresolved_class) {
break;
} ZEND_HASH_FOREACH_END();
ZEND_ASSERT(unresolved_class);
zend_error_at(E_COMPILE_ERROR, NULL, func_lineno(child),
"Could not check compatibility between %s and %s, because class %s is not available",
ZSTR_VAL(child_prototype), ZSTR_VAL(parent_prototype), ZSTR_VAL(unresolved_class));
} else {
zend_error_at(E_COMPILE_ERROR, NULL, func_lineno(child),
"Declaration of %s must be compatible with %s",
ZSTR_VAL(child_prototype), ZSTR_VAL(parent_prototype));
}
zend_string_efree(child_prototype);
zend_string_efree(parent_prototype);
}
static void perform_delayable_implementation_check(
zend_class_entry *ce,
const zend_function *fe, zend_class_entry *fe_scope,
const zend_function *proto, zend_class_entry *proto_scope)
{
inheritance_status status =
zend_do_perform_implementation_check(fe, fe_scope, proto, proto_scope);
if (UNEXPECTED(status != INHERITANCE_SUCCESS)) {
if (EXPECTED(status == INHERITANCE_UNRESOLVED)) {
add_compatibility_obligation(ce, fe, fe_scope, proto, proto_scope);
} else {
ZEND_ASSERT(status == INHERITANCE_ERROR);
emit_incompatible_method_error(fe, fe_scope, proto, proto_scope, status);
}
}
}
static zend_always_inline inheritance_status do_inheritance_check_on_method_ex(
zend_function *child, zend_class_entry *child_scope,
zend_function *parent, zend_class_entry *parent_scope,
zend_class_entry *ce, zval *child_zv,
zend_bool check_visibility, zend_bool check_only, zend_bool checked) /* {{{ */
{
uint32_t child_flags;
uint32_t parent_flags = parent->common.fn_flags;
zend_function *proto;
if (UNEXPECTED((parent_flags & ZEND_ACC_PRIVATE) && !(parent_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_CTOR))) {
if (!check_only) {
child->common.fn_flags |= ZEND_ACC_CHANGED;
}
/* The parent method is private and not an abstract so we don't need to check any inheritance rules */
return INHERITANCE_SUCCESS;
}
if (!checked && UNEXPECTED(parent_flags & ZEND_ACC_FINAL)) {
if (check_only) {
return INHERITANCE_ERROR;
}
zend_error_at_noreturn(E_COMPILE_ERROR, NULL, func_lineno(child),
"Cannot override final method %s::%s()",
ZEND_FN_SCOPE_NAME(parent), ZSTR_VAL(child->common.function_name));
}
child_flags = child->common.fn_flags;
/* You cannot change from static to non static and vice versa.
*/
if (!checked && UNEXPECTED((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC))) {
if (check_only) {
return INHERITANCE_ERROR;
}
if (child_flags & ZEND_ACC_STATIC) {
zend_error_at_noreturn(E_COMPILE_ERROR, NULL, func_lineno(child),
"Cannot make non static method %s::%s() static in class %s",
ZEND_FN_SCOPE_NAME(parent), ZSTR_VAL(child->common.function_name), ZEND_FN_SCOPE_NAME(child));
} else {
zend_error_at_noreturn(E_COMPILE_ERROR, NULL, func_lineno(child),
"Cannot make static method %s::%s() non static in class %s",
ZEND_FN_SCOPE_NAME(parent), ZSTR_VAL(child->common.function_name), ZEND_FN_SCOPE_NAME(child));
}
}
/* Disallow making an inherited method abstract. */
if (!checked && UNEXPECTED((child_flags & ZEND_ACC_ABSTRACT) > (parent_flags & ZEND_ACC_ABSTRACT))) {
if (check_only) {
return INHERITANCE_ERROR;
}
zend_error_at_noreturn(E_COMPILE_ERROR, NULL, func_lineno(child),
"Cannot make non abstract method %s::%s() abstract in class %s",
ZEND_FN_SCOPE_NAME(parent), ZSTR_VAL(child->common.function_name), ZEND_FN_SCOPE_NAME(child));
}
if (!check_only && (parent_flags & (ZEND_ACC_PRIVATE|ZEND_ACC_CHANGED))) {
child->common.fn_flags |= ZEND_ACC_CHANGED;
}
proto = parent->common.prototype ?
parent->common.prototype : parent;
if (parent_flags & ZEND_ACC_CTOR) {
/* ctors only have a prototype if is abstract (or comes from an interface) */
/* and if that is the case, we want to check inheritance against it */
if (!(proto->common.fn_flags & ZEND_ACC_ABSTRACT)) {
return INHERITANCE_SUCCESS;
}
parent = proto;
}
if (!check_only && child->common.prototype != proto && child_zv) {
do {
if (child->common.scope != ce
&& child->type == ZEND_USER_FUNCTION
&& !child->op_array.static_variables) {
if (ce->ce_flags & ZEND_ACC_INTERFACE) {
/* Few parent interfaces contain the same method */
break;
} else {
/* op_array wasn't duplicated yet */
zend_function *new_function = zend_arena_alloc(&CG(arena), sizeof(zend_op_array));
memcpy(new_function, child, sizeof(zend_op_array));
Z_PTR_P(child_zv) = child = new_function;
}
}
child->common.prototype = proto;
} while (0);
}
/* Prevent derived classes from restricting access that was available in parent classes (except deriving from non-abstract ctors) */
if (!checked && check_visibility
&& (child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) {
if (check_only) {
return INHERITANCE_ERROR;
}
zend_error_at_noreturn(E_COMPILE_ERROR, NULL, func_lineno(child),
"Access level to %s::%s() must be %s (as in class %s)%s",
ZEND_FN_SCOPE_NAME(child), ZSTR_VAL(child->common.function_name), zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker");
}
if (!checked) {
if (check_only) {
return zend_do_perform_implementation_check(child, child_scope, parent, parent_scope);
}
perform_delayable_implementation_check(ce, child, child_scope, parent, parent_scope);
}
return INHERITANCE_SUCCESS;
}
/* }}} */
static zend_never_inline void do_inheritance_check_on_method(
zend_function *child, zend_class_entry *child_scope,
zend_function *parent, zend_class_entry *parent_scope,
zend_class_entry *ce, zval *child_zv, zend_bool check_visibility)
{
do_inheritance_check_on_method_ex(child, child_scope, parent, parent_scope, ce, child_zv, check_visibility, 0, 0);
}
static zend_always_inline void do_inherit_method(zend_string *key, zend_function *parent, zend_class_entry *ce, zend_bool is_interface, zend_bool checked) /* {{{ */
{
zval *child = zend_hash_find_ex(&ce->function_table, key, 1);
if (child) {
zend_function *func = (zend_function*)Z_PTR_P(child);
if (is_interface && UNEXPECTED(func == parent)) {
/* The same method in interface may be inherited few times */
return;
}
if (checked) {
do_inheritance_check_on_method_ex(
func, func->common.scope, parent, parent->common.scope, ce, child,
/* check_visibility */ 1, 0, checked);
} else {
do_inheritance_check_on_method(
func, func->common.scope, parent, parent->common.scope, ce, child,
/* check_visibility */ 1);
}
} else {
if (is_interface || (parent->common.fn_flags & (ZEND_ACC_ABSTRACT))) {
ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS;
}
parent = zend_duplicate_function(parent, ce, is_interface);
if (!is_interface) {
_zend_hash_append_ptr(&ce->function_table, key, parent);
} else {
zend_hash_add_new_ptr(&ce->function_table, key, parent);
}
}
}
/* }}} */
inheritance_status property_types_compatible(
const zend_property_info *parent_info, const zend_property_info *child_info) {
if (ZEND_TYPE_PURE_MASK(parent_info->type) == ZEND_TYPE_PURE_MASK(child_info->type)
&& ZEND_TYPE_NAME(parent_info->type) == ZEND_TYPE_NAME(child_info->type)) {
return INHERITANCE_SUCCESS;
}
if (ZEND_TYPE_IS_SET(parent_info->type) != ZEND_TYPE_IS_SET(child_info->type)) {
return INHERITANCE_ERROR;
}
/* Perform a covariant type check in both directions to determined invariance. */
inheritance_status status1 = zend_perform_covariant_type_check(
child_info->ce, child_info->type, parent_info->ce, parent_info->type);
inheritance_status status2 = zend_perform_covariant_type_check(
parent_info->ce, parent_info->type, child_info->ce, child_info->type);
if (status1 == INHERITANCE_SUCCESS && status2 == INHERITANCE_SUCCESS) {
return INHERITANCE_SUCCESS;
}
if (status1 == INHERITANCE_ERROR || status2 == INHERITANCE_ERROR) {
return INHERITANCE_ERROR;
}
ZEND_ASSERT(status1 == INHERITANCE_UNRESOLVED || status2 == INHERITANCE_UNRESOLVED);
return INHERITANCE_UNRESOLVED;
}
static void emit_incompatible_property_error(
const zend_property_info *child, const zend_property_info *parent) {
zend_string *type_str = zend_type_to_string_resolved(parent->type, parent->ce);
zend_error_noreturn(E_COMPILE_ERROR,
"Type of %s::$%s must be %s (as in class %s)",
ZSTR_VAL(child->ce->name),
zend_get_unmangled_property_name(child->name),
ZSTR_VAL(type_str),
ZSTR_VAL(parent->ce->name));
}
static void do_inherit_property(zend_property_info *parent_info, zend_string *key, zend_class_entry *ce) /* {{{ */
{
zval *child = zend_hash_find_ex(&ce->properties_info, key, 1);
zend_property_info *child_info;
if (UNEXPECTED(child)) {
child_info = Z_PTR_P(child);
if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_CHANGED)) {
child_info->flags |= ZEND_ACC_CHANGED;
}
if (!(parent_info->flags & ZEND_ACC_PRIVATE)) {
if (UNEXPECTED((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC))) {
zend_error_noreturn(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s",
(parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ZSTR_VAL(parent_info->ce->name), ZSTR_VAL(key),
(child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ZSTR_VAL(ce->name), ZSTR_VAL(key));
}
if (UNEXPECTED((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK))) {
zend_error_noreturn(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ZSTR_VAL(ce->name), ZSTR_VAL(key), zend_visibility_string(parent_info->flags), ZSTR_VAL(parent_info->ce->name), (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker");
} else if ((child_info->flags & ZEND_ACC_STATIC) == 0) {
int parent_num = OBJ_PROP_TO_NUM(parent_info->offset);
int child_num = OBJ_PROP_TO_NUM(child_info->offset);
/* Don't keep default properties in GC (they may be freed by opcache) */
zval_ptr_dtor_nogc(&(ce->default_properties_table[parent_num]));
ce->default_properties_table[parent_num] = ce->default_properties_table[child_num];
ZVAL_UNDEF(&ce->default_properties_table[child_num]);
child_info->offset = parent_info->offset;
}
if (UNEXPECTED(ZEND_TYPE_IS_SET(parent_info->type))) {
inheritance_status status = property_types_compatible(parent_info, child_info);
if (status == INHERITANCE_ERROR) {
emit_incompatible_property_error(child_info, parent_info);
}
if (status == INHERITANCE_UNRESOLVED) {
add_property_compatibility_obligation(ce, child_info, parent_info);
}
} else if (UNEXPECTED(ZEND_TYPE_IS_SET(child_info->type) && !ZEND_TYPE_IS_SET(parent_info->type))) {
zend_error_noreturn(E_COMPILE_ERROR,
"Type of %s::$%s must not be defined (as in class %s)",
ZSTR_VAL(ce->name),
ZSTR_VAL(key),
ZSTR_VAL(parent_info->ce->name));
}
}
} else {
if (UNEXPECTED(ce->type & ZEND_INTERNAL_CLASS)) {
child_info = zend_duplicate_property_info_internal(parent_info);
} else {
child_info = parent_info;
}
_zend_hash_append_ptr(&ce->properties_info, key, child_info);
}
}
/* }}} */
static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface) /* {{{ */
{
if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce) == FAILURE) {
zend_error_noreturn(E_CORE_ERROR, "Class %s could not implement interface %s", ZSTR_VAL(ce->name), ZSTR_VAL(iface->name));
}
/* This should be prevented by the class lookup logic. */
ZEND_ASSERT(ce != iface);
}
/* }}} */
static void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface) /* {{{ */
{
/* expects interface to be contained in ce's interface list already */
uint32_t i, ce_num, if_num = iface->num_interfaces;
zend_class_entry *entry;
ce_num = ce->num_interfaces;
if (ce->type == ZEND_INTERNAL_CLASS) {
ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num));
} else {
ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num));
}
/* Inherit the interfaces, only if they're not already inherited by the class */
while (if_num--) {
entry = iface->interfaces[if_num];
for (i = 0; i < ce_num; i++) {
if (ce->interfaces[i] == entry) {
break;
}
}
if (i == ce_num) {
ce->interfaces[ce->num_interfaces++] = entry;
}
}
ce->ce_flags |= ZEND_ACC_RESOLVED_INTERFACES;
/* and now call the implementing handlers */
while (ce_num < ce->num_interfaces) {
do_implement_interface(ce, ce->interfaces[ce_num++]);
}
}
/* }}} */
static void do_inherit_class_constant(zend_string *name, zend_class_constant *parent_const, zend_class_entry *ce) /* {{{ */
{
zval *zv = zend_hash_find_ex(&ce->constants_table, name, 1);
zend_class_constant *c;
if (zv != NULL) {
c = (zend_class_constant*)Z_PTR_P(zv);
if (UNEXPECTED((Z_ACCESS_FLAGS(c->value) & ZEND_ACC_PPP_MASK) > (Z_ACCESS_FLAGS(parent_const->value) & ZEND_ACC_PPP_MASK))) {
zend_error_noreturn(E_COMPILE_ERROR, "Access level to %s::%s must be %s (as in class %s)%s",
ZSTR_VAL(ce->name), ZSTR_VAL(name), zend_visibility_string(Z_ACCESS_FLAGS(parent_const->value)), ZSTR_VAL(parent_const->ce->name), (Z_ACCESS_FLAGS(parent_const->value) & ZEND_ACC_PUBLIC) ? "" : " or weaker");
}
} else if (!(Z_ACCESS_FLAGS(parent_const->value) & ZEND_ACC_PRIVATE)) {
if (Z_TYPE(parent_const->value) == IS_CONSTANT_AST) {
ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED;
}
if (ce->type & ZEND_INTERNAL_CLASS) {
c = pemalloc(sizeof(zend_class_constant), 1);
memcpy(c, parent_const, sizeof(zend_class_constant));
parent_const = c;
}
_zend_hash_append_ptr(&ce->constants_table, name, parent_const);
}
}
/* }}} */
void zend_build_properties_info_table(zend_class_entry *ce)
{
zend_property_info **table, *prop;
size_t size;
if (ce->default_properties_count == 0) {
return;
}
ZEND_ASSERT(ce->properties_info_table == NULL);
size = sizeof(zend_property_info *) * ce->default_properties_count;
if (ce->type == ZEND_USER_CLASS) {
ce->properties_info_table = table = zend_arena_alloc(&CG(arena), size);
} else {
ce->properties_info_table = table = pemalloc(size, 1);
}
/* Dead slots may be left behind during inheritance. Make sure these are NULLed out. */
memset(table, 0, size);
if (ce->parent && ce->parent->default_properties_count != 0) {
zend_property_info **parent_table = ce->parent->properties_info_table;
memcpy(
table, parent_table,
sizeof(zend_property_info *) * ce->parent->default_properties_count
);
/* Child did not add any new properties, we are done */
if (ce->default_properties_count == ce->parent->default_properties_count) {
return;
}
}
ZEND_HASH_FOREACH_PTR(&ce->properties_info, prop) {
if (prop->ce == ce && (prop->flags & ZEND_ACC_STATIC) == 0) {
table[OBJ_PROP_TO_NUM(prop->offset)] = prop;
}
} ZEND_HASH_FOREACH_END();
}
ZEND_API void zend_do_inheritance_ex(zend_class_entry *ce, zend_class_entry *parent_ce, zend_bool checked) /* {{{ */
{
zend_property_info *property_info;
zend_function *func;
zend_string *key;
if (UNEXPECTED(ce->ce_flags & ZEND_ACC_INTERFACE)) {
/* Interface can only inherit other interfaces */
if (UNEXPECTED(!(parent_ce->ce_flags & ZEND_ACC_INTERFACE))) {
zend_error_noreturn(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ZSTR_VAL(ce->name), ZSTR_VAL(parent_ce->name));
}
} else if (UNEXPECTED(parent_ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_TRAIT|ZEND_ACC_FINAL))) {
/* Class declaration must not extend traits or interfaces */
if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) {
zend_error_noreturn(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ZSTR_VAL(ce->name), ZSTR_VAL(parent_ce->name));
} else if (parent_ce->ce_flags & ZEND_ACC_TRAIT) {
zend_error_noreturn(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ZSTR_VAL(ce->name), ZSTR_VAL(parent_ce->name));
}
/* Class must not extend a final class */
if (parent_ce->ce_flags & ZEND_ACC_FINAL) {
zend_error_noreturn(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ZSTR_VAL(ce->name), ZSTR_VAL(parent_ce->name));
}
}
if (ce->parent_name) {
zend_string_release_ex(ce->parent_name, 0);
}
ce->parent = parent_ce;
ce->ce_flags |= ZEND_ACC_RESOLVED_PARENT;
/* Inherit properties */
if (parent_ce->default_properties_count) {
zval *src, *dst, *end;
if (ce->default_properties_count) {
zval *table = pemalloc(sizeof(zval) * (ce->default_properties_count + parent_ce->default_properties_count), ce->type == ZEND_INTERNAL_CLASS);
src = ce->default_properties_table + ce->default_properties_count;
end = table + parent_ce->default_properties_count;
dst = end + ce->default_properties_count;
ce->default_properties_table = table;
do {
dst--;
src--;
ZVAL_COPY_VALUE_PROP(dst, src);
} while (dst != end);
pefree(src, ce->type == ZEND_INTERNAL_CLASS);
end = ce->default_properties_table;
} else {
end = pemalloc(sizeof(zval) * parent_ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS);
dst = end + parent_ce->default_properties_count;
ce->default_properties_table = end;
}
src = parent_ce->default_properties_table + parent_ce->default_properties_count;
if (UNEXPECTED(parent_ce->type != ce->type)) {
/* User class extends internal */
do {
dst--;
src--;
ZVAL_COPY_OR_DUP_PROP(dst, src);
if (Z_OPT_TYPE_P(dst) == IS_CONSTANT_AST) {
ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED;
}
continue;
} while (dst != end);
} else {
do {
dst--;
src--;
ZVAL_COPY_PROP(dst, src);
if (Z_OPT_TYPE_P(dst) == IS_CONSTANT_AST) {
ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED;
}
continue;
} while (dst != end);
}
ce->default_properties_count += parent_ce->default_properties_count;
}
if (parent_ce->default_static_members_count) {
zval *src, *dst, *end;
if (ce->default_static_members_count) {
zval *table = pemalloc(sizeof(zval) * (ce->default_static_members_count + parent_ce->default_static_members_count), ce->type == ZEND_INTERNAL_CLASS);
src = ce->default_static_members_table + ce->default_static_members_count;
end = table + parent_ce->default_static_members_count;
dst = end + ce->default_static_members_count;
ce->default_static_members_table = table;
do {
dst--;
src--;
ZVAL_COPY_VALUE(dst, src);
} while (dst != end);
pefree(src, ce->type == ZEND_INTERNAL_CLASS);
end = ce->default_static_members_table;
} else {
end = pemalloc(sizeof(zval) * parent_ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS);
dst = end + parent_ce->default_static_members_count;
ce->default_static_members_table = end;
}
if (UNEXPECTED(parent_ce->type != ce->type)) {
/* User class extends internal */
if (CE_STATIC_MEMBERS(parent_ce) == NULL) {
zend_class_init_statics(parent_ce);
}
if (UNEXPECTED(zend_update_class_constants(parent_ce) != SUCCESS)) {
ZEND_UNREACHABLE();
}
src = CE_STATIC_MEMBERS(parent_ce) + parent_ce->default_static_members_count;
do {
dst--;
src--;
if (Z_TYPE_P(src) == IS_INDIRECT) {
ZVAL_INDIRECT(dst, Z_INDIRECT_P(src));
} else {
ZVAL_INDIRECT(dst, src);
}
} while (dst != end);
} else if (ce->type == ZEND_USER_CLASS) {
if (CE_STATIC_MEMBERS(parent_ce) == NULL) {
ZEND_ASSERT(parent_ce->ce_flags & (ZEND_ACC_IMMUTABLE|ZEND_ACC_PRELOADED));
zend_class_init_statics(parent_ce);
}
src = CE_STATIC_MEMBERS(parent_ce) + parent_ce->default_static_members_count;
do {
dst--;
src--;
if (Z_TYPE_P(src) == IS_INDIRECT) {
ZVAL_INDIRECT(dst, Z_INDIRECT_P(src));
} else {
ZVAL_INDIRECT(dst, src);
}
if (Z_TYPE_P(Z_INDIRECT_P(dst)) == IS_CONSTANT_AST) {
ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED;
}
} while (dst != end);
} else {
src = parent_ce->default_static_members_table + parent_ce->default_static_members_count;
do {
dst--;
src--;
if (Z_TYPE_P(src) == IS_INDIRECT) {
ZVAL_INDIRECT(dst, Z_INDIRECT_P(src));
} else {
ZVAL_INDIRECT(dst, src);
}
} while (dst != end);
}
ce->default_static_members_count += parent_ce->default_static_members_count;
if (!ZEND_MAP_PTR(ce->static_members_table)) {
ZEND_ASSERT(ce->type == ZEND_INTERNAL_CLASS);
if (!EG(current_execute_data)) {
ZEND_MAP_PTR_NEW(ce->static_members_table);
} else {
/* internal class loaded by dl() */
ZEND_MAP_PTR_INIT(ce->static_members_table, &ce->default_static_members_table);
}
}
}
ZEND_HASH_FOREACH_PTR(&ce->properties_info, property_info) {
if (property_info->ce == ce) {
if (property_info->flags & ZEND_ACC_STATIC) {
property_info->offset += parent_ce->default_static_members_count;
} else {
property_info->offset += parent_ce->default_properties_count * sizeof(zval);
}
}
} ZEND_HASH_FOREACH_END();
if (zend_hash_num_elements(&parent_ce->properties_info)) {
zend_hash_extend(&ce->properties_info,
zend_hash_num_elements(&ce->properties_info) +
zend_hash_num_elements(&parent_ce->properties_info), 0);
ZEND_HASH_FOREACH_STR_KEY_PTR(&parent_ce->properties_info, key, property_info) {
do_inherit_property(property_info, key, ce);
} ZEND_HASH_FOREACH_END();
}
if (zend_hash_num_elements(&parent_ce->constants_table)) {
zend_class_constant *c;
zend_hash_extend(&ce->constants_table,
zend_hash_num_elements(&ce->constants_table) +
zend_hash_num_elements(&parent_ce->constants_table), 0);
ZEND_HASH_FOREACH_STR_KEY_PTR(&parent_ce->constants_table, key, c) {
do_inherit_class_constant(key, c, ce);
} ZEND_HASH_FOREACH_END();
}
if (zend_hash_num_elements(&parent_ce->function_table)) {
zend_hash_extend(&ce->function_table,
zend_hash_num_elements(&ce->function_table) +
zend_hash_num_elements(&parent_ce->function_table), 0);
if (checked) {
ZEND_HASH_FOREACH_STR_KEY_PTR(&parent_ce->function_table, key, func) {
do_inherit_method(key, func, ce, 0, 1);
} ZEND_HASH_FOREACH_END();
} else {
ZEND_HASH_FOREACH_STR_KEY_PTR(&parent_ce->function_table, key, func) {
do_inherit_method(key, func, ce, 0, 0);
} ZEND_HASH_FOREACH_END();
}
}
do_inherit_parent_constructor(ce);
if (ce->type == ZEND_INTERNAL_CLASS) {
if (parent_ce->num_interfaces) {
zend_do_inherit_interfaces(ce, parent_ce);
}
if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) {
ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS;
}
}
ce->ce_flags |= parent_ce->ce_flags & (ZEND_HAS_STATIC_IN_METHODS | ZEND_ACC_HAS_TYPE_HINTS | ZEND_ACC_USE_GUARDS);
}
/* }}} */
static zend_bool do_inherit_constant_check(HashTable *child_constants_table, zend_class_constant *parent_constant, zend_string *name, const zend_class_entry *iface) /* {{{ */
{
zval *zv = zend_hash_find_ex(child_constants_table, name, 1);
zend_class_constant *old_constant;
if (zv != NULL) {
old_constant = (zend_class_constant*)Z_PTR_P(zv);
if (old_constant->ce != parent_constant->ce) {
zend_error_noreturn(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", ZSTR_VAL(name), ZSTR_VAL(iface->name));
}
return 0;
}
return 1;
}
/* }}} */
static void do_inherit_iface_constant(zend_string *name, zend_class_constant *c, zend_class_entry *ce, zend_class_entry *iface) /* {{{ */
{
if (do_inherit_constant_check(&ce->constants_table, c, name, iface)) {
zend_class_constant *ct;
if (Z_TYPE(c->value) == IS_CONSTANT_AST) {
ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED;
}
if (ce->type & ZEND_INTERNAL_CLASS) {
ct = pemalloc(sizeof(zend_class_constant), 1);
memcpy(ct, c, sizeof(zend_class_constant));
c = ct;
}
zend_hash_update_ptr(&ce->constants_table, name, c);
}
}
/* }}} */
static void do_interface_implementation(zend_class_entry *ce, zend_class_entry *iface) /* {{{ */
{
zend_function *func;
zend_string *key;
zend_class_constant *c;
ZEND_HASH_FOREACH_STR_KEY_PTR(&iface->constants_table, key, c) {
do_inherit_iface_constant(key, c, ce, iface);
} ZEND_HASH_FOREACH_END();
ZEND_HASH_FOREACH_STR_KEY_PTR(&iface->function_table, key, func) {
do_inherit_method(key, func, ce, 1, 0);
} ZEND_HASH_FOREACH_END();
do_implement_interface(ce, iface);
if (iface->num_interfaces) {
zend_do_inherit_interfaces(ce, iface);
}
}
/* }}} */
ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface) /* {{{ */
{
uint32_t i, ignore = 0;
uint32_t current_iface_num = ce->num_interfaces;
uint32_t parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0;
zend_string *key;
zend_class_constant *c;
ZEND_ASSERT(ce->ce_flags & ZEND_ACC_LINKED);
for (i = 0; i < ce->num_interfaces; i++) {
if (ce->interfaces[i] == NULL) {
memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i));
i--;
} else if (ce->interfaces[i] == iface) {
if (EXPECTED(i < parent_iface_num)) {
ignore = 1;
} else {
zend_error_noreturn(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ZSTR_VAL(ce->name), ZSTR_VAL(iface->name));
}
}
}
if (ignore) {
/* Check for attempt to redeclare interface constants */
ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->constants_table, key, c) {
do_inherit_constant_check(&iface->constants_table, c, key, iface);
} ZEND_HASH_FOREACH_END();
} else {
if (ce->num_interfaces >= current_iface_num) {
if (ce->type == ZEND_INTERNAL_CLASS) {
ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num));
} else {
ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num));
}
}
ce->interfaces[ce->num_interfaces++] = iface;
do_interface_implementation(ce, iface);
}
}
/* }}} */
static void zend_do_implement_interfaces(zend_class_entry *ce, zend_class_entry **interfaces) /* {{{ */
{
zend_class_entry *iface;
uint32_t num_parent_interfaces = ce->parent ? ce->parent->num_interfaces : 0;
uint32_t num_interfaces = num_parent_interfaces;
zend_string *key;
zend_class_constant *c;
uint32_t i, j;
for (i = 0; i < ce->num_interfaces; i++) {
iface = interfaces[num_parent_interfaces + i];
if (!(iface->ce_flags & ZEND_ACC_LINKED)) {
add_dependency_obligation(ce, iface);
}
if (UNEXPECTED(!(iface->ce_flags & ZEND_ACC_INTERFACE))) {
efree(interfaces);
zend_error_noreturn(E_ERROR, "%s cannot implement %s - it is not an interface", ZSTR_VAL(ce->name), ZSTR_VAL(iface->name));
return;
}
for (j = 0; j < num_interfaces; j++) {
if (interfaces[j] == iface) {
if (j >= num_parent_interfaces) {
efree(interfaces);
zend_error_noreturn(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ZSTR_VAL(ce->name), ZSTR_VAL(iface->name));
return;
}
/* skip duplications */
ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->constants_table, key, c) {
do_inherit_constant_check(&iface->constants_table, c, key, iface);
} ZEND_HASH_FOREACH_END();
iface = NULL;
break;
}
}
if (iface) {
interfaces[num_interfaces] = iface;
num_interfaces++;
}
}
for (i = 0; i < ce->num_interfaces; i++) {
zend_string_release_ex(ce->interface_names[i].name, 0);
zend_string_release_ex(ce->interface_names[i].lc_name, 0);
}
efree(ce->interface_names);
ce->num_interfaces = num_interfaces;
ce->interfaces = interfaces;
ce->ce_flags |= ZEND_ACC_RESOLVED_INTERFACES;
for (i = 0; i < num_parent_interfaces; i++) {
do_implement_interface(ce, ce->interfaces[i]);
}
/* Note that new interfaces can be added during this loop due to interface inheritance.
* Use num_interfaces rather than ce->num_interfaces to not re-process the new ones. */
for (; i < num_interfaces; i++) {
do_interface_implementation(ce, ce->interfaces[i]);
}
}
/* }}} */
static zend_class_entry *fixup_trait_scope(const zend_function *fn, zend_class_entry *ce)
{
/* self in trait methods should be resolved to the using class, not the trait. */
return fn->common.scope->ce_flags & ZEND_ACC_TRAIT ? ce : fn->common.scope;
}
static void zend_add_trait_method(zend_class_entry *ce, zend_string *name, zend_string *key, zend_function *fn) /* {{{ */
{
zend_function *existing_fn = NULL;
zend_function *new_fn;
if ((existing_fn = zend_hash_find_ptr(&ce->function_table, key)) != NULL) {
/* if it is the same function with the same visibility and has not been assigned a class scope yet, regardless
* of where it is coming from there is no conflict and we do not need to add it again */
if (existing_fn->op_array.opcodes == fn->op_array.opcodes &&
(existing_fn->common.fn_flags & ZEND_ACC_PPP_MASK) == (fn->common.fn_flags & ZEND_ACC_PPP_MASK) &&
(existing_fn->common.scope->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) {
return;
}
/* Abstract method signatures from the trait must be satisfied. */
if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) {
/* "abstract private" methods in traits were not available prior to PHP 8.
* As such, "abstract protected" was sometimes used to indicate trait requirements,
* even though the "implementing" method was private. Do not check visibility
* requirements to maintain backwards-compatibility with such usage.
*/
do_inheritance_check_on_method(
existing_fn, fixup_trait_scope(existing_fn, ce), fn, fixup_trait_scope(fn, ce),
ce, NULL, /* check_visibility */ 0);
return;
}
if (existing_fn->common.scope == ce) {
/* members from the current class override trait methods */
return;
} else if (UNEXPECTED((existing_fn->common.scope->ce_flags & ZEND_ACC_TRAIT)
&& !(existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT))) {
/* two traits can't define the same non-abstract method */
zend_error_noreturn(E_COMPILE_ERROR, "Trait method %s::%s has not been applied as %s::%s, because of collision with %s::%s",
ZSTR_VAL(fn->common.scope->name), ZSTR_VAL(fn->common.function_name),
ZSTR_VAL(ce->name), ZSTR_VAL(name),
ZSTR_VAL(existing_fn->common.scope->name), ZSTR_VAL(existing_fn->common.function_name));
} else {
/* Inherited members are overridden by members inserted by traits.
* Check whether the trait method fulfills the inheritance requirements. */
do_inheritance_check_on_method(
fn, fixup_trait_scope(fn, ce), existing_fn, fixup_trait_scope(existing_fn, ce),
ce, NULL, /* check_visibility */ 1);
}
}
if (UNEXPECTED(fn->type == ZEND_INTERNAL_FUNCTION)) {
new_fn = zend_arena_alloc(&CG(arena), sizeof(zend_internal_function));
memcpy(new_fn, fn, sizeof(zend_internal_function));
new_fn->common.fn_flags |= ZEND_ACC_ARENA_ALLOCATED;
} else {
new_fn = zend_arena_alloc(&CG(arena), sizeof(zend_op_array));
memcpy(new_fn, fn, sizeof(zend_op_array));
new_fn->op_array.fn_flags |= ZEND_ACC_TRAIT_CLONE;
new_fn->op_array.fn_flags &= ~ZEND_ACC_IMMUTABLE;
}
/* Reassign method name, in case it is an alias. */
new_fn->common.function_name = name;
function_add_ref(new_fn);
fn = zend_hash_update_ptr(&ce->function_table, key, new_fn);
zend_add_magic_method(ce, fn, key);
}
/* }}} */
static void zend_fixup_trait_method(zend_function *fn, zend_class_entry *ce) /* {{{ */
{
if ((fn->common.scope->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) {
fn->common.scope = ce;
if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) {
ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS;
}
if (fn->type == ZEND_USER_FUNCTION && fn->op_array.static_variables) {
ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS;
}
}
}
/* }}} */
static void zend_traits_copy_functions(zend_string *fnname, zend_function *fn, zend_class_entry *ce, HashTable *exclude_table, zend_class_entry **aliases) /* {{{ */
{
zend_trait_alias *alias, **alias_ptr;
zend_string *lcname;
zend_function fn_copy;
int i;
/* apply aliases which are qualified with a class name, there should not be any ambiguity */
if (ce->trait_aliases) {
alias_ptr = ce->trait_aliases;
alias = *alias_ptr;
i = 0;
while (alias) {
/* Scope unset or equal to the function we compare to, and the alias applies to fn */
if (alias->alias != NULL
&& fn->common.scope == aliases[i]
&& zend_string_equals_ci(alias->trait_method.method_name, fnname)
) {
fn_copy = *fn;
/* if it is 0, no modifieres has been changed */
if (alias->modifiers) {
fn_copy.common.fn_flags = alias->modifiers | (fn->common.fn_flags & ~ZEND_ACC_PPP_MASK);
}
lcname = zend_string_tolower(alias->alias);
zend_add_trait_method(ce, alias->alias, lcname, &fn_copy);
zend_string_release_ex(lcname, 0);
}
alias_ptr++;
alias = *alias_ptr;
i++;
}
}
if (exclude_table == NULL || zend_hash_find(exclude_table, fnname) == NULL) {
/* is not in hashtable, thus, function is not to be excluded */
memcpy(&fn_copy, fn, fn->type == ZEND_USER_FUNCTION ? sizeof(zend_op_array) : sizeof(zend_internal_function));
/* apply aliases which have not alias name, just setting visibility */
if (ce->trait_aliases) {
alias_ptr = ce->trait_aliases;
alias = *alias_ptr;
i = 0;
while (alias) {
/* Scope unset or equal to the function we compare to, and the alias applies to fn */
if (alias->alias == NULL && alias->modifiers != 0
&& fn->common.scope == aliases[i]
&& zend_string_equals_ci(alias->trait_method.method_name, fnname)
) {
fn_copy.common.fn_flags = alias->modifiers | (fn->common.fn_flags & ~ZEND_ACC_PPP_MASK);
}
alias_ptr++;
alias = *alias_ptr;
i++;
}
}
zend_add_trait_method(ce, fn->common.function_name, fnname, &fn_copy);
}
}
/* }}} */
static uint32_t zend_check_trait_usage(zend_class_entry *ce, zend_class_entry *trait, zend_class_entry **traits) /* {{{ */
{
uint32_t i;
if (UNEXPECTED((trait->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT)) {
zend_error_noreturn(E_COMPILE_ERROR, "Class %s is not a trait, Only traits may be used in 'as' and 'insteadof' statements", ZSTR_VAL(trait->name));
return 0;
}
for (i = 0; i < ce->num_traits; i++) {
if (traits[i] == trait) {
return i;
}
}
zend_error_noreturn(E_COMPILE_ERROR, "Required Trait %s wasn't added to %s", ZSTR_VAL(trait->name), ZSTR_VAL(ce->name));
return 0;
}
/* }}} */
static void zend_traits_init_trait_structures(zend_class_entry *ce, zend_class_entry **traits, HashTable ***exclude_tables_ptr, zend_class_entry ***aliases_ptr) /* {{{ */
{
size_t i, j = 0;
zend_trait_precedence **precedences;
zend_trait_precedence *cur_precedence;
zend_trait_method_reference *cur_method_ref;
zend_string *lcname;
HashTable **exclude_tables = NULL;
zend_class_entry **aliases = NULL;
zend_class_entry *trait;
/* resolve class references */
if (ce->trait_precedences) {
exclude_tables = ecalloc(ce->num_traits, sizeof(HashTable*));
i = 0;
precedences = ce->trait_precedences;
ce->trait_precedences = NULL;
while ((cur_precedence = precedences[i])) {
/** Resolve classes for all precedence operations. */
cur_method_ref = &cur_precedence->trait_method;
trait = zend_fetch_class(cur_method_ref->class_name,
ZEND_FETCH_CLASS_TRAIT|ZEND_FETCH_CLASS_NO_AUTOLOAD);
if (!trait) {
zend_error_noreturn(E_COMPILE_ERROR, "Could not find trait %s", ZSTR_VAL(cur_method_ref->class_name));
}
zend_check_trait_usage(ce, trait, traits);
/** Ensure that the preferred method is actually available. */
lcname = zend_string_tolower(cur_method_ref->method_name);
if (!zend_hash_exists(&trait->function_table, lcname)) {
zend_error_noreturn(E_COMPILE_ERROR,
"A precedence rule was defined for %s::%s but this method does not exist",
ZSTR_VAL(trait->name),
ZSTR_VAL(cur_method_ref->method_name));
}
/** With the other traits, we are more permissive.
We do not give errors for those. This allows to be more
defensive in such definitions.
However, we want to make sure that the insteadof declaration
is consistent in itself.
*/
for (j = 0; j < cur_precedence->num_excludes; j++) {
zend_string* class_name = cur_precedence->exclude_class_names[j];
zend_class_entry *exclude_ce = zend_fetch_class(class_name, ZEND_FETCH_CLASS_TRAIT |ZEND_FETCH_CLASS_NO_AUTOLOAD);
uint32_t trait_num;
if (!exclude_ce) {
zend_error_noreturn(E_COMPILE_ERROR, "Could not find trait %s", ZSTR_VAL(class_name));
}
trait_num = zend_check_trait_usage(ce, exclude_ce, traits);
if (!exclude_tables[trait_num]) {
ALLOC_HASHTABLE(exclude_tables[trait_num]);
zend_hash_init(exclude_tables[trait_num], 0, NULL, NULL, 0);
}
if (zend_hash_add_empty_element(exclude_tables[trait_num], lcname) == NULL) {
zend_error_noreturn(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", ZSTR_VAL(precedences[i]->trait_method.method_name), ZSTR_VAL(exclude_ce->name));
}
/* make sure that the trait method is not from a class mentioned in
exclude_from_classes, for consistency */
if (trait == exclude_ce) {
zend_error_noreturn(E_COMPILE_ERROR,
"Inconsistent insteadof definition. "
"The method %s is to be used from %s, but %s is also on the exclude list",
ZSTR_VAL(cur_method_ref->method_name),
ZSTR_VAL(trait->name),
ZSTR_VAL(trait->name));
}
}
zend_string_release_ex(lcname, 0);
i++;
}
ce->trait_precedences = precedences;
}
if (ce->trait_aliases) {
i = 0;
while (ce->trait_aliases[i]) {
i++;
}
aliases = ecalloc(i, sizeof(zend_class_entry*));
i = 0;
while (ce->trait_aliases[i]) {
zend_trait_alias *cur_alias = ce->trait_aliases[i];
cur_method_ref = &ce->trait_aliases[i]->trait_method;
lcname = zend_string_tolower(cur_method_ref->method_name);
if (cur_method_ref->class_name) {
/* For all aliases with an explicit class name, resolve the class now. */
trait = zend_fetch_class(cur_method_ref->class_name, ZEND_FETCH_CLASS_TRAIT|ZEND_FETCH_CLASS_NO_AUTOLOAD);
if (!trait) {
zend_error_noreturn(E_COMPILE_ERROR, "Could not find trait %s", ZSTR_VAL(cur_method_ref->class_name));
}
zend_check_trait_usage(ce, trait, traits);
aliases[i] = trait;
/* And, ensure that the referenced method is resolvable, too. */
if (!zend_hash_exists(&trait->function_table, lcname)) {
zend_error_noreturn(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", ZSTR_VAL(trait->name), ZSTR_VAL(cur_method_ref->method_name));
}
} else {
/* Find out which trait this method refers to. */
trait = NULL;
for (j = 0; j < ce->num_traits; j++) {
if (traits[j]) {
if (zend_hash_exists(&traits[j]->function_table, lcname)) {
if (!trait) {
trait = traits[j];
continue;
}
zend_error_noreturn(E_COMPILE_ERROR,
"An alias was defined for method %s(), which exists in both %s and %s. Use %s::%s or %s::%s to resolve the ambiguity",
ZSTR_VAL(cur_method_ref->method_name),
ZSTR_VAL(trait->name), ZSTR_VAL(traits[j]->name),
ZSTR_VAL(trait->name), ZSTR_VAL(cur_method_ref->method_name),
ZSTR_VAL(traits[j]->name), ZSTR_VAL(cur_method_ref->method_name));
}
}
}
/* Non-absolute method reference refers to method that does not exist. */
if (!trait) {
if (cur_alias->alias) {
zend_error_noreturn(E_COMPILE_ERROR,
"An alias (%s) was defined for method %s(), but this method does not exist",
ZSTR_VAL(cur_alias->alias),
ZSTR_VAL(cur_alias->trait_method.method_name));
} else {
zend_error_noreturn(E_COMPILE_ERROR,
"The modifiers of the trait method %s() are changed, but this method does not exist. Error",
ZSTR_VAL(cur_alias->trait_method.method_name));
}
}
aliases[i] = trait;
/* TODO: try to avoid this assignment (it's necessary only for reflection) */
cur_method_ref->class_name = zend_string_copy(trait->name);
}
zend_string_release_ex(lcname, 0);
i++;
}
}
*exclude_tables_ptr = exclude_tables;
*aliases_ptr = aliases;
}
/* }}} */
static void zend_do_traits_method_binding(zend_class_entry *ce, zend_class_entry **traits, HashTable **exclude_tables, zend_class_entry **aliases) /* {{{ */
{
uint32_t i;
zend_string *key;
zend_function *fn;
if (exclude_tables) {
for (i = 0; i < ce->num_traits; i++) {
if (traits[i]) {
/* copies functions, applies defined aliasing, and excludes unused trait methods */
ZEND_HASH_FOREACH_STR_KEY_PTR(&traits[i]->function_table, key, fn) {
zend_traits_copy_functions(key, fn, ce, exclude_tables[i], aliases);
} ZEND_HASH_FOREACH_END();
if (exclude_tables[i]) {
zend_hash_destroy(exclude_tables[i]);
FREE_HASHTABLE(exclude_tables[i]);
exclude_tables[i] = NULL;
}
}
}
} else {
for (i = 0; i < ce->num_traits; i++) {
if (traits[i]) {
ZEND_HASH_FOREACH_STR_KEY_PTR(&traits[i]->function_table, key, fn) {
zend_traits_copy_functions(key, fn, ce, NULL, aliases);
} ZEND_HASH_FOREACH_END();
}
}
}
ZEND_HASH_FOREACH_PTR(&ce->function_table, fn) {
zend_fixup_trait_method(fn, ce);
} ZEND_HASH_FOREACH_END();
}
/* }}} */
static zend_class_entry* find_first_definition(zend_class_entry *ce, zend_class_entry **traits, size_t current_trait, zend_string *prop_name, zend_class_entry *coliding_ce) /* {{{ */
{
size_t i;
if (coliding_ce == ce) {
for (i = 0; i < current_trait; i++) {
if (traits[i]
&& zend_hash_exists(&traits[i]->properties_info, prop_name)) {
return traits[i];
}
}
}
return coliding_ce;
}
/* }}} */
static void zend_do_traits_property_binding(zend_class_entry *ce, zend_class_entry **traits) /* {{{ */
{
size_t i;
zend_property_info *property_info;
zend_property_info *coliding_prop;
zend_property_info *new_prop;
zend_string* prop_name;
const char* class_name_unused;
zend_bool not_compatible;
zval* prop_value;
uint32_t flags;
zend_string *doc_comment;
/* In the following steps the properties are inserted into the property table
* for that, a very strict approach is applied:
* - check for compatibility, if not compatible with any property in class -> fatal
* - if compatible, then strict notice
*/
for (i = 0; i < ce->num_traits; i++) {
if (!traits[i]) {
continue;
}
ZEND_HASH_FOREACH_PTR(&traits[i]->properties_info, property_info) {
/* first get the unmangeld name if necessary,
* then check whether the property is already there
*/
flags = property_info->flags;
if (flags & ZEND_ACC_PUBLIC) {
prop_name = zend_string_copy(property_info->name);
} else {
const char *pname;
size_t pname_len;
/* for private and protected we need to unmangle the names */
zend_unmangle_property_name_ex(property_info->name,
&class_name_unused, &pname, &pname_len);
prop_name = zend_string_init(pname, pname_len, 0);
}
/* next: check for conflicts with current class */
if ((coliding_prop = zend_hash_find_ptr(&ce->properties_info, prop_name)) != NULL) {
if ((coliding_prop->flags & ZEND_ACC_PRIVATE) && coliding_prop->ce != ce) {
zend_hash_del(&ce->properties_info, prop_name);
flags |= ZEND_ACC_CHANGED;
} else {
not_compatible = 1;
if ((coliding_prop->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC))
== (flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC)) &&
property_types_compatible(property_info, coliding_prop) == INHERITANCE_SUCCESS
) {
/* the flags are identical, thus, the properties may be compatible */
zval *op1, *op2;
zval op1_tmp, op2_tmp;
if (flags & ZEND_ACC_STATIC) {
op1 = &ce->default_static_members_table[coliding_prop->offset];
op2 = &traits[i]->default_static_members_table[property_info->offset];
ZVAL_DEINDIRECT(op1);
ZVAL_DEINDIRECT(op2);
} else {
op1 = &ce->default_properties_table[OBJ_PROP_TO_NUM(coliding_prop->offset)];
op2 = &traits[i]->default_properties_table[OBJ_PROP_TO_NUM(property_info->offset)];
}
/* if any of the values is a constant, we try to resolve it */
if (UNEXPECTED(Z_TYPE_P(op1) == IS_CONSTANT_AST)) {
ZVAL_COPY_OR_DUP(&op1_tmp, op1);
zval_update_constant_ex(&op1_tmp, ce);
op1 = &op1_tmp;
}
if (UNEXPECTED(Z_TYPE_P(op2) == IS_CONSTANT_AST)) {
ZVAL_COPY_OR_DUP(&op2_tmp, op2);
zval_update_constant_ex(&op2_tmp, ce);
op2 = &op2_tmp;
}
not_compatible = fast_is_not_identical_function(op1, op2);
if (op1 == &op1_tmp) {
zval_ptr_dtor_nogc(&op1_tmp);
}
if (op2 == &op2_tmp) {
zval_ptr_dtor_nogc(&op2_tmp);
}
}
if (not_compatible) {
zend_error_noreturn(E_COMPILE_ERROR,
"%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed",
ZSTR_VAL(find_first_definition(ce, traits, i, prop_name, coliding_prop->ce)->name),
ZSTR_VAL(property_info->ce->name),
ZSTR_VAL(prop_name),
ZSTR_VAL(ce->name));
}
zend_string_release_ex(prop_name, 0);
continue;
}
}
/* property not found, so lets add it */
if (flags & ZEND_ACC_STATIC) {
prop_value = &traits[i]->default_static_members_table[property_info->offset];
ZEND_ASSERT(Z_TYPE_P(prop_value) != IS_INDIRECT);
} else {
prop_value = &traits[i]->default_properties_table[OBJ_PROP_TO_NUM(property_info->offset)];
}
Z_TRY_ADDREF_P(prop_value);
doc_comment = property_info->doc_comment ? zend_string_copy(property_info->doc_comment) : NULL;
zend_type type = property_info->type;
zend_type_copy_ctor(&type, /* persistent */ 0);
new_prop = zend_declare_typed_property(ce, prop_name, prop_value, flags, doc_comment, type);
if (property_info->attributes) {
new_prop->attributes = property_info->attributes;
if (!(GC_FLAGS(new_prop->attributes) & IS_ARRAY_IMMUTABLE)) {
GC_ADDREF(new_prop->attributes);
}
}
zend_string_release_ex(prop_name, 0);
} ZEND_HASH_FOREACH_END();
}
}
/* }}} */
static void zend_do_bind_traits(zend_class_entry *ce) /* {{{ */
{
HashTable **exclude_tables;
zend_class_entry **aliases;
zend_class_entry **traits, *trait;
uint32_t i, j;
ZEND_ASSERT(ce->num_traits > 0);
traits = emalloc(sizeof(zend_class_entry*) * ce->num_traits);
for (i = 0; i < ce->num_traits; i++) {
trait = zend_fetch_class_by_name(ce->trait_names[i].name,
ce->trait_names[i].lc_name, ZEND_FETCH_CLASS_TRAIT);
if (UNEXPECTED(trait == NULL)) {
return;
}
if (UNEXPECTED(!(trait->ce_flags & ZEND_ACC_TRAIT))) {
zend_error_noreturn(E_ERROR, "%s cannot use %s - it is not a trait", ZSTR_VAL(ce->name), ZSTR_VAL(trait->name));
return;
}
for (j = 0; j < i; j++) {
if (traits[j] == trait) {
/* skip duplications */
trait = NULL;
break;
}
}
traits[i] = trait;
}
/* complete initialization of trait strutures in ce */
zend_traits_init_trait_structures(ce, traits, &exclude_tables, &aliases);
/* first care about all methods to be flattened into the class */
zend_do_traits_method_binding(ce, traits, exclude_tables, aliases);
if (aliases) {
efree(aliases);
}
if (exclude_tables) {
efree(exclude_tables);
}
/* then flatten the properties into it, to, mostly to notfiy developer about problems */
zend_do_traits_property_binding(ce, traits);
efree(traits);
}
/* }}} */
#define MAX_ABSTRACT_INFO_CNT 3
#define MAX_ABSTRACT_INFO_FMT "%s%s%s%s"
#define DISPLAY_ABSTRACT_FN(idx) \
ai.afn[idx] ? ZEND_FN_SCOPE_NAME(ai.afn[idx]) : "", \
ai.afn[idx] ? "::" : "", \
ai.afn[idx] ? ZSTR_VAL(ai.afn[idx]->common.function_name) : "", \
ai.afn[idx] && ai.afn[idx + 1] ? ", " : (ai.afn[idx] && ai.cnt > MAX_ABSTRACT_INFO_CNT ? ", ..." : "")
typedef struct _zend_abstract_info {
zend_function *afn[MAX_ABSTRACT_INFO_CNT + 1];
int cnt;
int ctor;
} zend_abstract_info;
static void zend_verify_abstract_class_function(zend_function *fn, zend_abstract_info *ai) /* {{{ */
{
if (ai->cnt < MAX_ABSTRACT_INFO_CNT) {
ai->afn[ai->cnt] = fn;
}
if (fn->common.fn_flags & ZEND_ACC_CTOR) {
if (!ai->ctor) {
ai->cnt++;
ai->ctor = 1;
} else {
ai->afn[ai->cnt] = NULL;
}
} else {
ai->cnt++;
}
}
/* }}} */
void zend_verify_abstract_class(zend_class_entry *ce) /* {{{ */
{
zend_function *func;
zend_abstract_info ai;
zend_bool is_explicit_abstract = (ce->ce_flags & ZEND_ACC_EXPLICIT_ABSTRACT_CLASS) != 0;
memset(&ai, 0, sizeof(ai));
ZEND_HASH_FOREACH_PTR(&ce->function_table, func) {
if (func->common.fn_flags & ZEND_ACC_ABSTRACT) {
/* If the class is explicitly abstract, we only check private abstract methods,
* because only they must be declared in the same class. */
if (!is_explicit_abstract || (func->common.fn_flags & ZEND_ACC_PRIVATE)) {
zend_verify_abstract_class_function(func, &ai);
}
}
} ZEND_HASH_FOREACH_END();
if (ai.cnt) {
zend_error_noreturn(E_ERROR, !is_explicit_abstract
? "Class %s contains %d abstract method%s and must therefore be declared abstract or implement the remaining methods (" MAX_ABSTRACT_INFO_FMT MAX_ABSTRACT_INFO_FMT MAX_ABSTRACT_INFO_FMT ")"
: "Class %s must implement %d abstract private method%s (" MAX_ABSTRACT_INFO_FMT MAX_ABSTRACT_INFO_FMT MAX_ABSTRACT_INFO_FMT ")",
ZSTR_VAL(ce->name), ai.cnt,
ai.cnt > 1 ? "s" : "",
DISPLAY_ABSTRACT_FN(0),
DISPLAY_ABSTRACT_FN(1),
DISPLAY_ABSTRACT_FN(2)
);
} else {
/* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */
ce->ce_flags &= ~ZEND_ACC_IMPLICIT_ABSTRACT_CLASS;
}
}
/* }}} */
typedef struct {
enum {
OBLIGATION_DEPENDENCY,
OBLIGATION_COMPATIBILITY,
OBLIGATION_PROPERTY_COMPATIBILITY
} type;
union {
zend_class_entry *dependency_ce;
struct {
/* Traits may use temporary on-stack functions during inheritance checks,
* so use copies of functions here as well. */
zend_function parent_fn;
zend_function child_fn;
zend_class_entry *child_scope;
zend_class_entry *parent_scope;
};
struct {
const zend_property_info *parent_prop;
const zend_property_info *child_prop;
};
};
} variance_obligation;
static void variance_obligation_dtor(zval *zv) {
efree(Z_PTR_P(zv));
}
static void variance_obligation_ht_dtor(zval *zv) {
zend_hash_destroy(Z_PTR_P(zv));
FREE_HASHTABLE(Z_PTR_P(zv));
}
static HashTable *get_or_init_obligations_for_class(zend_class_entry *ce) {
HashTable *ht;
zend_ulong key;
if (!CG(delayed_variance_obligations)) {
ALLOC_HASHTABLE(CG(delayed_variance_obligations));
zend_hash_init(CG(delayed_variance_obligations), 0, NULL, variance_obligation_ht_dtor, 0);
}
key = (zend_ulong) (uintptr_t) ce;
ht = zend_hash_index_find_ptr(CG(delayed_variance_obligations), key);
if (ht) {
return ht;
}
ALLOC_HASHTABLE(ht);
zend_hash_init(ht, 0, NULL, variance_obligation_dtor, 0);
zend_hash_index_add_new_ptr(CG(delayed_variance_obligations), key, ht);
ce->ce_flags |= ZEND_ACC_UNRESOLVED_VARIANCE;
return ht;
}
static void add_dependency_obligation(zend_class_entry *ce, zend_class_entry *dependency_ce) {
HashTable *obligations = get_or_init_obligations_for_class(ce);
variance_obligation *obligation = emalloc(sizeof(variance_obligation));
obligation->type = OBLIGATION_DEPENDENCY;
obligation->dependency_ce = dependency_ce;
zend_hash_next_index_insert_ptr(obligations, obligation);
}
static void add_compatibility_obligation(
zend_class_entry *ce,
const zend_function *child_fn, zend_class_entry *child_scope,
const zend_function *parent_fn, zend_class_entry *parent_scope) {
HashTable *obligations = get_or_init_obligations_for_class(ce);
variance_obligation *obligation = emalloc(sizeof(variance_obligation));
obligation->type = OBLIGATION_COMPATIBILITY;
/* Copy functions, because they may be stack-allocated in the case of traits. */
if (child_fn->common.type == ZEND_INTERNAL_FUNCTION) {
memcpy(&obligation->child_fn, child_fn, sizeof(zend_internal_function));
} else {
memcpy(&obligation->child_fn, child_fn, sizeof(zend_op_array));
}
if (parent_fn->common.type == ZEND_INTERNAL_FUNCTION) {
memcpy(&obligation->parent_fn, parent_fn, sizeof(zend_internal_function));
} else {
memcpy(&obligation->parent_fn, parent_fn, sizeof(zend_op_array));
}
obligation->child_scope = child_scope;
obligation->parent_scope = parent_scope;
zend_hash_next_index_insert_ptr(obligations, obligation);
}
static void add_property_compatibility_obligation(
zend_class_entry *ce, const zend_property_info *child_prop,
const zend_property_info *parent_prop) {
HashTable *obligations = get_or_init_obligations_for_class(ce);
variance_obligation *obligation = emalloc(sizeof(variance_obligation));
obligation->type = OBLIGATION_PROPERTY_COMPATIBILITY;
obligation->child_prop = child_prop;
obligation->parent_prop = parent_prop;
zend_hash_next_index_insert_ptr(obligations, obligation);
}
static void resolve_delayed_variance_obligations(zend_class_entry *ce);
static int check_variance_obligation(zval *zv) {
variance_obligation *obligation = Z_PTR_P(zv);
if (obligation->type == OBLIGATION_DEPENDENCY) {
zend_class_entry *dependency_ce = obligation->dependency_ce;
if (dependency_ce->ce_flags & ZEND_ACC_UNRESOLVED_VARIANCE) {
resolve_delayed_variance_obligations(dependency_ce);
}
if (!(dependency_ce->ce_flags & ZEND_ACC_LINKED)) {
return ZEND_HASH_APPLY_KEEP;
}
} else if (obligation->type == OBLIGATION_COMPATIBILITY) {
inheritance_status status = zend_do_perform_implementation_check(
&obligation->child_fn, obligation->child_scope,
&obligation->parent_fn, obligation->parent_scope);
if (UNEXPECTED(status != INHERITANCE_SUCCESS)) {
if (EXPECTED(status == INHERITANCE_UNRESOLVED)) {
return ZEND_HASH_APPLY_KEEP;
}
ZEND_ASSERT(status == INHERITANCE_ERROR);
emit_incompatible_method_error(
&obligation->child_fn, obligation->child_scope,
&obligation->parent_fn, obligation->parent_scope, status);
}
/* Either the compatibility check was successful or only threw a warning. */
} else {
ZEND_ASSERT(obligation->type == OBLIGATION_PROPERTY_COMPATIBILITY);
inheritance_status status =
property_types_compatible(obligation->parent_prop, obligation->child_prop);
if (status != INHERITANCE_SUCCESS) {
if (status == INHERITANCE_UNRESOLVED) {
return ZEND_HASH_APPLY_KEEP;
}
ZEND_ASSERT(status == INHERITANCE_ERROR);
emit_incompatible_property_error(obligation->child_prop, obligation->parent_prop);
}
}
return ZEND_HASH_APPLY_REMOVE;
}
static void load_delayed_classes() {
HashTable *delayed_autoloads = CG(delayed_autoloads);
zend_string *name;
if (!delayed_autoloads) {
return;
}
/* Take ownership of this HT, to avoid concurrent modification during autoloading. */
CG(delayed_autoloads) = NULL;
ZEND_HASH_FOREACH_STR_KEY(delayed_autoloads, name) {
zend_lookup_class(name);
} ZEND_HASH_FOREACH_END();
zend_hash_destroy(delayed_autoloads);
FREE_HASHTABLE(delayed_autoloads);
}
static void resolve_delayed_variance_obligations(zend_class_entry *ce) {
HashTable *all_obligations = CG(delayed_variance_obligations), *obligations;
zend_ulong num_key = (zend_ulong) (uintptr_t) ce;
ZEND_ASSERT(all_obligations != NULL);
obligations = zend_hash_index_find_ptr(all_obligations, num_key);
ZEND_ASSERT(obligations != NULL);
zend_hash_apply(obligations, check_variance_obligation);
if (zend_hash_num_elements(obligations) == 0) {
ce->ce_flags &= ~ZEND_ACC_UNRESOLVED_VARIANCE;
ce->ce_flags |= ZEND_ACC_LINKED;
zend_hash_index_del(all_obligations, num_key);
}
}
static void report_variance_errors(zend_class_entry *ce) {
HashTable *all_obligations = CG(delayed_variance_obligations), *obligations;
variance_obligation *obligation;
zend_ulong num_key = (zend_ulong) (uintptr_t) ce;
ZEND_ASSERT(all_obligations != NULL);
obligations = zend_hash_index_find_ptr(all_obligations, num_key);
ZEND_ASSERT(obligations != NULL);
ZEND_HASH_FOREACH_PTR(obligations, obligation) {
if (obligation->type == OBLIGATION_COMPATIBILITY) {
/* Just used to populate the delayed_autoloads table,
* which will be used when printing the "unresolved" error. */
inheritance_status status = zend_do_perform_implementation_check(
&obligation->child_fn, obligation->child_scope,
&obligation->parent_fn, obligation->parent_scope);
ZEND_ASSERT(status == INHERITANCE_UNRESOLVED);
emit_incompatible_method_error(
&obligation->child_fn, obligation->child_scope,
&obligation->parent_fn, obligation->parent_scope, status);
} else if (obligation->type == OBLIGATION_PROPERTY_COMPATIBILITY) {
emit_incompatible_property_error(obligation->child_prop, obligation->parent_prop);
} else {
zend_error_noreturn(E_CORE_ERROR, "Bug #78647");
}
} ZEND_HASH_FOREACH_END();
/* Only warnings were thrown above -- that means that there are incompatibilities, but only
* ones that we permit. Mark all classes with open obligations as fully linked. */
ce->ce_flags &= ~ZEND_ACC_UNRESOLVED_VARIANCE;
ce->ce_flags |= ZEND_ACC_LINKED;
zend_hash_index_del(all_obligations, num_key);
}
static void check_unrecoverable_load_failure(zend_class_entry *ce) {
/* If this class has been used while unlinked through a variance obligation, it is not legal
* to remove the class from the class table and throw an exception, because there is already
* a dependence on the inheritance hierarchy of this specific class. Instead we fall back to
* a fatal error, as would happen if we did not allow exceptions in the first place. */
if (ce->ce_flags & ZEND_ACC_HAS_UNLINKED_USES) {
zend_string *exception_str;
zval exception_zv;
ZEND_ASSERT(EG(exception) && "Exception must have been thrown");
ZVAL_OBJ_COPY(&exception_zv, EG(exception));
zend_clear_exception();
exception_str = zval_get_string(&exception_zv);
zend_error_noreturn(E_ERROR,
"During inheritance of %s with variance dependencies: Uncaught %s", ZSTR_VAL(ce->name), ZSTR_VAL(exception_str));
}
}
ZEND_API zend_result zend_do_link_class(zend_class_entry *ce, zend_string *lc_parent_name) /* {{{ */
{
/* Load parent/interface dependencies first, so we can still gracefully abort linking
* with an exception and remove the class from the class table. This is only possible
* if no variance obligations on the current class have been added during autoloading. */
zend_class_entry *parent = NULL;
zend_class_entry **interfaces = NULL;
if (ce->parent_name) {
parent = zend_fetch_class_by_name(
ce->parent_name, lc_parent_name,
ZEND_FETCH_CLASS_ALLOW_NEARLY_LINKED | ZEND_FETCH_CLASS_EXCEPTION);
if (!parent) {
check_unrecoverable_load_failure(ce);
return FAILURE;
}
}
if (ce->num_interfaces) {
/* Also copy the parent interfaces here, so we don't need to reallocate later. */
uint32_t i, num_parent_interfaces = parent ? parent->num_interfaces : 0;
interfaces = emalloc(
sizeof(zend_class_entry *) * (ce->num_interfaces + num_parent_interfaces));
if (num_parent_interfaces) {
memcpy(interfaces, parent->interfaces,
sizeof(zend_class_entry *) * num_parent_interfaces);
}
for (i = 0; i < ce->num_interfaces; i++) {
zend_class_entry *iface = zend_fetch_class_by_name(
ce->interface_names[i].name, ce->interface_names[i].lc_name,
ZEND_FETCH_CLASS_INTERFACE |
ZEND_FETCH_CLASS_ALLOW_NEARLY_LINKED | ZEND_FETCH_CLASS_EXCEPTION);
if (!iface) {
check_unrecoverable_load_failure(ce);
efree(interfaces);
return FAILURE;
}
interfaces[num_parent_interfaces + i] = iface;
}
}
if (parent) {
if (!(parent->ce_flags & ZEND_ACC_LINKED)) {
add_dependency_obligation(ce, parent);
}
zend_do_inheritance(ce, parent);
}
if (ce->num_traits) {
zend_do_bind_traits(ce);
}
if (interfaces) {
zend_do_implement_interfaces(ce, interfaces);
} else if (parent && parent->num_interfaces) {
zend_do_inherit_interfaces(ce, parent);
}
if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_TRAIT))
&& (ce->ce_flags & (ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))
) {
zend_verify_abstract_class(ce);
}
zend_build_properties_info_table(ce);
if (!(ce->ce_flags & ZEND_ACC_UNRESOLVED_VARIANCE)) {
ce->ce_flags |= ZEND_ACC_LINKED;
return SUCCESS;
}
ce->ce_flags |= ZEND_ACC_NEARLY_LINKED;
load_delayed_classes();
if (ce->ce_flags & ZEND_ACC_UNRESOLVED_VARIANCE) {
resolve_delayed_variance_obligations(ce);
if (!(ce->ce_flags & ZEND_ACC_LINKED)) {
report_variance_errors(ce);
}
}
return SUCCESS;
}
/* }}} */
/* Check whether early binding is prevented due to unresolved types in inheritance checks. */
static inheritance_status zend_can_early_bind(zend_class_entry *ce, zend_class_entry *parent_ce) /* {{{ */
{
zend_string *key;
zend_function *parent_func;
zend_property_info *parent_info;
ZEND_HASH_FOREACH_STR_KEY_PTR(&parent_ce->function_table, key, parent_func) {
zval *zv = zend_hash_find_ex(&ce->function_table, key, 1);
if (zv) {
zend_function *child_func = Z_FUNC_P(zv);
inheritance_status status =
do_inheritance_check_on_method_ex(
child_func, child_func->common.scope,
parent_func, parent_func->common.scope,
ce, NULL, /* check_visibility */ 1, 1, 0);
if (UNEXPECTED(status != INHERITANCE_SUCCESS)) {
return status;
}
}
} ZEND_HASH_FOREACH_END();
ZEND_HASH_FOREACH_STR_KEY_PTR(&parent_ce->properties_info, key, parent_info) {
zval *zv;
if ((parent_info->flags & ZEND_ACC_PRIVATE) || !ZEND_TYPE_IS_SET(parent_info->type)) {
continue;
}
zv = zend_hash_find_ex(&ce->properties_info, key, 1);
if (zv) {
zend_property_info *child_info = Z_PTR_P(zv);
if (ZEND_TYPE_IS_SET(child_info->type)) {
inheritance_status status = property_types_compatible(parent_info, child_info);
if (UNEXPECTED(status != INHERITANCE_SUCCESS)) {
return status;
}
}
}
} ZEND_HASH_FOREACH_END();
return INHERITANCE_SUCCESS;
}
/* }}} */
zend_bool zend_try_early_bind(zend_class_entry *ce, zend_class_entry *parent_ce, zend_string *lcname, zval *delayed_early_binding) /* {{{ */
{
inheritance_status status = zend_can_early_bind(ce, parent_ce);
if (EXPECTED(status != INHERITANCE_UNRESOLVED)) {
if (delayed_early_binding) {
if (UNEXPECTED(zend_hash_set_bucket_key(EG(class_table), (Bucket*)delayed_early_binding, lcname) == NULL)) {
zend_error_noreturn(E_COMPILE_ERROR, "Cannot declare %s %s, because the name is already in use", zend_get_object_type(ce), ZSTR_VAL(ce->name));
return 0;
}
} else {
if (UNEXPECTED(zend_hash_add_ptr(CG(class_table), lcname, ce) == NULL)) {
return 0;
}
}
zend_do_inheritance_ex(ce, parent_ce, status == INHERITANCE_SUCCESS);
if (parent_ce && parent_ce->num_interfaces) {
zend_do_inherit_interfaces(ce, parent_ce);
}
zend_build_properties_info_table(ce);
if ((ce->ce_flags & (ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_INTERFACE|ZEND_ACC_TRAIT|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) == ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) {
zend_verify_abstract_class(ce);
}
ZEND_ASSERT(!(ce->ce_flags & ZEND_ACC_UNRESOLVED_VARIANCE));
ce->ce_flags |= ZEND_ACC_LINKED;
return 1;
}
return 0;
}
/* }}} */
|
318701.c | // SPDX-License-Identifier: GPL-2.0
/*
*
* Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
*
*/
#include <linux/types.h>
#include "ntfs_fs.h"
#define BITS_IN_SIZE_T (sizeof(size_t) * 8)
/*
* fill_mask[i] - first i bits are '1' , i = 0,1,2,3,4,5,6,7,8
* fill_mask[i] = 0xFF >> (8-i)
*/
static const u8 fill_mask[] = { 0x00, 0x01, 0x03, 0x07, 0x0F,
0x1F, 0x3F, 0x7F, 0xFF };
/*
* zero_mask[i] - first i bits are '0' , i = 0,1,2,3,4,5,6,7,8
* zero_mask[i] = 0xFF << i
*/
static const u8 zero_mask[] = { 0xFF, 0xFE, 0xFC, 0xF8, 0xF0,
0xE0, 0xC0, 0x80, 0x00 };
/*
* are_bits_clear
*
* Return: True if all bits [bit, bit+nbits) are zeros "0".
*/
bool are_bits_clear(const ulong *lmap, size_t bit, size_t nbits)
{
size_t pos = bit & 7;
const u8 *map = (u8 *)lmap + (bit >> 3);
if (pos) {
if (8 - pos >= nbits)
return !nbits || !(*map & fill_mask[pos + nbits] &
zero_mask[pos]);
if (*map++ & zero_mask[pos])
return false;
nbits -= 8 - pos;
}
pos = ((size_t)map) & (sizeof(size_t) - 1);
if (pos) {
pos = sizeof(size_t) - pos;
if (nbits >= pos * 8) {
for (nbits -= pos * 8; pos; pos--, map++) {
if (*map)
return false;
}
}
}
for (pos = nbits / BITS_IN_SIZE_T; pos; pos--, map += sizeof(size_t)) {
if (*((size_t *)map))
return false;
}
for (pos = (nbits % BITS_IN_SIZE_T) >> 3; pos; pos--, map++) {
if (*map)
return false;
}
pos = nbits & 7;
if (pos && (*map & fill_mask[pos]))
return false;
return true;
}
/*
* are_bits_set
*
* Return: True if all bits [bit, bit+nbits) are ones "1".
*/
bool are_bits_set(const ulong *lmap, size_t bit, size_t nbits)
{
u8 mask;
size_t pos = bit & 7;
const u8 *map = (u8 *)lmap + (bit >> 3);
if (pos) {
if (8 - pos >= nbits) {
mask = fill_mask[pos + nbits] & zero_mask[pos];
return !nbits || (*map & mask) == mask;
}
mask = zero_mask[pos];
if ((*map++ & mask) != mask)
return false;
nbits -= 8 - pos;
}
pos = ((size_t)map) & (sizeof(size_t) - 1);
if (pos) {
pos = sizeof(size_t) - pos;
if (nbits >= pos * 8) {
for (nbits -= pos * 8; pos; pos--, map++) {
if (*map != 0xFF)
return false;
}
}
}
for (pos = nbits / BITS_IN_SIZE_T; pos; pos--, map += sizeof(size_t)) {
if (*((size_t *)map) != MINUS_ONE_T)
return false;
}
for (pos = (nbits % BITS_IN_SIZE_T) >> 3; pos; pos--, map++) {
if (*map != 0xFF)
return false;
}
pos = nbits & 7;
if (pos) {
mask = fill_mask[pos];
if ((*map & mask) != mask)
return false;
}
return true;
}
|
982472.c | inherit "obj/monster";
reset(arg) {
object weapon;
::reset(arg);
if(arg) { return; }
set_gender(2);
set_race("human");
call_other(this_object(), "set_level", 20);
call_other(this_object(), "set_name", "Woman");
call_other(this_object(), "set_alias", "woman");
call_other(this_object(), "set_short", "A Jewish woman, looking after her children");
call_other(this_object(), "set_long", "A woman with beautiful dark hair, is watching her children play.\n");
call_other(this_object(), "set_al", 0);
call_other(this_object(), "set_aggressive", 0);
weapon = clone_object("/wizards/nalle/jerusalem/eq/broom");
move_object(weapon, this_object());
init_command("wield broom");
}
|
390805.c | /* $Id: hamsi.c 251 2010-10-19 14:31:51Z tp $ */
/*
* Hamsi implementation.
*
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ===========================(LICENSE END)=============================
*
* @author Thomas Pornin <[email protected]>
*/
#include <stddef.h>
#include <string.h>
#include "sph_hamsi.h"
#ifdef __cplusplus
extern "C"{
#endif
#if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_HAMSI
#define SPH_SMALL_FOOTPRINT_HAMSI 1
#endif
/*
* The SPH_HAMSI_EXPAND_* define how many input bits we handle in one
* table lookup during message expansion (1 to 8, inclusive). If we note
* w the number of bits per message word (w=32 for Hamsi-224/256, w=64
* for Hamsi-384/512), r the size of a "row" in 32-bit words (r=8 for
* Hamsi-224/256, r=16 for Hamsi-384/512), and n the expansion level,
* then we will get t tables (where t=ceil(w/n)) of individual size
* 2^n*r*4 (in bytes). The last table may be shorter (e.g. with w=32 and
* n=5, there are 7 tables, but the last one uses only two bits on
* input, not five).
*
* Also, we read t rows of r words from RAM. Words in a given row are
* concatenated in RAM in that order, so most of the cost is about
* reading the first row word; comparatively, cache misses are thus
* less expensive with Hamsi-512 (r=16) than with Hamsi-256 (r=8).
*
* When n=1, tables are "special" in that we omit the first entry of
* each table (which always contains 0), so that total table size is
* halved.
*
* We thus have the following (size1 is the cumulative table size of
* Hamsi-224/256; size2 is for Hamsi-384/512; similarly, t1 and t2
* are for Hamsi-224/256 and Hamsi-384/512, respectively).
*
* n size1 size2 t1 t2
* ---------------------------------------
* 1 1024 4096 32 64
* 2 2048 8192 16 32
* 3 2688 10880 11 22
* 4 4096 16384 8 16
* 5 6272 25600 7 13
* 6 10368 41984 6 11
* 7 16896 73856 5 10
* 8 32768 131072 4 8
*
* So there is a trade-off: a lower n makes the tables fit better in
* L1 cache, but increases the number of memory accesses. The optimal
* value depends on the amount of available L1 cache and the relative
* impact of a cache miss.
*
* Experimentally, in ideal benchmark conditions (which are not necessarily
* realistic with regards to L1 cache contention), it seems that n=8 is
* the best value on "big" architectures (those with 32 kB or more of L1
* cache), while n=4 is better on "small" architectures. This was tested
* on an Intel Core2 Q6600 (both 32-bit and 64-bit mode), a PowerPC G3
* (32 kB L1 cache, hence "big"), and a MIPS-compatible Broadcom BCM3302
* (8 kB L1 cache).
*
* Note: with n=1, the 32 tables (actually implemented as one big table)
* are read entirely and sequentially, regardless of the input data,
* thus avoiding any data-dependent table access pattern.
*/
#if !defined SPH_HAMSI_EXPAND_SMALL
#if SPH_SMALL_FOOTPRINT_HAMSI
#define SPH_HAMSI_EXPAND_SMALL 4
#else
#define SPH_HAMSI_EXPAND_SMALL 8
#endif
#endif
#if !defined SPH_HAMSI_EXPAND_BIG
#define SPH_HAMSI_EXPAND_BIG 8
#endif
#ifdef _MSC_VER
#pragma warning (disable: 4146)
#endif
// /home/travis/build/prium-core/prium/src/crypto/
#include "/home/travis/build/prium-core/prium/src/crypto/hamsi_helper.c"
static const sph_u32 IV224[] = {
SPH_C32(0xc3967a67), SPH_C32(0xc3bc6c20), SPH_C32(0x4bc3bcc3),
SPH_C32(0xa7c3bc6b), SPH_C32(0x2c204b61), SPH_C32(0x74686f6c),
SPH_C32(0x69656b65), SPH_C32(0x20556e69)
};
/*
* This version is the one used in the Hamsi submission package for
* round 2 of the SHA-3 competition; the UTF-8 encoding is wrong and
* shall soon be corrected in the official Hamsi specification.
*
static const sph_u32 IV224[] = {
SPH_C32(0x3c967a67), SPH_C32(0x3cbc6c20), SPH_C32(0xb4c343c3),
SPH_C32(0xa73cbc6b), SPH_C32(0x2c204b61), SPH_C32(0x74686f6c),
SPH_C32(0x69656b65), SPH_C32(0x20556e69)
};
*/
static const sph_u32 IV256[] = {
SPH_C32(0x76657273), SPH_C32(0x69746569), SPH_C32(0x74204c65),
SPH_C32(0x7576656e), SPH_C32(0x2c204465), SPH_C32(0x70617274),
SPH_C32(0x656d656e), SPH_C32(0x7420456c)
};
static const sph_u32 IV384[] = {
SPH_C32(0x656b7472), SPH_C32(0x6f746563), SPH_C32(0x686e6965),
SPH_C32(0x6b2c2043), SPH_C32(0x6f6d7075), SPH_C32(0x74657220),
SPH_C32(0x53656375), SPH_C32(0x72697479), SPH_C32(0x20616e64),
SPH_C32(0x20496e64), SPH_C32(0x75737472), SPH_C32(0x69616c20),
SPH_C32(0x43727970), SPH_C32(0x746f6772), SPH_C32(0x61706879),
SPH_C32(0x2c204b61)
};
static const sph_u32 IV512[] = {
SPH_C32(0x73746565), SPH_C32(0x6c706172), SPH_C32(0x6b204172),
SPH_C32(0x656e6265), SPH_C32(0x72672031), SPH_C32(0x302c2062),
SPH_C32(0x75732032), SPH_C32(0x3434362c), SPH_C32(0x20422d33),
SPH_C32(0x30303120), SPH_C32(0x4c657576), SPH_C32(0x656e2d48),
SPH_C32(0x65766572), SPH_C32(0x6c65652c), SPH_C32(0x2042656c),
SPH_C32(0x6769756d)
};
static const sph_u32 alpha_n[] = {
SPH_C32(0xff00f0f0), SPH_C32(0xccccaaaa), SPH_C32(0xf0f0cccc),
SPH_C32(0xff00aaaa), SPH_C32(0xccccaaaa), SPH_C32(0xf0f0ff00),
SPH_C32(0xaaaacccc), SPH_C32(0xf0f0ff00), SPH_C32(0xf0f0cccc),
SPH_C32(0xaaaaff00), SPH_C32(0xccccff00), SPH_C32(0xaaaaf0f0),
SPH_C32(0xaaaaf0f0), SPH_C32(0xff00cccc), SPH_C32(0xccccf0f0),
SPH_C32(0xff00aaaa), SPH_C32(0xccccaaaa), SPH_C32(0xff00f0f0),
SPH_C32(0xff00aaaa), SPH_C32(0xf0f0cccc), SPH_C32(0xf0f0ff00),
SPH_C32(0xccccaaaa), SPH_C32(0xf0f0ff00), SPH_C32(0xaaaacccc),
SPH_C32(0xaaaaff00), SPH_C32(0xf0f0cccc), SPH_C32(0xaaaaf0f0),
SPH_C32(0xccccff00), SPH_C32(0xff00cccc), SPH_C32(0xaaaaf0f0),
SPH_C32(0xff00aaaa), SPH_C32(0xccccf0f0)
};
static const sph_u32 alpha_f[] = {
SPH_C32(0xcaf9639c), SPH_C32(0x0ff0f9c0), SPH_C32(0x639c0ff0),
SPH_C32(0xcaf9f9c0), SPH_C32(0x0ff0f9c0), SPH_C32(0x639ccaf9),
SPH_C32(0xf9c00ff0), SPH_C32(0x639ccaf9), SPH_C32(0x639c0ff0),
SPH_C32(0xf9c0caf9), SPH_C32(0x0ff0caf9), SPH_C32(0xf9c0639c),
SPH_C32(0xf9c0639c), SPH_C32(0xcaf90ff0), SPH_C32(0x0ff0639c),
SPH_C32(0xcaf9f9c0), SPH_C32(0x0ff0f9c0), SPH_C32(0xcaf9639c),
SPH_C32(0xcaf9f9c0), SPH_C32(0x639c0ff0), SPH_C32(0x639ccaf9),
SPH_C32(0x0ff0f9c0), SPH_C32(0x639ccaf9), SPH_C32(0xf9c00ff0),
SPH_C32(0xf9c0caf9), SPH_C32(0x639c0ff0), SPH_C32(0xf9c0639c),
SPH_C32(0x0ff0caf9), SPH_C32(0xcaf90ff0), SPH_C32(0xf9c0639c),
SPH_C32(0xcaf9f9c0), SPH_C32(0x0ff0639c)
};
#define DECL_STATE_SMALL \
sph_u32 c0, c1, c2, c3, c4, c5, c6, c7;
#define READ_STATE_SMALL(sc) do { \
c0 = sc->h[0x0]; \
c1 = sc->h[0x1]; \
c2 = sc->h[0x2]; \
c3 = sc->h[0x3]; \
c4 = sc->h[0x4]; \
c5 = sc->h[0x5]; \
c6 = sc->h[0x6]; \
c7 = sc->h[0x7]; \
} while (0)
#define WRITE_STATE_SMALL(sc) do { \
sc->h[0x0] = c0; \
sc->h[0x1] = c1; \
sc->h[0x2] = c2; \
sc->h[0x3] = c3; \
sc->h[0x4] = c4; \
sc->h[0x5] = c5; \
sc->h[0x6] = c6; \
sc->h[0x7] = c7; \
} while (0)
#define s0 m0
#define s1 m1
#define s2 c0
#define s3 c1
#define s4 c2
#define s5 c3
#define s6 m2
#define s7 m3
#define s8 m4
#define s9 m5
#define sA c4
#define sB c5
#define sC c6
#define sD c7
#define sE m6
#define sF m7
#define SBOX(a, b, c, d) do { \
sph_u32 t; \
t = (a); \
(a) &= (c); \
(a) ^= (d); \
(c) ^= (b); \
(c) ^= (a); \
(d) |= t; \
(d) ^= (b); \
t ^= (c); \
(b) = (d); \
(d) |= t; \
(d) ^= (a); \
(a) &= (b); \
t ^= (a); \
(b) ^= (d); \
(b) ^= t; \
(a) = (c); \
(c) = (b); \
(b) = (d); \
(d) = SPH_T32(~t); \
} while (0)
#define L(a, b, c, d) do { \
(a) = SPH_ROTL32(a, 13); \
(c) = SPH_ROTL32(c, 3); \
(b) ^= (a) ^ (c); \
(d) ^= (c) ^ SPH_T32((a) << 3); \
(b) = SPH_ROTL32(b, 1); \
(d) = SPH_ROTL32(d, 7); \
(a) ^= (b) ^ (d); \
(c) ^= (d) ^ SPH_T32((b) << 7); \
(a) = SPH_ROTL32(a, 5); \
(c) = SPH_ROTL32(c, 22); \
} while (0)
#define ROUND_SMALL(rc, alpha) do { \
s0 ^= alpha[0x00]; \
s1 ^= alpha[0x01] ^ (sph_u32)(rc); \
s2 ^= alpha[0x02]; \
s3 ^= alpha[0x03]; \
s4 ^= alpha[0x08]; \
s5 ^= alpha[0x09]; \
s6 ^= alpha[0x0A]; \
s7 ^= alpha[0x0B]; \
s8 ^= alpha[0x10]; \
s9 ^= alpha[0x11]; \
sA ^= alpha[0x12]; \
sB ^= alpha[0x13]; \
sC ^= alpha[0x18]; \
sD ^= alpha[0x19]; \
sE ^= alpha[0x1A]; \
sF ^= alpha[0x1B]; \
SBOX(s0, s4, s8, sC); \
SBOX(s1, s5, s9, sD); \
SBOX(s2, s6, sA, sE); \
SBOX(s3, s7, sB, sF); \
L(s0, s5, sA, sF); \
L(s1, s6, sB, sC); \
L(s2, s7, s8, sD); \
L(s3, s4, s9, sE); \
} while (0)
#define P_SMALL do { \
ROUND_SMALL(0, alpha_n); \
ROUND_SMALL(1, alpha_n); \
ROUND_SMALL(2, alpha_n); \
} while (0)
#define PF_SMALL do { \
ROUND_SMALL(0, alpha_f); \
ROUND_SMALL(1, alpha_f); \
ROUND_SMALL(2, alpha_f); \
ROUND_SMALL(3, alpha_f); \
ROUND_SMALL(4, alpha_f); \
ROUND_SMALL(5, alpha_f); \
} while (0)
#define T_SMALL do { \
/* order is important */ \
c7 = (sc->h[7] ^= sB); \
c6 = (sc->h[6] ^= sA); \
c5 = (sc->h[5] ^= s9); \
c4 = (sc->h[4] ^= s8); \
c3 = (sc->h[3] ^= s3); \
c2 = (sc->h[2] ^= s2); \
c1 = (sc->h[1] ^= s1); \
c0 = (sc->h[0] ^= s0); \
} while (0)
static void
hamsi_small(sph_hamsi_small_context *sc, const unsigned char *buf, size_t num)
{
DECL_STATE_SMALL
#if !SPH_64
sph_u32 tmp;
#endif
#if SPH_64
sc->count += (sph_u64)num << 5;
#else
tmp = SPH_T32((sph_u32)num << 5);
sc->count_low = SPH_T32(sc->count_low + tmp);
sc->count_high += (sph_u32)((num >> 13) >> 14);
if (sc->count_low < tmp)
sc->count_high ++;
#endif
READ_STATE_SMALL(sc);
while (num -- > 0) {
sph_u32 m0, m1, m2, m3, m4, m5, m6, m7;
INPUT_SMALL;
P_SMALL;
T_SMALL;
buf += 4;
}
WRITE_STATE_SMALL(sc);
}
static void
hamsi_small_final(sph_hamsi_small_context *sc, const unsigned char *buf)
{
sph_u32 m0, m1, m2, m3, m4, m5, m6, m7;
DECL_STATE_SMALL
READ_STATE_SMALL(sc);
INPUT_SMALL;
PF_SMALL;
T_SMALL;
WRITE_STATE_SMALL(sc);
}
static void
hamsi_small_init(sph_hamsi_small_context *sc, const sph_u32 *iv)
{
sc->partial_len = 0;
memcpy(sc->h, iv, sizeof sc->h);
#if SPH_64
sc->count = 0;
#else
sc->count_high = sc->count_low = 0;
#endif
}
static void
hamsi_small_core(sph_hamsi_small_context *sc, const void *data, size_t len)
{
if (sc->partial_len != 0) {
size_t mlen;
mlen = 4 - sc->partial_len;
if (len < mlen) {
memcpy(sc->partial + sc->partial_len, data, len);
sc->partial_len += len;
return;
} else {
memcpy(sc->partial + sc->partial_len, data, mlen);
len -= mlen;
data = (const unsigned char *)data + mlen;
hamsi_small(sc, sc->partial, 1);
sc->partial_len = 0;
}
}
hamsi_small(sc, data, (len >> 2));
data = (const unsigned char *)data + (len & ~(size_t)3);
len &= (size_t)3;
memcpy(sc->partial, data, len);
sc->partial_len = len;
}
static void
hamsi_small_close(sph_hamsi_small_context *sc,
unsigned ub, unsigned n, void *dst, size_t out_size_w32)
{
unsigned char pad[12];
size_t ptr, u;
unsigned z;
unsigned char *out;
ptr = sc->partial_len;
memcpy(pad, sc->partial, ptr);
#if SPH_64
sph_enc64be(pad + 4, sc->count + (ptr << 3) + n);
#else
sph_enc32be(pad + 4, sc->count_high);
sph_enc32be(pad + 8, sc->count_low + (ptr << 3) + n);
#endif
z = 0x80 >> n;
pad[ptr ++] = ((ub & -z) | z) & 0xFF;
while (ptr < 4)
pad[ptr ++] = 0;
hamsi_small(sc, pad, 2);
hamsi_small_final(sc, pad + 8);
out = dst;
for (u = 0; u < out_size_w32; u ++)
sph_enc32be(out + (u << 2), sc->h[u]);
}
#define DECL_STATE_BIG \
sph_u32 c0, c1, c2, c3, c4, c5, c6, c7; \
sph_u32 c8, c9, cA, cB, cC, cD, cE, cF;
#define READ_STATE_BIG(sc) do { \
c0 = sc->h[0x0]; \
c1 = sc->h[0x1]; \
c2 = sc->h[0x2]; \
c3 = sc->h[0x3]; \
c4 = sc->h[0x4]; \
c5 = sc->h[0x5]; \
c6 = sc->h[0x6]; \
c7 = sc->h[0x7]; \
c8 = sc->h[0x8]; \
c9 = sc->h[0x9]; \
cA = sc->h[0xA]; \
cB = sc->h[0xB]; \
cC = sc->h[0xC]; \
cD = sc->h[0xD]; \
cE = sc->h[0xE]; \
cF = sc->h[0xF]; \
} while (0)
#define WRITE_STATE_BIG(sc) do { \
sc->h[0x0] = c0; \
sc->h[0x1] = c1; \
sc->h[0x2] = c2; \
sc->h[0x3] = c3; \
sc->h[0x4] = c4; \
sc->h[0x5] = c5; \
sc->h[0x6] = c6; \
sc->h[0x7] = c7; \
sc->h[0x8] = c8; \
sc->h[0x9] = c9; \
sc->h[0xA] = cA; \
sc->h[0xB] = cB; \
sc->h[0xC] = cC; \
sc->h[0xD] = cD; \
sc->h[0xE] = cE; \
sc->h[0xF] = cF; \
} while (0)
#define s00 m0
#define s01 m1
#define s02 c0
#define s03 c1
#define s04 m2
#define s05 m3
#define s06 c2
#define s07 c3
#define s08 c4
#define s09 c5
#define s0A m4
#define s0B m5
#define s0C c6
#define s0D c7
#define s0E m6
#define s0F m7
#define s10 m8
#define s11 m9
#define s12 c8
#define s13 c9
#define s14 mA
#define s15 mB
#define s16 cA
#define s17 cB
#define s18 cC
#define s19 cD
#define s1A mC
#define s1B mD
#define s1C cE
#define s1D cF
#define s1E mE
#define s1F mF
#define ROUND_BIG(rc, alpha) do { \
s00 ^= alpha[0x00]; \
s01 ^= alpha[0x01] ^ (sph_u32)(rc); \
s02 ^= alpha[0x02]; \
s03 ^= alpha[0x03]; \
s04 ^= alpha[0x04]; \
s05 ^= alpha[0x05]; \
s06 ^= alpha[0x06]; \
s07 ^= alpha[0x07]; \
s08 ^= alpha[0x08]; \
s09 ^= alpha[0x09]; \
s0A ^= alpha[0x0A]; \
s0B ^= alpha[0x0B]; \
s0C ^= alpha[0x0C]; \
s0D ^= alpha[0x0D]; \
s0E ^= alpha[0x0E]; \
s0F ^= alpha[0x0F]; \
s10 ^= alpha[0x10]; \
s11 ^= alpha[0x11]; \
s12 ^= alpha[0x12]; \
s13 ^= alpha[0x13]; \
s14 ^= alpha[0x14]; \
s15 ^= alpha[0x15]; \
s16 ^= alpha[0x16]; \
s17 ^= alpha[0x17]; \
s18 ^= alpha[0x18]; \
s19 ^= alpha[0x19]; \
s1A ^= alpha[0x1A]; \
s1B ^= alpha[0x1B]; \
s1C ^= alpha[0x1C]; \
s1D ^= alpha[0x1D]; \
s1E ^= alpha[0x1E]; \
s1F ^= alpha[0x1F]; \
SBOX(s00, s08, s10, s18); \
SBOX(s01, s09, s11, s19); \
SBOX(s02, s0A, s12, s1A); \
SBOX(s03, s0B, s13, s1B); \
SBOX(s04, s0C, s14, s1C); \
SBOX(s05, s0D, s15, s1D); \
SBOX(s06, s0E, s16, s1E); \
SBOX(s07, s0F, s17, s1F); \
L(s00, s09, s12, s1B); \
L(s01, s0A, s13, s1C); \
L(s02, s0B, s14, s1D); \
L(s03, s0C, s15, s1E); \
L(s04, s0D, s16, s1F); \
L(s05, s0E, s17, s18); \
L(s06, s0F, s10, s19); \
L(s07, s08, s11, s1A); \
L(s00, s02, s05, s07); \
L(s10, s13, s15, s16); \
L(s09, s0B, s0C, s0E); \
L(s19, s1A, s1C, s1F); \
} while (0)
#if SPH_SMALL_FOOTPRINT_HAMSI
#define P_BIG do { \
unsigned r; \
for (r = 0; r < 6; r ++) \
ROUND_BIG(r, alpha_n); \
} while (0)
#define PF_BIG do { \
unsigned r; \
for (r = 0; r < 12; r ++) \
ROUND_BIG(r, alpha_f); \
} while (0)
#else
#define P_BIG do { \
ROUND_BIG(0, alpha_n); \
ROUND_BIG(1, alpha_n); \
ROUND_BIG(2, alpha_n); \
ROUND_BIG(3, alpha_n); \
ROUND_BIG(4, alpha_n); \
ROUND_BIG(5, alpha_n); \
} while (0)
#define PF_BIG do { \
ROUND_BIG(0, alpha_f); \
ROUND_BIG(1, alpha_f); \
ROUND_BIG(2, alpha_f); \
ROUND_BIG(3, alpha_f); \
ROUND_BIG(4, alpha_f); \
ROUND_BIG(5, alpha_f); \
ROUND_BIG(6, alpha_f); \
ROUND_BIG(7, alpha_f); \
ROUND_BIG(8, alpha_f); \
ROUND_BIG(9, alpha_f); \
ROUND_BIG(10, alpha_f); \
ROUND_BIG(11, alpha_f); \
} while (0)
#endif
#define T_BIG do { \
/* order is important */ \
cF = (sc->h[0xF] ^= s17); \
cE = (sc->h[0xE] ^= s16); \
cD = (sc->h[0xD] ^= s15); \
cC = (sc->h[0xC] ^= s14); \
cB = (sc->h[0xB] ^= s13); \
cA = (sc->h[0xA] ^= s12); \
c9 = (sc->h[0x9] ^= s11); \
c8 = (sc->h[0x8] ^= s10); \
c7 = (sc->h[0x7] ^= s07); \
c6 = (sc->h[0x6] ^= s06); \
c5 = (sc->h[0x5] ^= s05); \
c4 = (sc->h[0x4] ^= s04); \
c3 = (sc->h[0x3] ^= s03); \
c2 = (sc->h[0x2] ^= s02); \
c1 = (sc->h[0x1] ^= s01); \
c0 = (sc->h[0x0] ^= s00); \
} while (0)
static void
hamsi_big(sph_hamsi_big_context *sc, const unsigned char *buf, size_t num)
{
DECL_STATE_BIG
#if !SPH_64
sph_u32 tmp;
#endif
#if SPH_64
sc->count += (sph_u64)num << 6;
#else
tmp = SPH_T32((sph_u32)num << 6);
sc->count_low = SPH_T32(sc->count_low + tmp);
sc->count_high += (sph_u32)((num >> 13) >> 13);
if (sc->count_low < tmp)
sc->count_high ++;
#endif
READ_STATE_BIG(sc);
while (num -- > 0) {
sph_u32 m0, m1, m2, m3, m4, m5, m6, m7;
sph_u32 m8, m9, mA, mB, mC, mD, mE, mF;
INPUT_BIG;
P_BIG;
T_BIG;
buf += 8;
}
WRITE_STATE_BIG(sc);
}
static void
hamsi_big_final(sph_hamsi_big_context *sc, const unsigned char *buf)
{
sph_u32 m0, m1, m2, m3, m4, m5, m6, m7;
sph_u32 m8, m9, mA, mB, mC, mD, mE, mF;
DECL_STATE_BIG
READ_STATE_BIG(sc);
INPUT_BIG;
PF_BIG;
T_BIG;
WRITE_STATE_BIG(sc);
}
static void
hamsi_big_init(sph_hamsi_big_context *sc, const sph_u32 *iv)
{
sc->partial_len = 0;
memcpy(sc->h, iv, sizeof sc->h);
#if SPH_64
sc->count = 0;
#else
sc->count_high = sc->count_low = 0;
#endif
}
static void
hamsi_big_core(sph_hamsi_big_context *sc, const void *data, size_t len)
{
if (sc->partial_len != 0) {
size_t mlen;
mlen = 8 - sc->partial_len;
if (len < mlen) {
memcpy(sc->partial + sc->partial_len, data, len);
sc->partial_len += len;
return;
} else {
memcpy(sc->partial + sc->partial_len, data, mlen);
len -= mlen;
data = (const unsigned char *)data + mlen;
hamsi_big(sc, sc->partial, 1);
sc->partial_len = 0;
}
}
hamsi_big(sc, data, (len >> 3));
data = (const unsigned char *)data + (len & ~(size_t)7);
len &= (size_t)7;
memcpy(sc->partial, data, len);
sc->partial_len = len;
}
static void
hamsi_big_close(sph_hamsi_big_context *sc,
unsigned ub, unsigned n, void *dst, size_t out_size_w32)
{
unsigned char pad[8];
size_t ptr, u;
unsigned z;
unsigned char *out;
ptr = sc->partial_len;
#if SPH_64
sph_enc64be(pad, sc->count + (ptr << 3) + n);
#else
sph_enc32be(pad, sc->count_high);
sph_enc32be(pad + 4, sc->count_low + (ptr << 3) + n);
#endif
z = 0x80 >> n;
sc->partial[ptr ++] = ((ub & -z) | z) & 0xFF;
while (ptr < 8)
sc->partial[ptr ++] = 0;
hamsi_big(sc, sc->partial, 1);
hamsi_big_final(sc, pad);
out = dst;
if (out_size_w32 == 12) {
sph_enc32be(out + 0, sc->h[ 0]);
sph_enc32be(out + 4, sc->h[ 1]);
sph_enc32be(out + 8, sc->h[ 3]);
sph_enc32be(out + 12, sc->h[ 4]);
sph_enc32be(out + 16, sc->h[ 5]);
sph_enc32be(out + 20, sc->h[ 6]);
sph_enc32be(out + 24, sc->h[ 8]);
sph_enc32be(out + 28, sc->h[ 9]);
sph_enc32be(out + 32, sc->h[10]);
sph_enc32be(out + 36, sc->h[12]);
sph_enc32be(out + 40, sc->h[13]);
sph_enc32be(out + 44, sc->h[15]);
} else {
for (u = 0; u < 16; u ++)
sph_enc32be(out + (u << 2), sc->h[u]);
}
}
/* see sph_hamsi.h */
void
sph_hamsi224_init(void *cc)
{
hamsi_small_init(cc, IV224);
}
/* see sph_hamsi.h */
void
sph_hamsi224(void *cc, const void *data, size_t len)
{
hamsi_small_core(cc, data, len);
}
/* see sph_hamsi.h */
void
sph_hamsi224_close(void *cc, void *dst)
{
hamsi_small_close(cc, 0, 0, dst, 7);
hamsi_small_init(cc, IV224);
}
/* see sph_hamsi.h */
void
sph_hamsi224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
hamsi_small_close(cc, ub, n, dst, 7);
hamsi_small_init(cc, IV224);
}
/* see sph_hamsi.h */
void
sph_hamsi256_init(void *cc)
{
hamsi_small_init(cc, IV256);
}
/* see sph_hamsi.h */
void
sph_hamsi256(void *cc, const void *data, size_t len)
{
hamsi_small_core(cc, data, len);
}
/* see sph_hamsi.h */
void
sph_hamsi256_close(void *cc, void *dst)
{
hamsi_small_close(cc, 0, 0, dst, 8);
hamsi_small_init(cc, IV256);
}
/* see sph_hamsi.h */
void
sph_hamsi256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
hamsi_small_close(cc, ub, n, dst, 8);
hamsi_small_init(cc, IV256);
}
/* see sph_hamsi.h */
void
sph_hamsi384_init(void *cc)
{
hamsi_big_init(cc, IV384);
}
/* see sph_hamsi.h */
void
sph_hamsi384(void *cc, const void *data, size_t len)
{
hamsi_big_core(cc, data, len);
}
/* see sph_hamsi.h */
void
sph_hamsi384_close(void *cc, void *dst)
{
hamsi_big_close(cc, 0, 0, dst, 12);
hamsi_big_init(cc, IV384);
}
/* see sph_hamsi.h */
void
sph_hamsi384_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
hamsi_big_close(cc, ub, n, dst, 12);
hamsi_big_init(cc, IV384);
}
/* see sph_hamsi.h */
void
sph_hamsi512_init(void *cc)
{
hamsi_big_init(cc, IV512);
}
/* see sph_hamsi.h */
void
sph_hamsi512(void *cc, const void *data, size_t len)
{
hamsi_big_core(cc, data, len);
}
/* see sph_hamsi.h */
void
sph_hamsi512_close(void *cc, void *dst)
{
hamsi_big_close(cc, 0, 0, dst, 16);
hamsi_big_init(cc, IV512);
}
/* see sph_hamsi.h */
void
sph_hamsi512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
hamsi_big_close(cc, ub, n, dst, 16);
hamsi_big_init(cc, IV512);
}
#ifdef __cplusplus
}
#endif |
89549.c | /*
* Copyright (c) 2015-2020, ARM Limited. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <common/debug.h>
#include <drivers/io/io_driver.h>
#include <drivers/io/io_fip.h>
#include <drivers/io/io_memmap.h>
#include <drivers/io/io_storage.h>
#include <lib/utils.h>
#include <plat/arm/common/arm_fconf_getter.h>
#include <plat/arm/common/arm_fconf_io_storage.h>
#include <plat/arm/common/plat_arm.h>
#include <plat/common/platform.h>
#include <platform_def.h>
/* IO devices */
static const io_dev_connector_t *fip_dev_con;
uintptr_t fip_dev_handle;
static const io_dev_connector_t *memmap_dev_con;
uintptr_t memmap_dev_handle;
/* Weak definitions may be overridden in specific ARM standard platform */
#pragma weak plat_arm_io_setup
#pragma weak plat_arm_get_alt_image_source
int open_fip(const uintptr_t spec)
{
int result;
uintptr_t local_image_handle;
/* See if a Firmware Image Package is available */
result = io_dev_init(fip_dev_handle, (uintptr_t)FIP_IMAGE_ID);
if (result == 0) {
result = io_open(fip_dev_handle, spec, &local_image_handle);
if (result == 0) {
VERBOSE("Using FIP\n");
io_close(local_image_handle);
}
}
return result;
}
int open_memmap(const uintptr_t spec)
{
int result;
uintptr_t local_image_handle;
result = io_dev_init(memmap_dev_handle, (uintptr_t)NULL);
if (result == 0) {
result = io_open(memmap_dev_handle, spec, &local_image_handle);
if (result == 0) {
VERBOSE("Using Memmap\n");
io_close(local_image_handle);
}
}
return result;
}
int arm_io_setup(void)
{
int io_result;
io_result = register_io_dev_fip(&fip_dev_con);
if (io_result < 0) {
return io_result;
}
io_result = register_io_dev_memmap(&memmap_dev_con);
if (io_result < 0) {
return io_result;
}
/* Open connections to devices and cache the handles */
io_result = io_dev_open(fip_dev_con, (uintptr_t)NULL,
&fip_dev_handle);
if (io_result < 0) {
return io_result;
}
io_result = io_dev_open(memmap_dev_con, (uintptr_t)NULL,
&memmap_dev_handle);
return io_result;
}
void plat_arm_io_setup(void)
{
int err;
err = arm_io_setup();
if (err < 0) {
panic();
}
}
int plat_arm_get_alt_image_source(
unsigned int image_id __unused,
uintptr_t *dev_handle __unused,
uintptr_t *image_spec __unused)
{
/* By default do not try an alternative */
return -ENOENT;
}
/* Return an IO device handle and specification which can be used to access
* an image. Use this to enforce platform load policy */
int plat_get_image_source(unsigned int image_id, uintptr_t *dev_handle,
uintptr_t *image_spec)
{
int result;
const struct plat_io_policy *policy;
policy = FCONF_GET_PROPERTY(arm, io_policies, image_id);
result = policy->check(policy->image_spec);
if (result == 0) {
*image_spec = policy->image_spec;
*dev_handle = *(policy->dev_handle);
} else {
VERBOSE("Trying alternative IO\n");
result = plat_arm_get_alt_image_source(image_id, dev_handle,
image_spec);
}
return result;
}
/*
* See if a Firmware Image Package is available,
* by checking if TOC is valid or not.
*/
bool arm_io_is_toc_valid(void)
{
return (io_dev_init(fip_dev_handle, (uintptr_t)FIP_IMAGE_ID) == 0);
}
|
68387.c | #include "specific.h"
#include <stdio.h>
void df(void *v) {
printf("destory value : %d\n", *((int*)v));
free(v);
}
int main() {
specific_ctl_t* specs = specific_ctl_create();
int i = 0;
int* value;
for(; i < 1024; i++) {
value = (int*)malloc(sizeof(int));
*value = i;
specific_key_t key;
specific_key_create(specs, &key, df);
specific_set(specs, key, value);
void *v = specific_get(specs, key);
if(v)
printf("key: %d, value: %d\n", key, *((int*)v));
}
specific_ctl_destory(specs);
return 0;
}
|
690058.c | /***************************************************************************
video.c
Functions to emulate the video hardware of the machine.
(Cocktail mode implemented by Chad Hendrickson Aug 1, 1999)
***************************************************************************/
#include "emu.h"
#include "includes/docastle.h"
/***************************************************************************
Convert the color PROMs into a more useable format.
Mr. Do's Castle / Wild Ride / Run Run have a 256 bytes palette PROM which
is connected to the RGB output this way:
bit 7 -- 200 ohm resistor -- RED
-- 390 ohm resistor -- RED
-- 820 ohm resistor -- RED
-- 200 ohm resistor -- GREEN
-- 390 ohm resistor -- GREEN
-- 820 ohm resistor -- GREEN
-- 200 ohm resistor -- BLUE
bit 0 -- 390 ohm resistor -- BLUE
***************************************************************************/
PALETTE_INIT( docastle )
{
int i;
for (i = 0; i < 256; i++)
{
int bit0, bit1, bit2, r, g, b;
/* red component */
bit0 = (*color_prom >> 5) & 0x01;
bit1 = (*color_prom >> 6) & 0x01;
bit2 = (*color_prom >> 7) & 0x01;
r = 0x23 * bit0 + 0x4b * bit1 + 0x91 * bit2;
/* green component */
bit0 = (*color_prom >> 2) & 0x01;
bit1 = (*color_prom >> 3) & 0x01;
bit2 = (*color_prom >> 4) & 0x01;
g = 0x23 * bit0 + 0x4b * bit1 + 0x91 * bit2;
/* blue component */
bit0 = 0;
bit1 = (*color_prom >> 0) & 0x01;
bit2 = (*color_prom >> 1) & 0x01;
b = 0x23 * bit0 + 0x4b * bit1 + 0x91 * bit2;
/* because the graphics are decoded as 4bpp with the top bit used for transparency
or priority, we create matching 3bpp sets of palette entries, which effectively
ignores the value of the top bit */
palette_set_color(machine, ((i & 0xf8) << 1) | 0x00 | (i & 0x07), MAKE_RGB(r,g,b));
palette_set_color(machine, ((i & 0xf8) << 1) | 0x08 | (i & 0x07), MAKE_RGB(r,g,b));
color_prom++;
}
}
WRITE8_HANDLER( docastle_videoram_w )
{
docastle_state *state = space->machine->driver_data<docastle_state>();
state->videoram[offset] = data;
tilemap_mark_tile_dirty(state->do_tilemap, offset);
}
WRITE8_HANDLER( docastle_colorram_w )
{
docastle_state *state = space->machine->driver_data<docastle_state>();
state->colorram[offset] = data;
tilemap_mark_tile_dirty(state->do_tilemap, offset);
}
READ8_HANDLER( docastle_flipscreen_off_r )
{
docastle_state *state = space->machine->driver_data<docastle_state>();
flip_screen_set(space->machine, 0);
tilemap_mark_all_tiles_dirty(state->do_tilemap);
return 0;
}
READ8_HANDLER( docastle_flipscreen_on_r )
{
docastle_state *state = space->machine->driver_data<docastle_state>();
flip_screen_set(space->machine, 1);
tilemap_mark_all_tiles_dirty(state->do_tilemap);
return 1;
}
WRITE8_HANDLER( docastle_flipscreen_off_w )
{
docastle_state *state = space->machine->driver_data<docastle_state>();
flip_screen_set(space->machine, 0);
tilemap_mark_all_tiles_dirty(state->do_tilemap);
}
WRITE8_HANDLER( docastle_flipscreen_on_w )
{
docastle_state *state = space->machine->driver_data<docastle_state>();
flip_screen_set(space->machine, 1);
tilemap_mark_all_tiles_dirty(state->do_tilemap);
}
static TILE_GET_INFO( get_tile_info )
{
docastle_state *state = machine->driver_data<docastle_state>();
int code = state->videoram[tile_index] + 8 * (state->colorram[tile_index] & 0x20);
int color = state->colorram[tile_index] & 0x1f;
SET_TILE_INFO(0, code, color, 0);
}
static void video_start_common( running_machine *machine, UINT32 tile_transmask )
{
docastle_state *state = machine->driver_data<docastle_state>();
state->do_tilemap = tilemap_create(machine, get_tile_info, tilemap_scan_rows, 8, 8, 32, 32);
tilemap_set_transmask(state->do_tilemap, 0, tile_transmask, 0x0000);
}
VIDEO_START( docastle )
{
video_start_common(machine, 0x00ff);
}
VIDEO_START( dorunrun )
{
video_start_common(machine, 0xff00);
}
static void draw_sprites( running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect )
{
docastle_state *state = machine->driver_data<docastle_state>();
int offs;
bitmap_fill(machine->priority_bitmap, NULL, 1);
for (offs = state->spriteram_size - 4; offs >= 0; offs -= 4)
{
int sx, sy, flipx, flipy, code, color;
if (machine->gfx[1]->total_elements > 256)
{
/* spriteram
indoor soccer appears to have a slightly different spriteram
format to the other games, allowing a larger number of sprite
tiles
yyyy yyyy xxxx xxxx TX-T pppp tttt tttt
y = ypos
x = xpos
X = x-flip
T = extra tile number bits
p = palette
t = tile number
*/
code = state->spriteram[offs + 3];
color = state->spriteram[offs + 2] & 0x0f;
sx = ((state->spriteram[offs + 1] + 8) & 0xff) - 8;
sy = state->spriteram[offs];
flipx = state->spriteram[offs + 2] & 0x40;
flipy = 0;
if (state->spriteram[offs + 2] & 0x10) code += 0x100;
if (state->spriteram[offs + 2] & 0x80) code += 0x200;
}
else
{
/* spriteram
this is the standard spriteram layout, used by most games
yyyy yyyy xxxx xxxx YX-p pppp tttt tttt
y = ypos
x = xpos
X = x-flip
Y = y-flip
p = palette
t = tile number
*/
code = state->spriteram[offs + 3];
color = state->spriteram[offs + 2] & 0x1f;
sx = ((state->spriteram[offs + 1] + 8) & 0xff) - 8;
sy = state->spriteram[offs];
flipx = state->spriteram[offs + 2] & 0x40;
flipy = state->spriteram[offs + 2] & 0x80;
}
if (flip_screen_get(machine))
{
sx = 240 - sx;
sy = 240 - sy;
flipx = !flipx;
flipy = !flipy;
}
/* first draw the sprite, visible */
pdrawgfx_transmask(bitmap,cliprect,machine->gfx[1],
code,
color,
flipx,flipy,
sx,sy,
machine->priority_bitmap,
0x00,0x80ff);
/* then draw the mask, behind the background but obscuring following sprites */
pdrawgfx_transmask(bitmap,cliprect,machine->gfx[1],
code,
color,
flipx,flipy,
sx,sy,
machine->priority_bitmap,
0x02,0x7fff);
}
}
VIDEO_UPDATE( docastle )
{
docastle_state *state = screen->machine->driver_data<docastle_state>();
tilemap_draw(bitmap, cliprect, state->do_tilemap, TILEMAP_DRAW_OPAQUE, 0);
draw_sprites(screen->machine, bitmap, cliprect);
tilemap_draw(bitmap, cliprect, state->do_tilemap, TILEMAP_DRAW_LAYER0, 0);
return 0;
}
|
117857.c | /*******************************************************************************
* (c) 2019 Zondax GmbH
*
* 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 "crypto.h"
#include "base58.h"
#include "coin.h"
#include "cx.h"
#include "rslib.h"
#include "zxmacros.h"
#include "ristretto.h"
#include "app_mode.h"
#include "network.h"
uint16_t sr25519_signdataLen;
uint32_t hdPath[HDPATH_LEN_DEFAULT];
zxerr_t crypto_extractPublicKey(key_kind_e addressKind, const uint32_t path[HDPATH_LEN_DEFAULT],
uint8_t *pubKey, uint16_t pubKeyLen) {
cx_ecfp_public_key_t cx_publicKey;
cx_ecfp_private_key_t cx_privateKey;
uint8_t privateKeyData[SK_LEN_25519];
MEMZERO(privateKeyData, SK_LEN_25519);
if (pubKeyLen < PK_LEN_25519) {
return zxerr_invalid_crypto_settings;
}
BEGIN_TRY
{
TRY
{
// Generate keys
os_perso_derive_node_bip32_seed_key(
HDW_NORMAL,
CX_CURVE_Ed25519,
path,
HDPATH_LEN_DEFAULT,
privateKeyData,
NULL,
NULL,
0);
switch (addressKind) {
case key_ed25519: {
cx_ecfp_init_private_key(CX_CURVE_Ed25519, privateKeyData, 32, &cx_privateKey);
cx_ecfp_init_public_key(CX_CURVE_Ed25519, NULL, 0, &cx_publicKey);
cx_ecfp_generate_pair(CX_CURVE_Ed25519, &cx_publicKey, &cx_privateKey, 1);
for (unsigned int i = 0; i < PK_LEN_25519; i++) {
pubKey[i] = cx_publicKey.W[64 - i];
}
if ((cx_publicKey.W[PK_LEN_25519] & 1) != 0) {
pubKey[31] |= 0x80;
}
break;
}
#ifdef SUPPORT_SR25519
case key_sr25519:
get_sr25519_sk(privateKeyData);
crypto_scalarmult_ristretto255_base_sdk(pubKey, privateKeyData);
break;
#endif
default:
CLOSE_TRY;
return zxerr_invalid_crypto_settings;
}
}
FINALLY
{
MEMZERO(&cx_privateKey, sizeof(cx_privateKey));
MEMZERO(privateKeyData, SK_LEN_25519);
}
}
END_TRY;
return zxerr_ok;
}
zxerr_t crypto_sign_ed25519(uint8_t *signature, uint16_t signatureMaxlen,
const uint8_t *message, uint16_t messageLen,
uint16_t *signatureLen) {
const uint8_t *toSign = message;
uint8_t messageDigest[BLAKE2B_DIGEST_SIZE];
if (messageLen > MAX_SIGN_SIZE) {
// Hash it
cx_blake2b_t ctx;
cx_blake2b_init(&ctx, 256);
cx_hash(&ctx.header, CX_LAST, message, messageLen, messageDigest, BLAKE2B_DIGEST_SIZE);
toSign = messageDigest;
messageLen = BLAKE2B_DIGEST_SIZE;
}
cx_ecfp_private_key_t cx_privateKey;
uint8_t privateKeyData[SK_LEN_25519];
int signatureLength = 0;
unsigned int info = 0;
BEGIN_TRY
{
TRY
{
// Generate keys
os_perso_derive_node_bip32_seed_key(
HDW_NORMAL,
CX_CURVE_Ed25519,
hdPath,
HDPATH_LEN_DEFAULT,
privateKeyData,
NULL,
NULL,
0);
cx_ecfp_init_private_key(CX_CURVE_Ed25519, privateKeyData, SCALAR_LEN_ED25519, &cx_privateKey);
// Sign
*signature = PREFIX_SIGNATURE_TYPE_ED25519;
signatureLength = cx_eddsa_sign(&cx_privateKey,
CX_LAST,
CX_SHA512,
toSign,
messageLen,
NULL,
0,
signature + 1,
signatureMaxlen - 1,
&info);
}
CATCH_ALL
{
MEMZERO(&cx_privateKey, sizeof(cx_privateKey));
*signatureLen = 0;
CLOSE_TRY;
return zxerr_unknown;
};
FINALLY
{
MEMZERO(&cx_privateKey, sizeof(cx_privateKey));
MEMZERO(privateKeyData, SK_LEN_25519);
MEMZERO(signature + signatureLength + 1, signatureMaxlen - signatureLength - 1);
}
}
END_TRY;
return zxerr_ok;
}
#ifdef SUPPORT_SR25519
zxerr_t crypto_sign_sr25519_prephase(uint8_t *buffer, uint16_t bufferLen,
const uint8_t *message, uint16_t messageLen) {
if (messageLen > MAX_SIGN_SIZE) {
uint8_t messageDigest[BLAKE2B_DIGEST_SIZE];
cx_blake2b_t *ctx = (cx_blake2b_t *) buffer;
cx_blake2b_init(ctx, 256);
cx_hash(&ctx->header, CX_LAST, message, messageLen, messageDigest, BLAKE2B_DIGEST_SIZE);
MEMCPY_NV((void *) &N_sr25519_signdata.signdata, messageDigest, BLAKE2B_DIGEST_SIZE);
sr25519_signdataLen = BLAKE2B_DIGEST_SIZE;
} else {
MEMCPY_NV((void *) &N_sr25519_signdata.signdata, (void *) message, messageLen);
sr25519_signdataLen = messageLen;
}
MEMZERO(buffer, bufferLen);
uint8_t privateKeyData[SK_LEN_25519];
MEMZERO(privateKeyData, SK_LEN_25519);
os_perso_derive_node_bip32_seed_key(
HDW_NORMAL,
CX_CURVE_Ed25519,
hdPath,
HDPATH_LEN_DEFAULT,
privateKeyData,
NULL,
NULL,
0);
uint8_t pubkey[PK_LEN_25519];
MEMZERO(pubkey, PK_LEN_25519);
get_sr25519_sk(privateKeyData);
crypto_scalarmult_ristretto255_base_sdk(pubkey, privateKeyData);
MEMCPY_NV((void *) &N_sr25519_signdata.sk, privateKeyData, SK_LEN_25519);
MEMCPY_NV((void *) &N_sr25519_signdata.pk, pubkey, PK_LEN_25519);
MEMZERO(buffer, bufferLen);
return zxerr_ok;
}
zxerr_t crypto_sign_sr25519(uint8_t *signature, uint16_t signatureMaxlen,
uint16_t *signatureLen) {
BEGIN_TRY
{
TRY
{
if (signatureMaxlen < MIN_BUFFER_LENGTH) {
CLOSE_TRY;
return zxerr_invalid_crypto_settings;
}
*signature = PREFIX_SIGNATURE_TYPE_SR25519;
sign_sr25519_phase1((uint8_t *) &N_sr25519_signdata.sk, (uint8_t *) &N_sr25519_signdata.pk, NULL, 0,
(uint8_t *) &N_sr25519_signdata.signdata, sr25519_signdataLen, signature + 1);
crypto_scalarmult_ristretto255_base_sdk(signature + 1, signature + 1 + PK_LEN_25519);
sign_sr25519_phase2((uint8_t *) &N_sr25519_signdata.sk, (uint8_t *) &N_sr25519_signdata.pk, NULL, 0,
(uint8_t *) &N_sr25519_signdata.signdata, sr25519_signdataLen, signature + 1);
MEMCPY_NV((void *) &N_sr25519_signdata.signature, signature, SIG_PLUS_TYPE_LEN);
}
CATCH_ALL
{
CLOSE_TRY;
return zxerr_unknown;
};
FINALLY
{
MEMZERO(signature + SIG_PLUS_TYPE_LEN, signatureMaxlen - SIG_PLUS_TYPE_LEN);
}
}
END_TRY;
return zxerr_ok;
}
#endif
zxerr_t crypto_fillAddress(key_kind_e addressKind, uint8_t *buffer, uint16_t bufferLen, uint16_t *addrResponseLen) {
if (bufferLen < PK_LEN_25519 + SS58_ADDRESS_MAX_LEN) {
return 0;
}
MEMZERO(buffer, bufferLen);
CHECK_ZXERR(crypto_extractPublicKey(addressKind, hdPath, buffer, bufferLen));
size_t outLen = crypto_SS58EncodePubkey(buffer + PK_LEN_25519,
bufferLen - PK_LEN_25519,
get_network_address_type(app_mode_network()), buffer);
if (outLen == 0) {
MEMZERO(buffer, bufferLen);
return zxerr_unknown;
}
*addrResponseLen = PK_LEN_25519 + outLen;
return zxerr_ok;
}
|
319489.c | /**********************************************************************
sjis.c - Oniguruma (regular expression library)
**********************************************************************/
/*-
* Copyright (c) 2002-2008 K.Kosako <sndgk393 AT ybb DOT ne DOT jp>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "regint.h"
static const int EncLen_SJIS[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1
};
static const char SJIS_CAN_BE_TRAIL_TABLE[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0
};
#define SJIS_ISMB_FIRST(byte) (EncLen_SJIS[byte] > 1)
#define SJIS_ISMB_TRAIL(byte) SJIS_CAN_BE_TRAIL_TABLE[(byte)]
typedef enum { FAILURE = -2, ACCEPT = -1, S0 = 0, S1 } state_t;
#define A ACCEPT
#define F FAILURE
static const signed char trans[][0x100] = {
{ /* S0 0 1 2 3 4 5 6 7 8 9 a b c d e f */
/* 0 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 1 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 2 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 3 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 4 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 5 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 6 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 7 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 8 */ F, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 9 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* a */ F, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* b */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* c */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* d */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* e */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* f */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, F, F, F
},
{ /* S1 0 1 2 3 4 5 6 7 8 9 a b c d e f */
/* 0 */ F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F,
/* 1 */ F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F,
/* 2 */ F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F,
/* 3 */ F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F,
/* 4 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 5 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 6 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 7 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, F,
/* 8 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* 9 */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* a */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* b */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* c */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* d */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* e */ A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A,
/* f */ A, A, A, A, A, A, A, A, A, A, A, A, A, F, F, F
}
};
#undef A
#undef F
static int
mbc_enc_len(const UChar* p, const UChar* e, OnigEncoding enc ARG_UNUSED)
{
int firstbyte = *p++;
state_t s;
s = trans[0][firstbyte];
if (s < 0) return s == ACCEPT ? ONIGENC_CONSTRUCT_MBCLEN_CHARFOUND(1) :
ONIGENC_CONSTRUCT_MBCLEN_INVALID();
if (p == e) return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(EncLen_SJIS[firstbyte]-1);
s = trans[s][*p++];
return s == ACCEPT ? ONIGENC_CONSTRUCT_MBCLEN_CHARFOUND(2) :
ONIGENC_CONSTRUCT_MBCLEN_INVALID();
}
static int
code_to_mbclen(OnigCodePoint code, OnigEncoding enc ARG_UNUSED)
{
if (code < 256) {
if (EncLen_SJIS[(int )code] == 1)
return 1;
else
return 0;
}
else if (code <= 0xffff) {
return 2;
}
else
return ONIGERR_INVALID_CODE_POINT_VALUE;
}
static OnigCodePoint
mbc_to_code(const UChar* p, const UChar* end, OnigEncoding enc)
{
int c, i, len;
OnigCodePoint n;
len = enclen(enc, p, end);
c = *p++;
n = c;
if (len == 1) return n;
for (i = 1; i < len; i++) {
if (p >= end) break;
c = *p++;
n <<= 8; n += c;
}
return n;
}
static int
code_to_mbc(OnigCodePoint code, UChar *buf, OnigEncoding enc)
{
UChar *p = buf;
if ((code & 0xff00) != 0) *p++ = (UChar )(((code >> 8) & 0xff));
*p++ = (UChar )(code & 0xff);
#if 0
if (enclen(enc, buf) != (p - buf))
return REGERR_INVALID_CODE_POINT_VALUE;
#endif
return (int)(p - buf);
}
static int
mbc_case_fold(OnigCaseFoldType flag,
const UChar** pp, const UChar* end, UChar* lower,
OnigEncoding enc)
{
const UChar* p = *pp;
if (ONIGENC_IS_MBC_ASCII(p)) {
*lower = ONIGENC_ASCII_CODE_TO_LOWER_CASE(*p);
(*pp)++;
return 1;
}
else {
int i;
int len = enclen(enc, p, end);
for (i = 0; i < len; i++) {
*lower++ = *p++;
}
(*pp) += len;
return len; /* return byte length of converted char to lower */
}
}
#if 0
static int
is_mbc_ambiguous(OnigCaseFoldType flag,
const UChar** pp, const UChar* end)
{
return onigenc_mbn_is_mbc_ambiguous(enc, flag, pp, end);
}
#endif
#if 0
static int
is_code_ctype(OnigCodePoint code, unsigned int ctype)
{
if (code < 128)
return ONIGENC_IS_ASCII_CODE_CTYPE(code, ctype);
else {
if (CTYPE_IS_WORD_GRAPH_PRINT(ctype)) {
return (code_to_mbclen(code) > 1 ? TRUE : FALSE);
}
}
return FALSE;
}
#endif
static UChar*
left_adjust_char_head(const UChar* start, const UChar* s, const UChar* end, OnigEncoding enc)
{
const UChar *p;
int len;
if (s <= start) return (UChar* )s;
p = s;
if (SJIS_ISMB_TRAIL(*p)) {
while (p > start) {
if (! SJIS_ISMB_FIRST(*--p)) {
p++;
break;
}
}
}
len = enclen(enc, p, end);
if (p + len > s) return (UChar* )p;
p += len;
return (UChar* )(p + ((s - p) & ~1));
}
static int
is_allowed_reverse_match(const UChar* s, const UChar* end, OnigEncoding enc ARG_UNUSED)
{
const UChar c = *s;
return (SJIS_ISMB_TRAIL(c) ? FALSE : TRUE);
}
static int PropertyInited = 0;
static const OnigCodePoint** PropertyList;
static int PropertyListNum;
static int PropertyListSize;
static hash_table_type* PropertyNameTable;
static const OnigCodePoint CR_Hiragana[] = {
1,
0x829f, 0x82f1
}; /* CR_Hiragana */
static const OnigCodePoint CR_Katakana[] = {
4,
0x00a6, 0x00af,
0x00b1, 0x00dd,
0x8340, 0x837e,
0x8380, 0x8396,
}; /* CR_Katakana */
static int
init_property_list(void)
{
int r;
PROPERTY_LIST_ADD_PROP("hiragana", CR_Hiragana);
PROPERTY_LIST_ADD_PROP("katakana", CR_Katakana);
PropertyInited = 1;
end:
return r;
}
static int
property_name_to_ctype(OnigEncoding enc, UChar* p, UChar* end)
{
hash_data_type ctype;
UChar *s, *e;
PROPERTY_LIST_INIT_CHECK;
s = e = ALLOCA_N(UChar, end-p+1);
for (; p < end; p++) {
*e++ = ONIGENC_ASCII_CODE_TO_LOWER_CASE(*p);
}
if (onig_st_lookup_strend(PropertyNameTable, s, e, &ctype) == 0) {
return onigenc_minimum_property_name_to_ctype(enc, s, e);
}
return (int)ctype;
}
static int
is_code_ctype(OnigCodePoint code, unsigned int ctype, OnigEncoding enc)
{
if (ctype <= ONIGENC_MAX_STD_CTYPE) {
if (code < 128)
return ONIGENC_IS_ASCII_CODE_CTYPE(code, ctype);
else {
if (CTYPE_IS_WORD_GRAPH_PRINT(ctype)) {
return TRUE;
}
}
}
else {
PROPERTY_LIST_INIT_CHECK;
ctype -= (ONIGENC_MAX_STD_CTYPE + 1);
if (ctype >= (unsigned int )PropertyListNum)
return ONIGERR_TYPE_BUG;
return onig_is_in_code_range((UChar* )PropertyList[ctype], code);
}
return FALSE;
}
static int
get_ctype_code_range(OnigCtype ctype, OnigCodePoint* sb_out,
const OnigCodePoint* ranges[], OnigEncoding enc ARG_UNUSED)
{
if (ctype <= ONIGENC_MAX_STD_CTYPE) {
return ONIG_NO_SUPPORT_CONFIG;
}
else {
*sb_out = 0x80;
PROPERTY_LIST_INIT_CHECK;
ctype -= (ONIGENC_MAX_STD_CTYPE + 1);
if (ctype >= (OnigCtype )PropertyListNum)
return ONIGERR_TYPE_BUG;
*ranges = PropertyList[ctype];
return 0;
}
}
OnigEncodingDefine(shift_jis, Shift_JIS) = {
mbc_enc_len,
"Shift_JIS", /* name */
2, /* max byte length */
1, /* min byte length */
onigenc_is_mbc_newline_0x0a,
mbc_to_code,
code_to_mbclen,
code_to_mbc,
mbc_case_fold,
onigenc_ascii_apply_all_case_fold,
onigenc_ascii_get_case_fold_codes_by_str,
property_name_to_ctype,
is_code_ctype,
get_ctype_code_range,
left_adjust_char_head,
is_allowed_reverse_match,
0
};
ENC_DEFINE("Shift_JIS", Shift_JIS)
/*
* Name: Shift_JIS
* MIBenum: 17
* Link: http://www.iana.org/assignments/character-sets
* Link: http://ja.wikipedia.org/wiki/Shift_JIS
*/
/*
* Name: Windows-31J
* MIBenum: 2024
* Link: http://www.iana.org/assignments/character-sets
* Link: http://www.microsoft.com/globaldev/reference/dbcs/932.mspx
* Link: http://ja.wikipedia.org/wiki/Windows-31J
* Link: http://source.icu-project.org/repos/icu/data/trunk/charset/data/ucm/windows-932-2000.ucm
*
* Windows Standard Character Set and its mapping to Unicode by Microsoft.
* Since 1.9.3, SJIS is the alias of Windows-31J because its character
* set is usually this one even if its mapping may differ.
*/
ENC_REPLICATE("Windows-31J", "Shift_JIS")
ENC_ALIAS("CP932", "Windows-31J")
ENC_ALIAS("csWindows31J", "Windows-31J") /* IANA. IE6 don't accept Windows-31J but csWindows31J. */
ENC_ALIAS("SJIS", "Windows-31J")
/*
* Name: PCK
* Link: http://download.oracle.com/docs/cd/E19253-01/819-0606/x-2chn0/index.html
* Link: http://download.oracle.com/docs/cd/E19253-01/819-0606/appb-pckwarn-1/index.html
*
* Solaris's SJIS variant. Its set is Windows Standard Character Set; it
* consists JIS X 0201 Latin (US-ASCII), JIS X 0201 Katakana, JIS X 0208, NEC
* special characters, NEC-selected IBM extended characters, and IBM extended
* characters. Solaris's iconv seems to use SJIS-open.
*/
ENC_ALIAS("PCK", "Windows-31J")
/*
* Name: MacJapanese
* Link: http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/JAPANESE.TXT
* Link: http://ja.wikipedia.org/wiki/MacJapanese
*/
ENC_REPLICATE("MacJapanese", "Shift_JIS")
ENC_ALIAS("MacJapan", "MacJapanese")
|
416382.c | /* $Id: tif_thunder.c,v 1.5.2.1 2010-06-08 18:50:43 bfriesen Exp $ */
/*
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#include "tiffiop.h"
#ifdef THUNDER_SUPPORT
/*
* TIFF Library.
*
* ThunderScan 4-bit Compression Algorithm Support
*/
/*
* ThunderScan uses an encoding scheme designed for
* 4-bit pixel values. Data is encoded in bytes, with
* each byte split into a 2-bit code word and a 6-bit
* data value. The encoding gives raw data, runs of
* pixels, or pixel values encoded as a delta from the
* previous pixel value. For the latter, either 2-bit
* or 3-bit delta values are used, with the deltas packed
* into a single byte.
*/
#define THUNDER_DATA 0x3f /* mask for 6-bit data */
#define THUNDER_CODE 0xc0 /* mask for 2-bit code word */
/* code values */
#define THUNDER_RUN 0x00 /* run of pixels w/ encoded count */
#define THUNDER_2BITDELTAS 0x40 /* 3 pixels w/ encoded 2-bit deltas */
#define DELTA2_SKIP 2 /* skip code for 2-bit deltas */
#define THUNDER_3BITDELTAS 0x80 /* 2 pixels w/ encoded 3-bit deltas */
#define DELTA3_SKIP 4 /* skip code for 3-bit deltas */
#define THUNDER_RAW 0xc0 /* raw data encoded */
static const int twobitdeltas[4] = { 0, 1, 0, -1 };
static const int threebitdeltas[8] = { 0, 1, 2, 3, 0, -3, -2, -1 };
#define SETPIXEL(op, v) { \
lastpixel = (v) & 0xf; \
if (npixels++ & 1) \
*op++ |= lastpixel; \
else \
op[0] = (tidataval_t) (lastpixel << 4); \
}
static int
ThunderDecode(TIFF* tif, tidata_t op, tsize_t maxpixels)
{
register unsigned char *bp;
register tsize_t cc;
unsigned int lastpixel;
tsize_t npixels;
bp = (unsigned char *)tif->tif_rawcp;
cc = tif->tif_rawcc;
lastpixel = 0;
npixels = 0;
while (cc > 0 && npixels < maxpixels) {
int n, delta;
n = *bp++, cc--;
switch (n & THUNDER_CODE) {
case THUNDER_RUN: /* pixel run */
/*
* Replicate the last pixel n times,
* where n is the lower-order 6 bits.
*/
if (npixels & 1) {
op[0] |= lastpixel;
lastpixel = *op++; npixels++; n--;
} else
lastpixel |= lastpixel << 4;
npixels += n;
if (npixels < maxpixels) {
for (; n > 0; n -= 2)
*op++ = (tidataval_t) lastpixel;
}
if (n == -1)
*--op &= 0xf0;
lastpixel &= 0xf;
break;
case THUNDER_2BITDELTAS: /* 2-bit deltas */
if ((delta = ((n >> 4) & 3)) != DELTA2_SKIP)
SETPIXEL(op, lastpixel + twobitdeltas[delta]);
if ((delta = ((n >> 2) & 3)) != DELTA2_SKIP)
SETPIXEL(op, lastpixel + twobitdeltas[delta]);
if ((delta = (n & 3)) != DELTA2_SKIP)
SETPIXEL(op, lastpixel + twobitdeltas[delta]);
break;
case THUNDER_3BITDELTAS: /* 3-bit deltas */
if ((delta = ((n >> 3) & 7)) != DELTA3_SKIP)
SETPIXEL(op, lastpixel + threebitdeltas[delta]);
if ((delta = (n & 7)) != DELTA3_SKIP)
SETPIXEL(op, lastpixel + threebitdeltas[delta]);
break;
case THUNDER_RAW: /* raw data */
SETPIXEL(op, n);
break;
}
}
tif->tif_rawcp = (tidata_t) bp;
tif->tif_rawcc = cc;
if (npixels != maxpixels) {
TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
"ThunderDecode: %s data at scanline %ld (%lu != %lu)",
npixels < maxpixels ? "Not enough" : "Too much",
(long) tif->tif_row, (long) npixels, (long) maxpixels);
return (0);
}
return (1);
}
static int
ThunderDecodeRow(TIFF* tif, tidata_t buf, tsize_t occ, tsample_t s)
{
tidata_t row = buf;
(void) s;
while ((long)occ > 0) {
if (!ThunderDecode(tif, row, tif->tif_dir.td_imagewidth))
return (0);
occ -= tif->tif_scanlinesize;
row += tif->tif_scanlinesize;
}
return (1);
}
int
TIFFInitThunderScan(TIFF* tif, int scheme)
{
(void) scheme;
tif->tif_decoderow = ThunderDecodeRow;
tif->tif_decodestrip = ThunderDecodeRow;
return (1);
}
#endif /* THUNDER_SUPPORT */
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
|
962134.c | /*
* Implementation of the Microsoft Installer (msi.dll)
*
* Copyright 2004 Aric Stewart for CodeWeavers
*
* This 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.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
#define COBJMACROS
#include <stdarg.h>
#include "windef.h"
#include "winbase.h"
#include "winreg.h"
#include "winnls.h"
#include "shlwapi.h"
#include "wingdi.h"
#include "wine/debug.h"
#include "msi.h"
#include "msiquery.h"
#include "objidl.h"
#include "wincrypt.h"
#include "winuser.h"
#include "wininet.h"
#include "winver.h"
#include "urlmon.h"
#include "shlobj.h"
#include "wine/unicode.h"
#include "objbase.h"
#include "msidefs.h"
#include "sddl.h"
#include "msipriv.h"
#include "msiserver.h"
#include "resource.h"
WINE_DEFAULT_DEBUG_CHANNEL(msi);
static void free_feature( MSIFEATURE *feature )
{
struct list *item, *cursor;
LIST_FOR_EACH_SAFE( item, cursor, &feature->Children )
{
FeatureList *fl = LIST_ENTRY( item, FeatureList, entry );
list_remove( &fl->entry );
msi_free( fl );
}
LIST_FOR_EACH_SAFE( item, cursor, &feature->Components )
{
ComponentList *cl = LIST_ENTRY( item, ComponentList, entry );
list_remove( &cl->entry );
msi_free( cl );
}
msi_free( feature->Feature );
msi_free( feature->Feature_Parent );
msi_free( feature->Directory );
msi_free( feature->Description );
msi_free( feature->Title );
msi_free( feature );
}
static void free_folder( MSIFOLDER *folder )
{
struct list *item, *cursor;
LIST_FOR_EACH_SAFE( item, cursor, &folder->children )
{
FolderList *fl = LIST_ENTRY( item, FolderList, entry );
list_remove( &fl->entry );
msi_free( fl );
}
msi_free( folder->Parent );
msi_free( folder->Directory );
msi_free( folder->TargetDefault );
msi_free( folder->SourceLongPath );
msi_free( folder->SourceShortPath );
msi_free( folder->ResolvedTarget );
msi_free( folder->ResolvedSource );
msi_free( folder );
}
static void free_extension( MSIEXTENSION *ext )
{
struct list *item, *cursor;
LIST_FOR_EACH_SAFE( item, cursor, &ext->verbs )
{
MSIVERB *verb = LIST_ENTRY( item, MSIVERB, entry );
list_remove( &verb->entry );
msi_free( verb->Verb );
msi_free( verb->Command );
msi_free( verb->Argument );
msi_free( verb );
}
msi_free( ext->Extension );
msi_free( ext->ProgIDText );
msi_free( ext );
}
static void free_assembly( MSIASSEMBLY *assembly )
{
msi_free( assembly->feature );
msi_free( assembly->manifest );
msi_free( assembly->application );
msi_free( assembly->display_name );
if (assembly->tempdir) RemoveDirectoryW( assembly->tempdir );
msi_free( assembly->tempdir );
msi_free( assembly );
}
void msi_free_action_script( MSIPACKAGE *package, UINT script )
{
UINT i;
for (i = 0; i < package->script_actions_count[script]; i++)
msi_free( package->script_actions[script][i] );
msi_free( package->script_actions[script] );
package->script_actions[script] = NULL;
package->script_actions_count[script] = 0;
}
static void free_package_structures( MSIPACKAGE *package )
{
struct list *item, *cursor;
int i;
LIST_FOR_EACH_SAFE( item, cursor, &package->features )
{
MSIFEATURE *feature = LIST_ENTRY( item, MSIFEATURE, entry );
list_remove( &feature->entry );
free_feature( feature );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->folders )
{
MSIFOLDER *folder = LIST_ENTRY( item, MSIFOLDER, entry );
list_remove( &folder->entry );
free_folder( folder );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->files )
{
MSIFILE *file = LIST_ENTRY( item, MSIFILE, entry );
list_remove( &file->entry );
msi_free( file->File );
msi_free( file->FileName );
msi_free( file->ShortName );
msi_free( file->LongName );
msi_free( file->Version );
msi_free( file->Language );
if (msi_is_global_assembly( file->Component )) DeleteFileW( file->TargetPath );
msi_free( file->TargetPath );
msi_free( file );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->components )
{
MSICOMPONENT *comp = LIST_ENTRY( item, MSICOMPONENT, entry );
list_remove( &comp->entry );
msi_free( comp->Component );
msi_free( comp->ComponentId );
msi_free( comp->Directory );
msi_free( comp->Condition );
msi_free( comp->KeyPath );
msi_free( comp->FullKeypath );
if (comp->assembly) free_assembly( comp->assembly );
msi_free( comp );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->filepatches )
{
MSIFILEPATCH *patch = LIST_ENTRY( item, MSIFILEPATCH, entry );
list_remove( &patch->entry );
msi_free( patch->path );
msi_free( patch );
}
/* clean up extension, progid, class and verb structures */
LIST_FOR_EACH_SAFE( item, cursor, &package->classes )
{
MSICLASS *cls = LIST_ENTRY( item, MSICLASS, entry );
list_remove( &cls->entry );
msi_free( cls->clsid );
msi_free( cls->Context );
msi_free( cls->Description );
msi_free( cls->FileTypeMask );
msi_free( cls->IconPath );
msi_free( cls->DefInprocHandler );
msi_free( cls->DefInprocHandler32 );
msi_free( cls->Argument );
msi_free( cls->ProgIDText );
msi_free( cls );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->extensions )
{
MSIEXTENSION *ext = LIST_ENTRY( item, MSIEXTENSION, entry );
list_remove( &ext->entry );
free_extension( ext );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->progids )
{
MSIPROGID *progid = LIST_ENTRY( item, MSIPROGID, entry );
list_remove( &progid->entry );
msi_free( progid->ProgID );
msi_free( progid->Description );
msi_free( progid->IconPath );
msi_free( progid );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->mimes )
{
MSIMIME *mt = LIST_ENTRY( item, MSIMIME, entry );
list_remove( &mt->entry );
msi_free( mt->suffix );
msi_free( mt->clsid );
msi_free( mt->ContentType );
msi_free( mt );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->appids )
{
MSIAPPID *appid = LIST_ENTRY( item, MSIAPPID, entry );
list_remove( &appid->entry );
msi_free( appid->AppID );
msi_free( appid->RemoteServerName );
msi_free( appid->LocalServer );
msi_free( appid->ServiceParameters );
msi_free( appid->DllSurrogate );
msi_free( appid );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->sourcelist_info )
{
MSISOURCELISTINFO *info = LIST_ENTRY( item, MSISOURCELISTINFO, entry );
list_remove( &info->entry );
msi_free( info->value );
msi_free( info );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->sourcelist_media )
{
MSIMEDIADISK *info = LIST_ENTRY( item, MSIMEDIADISK, entry );
list_remove( &info->entry );
msi_free( info->volume_label );
msi_free( info->disk_prompt );
msi_free( info );
}
for (i = 0; i < SCRIPT_MAX; i++)
msi_free_action_script( package, i );
for (i = 0; i < package->unique_actions_count; i++)
msi_free( package->unique_actions[i] );
msi_free( package->unique_actions);
LIST_FOR_EACH_SAFE( item, cursor, &package->binaries )
{
MSIBINARY *binary = LIST_ENTRY( item, MSIBINARY, entry );
list_remove( &binary->entry );
if (binary->module)
FreeLibrary( binary->module );
if (!DeleteFileW( binary->tmpfile ))
ERR("failed to delete %s (%u)\n", debugstr_w(binary->tmpfile), GetLastError());
msi_free( binary->source );
msi_free( binary->tmpfile );
msi_free( binary );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->cabinet_streams )
{
MSICABINETSTREAM *cab = LIST_ENTRY( item, MSICABINETSTREAM, entry );
list_remove( &cab->entry );
IStorage_Release( cab->storage );
msi_free( cab->stream );
msi_free( cab );
}
LIST_FOR_EACH_SAFE( item, cursor, &package->patches )
{
MSIPATCHINFO *patch = LIST_ENTRY( item, MSIPATCHINFO, entry );
list_remove( &patch->entry );
if (patch->delete_on_close && !DeleteFileW( patch->localfile ))
{
ERR("failed to delete %s (%u)\n", debugstr_w(patch->localfile), GetLastError());
}
msi_free_patchinfo( patch );
}
msi_free( package->BaseURL );
msi_free( package->PackagePath );
msi_free( package->ProductCode );
msi_free( package->ActionFormat );
msi_free( package->LastAction );
msi_free( package->LastActionTemplate );
msi_free( package->langids );
/* cleanup control event subscriptions */
msi_event_cleanup_all_subscriptions( package );
}
static void MSI_FreePackage( MSIOBJECTHDR *arg)
{
MSIPACKAGE *package = (MSIPACKAGE *)arg;
msi_destroy_assembly_caches( package );
if( package->dialog )
msi_dialog_destroy( package->dialog );
msiobj_release( &package->db->hdr );
free_package_structures(package);
CloseHandle( package->log_file );
if (package->delete_on_close) DeleteFileW( package->localfile );
msi_free( package->localfile );
MSI_ProcessMessage(NULL, INSTALLMESSAGE_TERMINATE, 0);
}
static UINT create_temp_property_table(MSIPACKAGE *package)
{
static const WCHAR query[] = {
'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
'`','_','P','r','o','p','e','r','t','y','`',' ','(',' ',
'`','_','P','r','o','p','e','r','t','y','`',' ',
'C','H','A','R','(','5','6',')',' ','N','O','T',' ','N','U','L','L',' ',
'T','E','M','P','O','R','A','R','Y',',',' ',
'`','V','a','l','u','e','`',' ','C','H','A','R','(','9','8',')',' ',
'N','O','T',' ','N','U','L','L',' ','T','E','M','P','O','R','A','R','Y',
' ','P','R','I','M','A','R','Y',' ','K','E','Y',' ',
'`','_','P','r','o','p','e','r','t','y','`',')',' ','H','O','L','D',0};
MSIQUERY *view;
UINT rc;
rc = MSI_DatabaseOpenViewW(package->db, query, &view);
if (rc != ERROR_SUCCESS)
return rc;
rc = MSI_ViewExecute(view, 0);
MSI_ViewClose(view);
msiobj_release(&view->hdr);
return rc;
}
UINT msi_clone_properties( MSIDATABASE *db )
{
static const WCHAR query_select[] = {
'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
'`','P','r','o','p','e','r','t','y','`',0};
static const WCHAR query_insert[] = {
'I','N','S','E','R','T',' ','I','N','T','O',' ',
'`','_','P','r','o','p','e','r','t','y','`',' ',
'(','`','_','P','r','o','p','e','r','t','y','`',',','`','V','a','l','u','e','`',')',' ',
'V','A','L','U','E','S',' ','(','?',',','?',')',0};
static const WCHAR query_update[] = {
'U','P','D','A','T','E',' ','`','_','P','r','o','p','e','r','t','y','`',' ',
'S','E','T',' ','`','V','a','l','u','e','`',' ','=',' ','?',' ',
'W','H','E','R','E',' ','`','_','P','r','o','p','e','r','t','y','`',' ','=',' ','?',0};
MSIQUERY *view_select;
UINT rc;
rc = MSI_DatabaseOpenViewW( db, query_select, &view_select );
if (rc != ERROR_SUCCESS)
return rc;
rc = MSI_ViewExecute( view_select, 0 );
if (rc != ERROR_SUCCESS)
{
MSI_ViewClose( view_select );
msiobj_release( &view_select->hdr );
return rc;
}
while (1)
{
MSIQUERY *view_insert, *view_update;
MSIRECORD *rec_select;
rc = MSI_ViewFetch( view_select, &rec_select );
if (rc != ERROR_SUCCESS)
break;
rc = MSI_DatabaseOpenViewW( db, query_insert, &view_insert );
if (rc != ERROR_SUCCESS)
{
msiobj_release( &rec_select->hdr );
continue;
}
rc = MSI_ViewExecute( view_insert, rec_select );
MSI_ViewClose( view_insert );
msiobj_release( &view_insert->hdr );
if (rc != ERROR_SUCCESS)
{
MSIRECORD *rec_update;
TRACE("insert failed, trying update\n");
rc = MSI_DatabaseOpenViewW( db, query_update, &view_update );
if (rc != ERROR_SUCCESS)
{
WARN("open view failed %u\n", rc);
msiobj_release( &rec_select->hdr );
continue;
}
rec_update = MSI_CreateRecord( 2 );
MSI_RecordCopyField( rec_select, 1, rec_update, 2 );
MSI_RecordCopyField( rec_select, 2, rec_update, 1 );
rc = MSI_ViewExecute( view_update, rec_update );
if (rc != ERROR_SUCCESS)
WARN("update failed %u\n", rc);
MSI_ViewClose( view_update );
msiobj_release( &view_update->hdr );
msiobj_release( &rec_update->hdr );
}
msiobj_release( &rec_select->hdr );
}
MSI_ViewClose( view_select );
msiobj_release( &view_select->hdr );
return rc;
}
/*
* set_installed_prop
*
* Sets the "Installed" property to indicate that
* the product is installed for the current user.
*/
static UINT set_installed_prop( MSIPACKAGE *package )
{
HKEY hkey;
UINT r;
if (!package->ProductCode) return ERROR_FUNCTION_FAILED;
r = MSIREG_OpenUninstallKey( package->ProductCode, package->platform, &hkey, FALSE );
if (r == ERROR_SUCCESS)
{
RegCloseKey( hkey );
msi_set_property( package->db, szInstalled, szOne, -1 );
}
return r;
}
static UINT set_user_sid_prop( MSIPACKAGE *package )
{
SID_NAME_USE use;
LPWSTR user_name;
LPWSTR sid_str = NULL, dom = NULL;
DWORD size, dom_size;
PSID psid = NULL;
UINT r = ERROR_FUNCTION_FAILED;
size = 0;
GetUserNameW( NULL, &size );
user_name = msi_alloc( (size + 1) * sizeof(WCHAR) );
if (!user_name)
return ERROR_OUTOFMEMORY;
if (!GetUserNameW( user_name, &size ))
goto done;
size = 0;
dom_size = 0;
LookupAccountNameW( NULL, user_name, NULL, &size, NULL, &dom_size, &use );
psid = msi_alloc( size );
dom = msi_alloc( dom_size*sizeof (WCHAR) );
if (!psid || !dom)
{
r = ERROR_OUTOFMEMORY;
goto done;
}
if (!LookupAccountNameW( NULL, user_name, psid, &size, dom, &dom_size, &use ))
goto done;
if (!ConvertSidToStringSidW( psid, &sid_str ))
goto done;
r = msi_set_property( package->db, szUserSID, sid_str, -1 );
done:
LocalFree( sid_str );
msi_free( dom );
msi_free( psid );
msi_free( user_name );
return r;
}
static LPWSTR get_fusion_filename(MSIPACKAGE *package)
{
HKEY netsetup;
LONG res;
LPWSTR file = NULL;
DWORD index = 0, size;
WCHAR ver[MAX_PATH];
WCHAR name[MAX_PATH];
WCHAR windir[MAX_PATH];
static const WCHAR fusion[] = {'f','u','s','i','o','n','.','d','l','l',0};
static const WCHAR sub[] = {
'S','o','f','t','w','a','r','e','\\',
'M','i','c','r','o','s','o','f','t','\\',
'N','E','T',' ','F','r','a','m','e','w','o','r','k',' ','S','e','t','u','p','\\',
'N','D','P',0
};
static const WCHAR subdir[] = {
'M','i','c','r','o','s','o','f','t','.','N','E','T','\\',
'F','r','a','m','e','w','o','r','k','\\',0
};
res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, sub, 0, KEY_ENUMERATE_SUB_KEYS, &netsetup);
if (res != ERROR_SUCCESS)
return NULL;
GetWindowsDirectoryW(windir, MAX_PATH);
ver[0] = '\0';
size = MAX_PATH;
while (RegEnumKeyExW(netsetup, index, name, &size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
{
index++;
/* verify existence of fusion.dll .Net 3.0 does not install a new one */
if (strcmpW( ver, name ) < 0)
{
LPWSTR check;
size = lstrlenW(windir) + lstrlenW(subdir) + lstrlenW(name) +lstrlenW(fusion) + 3;
check = msi_alloc(size * sizeof(WCHAR));
if (!check)
{
msi_free(file);
return NULL;
}
lstrcpyW(check, windir);
lstrcatW(check, szBackSlash);
lstrcatW(check, subdir);
lstrcatW(check, name);
lstrcatW(check, szBackSlash);
lstrcatW(check, fusion);
if(GetFileAttributesW(check) != INVALID_FILE_ATTRIBUTES)
{
msi_free(file);
file = check;
lstrcpyW(ver, name);
}
else
msi_free(check);
}
}
RegCloseKey(netsetup);
return file;
}
typedef struct tagLANGANDCODEPAGE
{
WORD wLanguage;
WORD wCodePage;
} LANGANDCODEPAGE;
static void set_msi_assembly_prop(MSIPACKAGE *package)
{
UINT val_len;
DWORD size, handle;
LPVOID version = NULL;
WCHAR buf[MAX_PATH];
LPWSTR fusion, verstr;
LANGANDCODEPAGE *translate;
static const WCHAR netasm[] = {
'M','s','i','N','e','t','A','s','s','e','m','b','l','y','S','u','p','p','o','r','t',0
};
static const WCHAR translation[] = {
'\\','V','a','r','F','i','l','e','I','n','f','o',
'\\','T','r','a','n','s','l','a','t','i','o','n',0
};
static const WCHAR verfmt[] = {
'\\','S','t','r','i','n','g','F','i','l','e','I','n','f','o',
'\\','%','0','4','x','%','0','4','x',
'\\','P','r','o','d','u','c','t','V','e','r','s','i','o','n',0
};
fusion = get_fusion_filename(package);
if (!fusion)
return;
size = GetFileVersionInfoSizeW(fusion, &handle);
if (!size)
goto done;
version = msi_alloc(size);
if (!version)
goto done;
if (!GetFileVersionInfoW(fusion, handle, size, version))
goto done;
if (!VerQueryValueW(version, translation, (LPVOID *)&translate, &val_len))
goto done;
sprintfW(buf, verfmt, translate[0].wLanguage, translate[0].wCodePage);
if (!VerQueryValueW(version, buf, (LPVOID *)&verstr, &val_len))
goto done;
if (!val_len || !verstr)
goto done;
msi_set_property( package->db, netasm, verstr, -1 );
done:
msi_free(fusion);
msi_free(version);
}
static VOID set_installer_properties(MSIPACKAGE *package)
{
WCHAR *ptr;
OSVERSIONINFOEXW OSVersion;
MEMORYSTATUSEX msex;
DWORD verval, len;
WCHAR pth[MAX_PATH], verstr[11], bufstr[22];
HDC dc;
HKEY hkey;
LPWSTR username, companyname;
SYSTEM_INFO sys_info;
LANGID langid;
static const WCHAR szCommonFilesFolder[] = {'C','o','m','m','o','n','F','i','l','e','s','F','o','l','d','e','r',0};
static const WCHAR szProgramFilesFolder[] = {'P','r','o','g','r','a','m','F','i','l','e','s','F','o','l','d','e','r',0};
static const WCHAR szCommonAppDataFolder[] = {'C','o','m','m','o','n','A','p','p','D','a','t','a','F','o','l','d','e','r',0};
static const WCHAR szFavoritesFolder[] = {'F','a','v','o','r','i','t','e','s','F','o','l','d','e','r',0};
static const WCHAR szFontsFolder[] = {'F','o','n','t','s','F','o','l','d','e','r',0};
static const WCHAR szSendToFolder[] = {'S','e','n','d','T','o','F','o','l','d','e','r',0};
static const WCHAR szStartMenuFolder[] = {'S','t','a','r','t','M','e','n','u','F','o','l','d','e','r',0};
static const WCHAR szStartupFolder[] = {'S','t','a','r','t','u','p','F','o','l','d','e','r',0};
static const WCHAR szTemplateFolder[] = {'T','e','m','p','l','a','t','e','F','o','l','d','e','r',0};
static const WCHAR szDesktopFolder[] = {'D','e','s','k','t','o','p','F','o','l','d','e','r',0};
static const WCHAR szProgramMenuFolder[] = {'P','r','o','g','r','a','m','M','e','n','u','F','o','l','d','e','r',0};
static const WCHAR szAdminToolsFolder[] = {'A','d','m','i','n','T','o','o','l','s','F','o','l','d','e','r',0};
static const WCHAR szSystemFolder[] = {'S','y','s','t','e','m','F','o','l','d','e','r',0};
static const WCHAR szSystem16Folder[] = {'S','y','s','t','e','m','1','6','F','o','l','d','e','r',0};
static const WCHAR szLocalAppDataFolder[] = {'L','o','c','a','l','A','p','p','D','a','t','a','F','o','l','d','e','r',0};
static const WCHAR szMyPicturesFolder[] = {'M','y','P','i','c','t','u','r','e','s','F','o','l','d','e','r',0};
static const WCHAR szPersonalFolder[] = {'P','e','r','s','o','n','a','l','F','o','l','d','e','r',0};
static const WCHAR szWindowsVolume[] = {'W','i','n','d','o','w','s','V','o','l','u','m','e',0};
static const WCHAR szPrivileged[] = {'P','r','i','v','i','l','e','g','e','d',0};
static const WCHAR szVersion9x[] = {'V','e','r','s','i','o','n','9','X',0};
static const WCHAR szVersionNT[] = {'V','e','r','s','i','o','n','N','T',0};
static const WCHAR szMsiNTProductType[] = {'M','s','i','N','T','P','r','o','d','u','c','t','T','y','p','e',0};
static const WCHAR szFormat[] = {'%','u',0};
static const WCHAR szFormat2[] = {'%','u','.','%','u',0};
static const WCHAR szWindowsBuild[] = {'W','i','n','d','o','w','s','B','u','i','l','d',0};
static const WCHAR szServicePackLevel[] = {'S','e','r','v','i','c','e','P','a','c','k','L','e','v','e','l',0};
static const WCHAR szVersionMsi[] = { 'V','e','r','s','i','o','n','M','s','i',0 };
static const WCHAR szVersionDatabase[] = { 'V','e','r','s','i','o','n','D','a','t','a','b','a','s','e',0 };
static const WCHAR szPhysicalMemory[] = { 'P','h','y','s','i','c','a','l','M','e','m','o','r','y',0 };
static const WCHAR szScreenX[] = {'S','c','r','e','e','n','X',0};
static const WCHAR szScreenY[] = {'S','c','r','e','e','n','Y',0};
static const WCHAR szColorBits[] = {'C','o','l','o','r','B','i','t','s',0};
static const WCHAR szIntFormat[] = {'%','d',0};
static const WCHAR szMsiAMD64[] = { 'M','s','i','A','M','D','6','4',0 };
static const WCHAR szMsix64[] = { 'M','s','i','x','6','4',0 };
static const WCHAR szSystem64Folder[] = { 'S','y','s','t','e','m','6','4','F','o','l','d','e','r',0 };
static const WCHAR szCommonFiles64Folder[] = { 'C','o','m','m','o','n','F','i','l','e','s','6','4','F','o','l','d','e','r',0 };
static const WCHAR szProgramFiles64Folder[] = { 'P','r','o','g','r','a','m','F','i','l','e','s','6','4','F','o','l','d','e','r',0 };
static const WCHAR szVersionNT64[] = { 'V','e','r','s','i','o','n','N','T','6','4',0 };
static const WCHAR szUserInfo[] = {
'S','O','F','T','W','A','R','E','\\',
'M','i','c','r','o','s','o','f','t','\\',
'M','S',' ','S','e','t','u','p',' ','(','A','C','M','E',')','\\',
'U','s','e','r',' ','I','n','f','o',0
};
static const WCHAR szDefName[] = { 'D','e','f','N','a','m','e',0 };
static const WCHAR szDefCompany[] = { 'D','e','f','C','o','m','p','a','n','y',0 };
static const WCHAR szCurrentVersion[] = {
'S','O','F','T','W','A','R','E','\\',
'M','i','c','r','o','s','o','f','t','\\',
'W','i','n','d','o','w','s',' ','N','T','\\',
'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0
};
static const WCHAR szRegisteredUser[] = {'R','e','g','i','s','t','e','r','e','d','O','w','n','e','r',0};
static const WCHAR szRegisteredOrganization[] = {
'R','e','g','i','s','t','e','r','e','d','O','r','g','a','n','i','z','a','t','i','o','n',0
};
static const WCHAR szUSERNAME[] = {'U','S','E','R','N','A','M','E',0};
static const WCHAR szCOMPANYNAME[] = {'C','O','M','P','A','N','Y','N','A','M','E',0};
static const WCHAR szUserLanguageID[] = {'U','s','e','r','L','a','n','g','u','a','g','e','I','D',0};
static const WCHAR szSystemLangID[] = {'S','y','s','t','e','m','L','a','n','g','u','a','g','e','I','D',0};
static const WCHAR szProductState[] = {'P','r','o','d','u','c','t','S','t','a','t','e',0};
static const WCHAR szLogonUser[] = {'L','o','g','o','n','U','s','e','r',0};
static const WCHAR szNetHoodFolder[] = {'N','e','t','H','o','o','d','F','o','l','d','e','r',0};
static const WCHAR szPrintHoodFolder[] = {'P','r','i','n','t','H','o','o','d','F','o','l','d','e','r',0};
static const WCHAR szRecentFolder[] = {'R','e','c','e','n','t','F','o','l','d','e','r',0};
static const WCHAR szComputerName[] = {'C','o','m','p','u','t','e','r','N','a','m','e',0};
/*
* Other things that probably should be set:
*
* VirtualMemory ShellAdvSupport DefaultUIFont PackagecodeChanging
* CaptionHeight BorderTop BorderSide TextHeight RedirectedDllSupport
*/
SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szCommonAppDataFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_FAVORITES, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szFavoritesFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_FONTS, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szFontsFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_SENDTO, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szSendToFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_STARTMENU, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szStartMenuFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szStartupFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_TEMPLATES, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szTemplateFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szDesktopFolder, pth, -1 );
/* FIXME: set to AllUsers profile path if ALLUSERS is set */
SHGetFolderPathW(NULL, CSIDL_PROGRAMS, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szProgramMenuFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_ADMINTOOLS, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szAdminToolsFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szAppDataFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_SYSTEM, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szSystemFolder, pth, -1 );
msi_set_property( package->db, szSystem16Folder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szLocalAppDataFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_MYPICTURES, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szMyPicturesFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_PERSONAL, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szPersonalFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_WINDOWS, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szWindowsFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_PRINTHOOD, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szPrintHoodFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_NETHOOD, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szNetHoodFolder, pth, -1 );
SHGetFolderPathW(NULL, CSIDL_RECENT, NULL, 0, pth);
strcatW(pth, szBackSlash);
msi_set_property( package->db, szRecentFolder, pth, -1 );
/* Physical Memory is specified in MB. Using total amount. */
msex.dwLength = sizeof(msex);
GlobalMemoryStatusEx( &msex );
len = sprintfW( bufstr, szIntFormat, (int)(msex.ullTotalPhys / 1024 / 1024) );
msi_set_property( package->db, szPhysicalMemory, bufstr, len );
SHGetFolderPathW(NULL, CSIDL_WINDOWS, NULL, 0, pth);
ptr = strchrW(pth,'\\');
if (ptr) *(ptr + 1) = 0;
msi_set_property( package->db, szWindowsVolume, pth, -1 );
len = GetTempPathW(MAX_PATH, pth);
msi_set_property( package->db, szTempFolder, pth, len );
/* in a wine environment the user is always admin and privileged */
msi_set_property( package->db, szAdminUser, szOne, -1 );
msi_set_property( package->db, szPrivileged, szOne, -1 );
/* set the os things */
OSVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
GetVersionExW((OSVERSIONINFOW *)&OSVersion);
verval = OSVersion.dwMinorVersion + OSVersion.dwMajorVersion * 100;
len = sprintfW( verstr, szFormat, verval );
switch (OSVersion.dwPlatformId)
{
case VER_PLATFORM_WIN32_WINDOWS:
msi_set_property( package->db, szVersion9x, verstr, len );
break;
case VER_PLATFORM_WIN32_NT:
msi_set_property( package->db, szVersionNT, verstr, len );
len = sprintfW( bufstr, szFormat,OSVersion.wProductType );
msi_set_property( package->db, szMsiNTProductType, bufstr, len );
break;
}
len = sprintfW( bufstr, szFormat, OSVersion.dwBuildNumber );
msi_set_property( package->db, szWindowsBuild, bufstr, len );
len = sprintfW( bufstr, szFormat, OSVersion.wServicePackMajor );
msi_set_property( package->db, szServicePackLevel, bufstr, len );
len = sprintfW( bufstr, szFormat2, MSI_MAJORVERSION, MSI_MINORVERSION );
msi_set_property( package->db, szVersionMsi, bufstr, len );
len = sprintfW( bufstr, szFormat, MSI_MAJORVERSION * 100 );
msi_set_property( package->db, szVersionDatabase, bufstr, len );
GetNativeSystemInfo( &sys_info );
len = sprintfW( bufstr, szIntFormat, sys_info.wProcessorLevel );
msi_set_property( package->db, szIntel, bufstr, len );
if (sys_info.u.s.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
{
GetSystemDirectoryW( pth, MAX_PATH );
PathAddBackslashW( pth );
msi_set_property( package->db, szSystemFolder, pth, -1 );
SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILES, NULL, 0, pth );
PathAddBackslashW( pth );
msi_set_property( package->db, szProgramFilesFolder, pth, -1 );
SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILES_COMMON, NULL, 0, pth );
PathAddBackslashW( pth );
msi_set_property( package->db, szCommonFilesFolder, pth, -1 );
}
else if (sys_info.u.s.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
{
msi_set_property( package->db, szMsiAMD64, bufstr, -1 );
msi_set_property( package->db, szMsix64, bufstr, -1 );
msi_set_property( package->db, szVersionNT64, verstr, -1 );
GetSystemDirectoryW( pth, MAX_PATH );
PathAddBackslashW( pth );
msi_set_property( package->db, szSystem64Folder, pth, -1 );
GetSystemWow64DirectoryW( pth, MAX_PATH );
PathAddBackslashW( pth );
msi_set_property( package->db, szSystemFolder, pth, -1 );
SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILES, NULL, 0, pth );
PathAddBackslashW( pth );
msi_set_property( package->db, szProgramFiles64Folder, pth, -1 );
SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILESX86, NULL, 0, pth );
PathAddBackslashW( pth );
msi_set_property( package->db, szProgramFilesFolder, pth, -1 );
SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILES_COMMON, NULL, 0, pth );
PathAddBackslashW( pth );
msi_set_property( package->db, szCommonFiles64Folder, pth, -1 );
SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILES_COMMONX86, NULL, 0, pth );
PathAddBackslashW( pth );
msi_set_property( package->db, szCommonFilesFolder, pth, -1 );
}
/* Screen properties. */
dc = GetDC(0);
len = sprintfW( bufstr, szIntFormat, GetDeviceCaps(dc, HORZRES) );
msi_set_property( package->db, szScreenX, bufstr, len );
len = sprintfW( bufstr, szIntFormat, GetDeviceCaps(dc, VERTRES) );
msi_set_property( package->db, szScreenY, bufstr, len );
len = sprintfW( bufstr, szIntFormat, GetDeviceCaps(dc, BITSPIXEL) );
msi_set_property( package->db, szColorBits, bufstr, len );
ReleaseDC(0, dc);
/* USERNAME and COMPANYNAME */
username = msi_dup_property( package->db, szUSERNAME );
companyname = msi_dup_property( package->db, szCOMPANYNAME );
if ((!username || !companyname) &&
RegOpenKeyW( HKEY_CURRENT_USER, szUserInfo, &hkey ) == ERROR_SUCCESS)
{
if (!username &&
(username = msi_reg_get_val_str( hkey, szDefName )))
msi_set_property( package->db, szUSERNAME, username, -1 );
if (!companyname &&
(companyname = msi_reg_get_val_str( hkey, szDefCompany )))
msi_set_property( package->db, szCOMPANYNAME, companyname, -1 );
CloseHandle( hkey );
}
if ((!username || !companyname) &&
RegOpenKeyW( HKEY_LOCAL_MACHINE, szCurrentVersion, &hkey ) == ERROR_SUCCESS)
{
if (!username &&
(username = msi_reg_get_val_str( hkey, szRegisteredUser )))
msi_set_property( package->db, szUSERNAME, username, -1 );
if (!companyname &&
(companyname = msi_reg_get_val_str( hkey, szRegisteredOrganization )))
msi_set_property( package->db, szCOMPANYNAME, companyname, -1 );
CloseHandle( hkey );
}
msi_free( username );
msi_free( companyname );
if ( set_user_sid_prop( package ) != ERROR_SUCCESS)
ERR("Failed to set the UserSID property\n");
set_msi_assembly_prop( package );
langid = GetUserDefaultLangID();
len = sprintfW( bufstr, szIntFormat, langid );
msi_set_property( package->db, szUserLanguageID, bufstr, len );
langid = GetSystemDefaultLangID();
len = sprintfW( bufstr, szIntFormat, langid );
msi_set_property( package->db, szSystemLangID, bufstr, len );
len = sprintfW( bufstr, szIntFormat, MsiQueryProductStateW(package->ProductCode) );
msi_set_property( package->db, szProductState, bufstr, len );
len = 0;
if (!GetUserNameW( NULL, &len ) && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
WCHAR *username;
if ((username = msi_alloc( len * sizeof(WCHAR) )))
{
if (GetUserNameW( username, &len ))
msi_set_property( package->db, szLogonUser, username, len - 1 );
msi_free( username );
}
}
len = 0;
if (!GetComputerNameW( NULL, &len ) && GetLastError() == ERROR_BUFFER_OVERFLOW)
{
WCHAR *computername;
if ((computername = msi_alloc( len * sizeof(WCHAR) )))
{
if (GetComputerNameW( computername, &len ))
msi_set_property( package->db, szComputerName, computername, len );
msi_free( computername );
}
}
}
static MSIPACKAGE *msi_alloc_package( void )
{
MSIPACKAGE *package;
package = alloc_msiobject( MSIHANDLETYPE_PACKAGE, sizeof (MSIPACKAGE),
MSI_FreePackage );
if( package )
{
list_init( &package->components );
list_init( &package->features );
list_init( &package->files );
list_init( &package->filepatches );
list_init( &package->tempfiles );
list_init( &package->folders );
list_init( &package->subscriptions );
list_init( &package->appids );
list_init( &package->classes );
list_init( &package->mimes );
list_init( &package->extensions );
list_init( &package->progids );
list_init( &package->RunningActions );
list_init( &package->sourcelist_info );
list_init( &package->sourcelist_media );
list_init( &package->patches );
list_init( &package->binaries );
list_init( &package->cabinet_streams );
}
return package;
}
static UINT msi_load_admin_properties(MSIPACKAGE *package)
{
BYTE *data;
UINT r, sz;
static const WCHAR stmname[] = {'A','d','m','i','n','P','r','o','p','e','r','t','i','e','s',0};
r = read_stream_data(package->db->storage, stmname, FALSE, &data, &sz);
if (r != ERROR_SUCCESS)
return r;
r = msi_parse_command_line(package, (WCHAR *)data, TRUE);
msi_free(data);
return r;
}
void msi_adjust_privilege_properties( MSIPACKAGE *package )
{
/* FIXME: this should depend on the user's privileges */
if (msi_get_property_int( package->db, szAllUsers, 0 ) == 2)
{
TRACE("resetting ALLUSERS property from 2 to 1\n");
msi_set_property( package->db, szAllUsers, szOne, -1 );
}
msi_set_property( package->db, szAdminUser, szOne, -1 );
}
MSIPACKAGE *MSI_CreatePackage( MSIDATABASE *db, LPCWSTR base_url )
{
static const WCHAR fmtW[] = {'%','u',0};
MSIPACKAGE *package;
WCHAR uilevel[11];
int len;
UINT r;
TRACE("%p\n", db);
package = msi_alloc_package();
if (package)
{
msiobj_addref( &db->hdr );
package->db = db;
package->LastAction = NULL;
package->LastActionTemplate = NULL;
package->LastActionResult = MSI_NULL_INTEGER;
package->WordCount = 0;
package->PackagePath = strdupW( db->path );
package->BaseURL = strdupW( base_url );
create_temp_property_table( package );
msi_clone_properties( package->db );
msi_adjust_privilege_properties( package );
package->ProductCode = msi_dup_property( package->db, szProductCode );
set_installer_properties( package );
package->ui_level = gUILevel;
len = sprintfW( uilevel, fmtW, gUILevel & INSTALLUILEVEL_MASK );
msi_set_property( package->db, szUILevel, uilevel, len );
r = msi_load_suminfo_properties( package );
if (r != ERROR_SUCCESS)
{
msiobj_release( &package->hdr );
return NULL;
}
if (package->WordCount & msidbSumInfoSourceTypeAdminImage)
msi_load_admin_properties( package );
package->log_file = INVALID_HANDLE_VALUE;
package->script = SCRIPT_NONE;
}
return package;
}
UINT msi_download_file( LPCWSTR szUrl, LPWSTR filename )
{
LPINTERNET_CACHE_ENTRY_INFOW cache_entry;
DWORD size = 0;
HRESULT hr;
/* call will always fail, because size is 0,
* but will return ERROR_FILE_NOT_FOUND first
* if the file doesn't exist
*/
GetUrlCacheEntryInfoW( szUrl, NULL, &size );
if ( GetLastError() != ERROR_FILE_NOT_FOUND )
{
cache_entry = msi_alloc( size );
if ( !GetUrlCacheEntryInfoW( szUrl, cache_entry, &size ) )
{
UINT error = GetLastError();
msi_free( cache_entry );
return error;
}
lstrcpyW( filename, cache_entry->lpszLocalFileName );
msi_free( cache_entry );
return ERROR_SUCCESS;
}
hr = URLDownloadToCacheFileW( NULL, szUrl, filename, MAX_PATH, 0, NULL );
if ( FAILED(hr) )
{
WARN("failed to download %s to cache file\n", debugstr_w(szUrl));
return ERROR_FUNCTION_FAILED;
}
return ERROR_SUCCESS;
}
UINT msi_create_empty_local_file( LPWSTR path, LPCWSTR suffix )
{
static const WCHAR szInstaller[] = {
'\\','I','n','s','t','a','l','l','e','r','\\',0};
static const WCHAR fmt[] = {'%','x',0};
DWORD time, len, i, offset;
HANDLE handle;
time = GetTickCount();
GetWindowsDirectoryW( path, MAX_PATH );
strcatW( path, szInstaller );
CreateDirectoryW( path, NULL );
len = strlenW(path);
for (i = 0; i < 0x10000; i++)
{
offset = snprintfW( path + len, MAX_PATH - len, fmt, (time + i) & 0xffff );
memcpy( path + len + offset, suffix, (strlenW( suffix ) + 1) * sizeof(WCHAR) );
handle = CreateFileW( path, GENERIC_WRITE, 0, NULL,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
if (handle != INVALID_HANDLE_VALUE)
{
CloseHandle(handle);
break;
}
if (GetLastError() != ERROR_FILE_EXISTS &&
GetLastError() != ERROR_SHARING_VIOLATION)
return ERROR_FUNCTION_FAILED;
}
return ERROR_SUCCESS;
}
static enum platform parse_platform( const WCHAR *str )
{
if (!str[0] || !strcmpW( str, szIntel )) return PLATFORM_INTEL;
else if (!strcmpW( str, szIntel64 )) return PLATFORM_INTEL64;
else if (!strcmpW( str, szX64 ) || !strcmpW( str, szAMD64 )) return PLATFORM_X64;
else if (!strcmpW( str, szARM )) return PLATFORM_ARM;
return PLATFORM_UNKNOWN;
}
static UINT parse_suminfo( MSISUMMARYINFO *si, MSIPACKAGE *package )
{
WCHAR *template, *p, *q, *platform;
DWORD i, count;
package->version = msi_suminfo_get_int32( si, PID_PAGECOUNT );
TRACE("version: %d\n", package->version);
template = msi_suminfo_dup_string( si, PID_TEMPLATE );
if (!template)
return ERROR_SUCCESS; /* native accepts missing template property */
TRACE("template: %s\n", debugstr_w(template));
p = strchrW( template, ';' );
if (!p)
{
WARN("invalid template string %s\n", debugstr_w(template));
msi_free( template );
return ERROR_PATCH_PACKAGE_INVALID;
}
*p = 0;
platform = template;
if ((q = strchrW( platform, ',' ))) *q = 0;
package->platform = parse_platform( platform );
while (package->platform == PLATFORM_UNKNOWN && q)
{
platform = q + 1;
if ((q = strchrW( platform, ',' ))) *q = 0;
package->platform = parse_platform( platform );
}
if (package->platform == PLATFORM_UNKNOWN)
{
WARN("unknown platform %s\n", debugstr_w(template));
msi_free( template );
return ERROR_INSTALL_PLATFORM_UNSUPPORTED;
}
p++;
if (!*p)
{
msi_free( template );
return ERROR_SUCCESS;
}
count = 1;
for (q = p; (q = strchrW( q, ',' )); q++) count++;
package->langids = msi_alloc( count * sizeof(LANGID) );
if (!package->langids)
{
msi_free( template );
return ERROR_OUTOFMEMORY;
}
i = 0;
while (*p)
{
q = strchrW( p, ',' );
if (q) *q = 0;
package->langids[i] = atoiW( p );
if (!q) break;
p = q + 1;
i++;
}
package->num_langids = i + 1;
msi_free( template );
return ERROR_SUCCESS;
}
static UINT validate_package( MSIPACKAGE *package )
{
UINT i;
if (package->platform == PLATFORM_INTEL64)
return ERROR_INSTALL_PLATFORM_UNSUPPORTED;
#ifndef __arm__
if (package->platform == PLATFORM_ARM)
return ERROR_INSTALL_PLATFORM_UNSUPPORTED;
#endif
if (package->platform == PLATFORM_X64)
{
if (!is_64bit && !is_wow64)
return ERROR_INSTALL_PLATFORM_UNSUPPORTED;
if (package->version < 200)
return ERROR_INSTALL_PACKAGE_INVALID;
}
if (!package->num_langids)
{
return ERROR_SUCCESS;
}
for (i = 0; i < package->num_langids; i++)
{
LANGID langid = package->langids[i];
if (PRIMARYLANGID( langid ) == LANG_NEUTRAL)
{
langid = MAKELANGID( PRIMARYLANGID( GetSystemDefaultLangID() ), SUBLANGID( langid ) );
}
if (SUBLANGID( langid ) == SUBLANG_NEUTRAL)
{
langid = MAKELANGID( PRIMARYLANGID( langid ), SUBLANGID( GetSystemDefaultLangID() ) );
}
if (IsValidLocale( langid, LCID_INSTALLED ))
return ERROR_SUCCESS;
}
return ERROR_INSTALL_LANGUAGE_UNSUPPORTED;
}
static WCHAR *get_product_code( MSIDATABASE *db )
{
static const WCHAR query[] = {
'S','E','L','E','C','T',' ','`','V','a','l','u','e','`',' ',
'F','R','O','M',' ','`','P','r','o','p','e','r','t','y','`',' ',
'W','H','E','R','E',' ','`','P','r','o','p','e','r','t','y','`','=',
'\'','P','r','o','d','u','c','t','C','o','d','e','\'',0};
MSIQUERY *view;
MSIRECORD *rec;
WCHAR *ret = NULL;
if (MSI_DatabaseOpenViewW( db, query, &view ) != ERROR_SUCCESS)
{
return NULL;
}
if (MSI_ViewExecute( view, 0 ) != ERROR_SUCCESS)
{
MSI_ViewClose( view );
msiobj_release( &view->hdr );
return NULL;
}
if (MSI_ViewFetch( view, &rec ) == ERROR_SUCCESS)
{
ret = strdupW( MSI_RecordGetString( rec, 1 ) );
msiobj_release( &rec->hdr );
}
MSI_ViewClose( view );
msiobj_release( &view->hdr );
return ret;
}
static UINT get_registered_local_package( const WCHAR *product, const WCHAR *package, WCHAR *localfile )
{
MSIINSTALLCONTEXT context;
HKEY product_key, props_key;
WCHAR *registered_package = NULL, unsquashed[GUID_SIZE];
UINT r;
r = msi_locate_product( product, &context );
if (r != ERROR_SUCCESS)
return r;
r = MSIREG_OpenProductKey( product, NULL, context, &product_key, FALSE );
if (r != ERROR_SUCCESS)
return r;
r = MSIREG_OpenInstallProps( product, context, NULL, &props_key, FALSE );
if (r != ERROR_SUCCESS)
{
RegCloseKey( product_key );
return r;
}
r = ERROR_FUNCTION_FAILED;
registered_package = msi_reg_get_val_str( product_key, INSTALLPROPERTY_PACKAGECODEW );
if (!registered_package)
goto done;
unsquash_guid( registered_package, unsquashed );
if (!strcmpiW( package, unsquashed ))
{
WCHAR *filename = msi_reg_get_val_str( props_key, INSTALLPROPERTY_LOCALPACKAGEW );
if (!filename)
goto done;
strcpyW( localfile, filename );
msi_free( filename );
r = ERROR_SUCCESS;
}
done:
msi_free( registered_package );
RegCloseKey( props_key );
RegCloseKey( product_key );
return r;
}
static WCHAR *get_package_code( MSIDATABASE *db )
{
WCHAR *ret;
MSISUMMARYINFO *si;
UINT r;
r = msi_get_suminfo( db->storage, 0, &si );
if (r != ERROR_SUCCESS)
{
r = msi_get_db_suminfo( db, 0, &si );
if (r != ERROR_SUCCESS)
{
WARN("failed to load summary info %u\n", r);
return NULL;
}
}
ret = msi_suminfo_dup_string( si, PID_REVNUMBER );
msiobj_release( &si->hdr );
return ret;
}
static UINT get_local_package( const WCHAR *filename, WCHAR *localfile )
{
WCHAR *product_code, *package_code;
MSIDATABASE *db;
UINT r;
if ((r = MSI_OpenDatabaseW( filename, MSIDBOPEN_READONLY, &db )) != ERROR_SUCCESS)
{
if (GetFileAttributesW( filename ) == INVALID_FILE_ATTRIBUTES)
return ERROR_FILE_NOT_FOUND;
return r;
}
if (!(product_code = get_product_code( db )))
{
msiobj_release( &db->hdr );
return ERROR_INSTALL_PACKAGE_INVALID;
}
if (!(package_code = get_package_code( db )))
{
msi_free( product_code );
msiobj_release( &db->hdr );
return ERROR_INSTALL_PACKAGE_INVALID;
}
r = get_registered_local_package( product_code, package_code, localfile );
msi_free( package_code );
msi_free( product_code );
msiobj_release( &db->hdr );
return r;
}
UINT msi_set_original_database_property( MSIDATABASE *db, const WCHAR *package )
{
UINT r;
if (UrlIsW( package, URLIS_URL ))
r = msi_set_property( db, szOriginalDatabase, package, -1 );
else if (package[0] == '#')
r = msi_set_property( db, szOriginalDatabase, db->path, -1 );
else
{
DWORD len;
WCHAR *path;
if (!(len = GetFullPathNameW( package, 0, NULL, NULL ))) return GetLastError();
if (!(path = msi_alloc( len * sizeof(WCHAR) ))) return ERROR_OUTOFMEMORY;
len = GetFullPathNameW( package, len, path, NULL );
r = msi_set_property( db, szOriginalDatabase, path, len );
msi_free( path );
}
return r;
}
UINT MSI_OpenPackageW(LPCWSTR szPackage, MSIPACKAGE **pPackage)
{
static const WCHAR dotmsi[] = {'.','m','s','i',0};
MSIDATABASE *db;
MSIPACKAGE *package;
MSIHANDLE handle;
MSIRECORD *data_row, *info_row;
LPWSTR ptr, base_url = NULL;
UINT r;
WCHAR localfile[MAX_PATH], cachefile[MAX_PATH];
LPCWSTR file = szPackage;
DWORD index = 0;
MSISUMMARYINFO *si;
BOOL delete_on_close = FALSE;
LPWSTR productname;
WCHAR *info_template;
TRACE("%s %p\n", debugstr_w(szPackage), pPackage);
MSI_ProcessMessage(NULL, INSTALLMESSAGE_INITIALIZE, 0);
localfile[0] = 0;
if( szPackage[0] == '#' )
{
handle = atoiW(&szPackage[1]);
db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
if( !db )
{
IWineMsiRemoteDatabase *remote_database;
remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
if ( !remote_database )
return ERROR_INVALID_HANDLE;
IWineMsiRemoteDatabase_Release( remote_database );
WARN("MsiOpenPackage not allowed during a custom action!\n");
return ERROR_FUNCTION_FAILED;
}
}
else
{
if ( UrlIsW( szPackage, URLIS_URL ) )
{
r = msi_download_file( szPackage, cachefile );
if (r != ERROR_SUCCESS)
return r;
file = cachefile;
base_url = strdupW( szPackage );
if (!base_url)
return ERROR_OUTOFMEMORY;
ptr = strrchrW( base_url, '/' );
if (ptr) *(ptr + 1) = '\0';
}
r = get_local_package( file, localfile );
if (r != ERROR_SUCCESS || GetFileAttributesW( localfile ) == INVALID_FILE_ATTRIBUTES)
{
r = msi_create_empty_local_file( localfile, dotmsi );
if (r != ERROR_SUCCESS)
{
msi_free ( base_url );
return r;
}
if (!CopyFileW( file, localfile, FALSE ))
{
r = GetLastError();
WARN("unable to copy package %s to %s (%u)\n", debugstr_w(file), debugstr_w(localfile), r);
DeleteFileW( localfile );
msi_free ( base_url );
return r;
}
delete_on_close = TRUE;
}
TRACE("opening package %s\n", debugstr_w( localfile ));
r = MSI_OpenDatabaseW( localfile, MSIDBOPEN_TRANSACT, &db );
if (r != ERROR_SUCCESS)
{
msi_free ( base_url );
return r;
}
}
package = MSI_CreatePackage( db, base_url );
msi_free( base_url );
msiobj_release( &db->hdr );
if (!package) return ERROR_INSTALL_PACKAGE_INVALID;
package->localfile = strdupW( localfile );
package->delete_on_close = delete_on_close;
r = msi_get_suminfo( db->storage, 0, &si );
if (r != ERROR_SUCCESS)
{
r = msi_get_db_suminfo( db, 0, &si );
if (r != ERROR_SUCCESS)
{
WARN("failed to load summary info\n");
msiobj_release( &package->hdr );
return ERROR_INSTALL_PACKAGE_INVALID;
}
}
r = parse_suminfo( si, package );
msiobj_release( &si->hdr );
if (r != ERROR_SUCCESS)
{
WARN("failed to parse summary info %u\n", r);
msiobj_release( &package->hdr );
return r;
}
r = validate_package( package );
if (r != ERROR_SUCCESS)
{
msiobj_release( &package->hdr );
return r;
}
msi_set_property( package->db, szDatabase, db->path, -1 );
set_installed_prop( package );
msi_set_context( package );
while (1)
{
WCHAR patch_code[GUID_SIZE];
r = MsiEnumPatchesExW( package->ProductCode, NULL, package->Context,
MSIPATCHSTATE_APPLIED, index, patch_code, NULL, NULL, NULL, NULL );
if (r != ERROR_SUCCESS)
break;
TRACE("found registered patch %s\n", debugstr_w(patch_code));
r = msi_apply_registered_patch( package, patch_code );
if (r != ERROR_SUCCESS)
{
ERR("registered patch failed to apply %u\n", r);
msiobj_release( &package->hdr );
return r;
}
index++;
}
if (index) msi_adjust_privilege_properties( package );
r = msi_set_original_database_property( package->db, szPackage );
if (r != ERROR_SUCCESS)
{
msiobj_release( &package->hdr );
return r;
}
if (gszLogFile)
package->log_file = CreateFileW( gszLogFile, GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
/* FIXME: when should these messages be sent? */
data_row = MSI_CreateRecord(3);
if (!data_row)
return ERROR_OUTOFMEMORY;
MSI_RecordSetStringW(data_row, 0, NULL);
MSI_RecordSetInteger(data_row, 1, 0);
MSI_RecordSetInteger(data_row, 2, package->num_langids ? package->langids[0] : 0);
MSI_RecordSetInteger(data_row, 3, msi_get_string_table_codepage(package->db->strings));
MSI_ProcessMessageVerbatim(package, INSTALLMESSAGE_COMMONDATA, data_row);
info_row = MSI_CreateRecord(0);
if (!info_row)
{
msiobj_release(&data_row->hdr);
return ERROR_OUTOFMEMORY;
}
info_template = msi_get_error_message(package->db, MSIERR_INFO_LOGGINGSTART);
MSI_RecordSetStringW(info_row, 0, info_template);
msi_free(info_template);
MSI_ProcessMessage(package, INSTALLMESSAGE_INFO|MB_ICONHAND, info_row);
MSI_ProcessMessage(package, INSTALLMESSAGE_COMMONDATA, data_row);
productname = msi_dup_property(package->db, INSTALLPROPERTY_PRODUCTNAMEW);
MSI_RecordSetInteger(data_row, 1, 1);
MSI_RecordSetStringW(data_row, 2, productname);
MSI_RecordSetStringW(data_row, 3, NULL);
MSI_ProcessMessage(package, INSTALLMESSAGE_COMMONDATA, data_row);
msi_free(productname);
msiobj_release(&info_row->hdr);
msiobj_release(&data_row->hdr);
*pPackage = package;
return ERROR_SUCCESS;
}
UINT WINAPI MsiOpenPackageExW(LPCWSTR szPackage, DWORD dwOptions, MSIHANDLE *phPackage)
{
MSIPACKAGE *package = NULL;
UINT ret;
TRACE("%s %08x %p\n", debugstr_w(szPackage), dwOptions, phPackage );
if( !szPackage || !phPackage )
return ERROR_INVALID_PARAMETER;
if ( !*szPackage )
{
FIXME("Should create an empty database and package\n");
return ERROR_FUNCTION_FAILED;
}
if( dwOptions )
FIXME("dwOptions %08x not supported\n", dwOptions);
ret = MSI_OpenPackageW( szPackage, &package );
if( ret == ERROR_SUCCESS )
{
*phPackage = alloc_msihandle( &package->hdr );
if (! *phPackage)
ret = ERROR_NOT_ENOUGH_MEMORY;
msiobj_release( &package->hdr );
}
else
MSI_ProcessMessage(NULL, INSTALLMESSAGE_TERMINATE, 0);
return ret;
}
UINT WINAPI MsiOpenPackageW(LPCWSTR szPackage, MSIHANDLE *phPackage)
{
return MsiOpenPackageExW( szPackage, 0, phPackage );
}
UINT WINAPI MsiOpenPackageExA(LPCSTR szPackage, DWORD dwOptions, MSIHANDLE *phPackage)
{
LPWSTR szwPack = NULL;
UINT ret;
if( szPackage )
{
szwPack = strdupAtoW( szPackage );
if( !szwPack )
return ERROR_OUTOFMEMORY;
}
ret = MsiOpenPackageExW( szwPack, dwOptions, phPackage );
msi_free( szwPack );
return ret;
}
UINT WINAPI MsiOpenPackageA(LPCSTR szPackage, MSIHANDLE *phPackage)
{
return MsiOpenPackageExA( szPackage, 0, phPackage );
}
MSIHANDLE WINAPI MsiGetActiveDatabase(MSIHANDLE hInstall)
{
MSIPACKAGE *package;
MSIHANDLE handle = 0;
IUnknown *remote_unk;
IWineMsiRemotePackage *remote_package;
TRACE("(%d)\n",hInstall);
package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE);
if( package)
{
handle = alloc_msihandle( &package->db->hdr );
msiobj_release( &package->hdr );
}
else if ((remote_unk = msi_get_remote(hInstall)))
{
if (IUnknown_QueryInterface(remote_unk, &IID_IWineMsiRemotePackage,
(LPVOID *)&remote_package) == S_OK)
{
IWineMsiRemotePackage_GetActiveDatabase(remote_package, &handle);
IWineMsiRemotePackage_Release(remote_package);
}
else
{
WARN("remote handle %d is not a package\n", hInstall);
}
IUnknown_Release(remote_unk);
}
return handle;
}
static INT internal_ui_handler(MSIPACKAGE *package, INSTALLMESSAGE eMessageType, MSIRECORD *record, LPCWSTR message)
{
static const WCHAR szActionData[] = {'A','c','t','i','o','n','D','a','t','a',0};
static const WCHAR szActionText[] = {'A','c','t','i','o','n','T','e','x','t',0};
static const WCHAR szSetProgress[] = {'S','e','t','P','r','o','g','r','e','s','s',0};
static const WCHAR szWindows_Installer[] =
{'W','i','n','d','o','w','s',' ','I','n','s','t','a','l','l','e','r',0};
if (!package || (package->ui_level & INSTALLUILEVEL_MASK) == INSTALLUILEVEL_NONE)
return 0;
/* todo: check if message needs additional styles (topmost/foreground/modality?) */
switch (eMessageType & 0xff000000)
{
case INSTALLMESSAGE_FATALEXIT:
case INSTALLMESSAGE_ERROR:
case INSTALLMESSAGE_OUTOFDISKSPACE:
if (package->ui_level & INSTALLUILEVEL_PROGRESSONLY) return 0;
if (!(eMessageType & MB_ICONMASK))
eMessageType |= MB_ICONEXCLAMATION;
return MessageBoxW(gUIhwnd, message, szWindows_Installer, eMessageType & 0x00ffffff);
case INSTALLMESSAGE_WARNING:
if (package->ui_level & INSTALLUILEVEL_PROGRESSONLY) return 0;
if (!(eMessageType & MB_ICONMASK))
eMessageType |= MB_ICONASTERISK;
return MessageBoxW(gUIhwnd, message, szWindows_Installer, eMessageType & 0x00ffffff);
case INSTALLMESSAGE_USER:
if (package->ui_level & INSTALLUILEVEL_PROGRESSONLY) return 0;
if (!(eMessageType & MB_ICONMASK))
eMessageType |= MB_USERICON;
return MessageBoxW(gUIhwnd, message, szWindows_Installer, eMessageType & 0x00ffffff);
case INSTALLMESSAGE_INFO:
case INSTALLMESSAGE_INITIALIZE:
case INSTALLMESSAGE_TERMINATE:
case INSTALLMESSAGE_INSTALLSTART:
case INSTALLMESSAGE_INSTALLEND:
return 0;
case INSTALLMESSAGE_SHOWDIALOG:
{
LPWSTR dialog = msi_dup_record_field(record, 0);
INT rc = ACTION_DialogBox(package, dialog);
msi_free(dialog);
return rc;
}
case INSTALLMESSAGE_ACTIONSTART:
{
LPWSTR deformatted;
MSIRECORD *uirow = MSI_CreateRecord(1);
if (!uirow) return -1;
deformat_string(package, MSI_RecordGetString(record, 2), &deformatted);
MSI_RecordSetStringW(uirow, 1, deformatted);
msi_event_fire(package, szActionText, uirow);
msi_free(deformatted);
msiobj_release(&uirow->hdr);
return 1;
}
case INSTALLMESSAGE_ACTIONDATA:
{
MSIRECORD *uirow = MSI_CreateRecord(1);
if (!uirow) return -1;
MSI_RecordSetStringW(uirow, 1, message);
msi_event_fire(package, szActionData, uirow);
msiobj_release(&uirow->hdr);
if (package->action_progress_increment)
{
uirow = MSI_CreateRecord(2);
if (!uirow) return -1;
MSI_RecordSetInteger(uirow, 1, 2);
MSI_RecordSetInteger(uirow, 2, package->action_progress_increment);
msi_event_fire(package, szSetProgress, uirow);
msiobj_release(&uirow->hdr);
}
return 1;
}
case INSTALLMESSAGE_PROGRESS:
msi_event_fire(package, szSetProgress, record);
return 1;
case INSTALLMESSAGE_COMMONDATA:
switch (MSI_RecordGetInteger(record, 1))
{
case 0:
case 1:
/* do nothing */
return 0;
default:
/* fall through */
;
}
default:
FIXME("internal UI not implemented for message 0x%08x (UI level = %x)\n", eMessageType, package->ui_level);
return 0;
}
}
static const WCHAR szActionNotFound[] = {'D','E','B','U','G',':',' ','E','r','r','o','r',' ','[','1',']',':',' ',' ','A','c','t','i','o','n',' ','n','o','t',' ','f','o','u','n','d',':',' ','[','2',']',0};
static const struct
{
int id;
const WCHAR *text;
}
internal_errors[] =
{
{2726, szActionNotFound},
{0}
};
static LPCWSTR get_internal_error_message(int error)
{
int i = 0;
while (internal_errors[i].id != 0)
{
if (internal_errors[i].id == error)
return internal_errors[i].text;
i++;
}
FIXME("missing error message %d\n", error);
return NULL;
}
/* Returned string must be freed */
LPWSTR msi_get_error_message(MSIDATABASE *db, int error)
{
static const WCHAR query[] =
{'S','E','L','E','C','T',' ','`','M','e','s','s','a','g','e','`',' ',
'F','R','O','M',' ','`','E','r','r','o','r','`',' ','W','H','E','R','E',' ',
'`','E','r','r','o','r','`',' ','=',' ','%','i',0};
MSIRECORD *record;
LPWSTR ret = NULL;
if ((record = MSI_QueryGetRecord(db, query, error)))
{
ret = msi_dup_record_field(record, 1);
msiobj_release(&record->hdr);
}
else if (error < 2000)
{
int len = LoadStringW(msi_hInstance, IDS_ERROR_BASE + error, (LPWSTR) &ret, 0);
if (len)
{
ret = msi_alloc((len + 1) * sizeof(WCHAR));
LoadStringW(msi_hInstance, IDS_ERROR_BASE + error, ret, len + 1);
}
else
ret = NULL;
}
return ret;
}
INT MSI_ProcessMessageVerbatim(MSIPACKAGE *package, INSTALLMESSAGE eMessageType, MSIRECORD *record)
{
LPWSTR message = {0};
DWORD len;
DWORD log_type = 1 << (eMessageType >> 24);
UINT res;
INT rc = 0;
char *msg;
TRACE("%x\n", eMessageType);
if (TRACE_ON(msi)) dump_record(record);
if (!package || !record)
message = NULL;
else {
res = MSI_FormatRecordW(package, record, message, &len);
if (res != ERROR_SUCCESS && res != ERROR_MORE_DATA)
return res;
len++;
message = msi_alloc(len * sizeof(WCHAR));
if (!message) return ERROR_OUTOFMEMORY;
MSI_FormatRecordW(package, record, message, &len);
}
/* convert it to ASCII */
len = WideCharToMultiByte( CP_ACP, 0, message, -1, NULL, 0, NULL, NULL );
msg = msi_alloc( len );
WideCharToMultiByte( CP_ACP, 0, message, -1, msg, len, NULL, NULL );
if (gUIHandlerRecord && (gUIFilterRecord & log_type))
{
MSIHANDLE rec = alloc_msihandle(&record->hdr);
TRACE("Calling UI handler %p(pvContext=%p, iMessageType=%08x, hRecord=%u)\n",
gUIHandlerRecord, gUIContextRecord, eMessageType, rec);
rc = gUIHandlerRecord( gUIContextRecord, eMessageType, rec );
MsiCloseHandle( rec );
}
if (!rc && gUIHandlerW && (gUIFilter & log_type))
{
TRACE("Calling UI handler %p(pvContext=%p, iMessageType=%08x, szMessage=%s)\n",
gUIHandlerW, gUIContext, eMessageType, debugstr_w(message));
rc = gUIHandlerW( gUIContext, eMessageType, message );
}
else if (!rc && gUIHandlerA && (gUIFilter & log_type))
{
TRACE("Calling UI handler %p(pvContext=%p, iMessageType=%08x, szMessage=%s)\n",
gUIHandlerA, gUIContext, eMessageType, debugstr_a(msg));
rc = gUIHandlerA( gUIContext, eMessageType, msg );
}
if (!rc)
rc = internal_ui_handler(package, eMessageType, record, message);
if (!rc && package && package->log_file != INVALID_HANDLE_VALUE &&
(eMessageType & 0xff000000) != INSTALLMESSAGE_PROGRESS)
{
DWORD written;
WriteFile( package->log_file, msg, len - 1, &written, NULL );
WriteFile( package->log_file, "\n", 1, &written, NULL );
}
msi_free( msg );
msi_free( message );
return rc;
}
INT MSI_ProcessMessage( MSIPACKAGE *package, INSTALLMESSAGE eMessageType, MSIRECORD *record )
{
switch (eMessageType & 0xff000000)
{
case INSTALLMESSAGE_FATALEXIT:
case INSTALLMESSAGE_ERROR:
case INSTALLMESSAGE_WARNING:
case INSTALLMESSAGE_USER:
case INSTALLMESSAGE_INFO:
case INSTALLMESSAGE_OUTOFDISKSPACE:
if (MSI_RecordGetInteger(record, 1) != MSI_NULL_INTEGER)
{
/* error message */
LPWSTR template;
LPWSTR template_rec = NULL, template_prefix = NULL;
int error = MSI_RecordGetInteger(record, 1);
if (MSI_RecordIsNull(record, 0))
{
if (error >= 32)
{
template_rec = msi_get_error_message(package->db, error);
if (!template_rec && error >= 2000)
{
/* internal error, not localized */
if ((template_rec = (LPWSTR) get_internal_error_message(error)))
{
MSI_RecordSetStringW(record, 0, template_rec);
MSI_ProcessMessageVerbatim(package, INSTALLMESSAGE_INFO, record);
}
template_rec = msi_get_error_message(package->db, MSIERR_INSTALLERROR);
MSI_RecordSetStringW(record, 0, template_rec);
MSI_ProcessMessageVerbatim(package, eMessageType, record);
msi_free(template_rec);
return 0;
}
}
}
else
template_rec = msi_dup_record_field(record, 0);
template_prefix = msi_get_error_message(package->db, eMessageType >> 24);
if (!template_prefix) template_prefix = strdupW(szEmpty);
if (!template_rec)
{
/* always returns 0 */
MSI_RecordSetStringW(record, 0, template_prefix);
MSI_ProcessMessageVerbatim(package, eMessageType, record);
msi_free(template_prefix);
return 0;
}
template = msi_alloc((strlenW(template_rec) + strlenW(template_prefix) + 1) * sizeof(WCHAR));
if (!template) return ERROR_OUTOFMEMORY;
strcpyW(template, template_prefix);
strcatW(template, template_rec);
MSI_RecordSetStringW(record, 0, template);
msi_free(template_prefix);
msi_free(template_rec);
msi_free(template);
}
break;
case INSTALLMESSAGE_ACTIONSTART:
{
WCHAR *template = msi_get_error_message(package->db, MSIERR_ACTIONSTART);
MSI_RecordSetStringW(record, 0, template);
msi_free(template);
msi_free(package->LastAction);
msi_free(package->LastActionTemplate);
package->LastAction = msi_dup_record_field(record, 1);
if (!package->LastAction) package->LastAction = strdupW(szEmpty);
package->LastActionTemplate = msi_dup_record_field(record, 3);
break;
}
case INSTALLMESSAGE_ACTIONDATA:
if (package->LastAction && package->LastActionTemplate)
{
static const WCHAR template_s[] =
{'{','{','%','s',':',' ','}','}','%','s',0};
WCHAR *template;
template = msi_alloc((strlenW(package->LastAction) + strlenW(package->LastActionTemplate) + 7) * sizeof(WCHAR));
if (!template) return ERROR_OUTOFMEMORY;
sprintfW(template, template_s, package->LastAction, package->LastActionTemplate);
MSI_RecordSetStringW(record, 0, template);
msi_free(template);
}
break;
case INSTALLMESSAGE_COMMONDATA:
{
WCHAR *template = msi_get_error_message(package->db, MSIERR_COMMONDATA);
MSI_RecordSetStringW(record, 0, template);
msi_free(template);
}
break;
}
return MSI_ProcessMessageVerbatim(package, eMessageType, record);
}
INT WINAPI MsiProcessMessage( MSIHANDLE hInstall, INSTALLMESSAGE eMessageType,
MSIHANDLE hRecord)
{
UINT ret = ERROR_INVALID_HANDLE;
MSIPACKAGE *package = NULL;
MSIRECORD *record = NULL;
if ((eMessageType & 0xff000000) == INSTALLMESSAGE_INITIALIZE ||
(eMessageType & 0xff000000) == INSTALLMESSAGE_TERMINATE)
return -1;
if ((eMessageType & 0xff000000) == INSTALLMESSAGE_COMMONDATA &&
MsiRecordGetInteger(hRecord, 1) != 2)
return -1;
package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE );
if( !package )
{
HRESULT hr;
IWineMsiRemotePackage *remote_package;
remote_package = (IWineMsiRemotePackage *)msi_get_remote( hInstall );
if (!remote_package)
return ERROR_INVALID_HANDLE;
hr = IWineMsiRemotePackage_ProcessMessage( remote_package, eMessageType, hRecord );
IWineMsiRemotePackage_Release( remote_package );
if (FAILED(hr))
{
if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
return HRESULT_CODE(hr);
return ERROR_FUNCTION_FAILED;
}
return ERROR_SUCCESS;
}
record = msihandle2msiinfo( hRecord, MSIHANDLETYPE_RECORD );
if( !record )
goto out;
ret = MSI_ProcessMessage( package, eMessageType, record );
out:
msiobj_release( &package->hdr );
if( record )
msiobj_release( &record->hdr );
return ret;
}
/* property code */
UINT WINAPI MsiSetPropertyA( MSIHANDLE hInstall, LPCSTR szName, LPCSTR szValue )
{
LPWSTR szwName = NULL, szwValue = NULL;
UINT r = ERROR_OUTOFMEMORY;
szwName = strdupAtoW( szName );
if( szName && !szwName )
goto end;
szwValue = strdupAtoW( szValue );
if( szValue && !szwValue )
goto end;
r = MsiSetPropertyW( hInstall, szwName, szwValue);
end:
msi_free( szwName );
msi_free( szwValue );
return r;
}
void msi_reset_folders( MSIPACKAGE *package, BOOL source )
{
MSIFOLDER *folder;
LIST_FOR_EACH_ENTRY( folder, &package->folders, MSIFOLDER, entry )
{
if ( source )
{
msi_free( folder->ResolvedSource );
folder->ResolvedSource = NULL;
}
else
{
msi_free( folder->ResolvedTarget );
folder->ResolvedTarget = NULL;
}
}
}
UINT msi_set_property( MSIDATABASE *db, const WCHAR *name, const WCHAR *value, int len )
{
static const WCHAR insert_query[] = {
'I','N','S','E','R','T',' ','I','N','T','O',' ',
'`','_','P','r','o','p','e','r','t','y','`',' ',
'(','`','_','P','r','o','p','e','r','t','y','`',',','`','V','a','l','u','e','`',')',' ',
'V','A','L','U','E','S',' ','(','?',',','?',')',0};
static const WCHAR update_query[] = {
'U','P','D','A','T','E',' ','`','_','P','r','o','p','e','r','t','y','`',' ',
'S','E','T',' ','`','V','a','l','u','e','`',' ','=',' ','?',' ','W','H','E','R','E',' ',
'`','_','P','r','o','p','e','r','t','y','`',' ','=',' ','\'','%','s','\'',0};
static const WCHAR delete_query[] = {
'D','E','L','E','T','E',' ','F','R','O','M',' ',
'`','_','P','r','o','p','e','r','t','y','`',' ','W','H','E','R','E',' ',
'`','_','P','r','o','p','e','r','t','y','`',' ','=',' ','\'','%','s','\'',0};
MSIQUERY *view;
MSIRECORD *row = NULL;
DWORD sz = 0;
WCHAR query[1024];
UINT rc;
TRACE("%p %s %s %d\n", db, debugstr_w(name), debugstr_wn(value, len), len);
if (!name)
return ERROR_INVALID_PARAMETER;
/* this one is weird... */
if (!name[0])
return value ? ERROR_FUNCTION_FAILED : ERROR_SUCCESS;
if (value && len < 0) len = strlenW( value );
rc = msi_get_property( db, name, 0, &sz );
if (!value || (!*value && !len))
{
sprintfW( query, delete_query, name );
}
else if (rc == ERROR_MORE_DATA || rc == ERROR_SUCCESS)
{
sprintfW( query, update_query, name );
row = MSI_CreateRecord(1);
msi_record_set_string( row, 1, value, len );
}
else
{
strcpyW( query, insert_query );
row = MSI_CreateRecord(2);
msi_record_set_string( row, 1, name, -1 );
msi_record_set_string( row, 2, value, len );
}
rc = MSI_DatabaseOpenViewW(db, query, &view);
if (rc == ERROR_SUCCESS)
{
rc = MSI_ViewExecute(view, row);
MSI_ViewClose(view);
msiobj_release(&view->hdr);
}
if (row) msiobj_release(&row->hdr);
return rc;
}
UINT WINAPI MsiSetPropertyW( MSIHANDLE hInstall, LPCWSTR szName, LPCWSTR szValue)
{
MSIPACKAGE *package;
UINT ret;
package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE);
if( !package )
{
HRESULT hr;
BSTR name = NULL, value = NULL;
IWineMsiRemotePackage *remote_package;
remote_package = (IWineMsiRemotePackage *)msi_get_remote( hInstall );
if (!remote_package)
return ERROR_INVALID_HANDLE;
name = SysAllocString( szName );
value = SysAllocString( szValue );
if ((!name && szName) || (!value && szValue))
{
SysFreeString( name );
SysFreeString( value );
IWineMsiRemotePackage_Release( remote_package );
return ERROR_OUTOFMEMORY;
}
hr = IWineMsiRemotePackage_SetProperty( remote_package, name, value );
SysFreeString( name );
SysFreeString( value );
IWineMsiRemotePackage_Release( remote_package );
if (FAILED(hr))
{
if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
return HRESULT_CODE(hr);
return ERROR_FUNCTION_FAILED;
}
return ERROR_SUCCESS;
}
ret = msi_set_property( package->db, szName, szValue, -1 );
if (ret == ERROR_SUCCESS && !strcmpW( szName, szSourceDir ))
msi_reset_folders( package, TRUE );
msiobj_release( &package->hdr );
return ret;
}
static MSIRECORD *msi_get_property_row( MSIDATABASE *db, LPCWSTR name )
{
static const WCHAR query[]= {
'S','E','L','E','C','T',' ','`','V','a','l','u','e','`',' ',
'F','R','O','M',' ' ,'`','_','P','r','o','p','e','r','t','y','`',' ',
'W','H','E','R','E',' ' ,'`','_','P','r','o','p','e','r','t','y','`','=','?',0};
MSIRECORD *rec, *row = NULL;
MSIQUERY *view;
UINT r;
static const WCHAR szDate[] = {'D','a','t','e',0};
static const WCHAR szTime[] = {'T','i','m','e',0};
WCHAR *buffer;
int length;
if (!name || !*name)
return NULL;
if (!strcmpW(name, szDate))
{
length = GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, NULL, 0);
if (!length)
return NULL;
buffer = msi_alloc(length * sizeof(WCHAR));
GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, buffer, length);
row = MSI_CreateRecord(1);
if (!row)
return NULL;
MSI_RecordSetStringW(row, 1, buffer);
msi_free(buffer);
return row;
}
else if (!strcmpW(name, szTime))
{
length = GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOTIMEMARKER, NULL, NULL, NULL, 0);
if (!length)
return NULL;
buffer = msi_alloc(length * sizeof(WCHAR));
GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOTIMEMARKER, NULL, NULL, buffer, length);
row = MSI_CreateRecord(1);
if (!row)
return NULL;
MSI_RecordSetStringW(row, 1, buffer);
msi_free(buffer);
return row;
}
rec = MSI_CreateRecord(1);
if (!rec)
return NULL;
MSI_RecordSetStringW(rec, 1, name);
r = MSI_DatabaseOpenViewW(db, query, &view);
if (r == ERROR_SUCCESS)
{
MSI_ViewExecute(view, rec);
MSI_ViewFetch(view, &row);
MSI_ViewClose(view);
msiobj_release(&view->hdr);
}
msiobj_release(&rec->hdr);
return row;
}
/* internal function, not compatible with MsiGetPropertyW */
UINT msi_get_property( MSIDATABASE *db, LPCWSTR szName,
LPWSTR szValueBuf, LPDWORD pchValueBuf )
{
MSIRECORD *row;
UINT rc = ERROR_FUNCTION_FAILED;
TRACE("%p %s %p %p\n", db, debugstr_w(szName), szValueBuf, pchValueBuf);
row = msi_get_property_row( db, szName );
if (*pchValueBuf > 0)
szValueBuf[0] = 0;
if (row)
{
rc = MSI_RecordGetStringW(row, 1, szValueBuf, pchValueBuf);
msiobj_release(&row->hdr);
}
if (rc == ERROR_SUCCESS)
TRACE("returning %s for property %s\n", debugstr_wn(szValueBuf, *pchValueBuf),
debugstr_w(szName));
else if (rc == ERROR_MORE_DATA)
TRACE("need %d sized buffer for %s\n", *pchValueBuf,
debugstr_w(szName));
else
{
*pchValueBuf = 0;
TRACE("property %s not found\n", debugstr_w(szName));
}
return rc;
}
LPWSTR msi_dup_property(MSIDATABASE *db, LPCWSTR prop)
{
DWORD sz = 0;
LPWSTR str;
UINT r;
r = msi_get_property(db, prop, NULL, &sz);
if (r != ERROR_SUCCESS && r != ERROR_MORE_DATA)
return NULL;
sz++;
str = msi_alloc(sz * sizeof(WCHAR));
r = msi_get_property(db, prop, str, &sz);
if (r != ERROR_SUCCESS)
{
msi_free(str);
str = NULL;
}
return str;
}
int msi_get_property_int( MSIDATABASE *db, LPCWSTR prop, int def )
{
LPWSTR str = msi_dup_property( db, prop );
int val = str ? atoiW(str) : def;
msi_free(str);
return val;
}
static UINT MSI_GetProperty( MSIHANDLE handle, LPCWSTR name,
awstring *szValueBuf, LPDWORD pchValueBuf )
{
MSIPACKAGE *package;
MSIRECORD *row = NULL;
UINT r = ERROR_FUNCTION_FAILED;
LPCWSTR val = NULL;
DWORD len = 0;
TRACE("%u %s %p %p\n", handle, debugstr_w(name),
szValueBuf->str.w, pchValueBuf );
if (!name)
return ERROR_INVALID_PARAMETER;
package = msihandle2msiinfo( handle, MSIHANDLETYPE_PACKAGE );
if (!package)
{
HRESULT hr;
IWineMsiRemotePackage *remote_package;
LPWSTR value = NULL;
BSTR bname;
remote_package = (IWineMsiRemotePackage *)msi_get_remote( handle );
if (!remote_package)
return ERROR_INVALID_HANDLE;
bname = SysAllocString( name );
if (!bname)
{
IWineMsiRemotePackage_Release( remote_package );
return ERROR_OUTOFMEMORY;
}
hr = IWineMsiRemotePackage_GetProperty( remote_package, bname, NULL, &len );
if (FAILED(hr))
goto done;
len++;
value = msi_alloc(len * sizeof(WCHAR));
if (!value)
{
r = ERROR_OUTOFMEMORY;
goto done;
}
hr = IWineMsiRemotePackage_GetProperty( remote_package, bname, value, &len );
if (FAILED(hr))
goto done;
r = msi_strcpy_to_awstring( value, len, szValueBuf, pchValueBuf );
/* Bug required by Adobe installers */
if (!szValueBuf->unicode && !szValueBuf->str.a)
*pchValueBuf *= sizeof(WCHAR);
done:
IWineMsiRemotePackage_Release(remote_package);
SysFreeString(bname);
msi_free(value);
if (FAILED(hr))
{
if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
return HRESULT_CODE(hr);
return ERROR_FUNCTION_FAILED;
}
return r;
}
row = msi_get_property_row( package->db, name );
if (row)
val = msi_record_get_string( row, 1, (int *)&len );
if (!val)
val = szEmpty;
r = msi_strcpy_to_awstring( val, len, szValueBuf, pchValueBuf );
if (row)
msiobj_release( &row->hdr );
msiobj_release( &package->hdr );
return r;
}
UINT WINAPI MsiGetPropertyA( MSIHANDLE hInstall, LPCSTR szName,
LPSTR szValueBuf, LPDWORD pchValueBuf )
{
awstring val;
LPWSTR name;
UINT r;
val.unicode = FALSE;
val.str.a = szValueBuf;
name = strdupAtoW( szName );
if (szName && !name)
return ERROR_OUTOFMEMORY;
r = MSI_GetProperty( hInstall, name, &val, pchValueBuf );
msi_free( name );
return r;
}
UINT WINAPI MsiGetPropertyW( MSIHANDLE hInstall, LPCWSTR szName,
LPWSTR szValueBuf, LPDWORD pchValueBuf )
{
awstring val;
val.unicode = TRUE;
val.str.w = szValueBuf;
return MSI_GetProperty( hInstall, szName, &val, pchValueBuf );
}
typedef struct _msi_remote_package_impl {
IWineMsiRemotePackage IWineMsiRemotePackage_iface;
MSIHANDLE package;
LONG refs;
} msi_remote_package_impl;
static inline msi_remote_package_impl *impl_from_IWineMsiRemotePackage( IWineMsiRemotePackage *iface )
{
return CONTAINING_RECORD(iface, msi_remote_package_impl, IWineMsiRemotePackage_iface);
}
static HRESULT WINAPI mrp_QueryInterface( IWineMsiRemotePackage *iface,
REFIID riid,LPVOID *ppobj)
{
if( IsEqualCLSID( riid, &IID_IUnknown ) ||
IsEqualCLSID( riid, &IID_IWineMsiRemotePackage ) )
{
IWineMsiRemotePackage_AddRef( iface );
*ppobj = iface;
return S_OK;
}
return E_NOINTERFACE;
}
static ULONG WINAPI mrp_AddRef( IWineMsiRemotePackage *iface )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
return InterlockedIncrement( &This->refs );
}
static ULONG WINAPI mrp_Release( IWineMsiRemotePackage *iface )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
ULONG r;
r = InterlockedDecrement( &This->refs );
if (r == 0)
{
MsiCloseHandle( This->package );
msi_free( This );
}
return r;
}
static HRESULT WINAPI mrp_SetMsiHandle( IWineMsiRemotePackage *iface, MSIHANDLE handle )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
This->package = handle;
return S_OK;
}
static HRESULT WINAPI mrp_GetActiveDatabase( IWineMsiRemotePackage *iface, MSIHANDLE *handle )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
IWineMsiRemoteDatabase *rdb = NULL;
HRESULT hr;
MSIHANDLE hdb;
hr = create_msi_remote_database( NULL, (LPVOID *)&rdb );
if (FAILED(hr) || !rdb)
{
ERR("Failed to create remote database\n");
return hr;
}
hdb = MsiGetActiveDatabase(This->package);
hr = IWineMsiRemoteDatabase_SetMsiHandle( rdb, hdb );
if (FAILED(hr))
{
ERR("Failed to set the database handle\n");
return hr;
}
*handle = alloc_msi_remote_handle( (IUnknown *)rdb );
return S_OK;
}
static HRESULT WINAPI mrp_GetProperty( IWineMsiRemotePackage *iface, BSTR property, BSTR value, DWORD *size )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiGetPropertyW(This->package, property, value, size);
if (r != ERROR_SUCCESS) return HRESULT_FROM_WIN32(r);
return S_OK;
}
static HRESULT WINAPI mrp_SetProperty( IWineMsiRemotePackage *iface, BSTR property, BSTR value )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiSetPropertyW(This->package, property, value);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_ProcessMessage( IWineMsiRemotePackage *iface, INSTALLMESSAGE message, MSIHANDLE record )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiProcessMessage(This->package, message, record);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_DoAction( IWineMsiRemotePackage *iface, BSTR action )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiDoActionW(This->package, action);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_Sequence( IWineMsiRemotePackage *iface, BSTR table, int sequence )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiSequenceW(This->package, table, sequence);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_GetTargetPath( IWineMsiRemotePackage *iface, BSTR folder, BSTR value, DWORD *size )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiGetTargetPathW(This->package, folder, value, size);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_SetTargetPath( IWineMsiRemotePackage *iface, BSTR folder, BSTR value)
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiSetTargetPathW(This->package, folder, value);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_GetSourcePath( IWineMsiRemotePackage *iface, BSTR folder, BSTR value, DWORD *size )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiGetSourcePathW(This->package, folder, value, size);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_GetMode( IWineMsiRemotePackage *iface, MSIRUNMODE mode, BOOL *ret )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
*ret = MsiGetMode(This->package, mode);
return S_OK;
}
static HRESULT WINAPI mrp_SetMode( IWineMsiRemotePackage *iface, MSIRUNMODE mode, BOOL state )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiSetMode(This->package, mode, state);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_GetFeatureState( IWineMsiRemotePackage *iface, BSTR feature,
INSTALLSTATE *installed, INSTALLSTATE *action )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiGetFeatureStateW(This->package, feature, installed, action);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_SetFeatureState( IWineMsiRemotePackage *iface, BSTR feature, INSTALLSTATE state )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiSetFeatureStateW(This->package, feature, state);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_GetComponentState( IWineMsiRemotePackage *iface, BSTR component,
INSTALLSTATE *installed, INSTALLSTATE *action )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiGetComponentStateW(This->package, component, installed, action);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_SetComponentState( IWineMsiRemotePackage *iface, BSTR component, INSTALLSTATE state )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiSetComponentStateW(This->package, component, state);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_GetLanguage( IWineMsiRemotePackage *iface, LANGID *language )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
*language = MsiGetLanguage(This->package);
return S_OK;
}
static HRESULT WINAPI mrp_SetInstallLevel( IWineMsiRemotePackage *iface, int level )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiSetInstallLevel(This->package, level);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_FormatRecord( IWineMsiRemotePackage *iface, MSIHANDLE record,
BSTR *value)
{
DWORD size = 0;
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiFormatRecordW(This->package, record, NULL, &size);
if (r == ERROR_SUCCESS)
{
*value = SysAllocStringLen(NULL, size);
if (!*value)
return E_OUTOFMEMORY;
size++;
r = MsiFormatRecordW(This->package, record, *value, &size);
}
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_EvaluateCondition( IWineMsiRemotePackage *iface, BSTR condition )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiEvaluateConditionW(This->package, condition);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_GetFeatureCost( IWineMsiRemotePackage *iface, BSTR feature,
INT cost_tree, INSTALLSTATE state, INT *cost )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiGetFeatureCostW(This->package, feature, cost_tree, state, cost);
return HRESULT_FROM_WIN32(r);
}
static HRESULT WINAPI mrp_EnumComponentCosts( IWineMsiRemotePackage *iface, BSTR component,
DWORD index, INSTALLSTATE state, BSTR drive,
DWORD *buflen, INT *cost, INT *temp )
{
msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
UINT r = MsiEnumComponentCostsW(This->package, component, index, state, drive, buflen, cost, temp);
return HRESULT_FROM_WIN32(r);
}
static const IWineMsiRemotePackageVtbl msi_remote_package_vtbl =
{
mrp_QueryInterface,
mrp_AddRef,
mrp_Release,
mrp_SetMsiHandle,
mrp_GetActiveDatabase,
mrp_GetProperty,
mrp_SetProperty,
mrp_ProcessMessage,
mrp_DoAction,
mrp_Sequence,
mrp_GetTargetPath,
mrp_SetTargetPath,
mrp_GetSourcePath,
mrp_GetMode,
mrp_SetMode,
mrp_GetFeatureState,
mrp_SetFeatureState,
mrp_GetComponentState,
mrp_SetComponentState,
mrp_GetLanguage,
mrp_SetInstallLevel,
mrp_FormatRecord,
mrp_EvaluateCondition,
mrp_GetFeatureCost,
mrp_EnumComponentCosts
};
HRESULT create_msi_remote_package( IUnknown *pOuter, LPVOID *ppObj )
{
msi_remote_package_impl* This;
This = msi_alloc( sizeof *This );
if (!This)
return E_OUTOFMEMORY;
This->IWineMsiRemotePackage_iface.lpVtbl = &msi_remote_package_vtbl;
This->package = 0;
This->refs = 1;
*ppObj = &This->IWineMsiRemotePackage_iface;
return S_OK;
}
UINT msi_package_add_info(MSIPACKAGE *package, DWORD context, DWORD options,
LPCWSTR property, LPWSTR value)
{
MSISOURCELISTINFO *info;
LIST_FOR_EACH_ENTRY( info, &package->sourcelist_info, MSISOURCELISTINFO, entry )
{
if (!strcmpW( info->value, value )) return ERROR_SUCCESS;
}
info = msi_alloc(sizeof(MSISOURCELISTINFO));
if (!info)
return ERROR_OUTOFMEMORY;
info->context = context;
info->options = options;
info->property = property;
info->value = strdupW(value);
list_add_head(&package->sourcelist_info, &info->entry);
return ERROR_SUCCESS;
}
UINT msi_package_add_media_disk(MSIPACKAGE *package, DWORD context, DWORD options,
DWORD disk_id, LPWSTR volume_label, LPWSTR disk_prompt)
{
MSIMEDIADISK *disk;
LIST_FOR_EACH_ENTRY( disk, &package->sourcelist_media, MSIMEDIADISK, entry )
{
if (disk->disk_id == disk_id) return ERROR_SUCCESS;
}
disk = msi_alloc(sizeof(MSIMEDIADISK));
if (!disk)
return ERROR_OUTOFMEMORY;
disk->context = context;
disk->options = options;
disk->disk_id = disk_id;
disk->volume_label = strdupW(volume_label);
disk->disk_prompt = strdupW(disk_prompt);
list_add_head(&package->sourcelist_media, &disk->entry);
return ERROR_SUCCESS;
}
|
945672.c | /*
SysmonForLinux
Copyright (c) Microsoft Corporation
All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
//====================================================================
//
// sysmonGenericEntry_tp.c
//
// Syscall entry programs, one for each of 0 arguments up to 6
// arguments. The purpose is that these generic entry programs can be
// attached to any syscall entry tracepoint, as long as the number of
// arguments matches correctly. The maximum number of arguments a
// syscall can take is 6.
//
//====================================================================
#include "sysmonEBPF_common.h"
#include <sysinternalsEBPF_helpers.c>
// sys_enter for 0 arguments
SEC("sysmon/generic/enter0")
__attribute__((flatten))
int genericEnter0(struct tracepoint__syscalls__sys_enter *args)
{
uint64_t pidTid = bpf_get_current_pid_tgid();
uint64_t cpuId = bpf_get_smp_processor_id();
argsStruct *eventArgs;
uint32_t syscall = args->__syscall_nr;
uint32_t configId = 0;
const ebpfConfig *config;
// retrieve config
config = bpf_map_lookup_elem(&configMap, &configId);
if (!config)
return 0;
// retrieve map storage for event
eventArgs = bpf_map_lookup_elem(&argsStorageMap, &cpuId);
if (!eventArgs)
return 0;
if (!sysEnterCheckAndInit(eventArgs, config, syscall, pidTid))
return 0;
sysEnterCompleteAndStore(eventArgs, syscall, pidTid);
return 0;
}
// sys_enter for 1 argument
SEC("sysmon/generic/enter1")
__attribute__((flatten))
int genericEnter1(struct tracepoint__syscalls__sys_enter *args)
{
uint64_t pidTid = bpf_get_current_pid_tgid();
uint64_t cpuId = bpf_get_smp_processor_id();
argsStruct *eventArgs;
uint32_t syscall = args->__syscall_nr;
uint32_t configId = 0;
const ebpfConfig *config;
// retrieve config
config = bpf_map_lookup_elem(&configMap, &configId);
if (!config)
return 0;
// retrieve map storage for event
eventArgs = bpf_map_lookup_elem(&argsStorageMap, &cpuId);
if (!eventArgs)
return 0;
if (!sysEnterCheckAndInit(eventArgs, config, syscall, pidTid))
return 0;
eventArgs->a[0] = args->a[0];
sysEnterCompleteAndStore(eventArgs, syscall, pidTid);
return 0;
}
// sys_enter for 2 arguments
SEC("sysmon/generic/enter2")
__attribute__((flatten))
int genericEnter2(struct tracepoint__syscalls__sys_enter *args)
{
uint64_t pidTid = bpf_get_current_pid_tgid();
uint64_t cpuId = bpf_get_smp_processor_id();
argsStruct *eventArgs;
uint32_t syscall = args->__syscall_nr;
uint32_t configId = 0;
const ebpfConfig *config;
// retrieve config
config = bpf_map_lookup_elem(&configMap, &configId);
if (!config)
return 0;
// retrieve map storage for event
eventArgs = bpf_map_lookup_elem(&argsStorageMap, &cpuId);
if (!eventArgs)
return 0;
if (!sysEnterCheckAndInit(eventArgs, config, syscall, pidTid))
return 0;
eventArgs->a[0] = args->a[0];
eventArgs->a[1] = args->a[1];
sysEnterCompleteAndStore(eventArgs, syscall, pidTid);
return 0;
}
// sys_enter for 3 arguments
SEC("sysmon/generic/enter3")
__attribute__((flatten))
int genericEnter3(struct tracepoint__syscalls__sys_enter *args)
{
uint64_t pidTid = bpf_get_current_pid_tgid();
uint64_t cpuId = bpf_get_smp_processor_id();
argsStruct *eventArgs;
uint32_t syscall = args->__syscall_nr;
uint32_t configId = 0;
const ebpfConfig *config;
// retrieve config
config = bpf_map_lookup_elem(&configMap, &configId);
if (!config)
return 0;
// retrieve map storage for event
eventArgs = bpf_map_lookup_elem(&argsStorageMap, &cpuId);
if (!eventArgs)
return 0;
if (!sysEnterCheckAndInit(eventArgs, config, syscall, pidTid))
return 0;
eventArgs->a[0] = args->a[0];
eventArgs->a[1] = args->a[1];
eventArgs->a[2] = args->a[2];
sysEnterCompleteAndStore(eventArgs, syscall, pidTid);
return 0;
}
// sys_enter for 4 arguments
SEC("sysmon/generic/enter4")
__attribute__((flatten))
int genericEnter4(struct tracepoint__syscalls__sys_enter *args)
{
uint64_t pidTid = bpf_get_current_pid_tgid();
uint64_t cpuId = bpf_get_smp_processor_id();
argsStruct *eventArgs;
uint32_t syscall = args->__syscall_nr;
uint32_t configId = 0;
const ebpfConfig *config;
// retrieve config
config = bpf_map_lookup_elem(&configMap, &configId);
if (!config)
return 0;
// retrieve map storage for event
eventArgs = bpf_map_lookup_elem(&argsStorageMap, &cpuId);
if (!eventArgs)
return 0;
if (!sysEnterCheckAndInit(eventArgs, config, syscall, pidTid))
return 0;
eventArgs->a[0] = args->a[0];
eventArgs->a[1] = args->a[1];
eventArgs->a[2] = args->a[2];
eventArgs->a[3] = args->a[3];
sysEnterCompleteAndStore(eventArgs, syscall, pidTid);
return 0;
}
// sys_enter for 5 arguments
SEC("sysmon/generic/enter5")
__attribute__((flatten))
int genericEnter5(struct tracepoint__syscalls__sys_enter *args)
{
uint64_t pidTid = bpf_get_current_pid_tgid();
uint64_t cpuId = bpf_get_smp_processor_id();
argsStruct *eventArgs;
uint32_t syscall = args->__syscall_nr;
uint32_t configId = 0;
const ebpfConfig *config;
// retrieve config
config = bpf_map_lookup_elem(&configMap, &configId);
if (!config)
return 0;
// retrieve map storage for event
eventArgs = bpf_map_lookup_elem(&argsStorageMap, &cpuId);
if (!eventArgs)
return 0;
if (!sysEnterCheckAndInit(eventArgs, config, syscall, pidTid))
return 0;
eventArgs->a[0] = args->a[0];
eventArgs->a[1] = args->a[1];
eventArgs->a[2] = args->a[2];
eventArgs->a[3] = args->a[3];
eventArgs->a[4] = args->a[4];
sysEnterCompleteAndStore(eventArgs, syscall, pidTid);
return 0;
}
// sys_enter for 6 arguments
SEC("sysmon/generic/enter6")
__attribute__((flatten))
int genericEnter6(struct tracepoint__syscalls__sys_enter *args)
{
uint64_t pidTid = bpf_get_current_pid_tgid();
uint64_t cpuId = bpf_get_smp_processor_id();
argsStruct *eventArgs;
uint32_t syscall = args->__syscall_nr;
uint32_t configId = 0;
const ebpfConfig *config;
// retrieve config
config = bpf_map_lookup_elem(&configMap, &configId);
if (!config)
return 0;
// retrieve map storage for event
eventArgs = bpf_map_lookup_elem(&argsStorageMap, &cpuId);
if (!eventArgs)
return 0;
if (!sysEnterCheckAndInit(eventArgs, config, syscall, pidTid))
return 0;
eventArgs->a[0] = args->a[0];
eventArgs->a[1] = args->a[1];
eventArgs->a[2] = args->a[2];
eventArgs->a[3] = args->a[3];
eventArgs->a[4] = args->a[4];
eventArgs->a[5] = args->a[5];
sysEnterCompleteAndStore(eventArgs, syscall, pidTid);
return 0;
}
|
671696.c | /*
* This source code is provided under the Apache 2.0 license and is provided
* AS IS with no warranty or guarantee of fit for purpose. See the project's
* LICENSE.md for details.
* Copyright Thomson Reuters 2015. All rights reserved.
*/
#include "rsslNILoginProvider.h"
#include "rsslVASendMessage.h"
#include "rtr/rsslRDMLoginMsg.h"
#include "rtr/rsslReactor.h"
static const char *applicationId = "256";
static const char *instanceId = "VAInstance";
RsslRet setupLoginRequest(NIChannelCommand* chnlCommand, RsslInt32 streamId)
{
RsslUInt32 ipAddress = 0;
rsslInitDefaultRDMLoginRequest((RsslRDMLoginRequest*)&chnlCommand->loginRequest, streamId);
chnlCommand->loginRequest.flags |= RDM_LG_RQF_HAS_ROLE;
chnlCommand->loginRequest.role = 1;
chnlCommand->loginRequest.flags |= RDM_LG_RQF_HAS_APPLICATION_ID;
if(chnlCommand->applicationId.length)
{
chnlCommand->loginRequest.applicationId = chnlCommand->applicationId;
}
else
{
chnlCommand->loginRequest.applicationId.data = (char *)applicationId;
chnlCommand->loginRequest.applicationId.length = (RsslUInt32)strlen(applicationId);
}
chnlCommand->loginRequest.flags |= RDM_LG_RQF_HAS_USERNAME_TYPE;
if(chnlCommand->authenticationToken.length)
{
chnlCommand->loginRequest.userName = chnlCommand->authenticationToken;
chnlCommand->loginRequest.userNameType = RDM_LOGIN_USER_AUTHN_TOKEN;
if(chnlCommand->authenticationExtended.length)
{
chnlCommand->loginRequest.flags |= RDM_LG_RQF_HAS_AUTHN_EXTENDED;
chnlCommand->loginRequest.authenticationExtended = chnlCommand->authenticationExtended;
}
printf("AuthenticationToken: %s\n", chnlCommand->loginRequest.userName.data);
printf("AuthenticationExtended: %s\n", chnlCommand->loginRequest.authenticationExtended.data);
}
else
{
chnlCommand->loginRequest.userNameType = RDM_LOGIN_USER_NAME;
if(chnlCommand->username.length)
{
chnlCommand->loginRequest.userName = chnlCommand->username;
}
printf("Username: %s\n", chnlCommand->loginRequest.userName.data);
}
return RSSL_RET_SUCCESS;
}
RsslReactorCallbackRet processLoginResponse(RsslReactor *pReactor, RsslReactorChannel *pChannel, RsslRDMLoginMsgEvent* pEvent )
{
RsslState *pState = 0;
RsslErrorInfo err;
NIChannelCommand *chnlCommand = (NIChannelCommand*)pChannel->userSpecPtr;
RsslBuffer tempBuffer = { 1024, (char *)alloca(1024) };
if(!pEvent->pRDMLoginMsg)
{
printf("No login response!\n");
printf("processLoginResponse %s(%s)\n", pEvent->baseMsgEvent.pErrorInfo->rsslError.text, pEvent->baseMsgEvent.pErrorInfo->errorLocation);
rsslReactorCloseChannel(pReactor, pChannel, &err);
return RSSL_RC_CRET_SUCCESS;
}
switch(pEvent->pRDMLoginMsg->rdmMsgBase.rdmMsgType)
{
case RDM_LG_MT_REFRESH:
{
RsslRDMLoginRefresh *pLoginRefresh = &pEvent->pRDMLoginMsg->refresh;
if(rsslCopyRDMLoginRefresh(&chnlCommand->loginRefresh, pLoginRefresh, &chnlCommand->loginRefreshBuffer) != RSSL_RET_SUCCESS)
{
printf("Failed to copy login response.\n");
exit(-1);
}
printf("\nReceived Login Response\n");
printf("streamId: %i\n", pEvent->pRDMLoginMsg->rdmMsgBase.streamId);
pState = &pLoginRefresh->state;
rsslStateToString(&tempBuffer, pState);
printf("\t%.*s\n\n", tempBuffer.length, tempBuffer.data);
if (pLoginRefresh->flags & RDM_LG_RFF_HAS_AUTHN_TT_REISSUE)
printf(" AuthenticationTTReissue: %llu\n", pLoginRefresh->authenticationTTReissue);
if (pLoginRefresh->flags & RDM_LG_RFF_HAS_AUTHN_EXTENDED_RESP)
printf(" AuthenticationExtendedResp: %.*s\n", pLoginRefresh->authenticationExtendedResp.length, pLoginRefresh->authenticationExtendedResp.data);
if (pLoginRefresh->flags & RDM_LG_RFF_HAS_AUTHN_ERROR_CODE)
printf(" AuthenticationErrorCode: %llu\n", pLoginRefresh->authenticationErrorCode);
if (pLoginRefresh->flags & RDM_LG_RFF_HAS_AUTHN_ERROR_TEXT)
printf(" AuthenticationErrorText: %.*s\n", pLoginRefresh->authenticationErrorText.length, pLoginRefresh->authenticationErrorText.data);
if(pState->streamState == RSSL_STREAM_OPEN &&
pState->dataState == RSSL_DATA_OK &&
pState->code == RSSL_SC_NONE)
{
printf("Login Stream established, sending Source Directory\n");
}
else
{
printf("\nLogin failure, shutting down\n");
return RSSL_RC_CRET_FAILURE;
}
// get login reissue time from authenticationTTReissue
if (pLoginRefresh->flags & RDM_LG_RFF_HAS_AUTHN_TT_REISSUE)
{
chnlCommand->loginReissueTime = pLoginRefresh->authenticationTTReissue;
chnlCommand->canSendLoginReissue = RSSL_TRUE;
}
break;
}
case RDM_LG_MT_STATUS:
{
RsslRDMLoginStatus *pLoginStatus = &pEvent->pRDMLoginMsg->status;
printf("\nReceived Login Status\n");
if (pLoginStatus->flags & RDM_LG_STF_HAS_AUTHN_ERROR_CODE)
printf(" AuthenticationErrorCode: %llu\n", pLoginStatus->authenticationErrorCode);
if (pLoginStatus->flags & RDM_LG_STF_HAS_AUTHN_ERROR_TEXT)
printf(" AuthenticationErrorText: %.*s\n", pLoginStatus->authenticationErrorText.length, pLoginStatus->authenticationErrorText.data);
if (pLoginStatus->flags & RDM_LG_STF_HAS_STATE)
{
/* get state information */
rsslStateToString(&tempBuffer, &pLoginStatus->state);
printf(" %.*s\n\n", tempBuffer.length, tempBuffer.data);
}
break;
}
default:
printf("\nReceived Unhandled Login Msg Class: %d\n", pEvent->baseMsgEvent.pRsslMsg->msgBase.msgClass);
break;
}
return RSSL_RC_CRET_SUCCESS;
}
|
980921.c | /* crypto/x509/x509_cmp.c */
/* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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 cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <ctype.h>
#include "cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b)
{
int i;
X509_CINF *ai,*bi;
ai=a->cert_info;
bi=b->cert_info;
i=M_ASN1_INTEGER_cmp(ai->serialNumber,bi->serialNumber);
if (i) return(i);
return(X509_NAME_cmp(ai->issuer,bi->issuer));
}
#ifndef OPENSSL_NO_MD5
unsigned long X509_issuer_and_serial_hash(X509 *a)
{
unsigned long ret=0;
EVP_MD_CTX ctx;
unsigned char md[16];
char *f;
EVP_MD_CTX_init(&ctx);
f=X509_NAME_oneline(a->cert_info->issuer,NULL,0);
if (!EVP_DigestInit_ex(&ctx, EVP_md5(), NULL))
goto err;
if (!EVP_DigestUpdate(&ctx,(unsigned char *)f,strlen(f)))
goto err;
OPENSSL_free(f);
if(!EVP_DigestUpdate(&ctx,(unsigned char *)a->cert_info->serialNumber->data,
(unsigned long)a->cert_info->serialNumber->length))
goto err;
if (!EVP_DigestFinal_ex(&ctx,&(md[0]),NULL))
goto err;
ret=( ((unsigned long)md[0] )|((unsigned long)md[1]<<8L)|
((unsigned long)md[2]<<16L)|((unsigned long)md[3]<<24L)
)&0xffffffffL;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
#endif
int X509_issuer_name_cmp(const X509 *a, const X509 *b)
{
return(X509_NAME_cmp(a->cert_info->issuer,b->cert_info->issuer));
}
int X509_subject_name_cmp(const X509 *a, const X509 *b)
{
return(X509_NAME_cmp(a->cert_info->subject,b->cert_info->subject));
}
int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b)
{
return(X509_NAME_cmp(a->crl->issuer,b->crl->issuer));
}
#ifndef OPENSSL_NO_SHA
int X509_CRL_match(const X509_CRL *a, const X509_CRL *b)
{
return memcmp(a->sha1_hash, b->sha1_hash, 20);
}
#endif
X509_NAME *X509_get_issuer_name(X509 *a)
{
return(a->cert_info->issuer);
}
unsigned long X509_issuer_name_hash(X509 *x)
{
return(X509_NAME_hash(x->cert_info->issuer));
}
#ifndef OPENSSL_NO_MD5
unsigned long X509_issuer_name_hash_old(X509 *x)
{
return(X509_NAME_hash_old(x->cert_info->issuer));
}
#endif
X509_NAME *X509_get_subject_name(X509 *a)
{
return(a->cert_info->subject);
}
ASN1_INTEGER *X509_get_serialNumber(X509 *a)
{
return(a->cert_info->serialNumber);
}
unsigned long X509_subject_name_hash(X509 *x)
{
return(X509_NAME_hash(x->cert_info->subject));
}
#ifndef OPENSSL_NO_MD5
unsigned long X509_subject_name_hash_old(X509 *x)
{
return(X509_NAME_hash_old(x->cert_info->subject));
}
#endif
#ifndef OPENSSL_NO_SHA
/* Compare two certificates: they must be identical for
* this to work. NB: Although "cmp" operations are generally
* prototyped to take "const" arguments (eg. for use in
* STACKs), the way X509 handling is - these operations may
* involve ensuring the hashes are up-to-date and ensuring
* certain cert information is cached. So this is the point
* where the "depth-first" constification tree has to halt
* with an evil cast.
*/
int X509_cmp(const X509 *a, const X509 *b)
{
/* ensure hash is valid */
X509_check_purpose((X509 *)a, -1, 0);
X509_check_purpose((X509 *)b, -1, 0);
return memcmp(a->sha1_hash, b->sha1_hash, SHA_DIGEST_LENGTH);
}
#endif
int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b)
{
int ret;
/* Ensure canonical encoding is present and up to date */
if (!a->canon_enc || a->modified)
{
ret = i2d_X509_NAME((X509_NAME *)a, NULL);
if (ret < 0)
return -2;
}
if (!b->canon_enc || b->modified)
{
ret = i2d_X509_NAME((X509_NAME *)b, NULL);
if (ret < 0)
return -2;
}
ret = a->canon_enclen - b->canon_enclen;
if (ret)
return ret;
return memcmp(a->canon_enc, b->canon_enc, a->canon_enclen);
}
unsigned long X509_NAME_hash(X509_NAME *x)
{
unsigned long ret=0;
unsigned char md[SHA_DIGEST_LENGTH];
/* Make sure X509_NAME structure contains valid cached encoding */
i2d_X509_NAME(x,NULL);
if (!EVP_Digest(x->canon_enc, x->canon_enclen, md, NULL, EVP_sha1(),
NULL))
return 0;
ret=( ((unsigned long)md[0] )|((unsigned long)md[1]<<8L)|
((unsigned long)md[2]<<16L)|((unsigned long)md[3]<<24L)
)&0xffffffffL;
return(ret);
}
#ifndef OPENSSL_NO_MD5
/* I now DER encode the name and hash it. Since I cache the DER encoding,
* this is reasonably efficient. */
unsigned long X509_NAME_hash_old(X509_NAME *x)
{
EVP_MD_CTX md_ctx;
unsigned long ret=0;
unsigned char md[16];
/* Make sure X509_NAME structure contains valid cached encoding */
i2d_X509_NAME(x,NULL);
EVP_MD_CTX_init(&md_ctx);
EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
if (EVP_DigestInit_ex(&md_ctx, EVP_md5(), NULL)
&& EVP_DigestUpdate(&md_ctx, x->bytes->data, x->bytes->length)
&& EVP_DigestFinal_ex(&md_ctx,md,NULL))
ret=(((unsigned long)md[0] )|((unsigned long)md[1]<<8L)|
((unsigned long)md[2]<<16L)|((unsigned long)md[3]<<24L)
)&0xffffffffL;
EVP_MD_CTX_cleanup(&md_ctx);
return(ret);
}
#endif
/* Search a stack of X509 for a match */
X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, X509_NAME *name,
ASN1_INTEGER *serial)
{
int i;
X509_CINF cinf;
X509 x,*x509=NULL;
if(!sk) return NULL;
x.cert_info= &cinf;
cinf.serialNumber=serial;
cinf.issuer=name;
for (i=0; i<sk_X509_num(sk); i++)
{
x509=sk_X509_value(sk,i);
if (X509_issuer_and_serial_cmp(x509,&x) == 0)
return(x509);
}
return(NULL);
}
X509 *X509_find_by_subject(STACK_OF(X509) *sk, X509_NAME *name)
{
X509 *x509;
int i;
for (i=0; i<sk_X509_num(sk); i++)
{
x509=sk_X509_value(sk,i);
if (X509_NAME_cmp(X509_get_subject_name(x509),name) == 0)
return(x509);
}
return(NULL);
}
EVP_PKEY *X509_get_pubkey(X509 *x)
{
if ((x == NULL) || (x->cert_info == NULL))
return(NULL);
return(X509_PUBKEY_get(x->cert_info->key));
}
ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x)
{
if(!x) return NULL;
return x->cert_info->key->public_key;
}
int X509_check_private_key(X509 *x, EVP_PKEY *k)
{
EVP_PKEY *xk;
int ret;
xk=X509_get_pubkey(x);
if (xk)
ret = EVP_PKEY_cmp(xk, k);
else
ret = -2;
switch (ret)
{
case 1:
break;
case 0:
X509err(X509_F_X509_CHECK_PRIVATE_KEY,X509_R_KEY_VALUES_MISMATCH);
break;
case -1:
X509err(X509_F_X509_CHECK_PRIVATE_KEY,X509_R_KEY_TYPE_MISMATCH);
break;
case -2:
X509err(X509_F_X509_CHECK_PRIVATE_KEY,X509_R_UNKNOWN_KEY_TYPE);
}
if (xk)
EVP_PKEY_free(xk);
if (ret > 0)
return 1;
return 0;
}
|
392556.c | //
// NextID
//
// Copyright (c) 2020 Wellington Marthas
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <sys/time.h>
#include "postgres.h"
#include "funcapi.h"
#define OUR_EPOCH 1546304400000
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(next_id);
int64 current_timestamp(void);
Datum next_id(PG_FUNCTION_ARGS) {
int64 seq_id = PG_GETARG_INT64(0);
int32 shard_id = PG_GETARG_INT32(1);
PG_RETURN_INT64(((current_timestamp() - OUR_EPOCH) << 23) | (shard_id << 10) | (seq_id % 1024));
}
int64 current_timestamp(void) {
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec * 1000LL + t.tv_usec / 1000;
}
|
908625.c | /*
* Copyright (c) 1988 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that this notice is preserved and that due credit is given
* to the University of California at Berkeley. The name of the University
* may not be used to endorse or promote products derived from this
* software without specific prior written permission. This software
* is provided ``as is'' without express or implied warranty.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)res_query.c 5.3 (Berkeley) 4/5/88";
#endif /* LIBC_SCCS and not lint */
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <ctype.h>
#include <netdb.h>
#include <stdio.h>
#include <errno.h>
#include <strings.h>
#include <arpa/inet.h>
#include <arpa/nameser.h>
#include <resolv.h>
#if PACKETSZ > 1024
#define MAXPACKET PACKETSZ
#else
#define MAXPACKET 1024
#endif
extern int errno;
int h_errno;
/*
* Formulate a normal query, send, and await answer.
* Returned answer is placed in supplied buffer "answer".
* Perform preliminary check of answer, returning success only
* if no error is indicated and the answer count is nonzero.
* Return the size of the response on success, -1 on error.
* Error number is left in h_errno.
* Caller must parse answer and determine whether it answers the question.
*/
res_query(name, class, type, answer, anslen)
char *name; /* domain name */
int class, type; /* class and type of query */
u_char *answer; /* buffer to put answer */
int anslen; /* size of answer buffer */
{
char buf[MAXPACKET];
HEADER *hp;
int n;
if ((_res.options & RES_INIT) == 0 && res_init() == -1)
return (-1);
#ifdef DEBUG
if (_res.options & RES_DEBUG)
printf("res_query(%s, %d, %d)\n", name, class, type);
#endif
n = res_mkquery(QUERY, name, class, type, (char *)NULL, 0, NULL,
buf, sizeof(buf));
if (n <= 0) {
#ifdef DEBUG
if (_res.options & RES_DEBUG)
printf("res_query: mkquery failed\n");
#endif
h_errno = NO_RECOVERY;
return (n);
}
n = res_send(buf, n, answer, anslen);
if (n < 0) {
#ifdef DEBUG
if (_res.options & RES_DEBUG)
printf("res_query: send error\n");
#endif
h_errno = TRY_AGAIN;
return(n);
}
hp = (HEADER *) answer;
if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
#ifdef DEBUG
if (_res.options & RES_DEBUG)
printf("rcode = %d, ancount=%d\n", hp->rcode,
ntohs(hp->ancount));
#endif
switch (hp->rcode) {
case NXDOMAIN:
h_errno = HOST_NOT_FOUND;
break;
case SERVFAIL:
h_errno = TRY_AGAIN;
break;
case NOERROR:
h_errno = NO_DATA;
break;
case FORMERR:
case NOTIMP:
case REFUSED:
default:
h_errno = NO_RECOVERY;
break;
}
return (-1);
}
return(n);
}
/*
* Formulate a normal query, send, and retrieve answer in supplied buffer.
* Return the size of the response on success, -1 on error.
* If enabled, implement search rules until answer or unrecoverable failure
* is detected. Error number is left in h_errno.
* Only useful for queries in the same name hierarchy as the local host
* (not, for example, for host address-to-name lookups in domain in-addr.arpa).
*/
res_search(name, class, type, answer, anslen)
char *name; /* domain name */
int class, type; /* class and type of query */
u_char *answer; /* buffer to put answer */
int anslen; /* size of answer */
{
register char *cp, **domain;
int n, ret;
char *hostalias();
if ((_res.options & RES_INIT) == 0 && res_init() == -1)
return (-1);
errno = 0;
h_errno = HOST_NOT_FOUND; /* default, if we never query */
for (cp = name, n = 0; *cp; cp++)
if (*cp == '.')
n++;
if (n == 0 && (cp = hostalias(name)))
return (res_query(cp, class, type, answer, anslen));
if ((n == 0 || *--cp != '.') && (_res.options & RES_DEFNAMES))
for (domain = _res.dnsrch; *domain; domain++) {
h_errno = 0;
ret = res_querydomain(name, *domain, class, type,
answer, anslen);
if (ret > 0)
return (ret);
/*
* If no server present, give up.
* If name isn't found in this domain,
* keep trying higher domains in the search list
* (if that's enabled).
* On a NO_DATA error, keep trying, otherwise
* a wildcard entry of another type could keep us
* from finding this entry higher in the domain.
* If we get some other error (non-authoritative negative
* answer or server failure), then stop searching up,
* but try the input name below in case it's fully-qualified.
*/
if (errno == ECONNREFUSED) {
h_errno = TRY_AGAIN;
return (-1);
}
if ((h_errno != HOST_NOT_FOUND && h_errno != NO_DATA) ||
(_res.options & RES_DNSRCH) == 0)
break;
}
/*
* If the search/default failed, try the name as fully-qualified,
* but only if it contained at least one dot (even trailing).
*/
if (n)
return (res_querydomain(name, (char *)NULL, class, type,
answer, anslen));
return (-1);
}
/*
* Perform a call on res_query on the concatenation of name and domain,
* removing a trailing dot from name if domain is NULL.
*/
res_querydomain(name, domain, class, type, answer, anslen)
char *name, *domain;
int class, type; /* class and type of query */
u_char *answer; /* buffer to put answer */
int anslen; /* size of answer */
{
char nbuf[2*MAXDNAME+2];
char *longname = nbuf;
int n;
#ifdef DEBUG
if (_res.options & RES_DEBUG)
printf("res_querydomain(%s, %s, %d, %d)\n",
name, domain, class, type);
#endif
if (domain == NULL) {
/*
* Check for trailing '.';
* copy without '.' if present.
*/
n = strlen(name) - 1;
if (name[n] == '.' && n < sizeof(nbuf) - 1) {
bcopy(name, nbuf, n);
nbuf[n] = '\0';
} else
longname = name;
} else
(void)sprintf(nbuf, "%.*s.%.*s",
MAXDNAME, name, MAXDNAME, domain);
return (res_query(longname, class, type, answer, anslen));
}
char *
hostalias(name)
register char *name;
{
register char *C1, *C2;
FILE *fp;
char *file, *getenv(), *strcpy(), *strncpy();
char buf[BUFSIZ];
static char abuf[MAXDNAME];
file = getenv("HOSTALIASES");
if (file == NULL || (fp = fopen(file, "r")) == NULL)
return (NULL);
buf[sizeof(buf) - 1] = '\0';
while (fgets(buf, sizeof(buf), fp)) {
for (C1 = buf; *C1 && !isspace(*C1); ++C1);
if (!*C1)
break;
*C1 = '\0';
if (!strcasecmp(buf, name)) {
while (isspace(*++C1));
if (!*C1)
break;
for (C2 = C1 + 1; *C2 && !isspace(*C2); ++C2);
abuf[sizeof(abuf) - 1] = *C2 = '\0';
(void)strncpy(abuf, C1, sizeof(abuf) - 1);
fclose(fp);
return (abuf);
}
}
fclose(fp);
return (NULL);
}
|
373398.c | /*
* carl9170 firmware - used by the ar9170 wireless device
*
* WakeUp on WLAN functions
*
* Copyright 2011 Christian Lamparter <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "carl9170.h"
#include "shared/phy.h"
#include "timer.h"
#include "wl.h"
#include "printf.h"
#include "rf.h"
#include "wol.h"
#include "linux/ieee80211.h"
#ifdef CONFIG_CARL9170FW_WOL
void wol_cmd(const struct carl9170_wol_cmd *cmd)
{
memcpy(&fw.wol.cmd, cmd, sizeof(cmd));
}
void wol_prepare(void)
{
/* set MAC filter */
memcpy((void *)AR9170_MAC_REG_MAC_ADDR_L, fw.wol.cmd.mac, 6);
memcpy((void *)AR9170_MAC_REG_BSSID_L, fw.wol.cmd.bssid, 6);
set(AR9170_MAC_REG_RX_CONTROL, AR9170_MAC_RX_CTRL_DEAGG);
/* set filter policy to: discard everything */
fw.wlan.rx_filter = CARL9170_RX_FILTER_EVERYTHING;
/* reenable rx dma */
wlan_trigger(AR9170_DMA_TRIGGER_RXQ);
/* initialize the last_beacon timer */
fw.wol.last_null = fw.wol.last_beacon = get_clock_counter();
}
#ifdef CONFIG_CARL9170FW_WOL_NL80211_TRIGGERS
static bool wlan_rx_wol_magic_packet(const struct ieee80211_hdr *hdr, const unsigned int len)
{
const unsigned char *data, *end, *mac;
unsigned int found = 0;
/*
* LIMITATION:
* We can only scan the first AR9170_BLOCK_SIZE [=~320] bytes
* for MAGIC patterns!
*/
mac = (const unsigned char *) AR9170_MAC_REG_MAC_ADDR_L;
data = (u8 *)((unsigned long)hdr + ieee80211_hdrlen(hdr->frame_control));
end = (u8 *)((unsigned long)hdr + len);
/*
* scan for standard WOL Magic frame
*
* "A physical WakeOnLAN (Magic Packet) will look like this:
* ---------------------------------------------------------------
* | Synchronization Stream | Target MAC | Password (optional) |
* | 6 octets | 96 octets | 0, 4 or 6 |
* ---------------------------------------------------------------
*
* The Synchronization Stream is defined as 6 bytes of FFh.
* The Target MAC block contains 16 duplications of the IEEEaddress
* of the target, with no breaks or interruptions.
*
* The Password field is optional, but if present, contains either
* 4 bytes or 6 bytes. The WakeOnLAN dissector was implemented to
* dissect the password, if present, according to the command-line
* format that ether-wake uses, therefore, if a 4-byte password is
* present, it will be dissected as an IPv4 address and if a 6-byte
* password is present, it will be dissected as an Ethernet address.
*
* <http://wiki.wireshark.org/WakeOnLAN>
*/
while (data < end) {
if (found >= 6) {
if (*data == mac[found % 6])
found++;
else
found = 0;
}
/* previous check might reset found counter */
if (found < 6) {
if (*data == 0xff)
found++;
else
found = 0;
}
if (found == (6 + 16 * 6))
return true;
data++;
}
return false;
}
static void wlan_wol_connect_callback(void __unused *dummy, bool success)
{
if (success)
fw.wol.lost_null = 0;
else
fw.wol.lost_null++;
}
static void wlan_wol_connection_monitor(void)
{
struct carl9170_tx_null_superframe *nullf = &dma_mem.reserved.cmd.null;
struct ieee80211_hdr *null = (struct ieee80211_hdr *) &nullf->f.null;
if (!fw.wlan.fw_desc_available)
return;
memset(nullf, 0, sizeof(*nullf));
nullf->s.len = sizeof(struct carl9170_tx_superdesc) +
sizeof(struct ar9170_tx_hwdesc) +
sizeof(struct ieee80211_hdr);
nullf->s.ri[0].tries = 3;
nullf->s.assign_seq = true;
nullf->s.queue = AR9170_TXQ_VO;
nullf->f.hdr.length = sizeof(struct ieee80211_hdr) + FCS_LEN;
nullf->f.hdr.mac.backoff = 1;
nullf->f.hdr.mac.hw_duration = 1;
nullf->f.hdr.mac.erp_prot = AR9170_TX_MAC_PROT_RTS;
nullf->f.hdr.phy.modulation = AR9170_TX_PHY_MOD_OFDM;
nullf->f.hdr.phy.bandwidth = AR9170_TX_PHY_BW_20MHZ;
nullf->f.hdr.phy.chains = AR9170_TX_PHY_TXCHAIN_2;
nullf->f.hdr.phy.tx_power = 29; /* 14.5 dBm */
nullf->f.hdr.phy.mcs = AR9170_TXRX_PHY_RATE_OFDM_6M;
/* format outgoing nullfunc */
null->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA |
IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_TODS);
memcpy(null->addr1, fw.wol.cmd.bssid, 6);
memcpy(null->addr2, fw.wol.cmd.mac, 6);
memcpy(null->addr3, fw.wol.cmd.bssid, 6);
wlan_tx_fw(&nullf->s, wlan_wol_connect_callback);
}
static bool wlan_rx_wol_disconnect(const unsigned int rx_filter,
const struct ieee80211_hdr *hdr,
const unsigned int __unused len)
{
const unsigned char *bssid;
bssid = (const unsigned char *) AR9170_MAC_REG_BSSID_L;
/* should catch both broadcast and unicast MLMEs */
if (!(rx_filter & CARL9170_RX_FILTER_OTHER_RA)) {
if (ieee80211_is_deauth(hdr->frame_control) ||
ieee80211_is_disassoc(hdr->frame_control))
return true;
}
if (ieee80211_is_beacon(hdr->frame_control) &&
compare_ether_address(hdr->addr3, bssid)) {
fw.wol.last_beacon = get_clock_counter();
}
return false;
}
#endif /* CARL9170FW_WOL_NL80211_TRIGGERS */
#ifdef CONFIG_CARL9170FW_WOL_PROBE_REQUEST
/*
* Note: CONFIG_CARL9170FW_WOL_PROBE_REQUEST_SSID is not a real
* string. We have to be careful not to add a \0 at the end.
*/
static const struct {
u8 ssid_ie;
u8 ssid_len;
u8 ssid[sizeof(CONFIG_CARL9170FW_WOL_PROBE_REQUEST_SSID) - 1];
} __packed probe_req = {
.ssid_ie = WLAN_EID_SSID,
.ssid_len = sizeof(CONFIG_CARL9170FW_WOL_PROBE_REQUEST_SSID) - 1,
.ssid = CONFIG_CARL9170FW_WOL_PROBE_REQUEST_SSID,
};
static bool wlan_rx_wol_probe_ssid(const struct ieee80211_hdr *hdr, const unsigned int len)
{
const unsigned char *data, *end, *scan = (void *) &probe_req;
/*
* IEEE 802.11-2007 7.3.2.1 specifies that the SSID is no
* longer than 32 octets.
*/
BUILD_BUG_ON((sizeof(CONFIG_CARL9170FW_WOL_PROBE_REQUEST_SSID) - 1) > 32);
if (ieee80211_is_probe_req(hdr->frame_control)) {
unsigned int i;
end = (u8 *)((unsigned long)hdr + len);
/*
* The position of the SSID information element inside
* a probe request frame is more or less "fixed".
*/
data = (u8 *)((struct ieee80211_mgmt *)hdr)->u.probe_req.variable;
for (i = 0; i < (unsigned int)(probe_req.ssid_len + 1); i++) {
if (data > end || scan[i] != data[i])
return false;
}
return true;
}
return false;
}
#endif /* CONFIG_CARL9170FW_WOL_PROBE_REQUEST */
void wol_rx(const unsigned int rx_filter __unused, const struct ieee80211_hdr *hdr __unused, const unsigned int len __unused)
{
#ifdef CONFIG_CARL9170FW_WOL_NL80211_TRIGGERS
/* Disconnect is always enabled */
if (fw.wol.cmd.flags & CARL9170_WOL_DISCONNECT &&
rx_filter & CARL9170_RX_FILTER_MGMT)
fw.wol.wake_up |= wlan_rx_wol_disconnect(rx_filter, hdr, len);
if (fw.wol.cmd.flags & CARL9170_WOL_MAGIC_PKT &&
rx_filter & CARL9170_RX_FILTER_DATA)
fw.wol.wake_up |= wlan_rx_wol_magic_packet(hdr, len);
#endif /* CONFIG_CARL9170FW_WOL_NL80211_TRIGGERS */
#ifdef CONFIG_CARL9170FW_WOL_PROBE_REQUEST
if (rx_filter & CARL9170_RX_FILTER_MGMT)
fw.wol.wake_up |= wlan_rx_wol_probe_ssid(hdr, len);
#endif /* CONFIG_CARL9170FW_WOL_PROBE_REQUEST */
}
void wol_janitor(void)
{
if (unlikely(fw.suspend_mode == CARL9170_HOST_SUSPENDED)) {
#ifdef CONFIG_CARL9170FW_WOL_NL80211_TRIGGERS
if (fw.wol.cmd.flags & CARL9170_WOL_DISCONNECT) {
/*
* connection lost after 10sec without receiving
* a beacon
*/
if (is_after_msecs(fw.wol.last_beacon, 10000))
fw.wol.wake_up |= true;
if (fw.wol.cmd.null_interval &&
is_after_msecs(fw.wol.last_null, fw.wol.cmd.null_interval))
wlan_wol_connection_monitor();
if (fw.wol.lost_null >= 5)
fw.wol.wake_up |= true;
}
#endif /* CONFIG_CARL9170FW_WOL_NL80211_TRIGGERS */
if (fw.wol.wake_up) {
fw.suspend_mode = CARL9170_AWAKE_HOST;
set(AR9170_USB_REG_WAKE_UP, AR9170_USB_WAKE_UP_WAKE);
}
}
}
#else
#endif /* CONFIG_CARL9170FW_WOL */
|
826116.c | /*
* =====================================================================================
*
* Filename: traverselinklist.c
*
* Description:
*
* Version: 1.0
* Created: Tuesday 25 September 2018 02:52:57 IST
* Revision: none
* Compiler: gcc
*
* Author: Utkarsh Mani Tripathi
* Organization: cBasics
*
* =====================================================================================
*/
#include <stdlib.h>
#include <stdio.h>
#include "node.h"
int length;
// traverse print all the data in the link list.
void traverse() {
length = 0;
printf("traverse the link list\n");
node = header;
if (!check(node)) {
return;
}
printf("Header: %p\n", header);
while(node != NULL) {
printf("data: %d\n", node->data);
node=node->next;
length++;
}
}
void reverse() {
length = 0;
printf("reverse the link list\n");
node = tail;
if (!check(node)) {
return;
}
printf("Tail: %p\n", tail);
while(node != NULL) {
printf("data: %d\n", node->data);
node=node->prev;
length++;
}
}
|
889954.c | /*
* Copyright (c) 2013 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.
*/
#include <linux/relay.h>
#include "core.h"
#include "debug.h"
#include "wmi-ops.h"
static void send_fft_sample(struct ath10k *ar,
const struct fft_sample_tlv *fft_sample_tlv)
{
int length;
if (!ar->spectral.rfs_chan_spec_scan)
return;
length = __be16_to_cpu(fft_sample_tlv->length) +
sizeof(*fft_sample_tlv);
relay_write(ar->spectral.rfs_chan_spec_scan, fft_sample_tlv, length);
}
static uint8_t get_max_exp(s8 max_index, u16 max_magnitude, size_t bin_len,
u8 *data)
{
int dc_pos;
u8 max_exp;
dc_pos = bin_len / 2;
/* peak index outside of bins */
if (dc_pos < max_index || -dc_pos >= max_index)
return 0;
for (max_exp = 0; max_exp < 8; max_exp++) {
if (data[dc_pos + max_index] == (max_magnitude >> max_exp))
break;
}
/* max_exp not found */
if (data[dc_pos + max_index] != (max_magnitude >> max_exp))
return 0;
return max_exp;
}
static inline size_t ath10k_spectral_fix_bin_size(struct ath10k *ar,
size_t bin_len)
{
/* some chipsets reports bin size as 2^n bytes + 'm' bytes in
* report mode 2. First 2^n bytes carries inband tones and last
* 'm' bytes carries band edge detection data mainly used in
* radar detection purpose. Strip last 'm' bytes to make bin size
* as a valid one. 'm' can take possible values of 4, 12.
*/
if (!is_power_of_2(bin_len))
bin_len -= ar->hw_params.spectral_bin_discard;
return bin_len;
}
int ath10k_spectral_process_fft(struct ath10k *ar,
struct wmi_phyerr_ev_arg *phyerr,
const struct phyerr_fft_report *fftr,
size_t bin_len, u64 tsf)
{
struct fft_sample_ath10k *fft_sample;
u8 buf[sizeof(*fft_sample) + SPECTRAL_ATH10K_MAX_NUM_BINS];
u16 freq1, freq2, total_gain_db, base_pwr_db, length, peak_mag;
u32 reg0, reg1;
u8 chain_idx, *bins;
int dc_pos;
fft_sample = (struct fft_sample_ath10k *)&buf;
bin_len = ath10k_spectral_fix_bin_size(ar, bin_len);
if (bin_len < 64 || bin_len > SPECTRAL_ATH10K_MAX_NUM_BINS)
return -EINVAL;
reg0 = __le32_to_cpu(fftr->reg0);
reg1 = __le32_to_cpu(fftr->reg1);
length = sizeof(*fft_sample) - sizeof(struct fft_sample_tlv) + bin_len;
fft_sample->tlv.type = ATH_FFT_SAMPLE_ATH10K;
fft_sample->tlv.length = __cpu_to_be16(length);
/* TODO: there might be a reason why the hardware reports 20/40/80 MHz,
* but the results/plots suggest that its actually 22/44/88 MHz.
*/
switch (phyerr->chan_width_mhz) {
case 20:
fft_sample->chan_width_mhz = 22;
break;
case 40:
fft_sample->chan_width_mhz = 44;
break;
case 80:
/* TODO: As experiments with an analogue sender and various
* configurations (fft-sizes of 64/128/256 and 20/40/80 Mhz)
* show, the particular configuration of 80 MHz/64 bins does
* not match with the other samples at all. Until the reason
* for that is found, don't report these samples.
*/
if (bin_len == 64)
return -EINVAL;
fft_sample->chan_width_mhz = 88;
break;
default:
fft_sample->chan_width_mhz = phyerr->chan_width_mhz;
}
fft_sample->relpwr_db = MS(reg1, SEARCH_FFT_REPORT_REG1_RELPWR_DB);
fft_sample->avgpwr_db = MS(reg1, SEARCH_FFT_REPORT_REG1_AVGPWR_DB);
peak_mag = MS(reg1, SEARCH_FFT_REPORT_REG1_PEAK_MAG);
fft_sample->max_magnitude = __cpu_to_be16(peak_mag);
fft_sample->max_index = MS(reg0, SEARCH_FFT_REPORT_REG0_PEAK_SIDX);
fft_sample->rssi = phyerr->rssi_combined;
total_gain_db = MS(reg0, SEARCH_FFT_REPORT_REG0_TOTAL_GAIN_DB);
base_pwr_db = MS(reg0, SEARCH_FFT_REPORT_REG0_BASE_PWR_DB);
fft_sample->total_gain_db = __cpu_to_be16(total_gain_db);
fft_sample->base_pwr_db = __cpu_to_be16(base_pwr_db);
freq1 = phyerr->freq1;
freq2 = phyerr->freq2;
fft_sample->freq1 = __cpu_to_be16(freq1);
fft_sample->freq2 = __cpu_to_be16(freq2);
chain_idx = MS(reg0, SEARCH_FFT_REPORT_REG0_FFT_CHN_IDX);
fft_sample->noise = __cpu_to_be16(phyerr->nf_chains[chain_idx]);
bins = (u8 *)fftr;
bins += sizeof(*fftr);
fft_sample->tsf = __cpu_to_be64(tsf);
/* max_exp has been directly reported by previous hardware (ath9k),
* maybe its possible to get it by other means?
*/
fft_sample->max_exp = get_max_exp(fft_sample->max_index, peak_mag,
bin_len, bins);
memcpy(fft_sample->data, bins, bin_len);
/* DC value (value in the middle) is the blind spot of the spectral
* sample and invalid, interpolate it.
*/
dc_pos = bin_len / 2;
fft_sample->data[dc_pos] = (fft_sample->data[dc_pos + 1] +
fft_sample->data[dc_pos - 1]) / 2;
send_fft_sample(ar, &fft_sample->tlv);
return 0;
}
static struct ath10k_vif *ath10k_get_spectral_vdev(struct ath10k *ar)
{
struct ath10k_vif *arvif;
lockdep_assert_held(&ar->conf_mutex);
if (list_empty(&ar->arvifs))
return NULL;
/* if there already is a vif doing spectral, return that. */
list_for_each_entry(arvif, &ar->arvifs, list)
if (arvif->spectral_enabled)
return arvif;
/* otherwise, return the first vif. */
return list_first_entry(&ar->arvifs, typeof(*arvif), list);
}
static int ath10k_spectral_scan_trigger(struct ath10k *ar)
{
struct ath10k_vif *arvif;
int res;
int vdev_id;
lockdep_assert_held(&ar->conf_mutex);
arvif = ath10k_get_spectral_vdev(ar);
if (!arvif)
return -ENODEV;
vdev_id = arvif->vdev_id;
if (ar->spectral.mode == SPECTRAL_DISABLED)
return 0;
res = ath10k_wmi_vdev_spectral_enable(ar, vdev_id,
WMI_SPECTRAL_TRIGGER_CMD_CLEAR,
WMI_SPECTRAL_ENABLE_CMD_ENABLE);
if (res < 0)
return res;
res = ath10k_wmi_vdev_spectral_enable(ar, vdev_id,
WMI_SPECTRAL_TRIGGER_CMD_TRIGGER,
WMI_SPECTRAL_ENABLE_CMD_ENABLE);
if (res < 0)
return res;
return 0;
}
static int ath10k_spectral_scan_config(struct ath10k *ar,
enum ath10k_spectral_mode mode)
{
struct wmi_vdev_spectral_conf_arg arg;
struct ath10k_vif *arvif;
int vdev_id, count, res = 0;
lockdep_assert_held(&ar->conf_mutex);
arvif = ath10k_get_spectral_vdev(ar);
if (!arvif)
return -ENODEV;
vdev_id = arvif->vdev_id;
arvif->spectral_enabled = (mode != SPECTRAL_DISABLED);
ar->spectral.mode = mode;
res = ath10k_wmi_vdev_spectral_enable(ar, vdev_id,
WMI_SPECTRAL_TRIGGER_CMD_CLEAR,
WMI_SPECTRAL_ENABLE_CMD_DISABLE);
if (res < 0) {
ath10k_warn(ar, "failed to enable spectral scan: %d\n", res);
return res;
}
if (mode == SPECTRAL_DISABLED)
return 0;
if (mode == SPECTRAL_BACKGROUND)
count = WMI_SPECTRAL_COUNT_DEFAULT;
else
count = max_t(u8, 1, ar->spectral.config.count);
arg.vdev_id = vdev_id;
arg.scan_count = count;
arg.scan_period = WMI_SPECTRAL_PERIOD_DEFAULT;
arg.scan_priority = WMI_SPECTRAL_PRIORITY_DEFAULT;
arg.scan_fft_size = ar->spectral.config.fft_size;
arg.scan_gc_ena = WMI_SPECTRAL_GC_ENA_DEFAULT;
arg.scan_restart_ena = WMI_SPECTRAL_RESTART_ENA_DEFAULT;
arg.scan_noise_floor_ref = WMI_SPECTRAL_NOISE_FLOOR_REF_DEFAULT;
arg.scan_init_delay = WMI_SPECTRAL_INIT_DELAY_DEFAULT;
arg.scan_nb_tone_thr = WMI_SPECTRAL_NB_TONE_THR_DEFAULT;
arg.scan_str_bin_thr = WMI_SPECTRAL_STR_BIN_THR_DEFAULT;
arg.scan_wb_rpt_mode = WMI_SPECTRAL_WB_RPT_MODE_DEFAULT;
arg.scan_rssi_rpt_mode = WMI_SPECTRAL_RSSI_RPT_MODE_DEFAULT;
arg.scan_rssi_thr = WMI_SPECTRAL_RSSI_THR_DEFAULT;
arg.scan_pwr_format = WMI_SPECTRAL_PWR_FORMAT_DEFAULT;
arg.scan_rpt_mode = WMI_SPECTRAL_RPT_MODE_DEFAULT;
arg.scan_bin_scale = WMI_SPECTRAL_BIN_SCALE_DEFAULT;
arg.scan_dbm_adj = WMI_SPECTRAL_DBM_ADJ_DEFAULT;
arg.scan_chn_mask = WMI_SPECTRAL_CHN_MASK_DEFAULT;
res = ath10k_wmi_vdev_spectral_conf(ar, &arg);
if (res < 0) {
ath10k_warn(ar, "failed to configure spectral scan: %d\n", res);
return res;
}
return 0;
}
static ssize_t read_file_spec_scan_ctl(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath10k *ar = file->private_data;
char *mode = "";
size_t len;
enum ath10k_spectral_mode spectral_mode;
mutex_lock(&ar->conf_mutex);
spectral_mode = ar->spectral.mode;
mutex_unlock(&ar->conf_mutex);
switch (spectral_mode) {
case SPECTRAL_DISABLED:
mode = "disable";
break;
case SPECTRAL_BACKGROUND:
mode = "background";
break;
case SPECTRAL_MANUAL:
mode = "manual";
break;
}
len = strlen(mode);
return simple_read_from_buffer(user_buf, count, ppos, mode, len);
}
static ssize_t write_file_spec_scan_ctl(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath10k *ar = file->private_data;
char buf[32];
ssize_t len;
int res;
len = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, len))
return -EFAULT;
buf[len] = '\0';
mutex_lock(&ar->conf_mutex);
if (strncmp("trigger", buf, 7) == 0) {
if (ar->spectral.mode == SPECTRAL_MANUAL ||
ar->spectral.mode == SPECTRAL_BACKGROUND) {
/* reset the configuration to adopt possibly changed
* debugfs parameters
*/
res = ath10k_spectral_scan_config(ar,
ar->spectral.mode);
if (res < 0) {
ath10k_warn(ar, "failed to reconfigure spectral scan: %d\n",
res);
}
res = ath10k_spectral_scan_trigger(ar);
if (res < 0) {
ath10k_warn(ar, "failed to trigger spectral scan: %d\n",
res);
}
} else {
res = -EINVAL;
}
} else if (strncmp("background", buf, 10) == 0) {
res = ath10k_spectral_scan_config(ar, SPECTRAL_BACKGROUND);
} else if (strncmp("manual", buf, 6) == 0) {
res = ath10k_spectral_scan_config(ar, SPECTRAL_MANUAL);
} else if (strncmp("disable", buf, 7) == 0) {
res = ath10k_spectral_scan_config(ar, SPECTRAL_DISABLED);
} else {
res = -EINVAL;
}
mutex_unlock(&ar->conf_mutex);
if (res < 0)
return res;
return count;
}
static const struct file_operations fops_spec_scan_ctl = {
.read = read_file_spec_scan_ctl,
.write = write_file_spec_scan_ctl,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
static ssize_t read_file_spectral_count(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath10k *ar = file->private_data;
char buf[32];
size_t len;
u8 spectral_count;
mutex_lock(&ar->conf_mutex);
spectral_count = ar->spectral.config.count;
mutex_unlock(&ar->conf_mutex);
len = sprintf(buf, "%d\n", spectral_count);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static ssize_t write_file_spectral_count(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath10k *ar = file->private_data;
unsigned long val;
char buf[32];
ssize_t len;
len = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, len))
return -EFAULT;
buf[len] = '\0';
if (kstrtoul(buf, 0, &val))
return -EINVAL;
if (val > 255)
return -EINVAL;
mutex_lock(&ar->conf_mutex);
ar->spectral.config.count = val;
mutex_unlock(&ar->conf_mutex);
return count;
}
static const struct file_operations fops_spectral_count = {
.read = read_file_spectral_count,
.write = write_file_spectral_count,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
static ssize_t read_file_spectral_bins(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath10k *ar = file->private_data;
char buf[32];
unsigned int bins, fft_size, bin_scale;
size_t len;
mutex_lock(&ar->conf_mutex);
fft_size = ar->spectral.config.fft_size;
bin_scale = WMI_SPECTRAL_BIN_SCALE_DEFAULT;
bins = 1 << (fft_size - bin_scale);
mutex_unlock(&ar->conf_mutex);
len = sprintf(buf, "%d\n", bins);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static ssize_t write_file_spectral_bins(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath10k *ar = file->private_data;
unsigned long val;
char buf[32];
ssize_t len;
len = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, len))
return -EFAULT;
buf[len] = '\0';
if (kstrtoul(buf, 0, &val))
return -EINVAL;
if (val < 64 || val > SPECTRAL_ATH10K_MAX_NUM_BINS)
return -EINVAL;
if (!is_power_of_2(val))
return -EINVAL;
mutex_lock(&ar->conf_mutex);
ar->spectral.config.fft_size = ilog2(val);
ar->spectral.config.fft_size += WMI_SPECTRAL_BIN_SCALE_DEFAULT;
mutex_unlock(&ar->conf_mutex);
return count;
}
static const struct file_operations fops_spectral_bins = {
.read = read_file_spectral_bins,
.write = write_file_spectral_bins,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
static struct dentry *create_buf_file_handler(const char *filename,
struct dentry *parent,
umode_t mode,
struct rchan_buf *buf,
int *is_global)
{
struct dentry *buf_file;
buf_file = debugfs_create_file(filename, mode, parent, buf,
&relay_file_operations);
*is_global = 1;
return buf_file;
}
static int remove_buf_file_handler(struct dentry *dentry)
{
debugfs_remove(dentry);
return 0;
}
static struct rchan_callbacks rfs_spec_scan_cb = {
.create_buf_file = create_buf_file_handler,
.remove_buf_file = remove_buf_file_handler,
};
int ath10k_spectral_start(struct ath10k *ar)
{
struct ath10k_vif *arvif;
lockdep_assert_held(&ar->conf_mutex);
list_for_each_entry(arvif, &ar->arvifs, list)
arvif->spectral_enabled = 0;
ar->spectral.mode = SPECTRAL_DISABLED;
ar->spectral.config.count = WMI_SPECTRAL_COUNT_DEFAULT;
ar->spectral.config.fft_size = WMI_SPECTRAL_FFT_SIZE_DEFAULT;
return 0;
}
int ath10k_spectral_vif_stop(struct ath10k_vif *arvif)
{
if (!arvif->spectral_enabled)
return 0;
return ath10k_spectral_scan_config(arvif->ar, SPECTRAL_DISABLED);
}
int ath10k_spectral_create(struct ath10k *ar)
{
/* The buffer size covers whole channels in dual bands up to 128 bins.
* Scan with bigger than 128 bins needs to be run on single band each.
*/
ar->spectral.rfs_chan_spec_scan = relay_open("spectral_scan",
ar->debug.debugfs_phy,
1140, 2500,
&rfs_spec_scan_cb, NULL);
debugfs_create_file("spectral_scan_ctl",
0600,
ar->debug.debugfs_phy, ar,
&fops_spec_scan_ctl);
debugfs_create_file("spectral_count",
0600,
ar->debug.debugfs_phy, ar,
&fops_spectral_count);
debugfs_create_file("spectral_bins",
0600,
ar->debug.debugfs_phy, ar,
&fops_spectral_bins);
return 0;
}
void ath10k_spectral_destroy(struct ath10k *ar)
{
if (ar->spectral.rfs_chan_spec_scan) {
relay_close(ar->spectral.rfs_chan_spec_scan);
ar->spectral.rfs_chan_spec_scan = NULL;
}
}
|
594228.c | /* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32f4xx_hal_msp.c
* @brief This file provides code for the MSP Initialization
* and de-Initialization codes.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2021 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN Define */
/* USER CODE END Define */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN Macro */
/* USER CODE END Macro */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* External functions --------------------------------------------------------*/
/* USER CODE BEGIN ExternalFunctions */
/* USER CODE END ExternalFunctions */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* Initializes the Global MSP.
*/
void HAL_MspInit(void)
{
/* USER CODE BEGIN MspInit 0 */
/* USER CODE END MspInit 0 */
__HAL_RCC_SYSCFG_CLK_ENABLE();
__HAL_RCC_PWR_CLK_ENABLE();
/* System interrupt init*/
/* USER CODE BEGIN MspInit 1 */
/* USER CODE END MspInit 1 */
}
/**
* @brief SPI MSP Initialization
* This function configures the hardware resources used in this example
* @param hspi: SPI handle pointer
* @retval None
*/
void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(hspi->Instance==SPI1)
{
/* USER CODE BEGIN SPI1_MspInit 0 */
/* USER CODE END SPI1_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_SPI1_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**SPI1 GPIO Configuration
PA5 ------> SPI1_SCK
PA6 ------> SPI1_MISO
PA7 ------> SPI1_MOSI
*/
GPIO_InitStruct.Pin = GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF5_SPI1;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* USER CODE BEGIN SPI1_MspInit 1 */
/* USER CODE END SPI1_MspInit 1 */
}
}
/**
* @brief SPI MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param hspi: SPI handle pointer
* @retval None
*/
void HAL_SPI_MspDeInit(SPI_HandleTypeDef* hspi)
{
if(hspi->Instance==SPI1)
{
/* USER CODE BEGIN SPI1_MspDeInit 0 */
/* USER CODE END SPI1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_SPI1_CLK_DISABLE();
/**SPI1 GPIO Configuration
PA5 ------> SPI1_SCK
PA6 ------> SPI1_MISO
PA7 ------> SPI1_MOSI
*/
HAL_GPIO_DeInit(GPIOA, GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7);
/* USER CODE BEGIN SPI1_MspDeInit 1 */
/* USER CODE END SPI1_MspDeInit 1 */
}
}
/**
* @brief UART MSP Initialization
* This function configures the hardware resources used in this example
* @param huart: UART handle pointer
* @retval None
*/
void HAL_UART_MspInit(UART_HandleTypeDef* huart)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(huart->Instance==USART2)
{
/* USER CODE BEGIN USART2_MspInit 0 */
/* USER CODE END USART2_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_USART2_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**USART2 GPIO Configuration
PA2 ------> USART2_TX
PA3 ------> USART2_RX
*/
GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF7_USART2;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* USER CODE BEGIN USART2_MspInit 1 */
/* USER CODE END USART2_MspInit 1 */
}
}
/**
* @brief UART MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param huart: UART handle pointer
* @retval None
*/
void HAL_UART_MspDeInit(UART_HandleTypeDef* huart)
{
if(huart->Instance==USART2)
{
/* USER CODE BEGIN USART2_MspDeInit 0 */
/* USER CODE END USART2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_USART2_CLK_DISABLE();
/**USART2 GPIO Configuration
PA2 ------> USART2_TX
PA3 ------> USART2_RX
*/
HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2|GPIO_PIN_3);
/* USER CODE BEGIN USART2_MspDeInit 1 */
/* USER CODE END USART2_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
801650.c | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "EUTRA-RRC-Definitions"
* found in "/home/lixh/enb_folder/openair2/RRC/LTE/MESSAGES/asn1c/ASN1_files/lte-rrc-14.7.0.asn1"
* `asn1c -pdu=all -fcompound-names -gen-PER -no-gen-OER -no-gen-example -D /home/lixh/enb_folder/cmake_targets/lte_build_oai/build/CMakeFiles/RRC_Rel14`
*/
#include "LTE_SL-DiscTxPoolDedicated-r13.h"
asn_TYPE_member_t asn_MBR_LTE_SL_DiscTxPoolDedicated_r13_1[] = {
{ ATF_POINTER, 2, offsetof(struct LTE_SL_DiscTxPoolDedicated_r13, poolToReleaseList_r13),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_LTE_SL_TxPoolToReleaseList_r12,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"poolToReleaseList-r13"
},
{ ATF_POINTER, 1, offsetof(struct LTE_SL_DiscTxPoolDedicated_r13, poolToAddModList_r13),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_LTE_SL_DiscTxPoolToAddModList_r12,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"poolToAddModList-r13"
},
};
static const int asn_MAP_LTE_SL_DiscTxPoolDedicated_r13_oms_1[] = { 0, 1 };
static const ber_tlv_tag_t asn_DEF_LTE_SL_DiscTxPoolDedicated_r13_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static const asn_TYPE_tag2member_t asn_MAP_LTE_SL_DiscTxPoolDedicated_r13_tag2el_1[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* poolToReleaseList-r13 */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* poolToAddModList-r13 */
};
asn_SEQUENCE_specifics_t asn_SPC_LTE_SL_DiscTxPoolDedicated_r13_specs_1 = {
sizeof(struct LTE_SL_DiscTxPoolDedicated_r13),
offsetof(struct LTE_SL_DiscTxPoolDedicated_r13, _asn_ctx),
asn_MAP_LTE_SL_DiscTxPoolDedicated_r13_tag2el_1,
2, /* Count of tags in the map */
asn_MAP_LTE_SL_DiscTxPoolDedicated_r13_oms_1, /* Optional members */
2, 0, /* Root/Additions */
-1, /* First extension addition */
};
asn_TYPE_descriptor_t asn_DEF_LTE_SL_DiscTxPoolDedicated_r13 = {
"SL-DiscTxPoolDedicated-r13",
"SL-DiscTxPoolDedicated-r13",
&asn_OP_SEQUENCE,
asn_DEF_LTE_SL_DiscTxPoolDedicated_r13_tags_1,
sizeof(asn_DEF_LTE_SL_DiscTxPoolDedicated_r13_tags_1)
/sizeof(asn_DEF_LTE_SL_DiscTxPoolDedicated_r13_tags_1[0]), /* 1 */
asn_DEF_LTE_SL_DiscTxPoolDedicated_r13_tags_1, /* Same as above */
sizeof(asn_DEF_LTE_SL_DiscTxPoolDedicated_r13_tags_1)
/sizeof(asn_DEF_LTE_SL_DiscTxPoolDedicated_r13_tags_1[0]), /* 1 */
{ 0, 0, SEQUENCE_constraint },
asn_MBR_LTE_SL_DiscTxPoolDedicated_r13_1,
2, /* Elements count */
&asn_SPC_LTE_SL_DiscTxPoolDedicated_r13_specs_1 /* Additional specs */
};
|
355756.c | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2008 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Hartmut Holzgraefe <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id: url_scanner.c,v 1.44.2.1.2.4 2007/12/31 07:20:13 sebastian Exp $ */
#include "php.h"
#include "php_globals.h"
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "basic_functions.h"
#include "url_scanner.h"
#ifndef BUFSIZE
#define BUFSIZE 256
#endif
int php_url_scanner_activate(TSRMLS_D)
{
url_adapt(NULL,0,NULL,NULL);
return SUCCESS;
}
int php_url_scanner_deactivate(TSRMLS_D)
{
url_adapt(NULL,0,NULL,NULL);
return SUCCESS;
}
/* {{{ url_attr_addon
*/
static char *url_attr_addon(const char *tag,const char *attr,const char *val,const char *buf)
{
int flag = 0;
if (!strcasecmp(tag,"a") && !strcasecmp(attr,"href")) {
flag = 1;
} else if (!strcasecmp(tag,"area" ) && !strcasecmp(attr,"href" )) {
flag = 1;
} else if (!strcasecmp(tag,"form" ) && !strcasecmp(attr,"action" )) {
flag = 1;
} else if (!strcasecmp(tag,"frame") && !strcasecmp(attr,"source" )) {
flag = 1;
} else if (!strcasecmp(tag,"img" ) && !strcasecmp(attr,"action" )) {
flag = 1;
}
if(flag && !strstr(val,buf) && !strchr(val,':')) {
char *result;
TSRMLS_FETCH();
spprintf(&result, 0, "%s%s", (strchr(val,'?') ? PG(arg_separator).output : "?"), buf);
return result;
}
return NULL;
}
/* }}} */
#define US BG(url_adapt_state)
/* {{{ url_adapt_ext
*/
char *url_adapt_ext(const char *src, uint srclen, const char *name, const char *val, size_t *newlen)
{
char buf[1024];
snprintf(buf, sizeof(buf)-1, "%s=%s", name, val);
return url_adapt(src, srclen, buf, newlen);
}
/* }}} */
/* {{{ url_adapt
*/
char *url_adapt(const char *src, size_t srclen, const char *data, size_t *newlen)
{
char *out,*outp;
int maxl,n;
TSRMLS_FETCH();
if(src==NULL) {
US.state=STATE_NORMAL;
if(US.tag) { efree(US.tag); US.tag =NULL; }
if(US.attr) { efree(US.attr); US.attr=NULL; }
if(US.val) { efree(US.val); US.val =NULL; }
return NULL;
}
if(srclen==0)
srclen=strlen(src);
out=malloc(srclen+1);
maxl=srclen;
n=srclen;
*newlen=0;
outp=out;
while(n--) {
switch(US.state) {
case STATE_NORMAL:
if(*src=='<')
US.state=STATE_TAG_START;
break;
case STATE_TAG_START:
if(! isalnum(*src))
US.state=STATE_NORMAL;
US.state=STATE_TAG;
US.ml=BUFSIZE;
US.p=US.tag=erealloc(US.tag,US.ml);
*(US.p)++=*src;
US.l=1;
break;
case STATE_TAG:
if(isalnum(*src)) {
*(US.p)++ = *src;
US.l++;
if(US.l==US.ml) {
US.ml+=BUFSIZE;
US.tag=erealloc(US.tag,US.ml);
US.p = US.tag+US.l;
}
} else if (isspace(*src)) {
US.state = STATE_IN_TAG;
*US.p='\0';
US.tag=erealloc(US.tag,US.l);
} else {
US.state = STATE_NORMAL;
efree(US.tag);
US.tag=NULL;
}
break;
case STATE_IN_TAG:
if(isalnum(*src)) {
US.state=STATE_TAG_ATTR;
US.ml=BUFSIZE;
US.p=US.attr=erealloc(US.attr,US.ml);
*(US.p)++=*src;
US.l=1;
} else if (! isspace(*src)) {
US.state = STATE_NORMAL;
efree(US.tag);
US.tag=NULL;
}
break;
case STATE_TAG_ATTR:
if(isalnum(*src)) {
*US.p++=*src;
++US.l;
if(US.l==US.ml) {
US.ml+=BUFSIZE;
US.attr=erealloc(US.attr,US.ml);
US.p = US.attr+US.l;
}
if(US.l==US.ml) {
US.ml+=BUFSIZE;
US.attr=erealloc(US.attr,US.ml);
US.p = US.attr+US.l;
}
} else if(isspace(*src)||(*src=='=')){
US.state=STATE_TAG_IS;
*US.p=0;
US.attr=erealloc(US.attr,US.l);
} else if(*src=='>') {
US.state=STATE_NORMAL;
} else {
efree(US.attr);
US.attr=NULL;
US.state=STATE_IN_TAG;
}
break;
case STATE_TAG_IS:
case STATE_TAG_IS2:
if(*src=='>'){
US.state=STATE_NORMAL;
if(! (US.attr_done)) {
char *p;
p=url_attr_addon(US.tag,US.attr,"",data);
if(p) {
int l= strlen(p);
maxl+=l;
out=realloc(out,maxl);
outp=out+*newlen;
strlcpy(outp,p,maxl);
outp+=l;
*newlen+=l;
efree(p);
}
}
} else if(*src=='#') {
if(! (US.attr_done)) {
char *p;
US.attr_done=1;
p=url_attr_addon(US.tag,US.attr,"#",data);
if(p) {
int l= strlen(p);
maxl+=l;
out=realloc(out,maxl);
outp=out+*newlen;
strlcpy(outp, p, maxl);
outp+=l;
*newlen+=l;
efree(p);
}
}
} else if(!isspace(*src)&&(*src!='=')) {
US.ml=BUFSIZE;
US.p=US.val=erealloc(US.val,US.ml);
US.l=0;
US.attr_done=0;
if((*src=='"')||(*src=='\'')) {
US.state=STATE_TAG_QVAL2;
US.delim=*src;
} else {
US.state=STATE_TAG_VAL;
*US.p++=*src;
US.l++;
}
}
break;
case STATE_TAG_QVAL2:
if(*src=='#') {
if(! (US.attr_done)) {
char *p;
US.attr_done=1;
*US.p='\0';
p=url_attr_addon(US.tag,US.attr,US.val,data);
if(p) {
int l= strlen(p);
maxl+=l;
out=realloc(out,maxl);
outp=out+*newlen;
strlcpy(outp,p,maxl);
outp+=l;
*newlen+=l;
efree(p);
}
}
} else if(*src==US.delim) {
US.state=STATE_IN_TAG;
*US.p='\0';
if(! (US.attr_done)) {
char *p;
p=url_attr_addon(US.tag,US.attr,US.val,data);
if(p) {
int l= strlen(p);
maxl+=l;
out=realloc(out,maxl);
outp=out+*newlen;
strlcpy(outp,p,maxl);
outp+=l;
*newlen+=l;
efree(p);
}
}
break;
} else if(*src=='\\') {
US.state=STATE_TAG_QVAL2b;
} else if (*src=='>') {
US.state=STATE_NORMAL;
}
*US.p++=*src;
++US.l;
if(US.l==US.ml) {
US.ml+=BUFSIZE;
US.val=erealloc(US.val,US.ml);
US.p = US.val+US.l;
}
break;
case STATE_TAG_QVAL2b:
US.state=STATE_TAG_QVAL2;
*US.p++=*src;
++US.l;
if(US.l==US.ml) {
US.ml+=BUFSIZE;
US.val=erealloc(US.val,US.ml);
US.p = US.val+US.l;
}
break;
case STATE_TAG_VAL:
case STATE_TAG_VAL2:
if(*src=='#') {
if(! (US.attr_done)) {
char *p;
US.attr_done=1;
*US.p='\0';
p=url_attr_addon(US.tag,US.attr,US.val,data);
if(p) {
int l= strlen(p);
maxl+=l;
out=realloc(out,maxl);
outp=out+*newlen;
strlcpy(outp,p,maxl);
outp+=l;
*newlen+=l;
efree(p);
}
}
} else if(isspace(*src)||(*src=='>')) {
US.state=(*src=='>')?STATE_NORMAL:STATE_IN_TAG;
*US.p='\0';
if(! (US.attr_done)) {
char *p;
p=url_attr_addon(US.tag,US.attr,US.val,data);
if(p) {
int l= strlen(p);
maxl+=l;
out=realloc(out,maxl);
outp=out+*newlen;
strlcpy(outp,p,maxl);
outp+=l;
*newlen+=l;
efree(p);
}
}
} else {
*US.p++=*src;
US.l++;
if(US.l==US.ml) {
US.ml+=BUFSIZE;
US.val=erealloc(US.val,US.ml);
US.p = US.val+US.l;
}
}
break;
default:
break;
}
*outp++=*src++;
*newlen+=1;
}
*outp='\0';
return out;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
|
372010.c | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the program and library */
/* SCIP --- Solving Constraint Integer Programs */
/* */
/* Copyright (C) 2002-2018 Konrad-Zuse-Zentrum */
/* fuer Informationstechnik Berlin */
/* */
/* SCIP is distributed under the terms of the ZIB Academic License. */
/* */
/* You should have received a copy of the ZIB Academic License */
/* along with SCIP; see the file COPYING. If not email to [email protected]. */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file cmain.c
* @brief main file for AMPL interface
* @author Stefan Vigerske
*/
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/
#include <stdio.h>
#include <string.h>
#include "scip/scip.h"
#include "scip/scipdefplugins.h"
#include "reader_nl.h"
static
SCIP_RETCODE run(
const char* nlfile, /**< name of AMPL .nl file */
const char* setfile, /**< SCIP settings file, or NULL to try default scip.set */
SCIP_Bool interactive /**< whether to start SCIP interactive shell instead of solving command */
)
{
SCIP* scip;
char buffer[SCIP_MAXSTRLEN];
SCIP_Bool printstat;
char* logfile = NULL;
assert(nlfile != NULL);
/* setup SCIP and print version information */
SCIP_CALL( SCIPcreate(&scip) );
/* we explicitly have to enable the use of a debug solution for this main SCIP instance */
SCIPenableDebugSol(scip);
SCIPprintVersion(scip, NULL);
SCIPinfoMessage(scip, NULL, "\n");
SCIP_CALL( SCIPincludeDefaultPlugins(scip) );
SCIP_CALL( SCIPincludeReaderNl(scip) );
SCIP_CALL( SCIPaddBoolParam(scip, "display/statistics",
"whether to print statistics on a solve",
&printstat, FALSE, FALSE, NULL, NULL) );
SCIP_CALL( SCIPaddStringParam(scip, "display/logfile",
"name of file to write SCIP log to (additionally to writing to stdout)",
&logfile, FALSE, "", NULL, NULL) );
assert(logfile != NULL);
SCIPprintExternalCodes(scip, NULL);
SCIPinfoMessage(scip, NULL, "\n");
/* read setting file */
if( setfile != NULL )
{
SCIP_CALL( SCIPreadParams(scip, setfile) );
}
/* set logfile, if not default empty string */
if( *logfile )
SCIPsetMessagehdlrLogfile(scip, logfile);
/* setup commands to be executed by SCIP */
SCIP_CALL( SCIPaddDialogInputLine(scip, "display param") );
/* add .nl extension, if not given */
(void) SCIPsnprintf(buffer, SCIP_MAXSTRLEN, "read %s%s", nlfile, (strlen(nlfile) < 3 || strcmp(nlfile+(strlen(nlfile)-3), ".nl") != 0) ? ".nl" : "");
SCIP_CALL( SCIPaddDialogInputLine(scip, buffer) );
if( !interactive )
{
/* SCIP_CALL( SCIPaddDialogInputLine(scip, "display problem") ); */
SCIP_CALL( SCIPaddDialogInputLine(scip, "optimize") );
SCIP_CALL( SCIPaddDialogInputLine(scip, "write amplsol") );
if( printstat )
{
SCIP_CALL( SCIPaddDialogInputLine(scip, "display statistics") );
}
SCIP_CALL( SCIPaddDialogInputLine(scip, "quit") );
}
/* run SCIP */
SCIP_CALL( SCIPstartInteraction(scip) );
SCIP_CALL( SCIPfree(&scip) );
return SCIP_OKAY;
}
/** main method starting SCIP */
int main(
int argc, /**< number of arguments from the shell */
char** argv /**< array of shell arguments */
)
{
SCIP_RETCODE retcode;
SCIP_Bool interactive;
const char* setfile;
int i;
assert(argc >= 1);
if( argc == 1 )
{
SCIP* scip;
SCIP_CALL_ABORT( SCIPcreate(&scip) );
SCIPprintVersion(scip, NULL);
printf("\n");
SCIP_CALL_ABORT( SCIPfree(&scip) );
printf("Usage: %s <nl-file> { [-AMPL] | [<settings-file>] | -i }\n", argv[0]);
printf("\n");
printf(" -i starts the SCIP shell after reading settings and .nl file, instead of starting the SCIP solve\n");
return 0;
}
/* check command line arguments after .nl file */
interactive = FALSE;
setfile = NULL;
for( i = 2; i < argc; ++i )
{
if( strcmp(argv[i], "-AMPL") == 0 )
continue;
if( strcmp(argv[i], "-i") == 0 )
{
interactive = TRUE;
continue;
}
setfile = argv[i];
}
if( setfile == NULL && SCIPfileExists("scip.set") )
setfile = "scip.set";
retcode = run(argv[1], setfile, interactive);
/* evaluate retrun code of the SCIP process */
if( retcode != SCIP_OKAY )
{
/* write error back trace */
SCIPprintError(retcode);
return -1;
}
return 0;
}
|
433997.c | inherit ROOM;
void create()
{
set("short", "客店二楼");
set("long", @LONG
这是一间很大的客房,陈设十分简陋。靠墙放了十几张小
木床,不少客人正和衣而卧,满屋子都是呼呼的打酣声。西边
有张床是空的,你蹑手蹑脚地走了过去。
LONG);
set("sleep_room", 1);
set("no_fight", 1);
set("hotel", 1);
set("no_clean_up", 0);
set("exits", ([
"down" : __DIR__"kedian1",
]));
setup();
}
int valid_leave(object me, string dir)
{
if (dir == "down")
me->delete_temp("rent_paid");
return ::valid_leave(me, dir);
}
|
132242.c | /*
* tclIOCmd.c --
*
* Contains the definitions of most of the Tcl commands relating to IO.
*
* Copyright (c) 1995-1997 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution of
* this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include "tclInt.h"
/*
* Callback structure for accept callback in a TCP server.
*/
<<<<<<< HEAD
<<<<<<< HEAD
typedef struct AcceptCallback {
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
char *script; /* Script to invoke. */
=======
=======
typedef struct {
>>>>>>> upstream/master
Tcl_Obj *script; /* Script to invoke. */
>>>>>>> upstream/master
=======
Tcl_Obj *script; /* Script to invoke. */
>>>>>>> upstream/master
=======
Tcl_Obj *script; /* Script to invoke. */
>>>>>>> upstream/master
=======
Tcl_Obj *script; /* Script to invoke. */
>>>>>>> upstream/master
=======
typedef struct {
Tcl_Obj *script; /* Script to invoke. */
>>>>>>> upstream/master
Tcl_Interp *interp; /* Interpreter in which to run it. */
} AcceptCallback;
/*
* Thread local storage used to maintain a per-thread stdout channel obj.
* It must be per-thread because of std channel limitations.
*/
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
typedef struct ThreadSpecificData {
=======
typedef struct {
>>>>>>> upstream/master
=======
typedef struct {
>>>>>>> upstream/master
=======
typedef struct {
>>>>>>> upstream/master
int initialized; /* Set to 1 when the module is initialized. */
Tcl_Obj *stdoutObjPtr; /* Cached stdout channel Tcl_Obj */
} ThreadSpecificData;
static Tcl_ThreadDataKey dataKey;
/*
* Static functions for this file:
*/
<<<<<<< HEAD
static void FinalizeIOCmdTSD(ClientData clientData);
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
static void AcceptCallbackProc(ClientData callbackData,
Tcl_Channel chan, char *address, int port);
=======
static Tcl_TcpAcceptProc AcceptCallbackProc;
>>>>>>> upstream/master
=======
static Tcl_TcpAcceptProc AcceptCallbackProc;
>>>>>>> upstream/master
=======
static Tcl_TcpAcceptProc AcceptCallbackProc;
>>>>>>> upstream/master
=======
static Tcl_TcpAcceptProc AcceptCallbackProc;
>>>>>>> upstream/master
=======
static Tcl_TcpAcceptProc AcceptCallbackProc;
>>>>>>> upstream/master
static int ChanPendingObjCmd(ClientData unused,
Tcl_Interp *interp, int objc,
Tcl_Obj *const objv[]);
static int ChanTruncateObjCmd(ClientData dummy,
Tcl_Interp *interp, int objc,
Tcl_Obj *const objv[]);
static void RegisterTcpServerInterpCleanup(Tcl_Interp *interp,
AcceptCallback *acceptCallbackPtr);
static void TcpAcceptCallbacksDeleteProc(ClientData clientData,
Tcl_Interp *interp);
=======
static Tcl_ExitProc FinalizeIOCmdTSD;
static Tcl_TcpAcceptProc AcceptCallbackProc;
static Tcl_ObjCmdProc ChanPendingObjCmd;
static Tcl_ObjCmdProc ChanTruncateObjCmd;
static void RegisterTcpServerInterpCleanup(
Tcl_Interp *interp,
AcceptCallback *acceptCallbackPtr);
static Tcl_InterpDeleteProc TcpAcceptCallbacksDeleteProc;
>>>>>>> upstream/master
static void TcpServerCloseProc(ClientData callbackData);
static void UnregisterTcpServerInterpCleanupProc(
Tcl_Interp *interp,
AcceptCallback *acceptCallbackPtr);
/*
*----------------------------------------------------------------------
*
* FinalizeIOCmdTSD --
*
* Release the storage associated with the per-thread cache.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static void
FinalizeIOCmdTSD(
TCL_UNUSED(ClientData))
{
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
if (tsdPtr->stdoutObjPtr != NULL) {
Tcl_DecrRefCount(tsdPtr->stdoutObjPtr);
tsdPtr->stdoutObjPtr = NULL;
}
tsdPtr->initialized = 0;
}
/*
*----------------------------------------------------------------------
*
* Tcl_PutsObjCmd --
*
* This function is invoked to process the "puts" Tcl command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* Produces output on a channel.
*
*----------------------------------------------------------------------
*/
int
Tcl_PutsObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel chan; /* The channel to puts on. */
Tcl_Obj *string; /* String to write. */
Tcl_Obj *chanObjPtr = NULL; /* channel object. */
int newline; /* Add a newline at end? */
int result; /* Result of puts operation. */
int mode; /* Mode in which channel is opened. */
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
ThreadSpecificData *tsdPtr;
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
switch (objc) {
case 2: /* [puts $x] */
string = objv[1];
newline = 1;
break;
case 3: /* [puts -nonewline $x] or [puts $chan $x] */
if (strcmp(TclGetString(objv[1]), "-nonewline") == 0) {
newline = 0;
} else {
newline = 1;
chanObjPtr = objv[1];
}
string = objv[2];
break;
case 4: /* [puts -nonewline $chan $x] or
* [puts $chan $x nonewline] */
newline = 0;
if (strcmp(TclGetString(objv[1]), "-nonewline") == 0) {
chanObjPtr = objv[2];
string = objv[3];
break;
}
/* Fall through */
default: /* [puts] or
* [puts some bad number of arguments...] */
Tcl_WrongNumArgs(interp, 1, objv, "?-nonewline? ?channelId? string");
return TCL_ERROR;
}
if (chanObjPtr == NULL) {
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
tsdPtr = TCL_TSD_INIT(&dataKey);
=======
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
>>>>>>> upstream/master
=======
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
>>>>>>> upstream/master
=======
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
>>>>>>> upstream/master
if (!tsdPtr->initialized) {
tsdPtr->initialized = 1;
TclNewLiteralStringObj(tsdPtr->stdoutObjPtr, "stdout");
Tcl_IncrRefCount(tsdPtr->stdoutObjPtr);
Tcl_CreateThreadExitHandler(FinalizeIOCmdTSD, NULL);
}
chanObjPtr = tsdPtr->stdoutObjPtr;
}
if (TclGetChannelFromObj(interp, chanObjPtr, &chan, &mode, 0) != TCL_OK) {
return TCL_ERROR;
}
if (!(mode & TCL_WRITABLE)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"channel \"%s\" wasn't opened for writing",
TclGetString(chanObjPtr)));
return TCL_ERROR;
}
TclChannelPreserve(chan);
result = Tcl_WriteObj(chan, string);
if (result == -1) {
goto error;
}
if (newline != 0) {
result = Tcl_WriteChars(chan, "\n", 1);
if (result == -1) {
goto error;
}
}
TclChannelRelease(chan);
return TCL_OK;
/*
* TIP #219.
* Capture error messages put by the driver into the bypass area and put
* them into the regular interpreter result. Fall back to the regular
* message if nothing was found in the bypass.
*/
error:
if (!TclChanCaughtErrorBypass(interp, chan)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf("error writing \"%s\": %s",
TclGetString(chanObjPtr), Tcl_PosixError(interp)));
}
TclChannelRelease(chan);
return TCL_ERROR;
}
/*
*----------------------------------------------------------------------
*
* Tcl_FlushObjCmd --
*
* This function is called to process the Tcl "flush" command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* May cause output to appear on the specified channel.
*
*----------------------------------------------------------------------
*/
int
Tcl_FlushObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Obj *chanObjPtr;
Tcl_Channel chan; /* The channel to flush on. */
int mode;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "channelId");
return TCL_ERROR;
}
chanObjPtr = objv[1];
if (TclGetChannelFromObj(interp, chanObjPtr, &chan, &mode, 0) != TCL_OK) {
return TCL_ERROR;
}
if (!(mode & TCL_WRITABLE)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"channel \"%s\" wasn't opened for writing",
TclGetString(chanObjPtr)));
return TCL_ERROR;
}
TclChannelPreserve(chan);
if (Tcl_Flush(chan) != TCL_OK) {
/*
* TIP #219.
* Capture error messages put by the driver into the bypass area and
* put them into the regular interpreter result. Fall back to the
* regular message if nothing was found in the bypass.
*/
if (!TclChanCaughtErrorBypass(interp, chan)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"error flushing \"%s\": %s",
TclGetString(chanObjPtr), Tcl_PosixError(interp)));
}
TclChannelRelease(chan);
return TCL_ERROR;
}
TclChannelRelease(chan);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* Tcl_GetsObjCmd --
*
* This function is called to process the Tcl "gets" command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* May consume input from channel.
*
*----------------------------------------------------------------------
*/
int
Tcl_GetsObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel chan; /* The channel to read from. */
int lineLen; /* Length of line just read. */
int mode; /* Mode in which channel is opened. */
Tcl_Obj *linePtr, *chanObjPtr;
int code = TCL_OK;
if ((objc != 2) && (objc != 3)) {
Tcl_WrongNumArgs(interp, 1, objv, "channelId ?varName?");
return TCL_ERROR;
}
chanObjPtr = objv[1];
if (TclGetChannelFromObj(interp, chanObjPtr, &chan, &mode, 0) != TCL_OK) {
return TCL_ERROR;
}
if (!(mode & TCL_READABLE)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"channel \"%s\" wasn't opened for reading",
TclGetString(chanObjPtr)));
return TCL_ERROR;
}
TclChannelPreserve(chan);
TclNewObj(linePtr);
lineLen = Tcl_GetsObj(chan, linePtr);
if (lineLen < 0) {
if (!Tcl_Eof(chan) && !Tcl_InputBlocked(chan)) {
Tcl_DecrRefCount(linePtr);
/*
* TIP #219.
* Capture error messages put by the driver into the bypass area
* and put them into the regular interpreter result. Fall back to
* the regular message if nothing was found in the bypass.
*/
if (!TclChanCaughtErrorBypass(interp, chan)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"error reading \"%s\": %s",
TclGetString(chanObjPtr), Tcl_PosixError(interp)));
}
code = TCL_ERROR;
goto done;
}
lineLen = -1;
}
if (objc == 3) {
if (Tcl_ObjSetVar2(interp, objv[2], NULL, linePtr,
TCL_LEAVE_ERR_MSG) == NULL) {
code = TCL_ERROR;
goto done;
}
Tcl_SetObjResult(interp, Tcl_NewWideIntObj(lineLen));
} else {
Tcl_SetObjResult(interp, linePtr);
}
done:
TclChannelRelease(chan);
return code;
}
/*
*----------------------------------------------------------------------
*
* Tcl_ReadObjCmd --
*
* This function is invoked to process the Tcl "read" command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* May consume input from channel.
*
*----------------------------------------------------------------------
*/
int
Tcl_ReadObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel chan; /* The channel to read from. */
int newline, i; /* Discard newline at end? */
int toRead; /* How many bytes to read? */
int charactersRead; /* How many characters were read? */
int mode; /* Mode in which channel is opened. */
Tcl_Obj *resultPtr, *chanObjPtr;
if ((objc != 2) && (objc != 3)) {
Interp *iPtr;
argerror:
iPtr = (Interp *) interp;
Tcl_WrongNumArgs(interp, 1, objv, "channelId ?numChars?");
/*
* Do not append directly; that makes ensembles using this command as
* a subcommand produce the wrong message.
*/
iPtr->flags |= INTERP_ALTERNATE_WRONG_ARGS;
Tcl_WrongNumArgs(interp, 1, objv, "?-nonewline? channelId");
return TCL_ERROR;
}
i = 1;
newline = 0;
if (strcmp(TclGetString(objv[1]), "-nonewline") == 0) {
newline = 1;
i++;
}
if (i == objc) {
goto argerror;
}
chanObjPtr = objv[i];
if (TclGetChannelFromObj(interp, chanObjPtr, &chan, &mode, 0) != TCL_OK) {
return TCL_ERROR;
}
if (!(mode & TCL_READABLE)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"channel \"%s\" wasn't opened for reading",
TclGetString(chanObjPtr)));
return TCL_ERROR;
}
i++; /* Consumed channel name. */
/*
* Compute how many bytes to read.
*/
toRead = -1;
if (i < objc) {
if ((TclGetIntFromObj(interp, objv[i], &toRead) != TCL_OK)
|| (toRead < 0)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"expected non-negative integer but got \"%s\"",
TclGetString(objv[i])));
Tcl_SetErrorCode(interp, "TCL", "VALUE", "NUMBER", NULL);
return TCL_ERROR;
}
}
TclNewObj(resultPtr);
Tcl_IncrRefCount(resultPtr);
TclChannelPreserve(chan);
charactersRead = Tcl_ReadChars(chan, resultPtr, toRead, 0);
if (charactersRead < 0) {
/*
* TIP #219.
* Capture error messages put by the driver into the bypass area and
* put them into the regular interpreter result. Fall back to the
* regular message if nothing was found in the bypass.
*/
if (!TclChanCaughtErrorBypass(interp, chan)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"error reading \"%s\": %s",
TclGetString(chanObjPtr), Tcl_PosixError(interp)));
}
TclChannelRelease(chan);
Tcl_DecrRefCount(resultPtr);
return TCL_ERROR;
}
/*
* If requested, remove the last newline in the channel if at EOF.
*/
if ((charactersRead > 0) && (newline != 0)) {
const char *result;
size_t length;
result = TclGetStringFromObj(resultPtr, &length);
if (result[length - 1] == '\n') {
Tcl_SetObjLength(resultPtr, length - 1);
}
}
Tcl_SetObjResult(interp, resultPtr);
TclChannelRelease(chan);
Tcl_DecrRefCount(resultPtr);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* Tcl_SeekObjCmd --
*
* This function is invoked to process the Tcl "seek" command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* Moves the position of the access point on the specified channel. May
* flush queued output.
*
*----------------------------------------------------------------------
*/
int
Tcl_SeekObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel chan; /* The channel to tell on. */
Tcl_WideInt offset; /* Where to seek? */
int mode; /* How to seek? */
Tcl_WideInt result; /* Of calling Tcl_Seek. */
int optionIndex;
static const char *const originOptions[] = {
"start", "current", "end", NULL
};
static const int modeArray[] = {SEEK_SET, SEEK_CUR, SEEK_END};
if ((objc != 3) && (objc != 4)) {
Tcl_WrongNumArgs(interp, 1, objv, "channelId offset ?origin?");
return TCL_ERROR;
}
if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
return TCL_ERROR;
}
if (Tcl_GetWideIntFromObj(interp, objv[2], &offset) != TCL_OK) {
return TCL_ERROR;
}
mode = SEEK_SET;
if (objc == 4) {
if (Tcl_GetIndexFromObj(interp, objv[3], originOptions, "origin", 0,
&optionIndex) != TCL_OK) {
return TCL_ERROR;
}
mode = modeArray[optionIndex];
}
TclChannelPreserve(chan);
result = Tcl_Seek(chan, offset, mode);
if (result == -1) {
/*
* TIP #219.
* Capture error messages put by the driver into the bypass area and
* put them into the regular interpreter result. Fall back to the
* regular message if nothing was found in the bypass.
*/
if (!TclChanCaughtErrorBypass(interp, chan)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"error during seek on \"%s\": %s",
TclGetString(objv[1]), Tcl_PosixError(interp)));
}
TclChannelRelease(chan);
return TCL_ERROR;
}
TclChannelRelease(chan);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* Tcl_TellObjCmd --
*
* This function is invoked to process the Tcl "tell" command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
Tcl_TellObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel chan; /* The channel to tell on. */
Tcl_WideInt newLoc;
int code;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "channelId");
return TCL_ERROR;
}
<<<<<<< HEAD
<<<<<<< HEAD
=======
>>>>>>> upstream/master
/*
* Try to find a channel with the right name and permissions in the IO
* channel table of this interpreter.
*/
if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
return TCL_ERROR;
}
TclChannelPreserve(chan);
newLoc = Tcl_Tell(chan);
/*
* TIP #219.
* Capture error messages put by the driver into the bypass area and put
* them into the regular interpreter result.
*/
code = TclChanCaughtErrorBypass(interp, chan);
TclChannelRelease(chan);
if (code) {
return TCL_ERROR;
}
<<<<<<< HEAD
=======
/*
* Try to find a channel with the right name and permissions in the IO
* channel table of this interpreter.
*/
if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
return TCL_ERROR;
}
TclChannelPreserve(chan);
newLoc = Tcl_Tell(chan);
/*
* TIP #219.
* Capture error messages put by the driver into the bypass area and put
* them into the regular interpreter result.
*/
code = TclChanCaughtErrorBypass(interp, chan);
TclChannelRelease(chan);
if (code) {
return TCL_ERROR;
}
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
Tcl_SetObjResult(interp, Tcl_NewWideIntObj(newLoc));
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* Tcl_CloseObjCmd --
*
* This function is invoked to process the Tcl "close" command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* May discard queued input; may flush queued output.
*
*----------------------------------------------------------------------
*/
int
Tcl_CloseObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel chan; /* The channel to close. */
static const char *const dirOptions[] = {
"read", "write", NULL
};
static const int dirArray[] = {TCL_CLOSE_READ, TCL_CLOSE_WRITE};
if ((objc != 2) && (objc != 3)) {
Tcl_WrongNumArgs(interp, 1, objv, "channelId ?direction?");
return TCL_ERROR;
}
if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
return TCL_ERROR;
}
if (objc == 3) {
int index, dir;
/*
* Get direction requested to close, and check syntax.
*/
if (Tcl_GetIndexFromObj(interp, objv[2], dirOptions, "direction", 0,
&index) != TCL_OK) {
return TCL_ERROR;
}
dir = dirArray[index];
/*
* Check direction against channel mode. It is an error if we try to
* close a direction not supported by the channel (already closed, or
* never opened for that direction).
*/
if (!(dir & Tcl_GetChannelMode(chan))) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"Half-close of %s-side not possible, side not opened"
" or already closed", dirOptions[index]));
return TCL_ERROR;
}
/*
* Special handling is needed if and only if the channel mode supports
* more than the direction to close. Because if the close the last
* direction supported we can and will go through the regular
* process.
*/
if ((Tcl_GetChannelMode(chan) &
(TCL_CLOSE_READ|TCL_CLOSE_WRITE)) != dir) {
return Tcl_CloseEx(interp, chan, dir);
}
}
if (Tcl_UnregisterChannel(interp, chan) != TCL_OK) {
/*
* If there is an error message and it ends with a newline, remove the
* newline. This is done for command pipeline channels where the error
* output from the subprocesses is stored in interp's result.
*
* NOTE: This is likely to not have any effect on regular error
* messages produced by drivers during the closing of a channel,
* because the Tcl convention is that such error messages do not have
* a terminating newline.
*/
Tcl_Obj *resultPtr = Tcl_GetObjResult(interp);
const char *string;
size_t len;
if (Tcl_IsShared(resultPtr)) {
resultPtr = Tcl_DuplicateObj(resultPtr);
Tcl_SetObjResult(interp, resultPtr);
}
string = TclGetStringFromObj(resultPtr, &len);
if ((len > 0) && (string[len - 1] == '\n')) {
Tcl_SetObjLength(resultPtr, len - 1);
}
return TCL_ERROR;
}
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* Tcl_FconfigureObjCmd --
*
* This function is invoked to process the Tcl "fconfigure" command. See
* the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* May modify the behavior of an IO channel.
*
*----------------------------------------------------------------------
*/
int
Tcl_FconfigureObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
const char *optionName, *valueName;
Tcl_Channel chan; /* The channel to set a mode on. */
int i; /* Iterate over arg-value pairs. */
if ((objc < 2) || (((objc % 2) == 1) && (objc != 3))) {
Tcl_WrongNumArgs(interp, 1, objv, "channelId ?-option value ...?");
return TCL_ERROR;
}
if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
return TCL_ERROR;
}
if (objc == 2) {
Tcl_DString ds; /* DString to hold result of calling
* Tcl_GetChannelOption. */
Tcl_DStringInit(&ds);
if (Tcl_GetChannelOption(interp, chan, NULL, &ds) != TCL_OK) {
Tcl_DStringFree(&ds);
return TCL_ERROR;
}
Tcl_DStringResult(interp, &ds);
return TCL_OK;
} else if (objc == 3) {
Tcl_DString ds; /* DString to hold result of calling
* Tcl_GetChannelOption. */
Tcl_DStringInit(&ds);
optionName = TclGetString(objv[2]);
if (Tcl_GetChannelOption(interp, chan, optionName, &ds) != TCL_OK) {
Tcl_DStringFree(&ds);
return TCL_ERROR;
}
Tcl_DStringResult(interp, &ds);
return TCL_OK;
}
for (i = 3; i < objc; i += 2) {
optionName = TclGetString(objv[i-1]);
valueName = TclGetString(objv[i]);
if (Tcl_SetChannelOption(interp, chan, optionName, valueName)
!= TCL_OK) {
return TCL_ERROR;
}
}
return TCL_OK;
}
/*
*---------------------------------------------------------------------------
*
* Tcl_EofObjCmd --
*
* This function is invoked to process the Tcl "eof" command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* Sets interp's result to boolean true or false depending on whether the
* specified channel has an EOF condition.
*
*---------------------------------------------------------------------------
*/
int
Tcl_EofObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel chan;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "channelId");
return TCL_ERROR;
}
if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
return TCL_ERROR;
}
Tcl_SetObjResult(interp, Tcl_NewBooleanObj(Tcl_Eof(chan)));
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* Tcl_ExecObjCmd --
*
* This function is invoked to process the "exec" Tcl command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
int
Tcl_ExecObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Obj *resultPtr;
const char **argv; /* An array for the string arguments. Stored
* on the _Tcl_ stack. */
const char *string;
Tcl_Channel chan;
int argc, background, i, index, keepNewline, result, skip, ignoreStderr;
size_t length;
static const char *const options[] = {
"-ignorestderr", "-keepnewline", "--", NULL
};
enum execOptionsEnum {
EXEC_IGNORESTDERR, EXEC_KEEPNEWLINE, EXEC_LAST
};
/*
* Check for any leading option arguments.
*/
keepNewline = 0;
ignoreStderr = 0;
for (skip = 1; skip < objc; skip++) {
string = TclGetString(objv[skip]);
if (string[0] != '-') {
break;
}
if (Tcl_GetIndexFromObj(interp, objv[skip], options, "option",
TCL_EXACT, &index) != TCL_OK) {
return TCL_ERROR;
}
if (index == EXEC_KEEPNEWLINE) {
keepNewline = 1;
} else if (index == EXEC_IGNORESTDERR) {
ignoreStderr = 1;
} else {
skip++;
break;
}
}
if (objc <= skip) {
Tcl_WrongNumArgs(interp, 1, objv, "?-option ...? arg ?arg ...?");
return TCL_ERROR;
}
/*
* See if the command is to be run in background.
*/
background = 0;
string = TclGetString(objv[objc - 1]);
if ((string[0] == '&') && (string[1] == '\0')) {
objc--;
background = 1;
}
/*
* Create the string argument array "argv". Make sure argv is large enough
* to hold the argc arguments plus 1 extra for the zero end-of-argv word.
*/
argc = objc - skip;
<<<<<<< HEAD
<<<<<<< HEAD
argv = TclStackAlloc(interp, (unsigned)(argc + 1) * sizeof(char *));
=======
argv = TclStackAlloc(interp, (argc + 1) * sizeof(char *));
>>>>>>> upstream/master
=======
argv = (const char **)TclStackAlloc(interp, (argc + 1) * sizeof(char *));
>>>>>>> upstream/master
/*
* Copy the string conversions of each (post option) object into the
* argument vector.
*/
for (i = 0; i < argc; i++) {
argv[i] = TclGetString(objv[i + skip]);
}
argv[argc] = NULL;
chan = Tcl_OpenCommandChannel(interp, argc, argv, (background ? 0 :
ignoreStderr ? TCL_STDOUT : TCL_STDOUT|TCL_STDERR));
/*
* Free the argv array.
*/
TclStackFree(interp, (void *) argv);
if (chan == NULL) {
return TCL_ERROR;
}
if (background) {
/*
* Store the list of PIDs from the pipeline in interp's result and
* detach the PIDs (instead of waiting for them).
*/
TclGetAndDetachPids(interp, chan);
if (Tcl_CloseEx(interp, chan, 0) != TCL_OK) {
return TCL_ERROR;
}
return TCL_OK;
}
TclNewObj(resultPtr);
if (Tcl_GetChannelHandle(chan, TCL_READABLE, NULL) == TCL_OK) {
if (Tcl_ReadChars(chan, resultPtr, -1, 0) == TCL_IO_FAILURE) {
/*
* TIP #219.
* Capture error messages put by the driver into the bypass area
* and put them into the regular interpreter result. Fall back to
* the regular message if nothing was found in the bypass.
*/
if (!TclChanCaughtErrorBypass(interp, chan)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"error reading output from command: %s",
Tcl_PosixError(interp)));
Tcl_DecrRefCount(resultPtr);
}
return TCL_ERROR;
}
}
/*
* If the process produced anything on stderr, it will have been returned
* in the interpreter result. It needs to be appended to the result
* string.
*/
result = Tcl_CloseEx(interp, chan, 0);
Tcl_AppendObjToObj(resultPtr, Tcl_GetObjResult(interp));
/*
* If the last character of the result is a newline, then remove the
* newline character.
*/
if (keepNewline == 0) {
string = TclGetStringFromObj(resultPtr, &length);
if ((length > 0) && (string[length - 1] == '\n')) {
Tcl_SetObjLength(resultPtr, length - 1);
}
}
Tcl_SetObjResult(interp, resultPtr);
return result;
}
/*
*---------------------------------------------------------------------------
*
* Tcl_FblockedObjCmd --
*
* This function is invoked to process the Tcl "fblocked" command. See
* the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* Sets interp's result to boolean true or false depending on whether the
* preceeding input operation on the channel would have blocked.
*
*---------------------------------------------------------------------------
*/
int
Tcl_FblockedObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel chan;
int mode;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "channelId");
return TCL_ERROR;
}
if (TclGetChannelFromObj(interp, objv[1], &chan, &mode, 0) != TCL_OK) {
return TCL_ERROR;
}
if (!(mode & TCL_READABLE)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"channel \"%s\" wasn't opened for reading",
TclGetString(objv[1])));
return TCL_ERROR;
}
Tcl_SetObjResult(interp, Tcl_NewBooleanObj(Tcl_InputBlocked(chan)));
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* Tcl_OpenObjCmd --
*
* This function is invoked to process the "open" Tcl command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
int
Tcl_OpenObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
int pipeline, prot;
const char *modeString, *what;
Tcl_Channel chan;
if ((objc < 2) || (objc > 4)) {
Tcl_WrongNumArgs(interp, 1, objv, "fileName ?access? ?permissions?");
return TCL_ERROR;
}
prot = 0666;
if (objc == 2) {
modeString = "r";
} else {
modeString = TclGetString(objv[2]);
if (objc == 4) {
const char *permString = TclGetString(objv[3]);
int code = TCL_ERROR;
int scanned = TclParseAllWhiteSpace(permString, -1);
/*
* Support legacy octal numbers.
*/
if ((permString[scanned] == '0')
&& (permString[scanned+1] >= '0')
&& (permString[scanned+1] <= '7')) {
Tcl_Obj *permObj;
TclNewLiteralStringObj(permObj, "0o");
Tcl_AppendToObj(permObj, permString+scanned+1, -1);
code = TclGetIntFromObj(NULL, permObj, &prot);
Tcl_DecrRefCount(permObj);
}
if ((code == TCL_ERROR)
&& TclGetIntFromObj(interp, objv[3], &prot) != TCL_OK) {
return TCL_ERROR;
}
}
}
pipeline = 0;
what = TclGetString(objv[1]);
if (what[0] == '|') {
pipeline = 1;
}
/*
* Open the file or create a process pipeline.
*/
if (!pipeline) {
chan = Tcl_FSOpenFileChannel(interp, objv[1], modeString, prot);
} else {
int mode, seekFlag, cmdObjc, binary;
const char **cmdArgv;
if (Tcl_SplitList(interp, what+1, &cmdObjc, &cmdArgv) != TCL_OK) {
return TCL_ERROR;
}
mode = TclGetOpenModeEx(interp, modeString, &seekFlag, &binary);
if (mode == -1) {
chan = NULL;
} else {
int flags = TCL_STDERR | TCL_ENFORCE_MODE;
switch (mode & (O_RDONLY | O_WRONLY | O_RDWR)) {
case O_RDONLY:
flags |= TCL_STDOUT;
break;
case O_WRONLY:
flags |= TCL_STDIN;
break;
case O_RDWR:
flags |= (TCL_STDIN | TCL_STDOUT);
break;
default:
Tcl_Panic("Tcl_OpenCmd: invalid mode value");
break;
}
chan = Tcl_OpenCommandChannel(interp, cmdObjc, cmdArgv, flags);
if (binary && chan) {
Tcl_SetChannelOption(interp, chan, "-translation", "binary");
}
}
<<<<<<< HEAD
Tcl_Free(cmdArgv);
=======
Tcl_Free((void *)cmdArgv);
>>>>>>> upstream/master
}
if (chan == NULL) {
return TCL_ERROR;
}
Tcl_RegisterChannel(interp, chan);
Tcl_SetObjResult(interp, Tcl_NewStringObj(Tcl_GetChannelName(chan), -1));
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TcpAcceptCallbacksDeleteProc --
*
* Assocdata cleanup routine called when an interpreter is being deleted
* to set the interp field of all the accept callback records registered
* with the interpreter to NULL. This will prevent the interpreter from
* being used in the future to eval accept scripts.
*
* Results:
* None.
*
* Side effects:
* Deallocates memory and sets the interp field of all the accept
* callback records to NULL to prevent this interpreter from being used
* subsequently to eval accept scripts.
*
*----------------------------------------------------------------------
*/
static void
TcpAcceptCallbacksDeleteProc(
ClientData clientData, /* Data which was passed when the assocdata
* was registered. */
TCL_UNUSED(Tcl_Interp *))
{
Tcl_HashTable *hTblPtr = (Tcl_HashTable *)clientData;
Tcl_HashEntry *hPtr;
Tcl_HashSearch hSearch;
for (hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch);
hPtr != NULL; hPtr = Tcl_NextHashEntry(&hSearch)) {
AcceptCallback *acceptCallbackPtr = (AcceptCallback *)Tcl_GetHashValue(hPtr);
acceptCallbackPtr->interp = NULL;
}
Tcl_DeleteHashTable(hTblPtr);
Tcl_Free(hTblPtr);
}
/*
*----------------------------------------------------------------------
*
* RegisterTcpServerInterpCleanup --
*
* Registers an accept callback record to have its interp field set to
* NULL when the interpreter is deleted.
*
* Results:
* None.
*
* Side effects:
* When, in the future, the interpreter is deleted, the interp field of
* the accept callback data structure will be set to NULL. This will
* prevent attempts to eval the accept script in a deleted interpreter.
*
*----------------------------------------------------------------------
*/
static void
RegisterTcpServerInterpCleanup(
Tcl_Interp *interp, /* Interpreter for which we want to be
* informed of deletion. */
AcceptCallback *acceptCallbackPtr)
/* The accept callback record whose interp
* field we want set to NULL when the
* interpreter is deleted. */
{
Tcl_HashTable *hTblPtr; /* Hash table for accept callback records to
* smash when the interpreter will be
* deleted. */
Tcl_HashEntry *hPtr; /* Entry for this record. */
int isNew; /* Is the entry new? */
hTblPtr = (Tcl_HashTable *)Tcl_GetAssocData(interp, "tclTCPAcceptCallbacks", NULL);
if (hTblPtr == NULL) {
hTblPtr = (Tcl_HashTable *)Tcl_Alloc(sizeof(Tcl_HashTable));
Tcl_InitHashTable(hTblPtr, TCL_ONE_WORD_KEYS);
Tcl_SetAssocData(interp, "tclTCPAcceptCallbacks",
TcpAcceptCallbacksDeleteProc, hTblPtr);
}
hPtr = Tcl_CreateHashEntry(hTblPtr, acceptCallbackPtr, &isNew);
if (!isNew) {
Tcl_Panic("RegisterTcpServerCleanup: damaged accept record table");
}
Tcl_SetHashValue(hPtr, acceptCallbackPtr);
}
/*
*----------------------------------------------------------------------
*
* UnregisterTcpServerInterpCleanupProc --
*
* Unregister a previously registered accept callback record. The interp
* field of this record will no longer be set to NULL in the future when
* the interpreter is deleted.
*
* Results:
* None.
*
* Side effects:
* Prevents the interp field of the accept callback record from being set
* to NULL in the future when the interpreter is deleted.
*
*----------------------------------------------------------------------
*/
static void
UnregisterTcpServerInterpCleanupProc(
Tcl_Interp *interp, /* Interpreter in which the accept callback
* record was registered. */
AcceptCallback *acceptCallbackPtr)
/* The record for which to delete the
* registration. */
{
Tcl_HashTable *hTblPtr;
Tcl_HashEntry *hPtr;
hTblPtr = (Tcl_HashTable *)Tcl_GetAssocData(interp, "tclTCPAcceptCallbacks", NULL);
if (hTblPtr == NULL) {
return;
}
hPtr = Tcl_FindHashEntry(hTblPtr, (char *) acceptCallbackPtr);
if (hPtr != NULL) {
Tcl_DeleteHashEntry(hPtr);
}
}
/*
*----------------------------------------------------------------------
*
* AcceptCallbackProc --
*
* This callback is invoked by the TCP channel driver when it accepts a
* new connection from a client on a server socket.
*
* Results:
* None.
*
* Side effects:
* Whatever the script does.
*
*----------------------------------------------------------------------
*/
static void
AcceptCallbackProc(
ClientData callbackData, /* The data stored when the callback was
* created in the call to
* Tcl_OpenTcpServer. */
Tcl_Channel chan, /* Channel for the newly accepted
* connection. */
char *address, /* Address of client that was accepted. */
int port) /* Port of client that was accepted. */
{
AcceptCallback *acceptCallbackPtr = (AcceptCallback *)callbackData;
/*
* Check if the callback is still valid; the interpreter may have gone
* away, this is signalled by setting the interp field of the callback
* data to NULL.
*/
if (acceptCallbackPtr->interp != NULL) {
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
char portBuf[TCL_INTEGER_SPACE];
char *script = acceptCallbackPtr->script;
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
Tcl_Interp *interp = acceptCallbackPtr->interp;
Tcl_Obj *script, *objv[2];
int result = TCL_OK;
objv[0] = acceptCallbackPtr->script;
objv[1] = Tcl_NewListObj(3, NULL);
Tcl_ListObjAppendElement(NULL, objv[1], Tcl_NewStringObj(
Tcl_GetChannelName(chan), -1));
Tcl_ListObjAppendElement(NULL, objv[1], Tcl_NewStringObj(address, -1));
<<<<<<< HEAD
Tcl_ListObjAppendElement(NULL, objv[1], Tcl_NewIntObj(port));
<<<<<<< HEAD
<<<<<<< HEAD
TclFormatInt(portBuf, port);
=======
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
Tcl_Interp *interp = acceptCallbackPtr->interp;
Tcl_Obj *script, *objv[2];
int result = TCL_OK;
objv[0] = acceptCallbackPtr->script;
objv[1] = Tcl_NewListObj(3, NULL);
Tcl_ListObjAppendElement(NULL, objv[1], Tcl_NewStringObj(
Tcl_GetChannelName(chan), -1));
Tcl_ListObjAppendElement(NULL, objv[1], Tcl_NewStringObj(address, -1));
Tcl_ListObjAppendElement(NULL, objv[1], Tcl_NewIntObj(port));
=======
>>>>>>> upstream/master
script = Tcl_ConcatObj(2, objv);
Tcl_IncrRefCount(script);
Tcl_DecrRefCount(objv[1]);
Tcl_Preserve(interp);
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
=======
=======
Tcl_ListObjAppendElement(NULL, objv[1], Tcl_NewWideIntObj(port));
>>>>>>> upstream/master
script = Tcl_ConcatObj(2, objv);
Tcl_IncrRefCount(script);
Tcl_DecrRefCount(objv[1]);
Tcl_Preserve(interp);
>>>>>>> upstream/master
Tcl_RegisterChannel(interp, chan);
/*
* Artificially bump the refcount to protect the channel from being
* deleted while the script is being evaluated.
*/
Tcl_RegisterChannel(NULL, chan);
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
result = Tcl_VarEval(interp, script, " ", Tcl_GetChannelName(chan),
" ", address, " ", portBuf, NULL);
=======
result = Tcl_EvalObjEx(interp, script, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL);
Tcl_DecrRefCount(script);
>>>>>>> upstream/master
=======
result = Tcl_EvalObjEx(interp, script, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL);
Tcl_DecrRefCount(script);
>>>>>>> upstream/master
=======
result = Tcl_EvalObjEx(interp, script, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL);
Tcl_DecrRefCount(script);
>>>>>>> upstream/master
=======
result = Tcl_EvalObjEx(interp, script, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL);
Tcl_DecrRefCount(script);
>>>>>>> upstream/master
=======
result = Tcl_EvalObjEx(interp, script, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL);
Tcl_DecrRefCount(script);
>>>>>>> upstream/master
if (result != TCL_OK) {
Tcl_BackgroundException(interp, result);
Tcl_UnregisterChannel(interp, chan);
}
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
/*
* Decrement the artificially bumped refcount. After this it is not
* safe anymore to use "chan", because it may now be deleted.
*/
Tcl_UnregisterChannel(NULL, chan);
Tcl_Release(interp);
<<<<<<< HEAD
<<<<<<< HEAD
Tcl_Release(script);
=======
/*
* Decrement the artificially bumped refcount. After this it is not
* safe anymore to use "chan", because it may now be deleted.
*/
Tcl_UnregisterChannel(NULL, chan);
Tcl_Release(interp);
>>>>>>> upstream/master
} else {
/*
* The interpreter has been deleted, so there is no useful way to use
* the client socket - just close it.
*/
<<<<<<< HEAD
=======
/*
* Decrement the artificially bumped refcount. After this it is not
* safe anymore to use "chan", because it may now be deleted.
*/
<<<<<<< HEAD
Tcl_UnregisterChannel(NULL, chan);
Tcl_Release(interp);
} else {
/*
* The interpreter has been deleted, so there is no useful way to use
* the client socket - just close it.
*/
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
=======
/*
* Decrement the artificially bumped refcount. After this it is not
* safe anymore to use "chan", because it may now be deleted.
*/
Tcl_UnregisterChannel(NULL, chan);
Tcl_Release(interp);
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
} else {
/*
* The interpreter has been deleted, so there is no useful way to use
* the client socket - just close it.
*/
>>>>>>> upstream/master
Tcl_Close(NULL, chan);
=======
Tcl_CloseEx(NULL, chan, 0);
>>>>>>> upstream/master
}
}
/*
*----------------------------------------------------------------------
*
* TcpServerCloseProc --
*
* This callback is called when the TCP server channel for which it was
* registered is being closed. It informs the interpreter in which the
* accept script is evaluated (if that interpreter still exists) that
* this channel no longer needs to be informed if the interpreter is
* deleted.
*
* Results:
* None.
*
* Side effects:
* In the future, if the interpreter is deleted this channel will no
* longer be informed.
*
*----------------------------------------------------------------------
*/
static void
TcpServerCloseProc(
ClientData callbackData) /* The data passed in the call to
* Tcl_CreateCloseHandler. */
{
AcceptCallback *acceptCallbackPtr = (AcceptCallback *)callbackData;
/* The actual data. */
if (acceptCallbackPtr->interp != NULL) {
UnregisterTcpServerInterpCleanupProc(acceptCallbackPtr->interp,
acceptCallbackPtr);
}
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
Tcl_EventuallyFree(acceptCallbackPtr->script, TCL_DYNAMIC);
=======
Tcl_DecrRefCount(acceptCallbackPtr->script);
>>>>>>> upstream/master
=======
Tcl_DecrRefCount(acceptCallbackPtr->script);
>>>>>>> upstream/master
=======
Tcl_DecrRefCount(acceptCallbackPtr->script);
<<<<<<< HEAD
>>>>>>> upstream/master
=======
Tcl_DecrRefCount(acceptCallbackPtr->script);
>>>>>>> upstream/master
ckfree(acceptCallbackPtr);
=======
Tcl_Free(acceptCallbackPtr);
>>>>>>> upstream/master
=======
Tcl_DecrRefCount(acceptCallbackPtr->script);
Tcl_Free(acceptCallbackPtr);
>>>>>>> upstream/master
}
/*
*----------------------------------------------------------------------
*
* Tcl_SocketObjCmd --
*
* This function is invoked to process the "socket" Tcl command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* Creates a socket based channel.
*
*----------------------------------------------------------------------
*/
int
Tcl_SocketObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
static const char *const socketOptions[] = {
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
"-async", "-myaddr", "-myport", "-server", NULL
=======
"-async", "-myaddr", "-myport", "-reuseaddr", "-reuseport", "-server",
NULL
>>>>>>> upstream/master
=======
"-async", "-myaddr", "-myport", "-reuseaddr", "-reuseport", "-server",
NULL
>>>>>>> upstream/master
};
enum socketOptions {
SKT_ASYNC, SKT_MYADDR, SKT_MYPORT, SKT_REUSEADDR, SKT_REUSEPORT,
SKT_SERVER
};
<<<<<<< HEAD
<<<<<<< HEAD
int optionIndex, a, server = 0, port, myport = 0, async = 0;
<<<<<<< HEAD
<<<<<<< HEAD
const char *host, *script = NULL, *myaddr = NULL;
=======
const char *host, *myaddr = NULL;
Tcl_Obj *script = NULL;
>>>>>>> upstream/master
=======
const char *host, *myaddr = NULL;
Tcl_Obj *script = NULL;
>>>>>>> upstream/master
=======
"-async", "-myaddr", "-myport", "-reuseaddr", "-reuseport", "-server",
NULL
};
enum socketOptionsEnum {
SKT_ASYNC, SKT_MYADDR, SKT_MYPORT, SKT_REUSEADDR, SKT_REUSEPORT,
SKT_SERVER
};
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
int optionIndex, a, server = 0, myport = 0, async = 0, reusep = -1,
reusea = -1;
unsigned int flags = 0;
const char *host, *port, *myaddr = NULL;
Tcl_Obj *script = NULL;
<<<<<<< HEAD
<<<<<<< HEAD
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
Tcl_Channel chan;
if (TclpHasSockets(interp) != TCL_OK) {
return TCL_ERROR;
}
for (a = 1; a < objc; a++) {
const char *arg = TclGetString(objv[a]);
if (arg[0] != '-') {
break;
}
if (Tcl_GetIndexFromObj(interp, objv[a], socketOptions, "option",
TCL_EXACT, &optionIndex) != TCL_OK) {
return TCL_ERROR;
}
switch ((enum socketOptionsEnum) optionIndex) {
case SKT_ASYNC:
if (server == 1) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"cannot set -async option for server sockets", -1));
return TCL_ERROR;
}
async = 1;
break;
case SKT_MYADDR:
a++;
if (a >= objc) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"no argument given for -myaddr option", -1));
return TCL_ERROR;
}
myaddr = TclGetString(objv[a]);
break;
case SKT_MYPORT: {
const char *myPortName;
a++;
if (a >= objc) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"no argument given for -myport option", -1));
return TCL_ERROR;
}
myPortName = TclGetString(objv[a]);
if (TclSockGetPort(interp, myPortName, "tcp", &myport) != TCL_OK) {
return TCL_ERROR;
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
}
break;
}
case SKT_SERVER:
if (async == 1) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"cannot set -async option for server sockets", -1));
return TCL_ERROR;
}
<<<<<<< HEAD
<<<<<<< HEAD
=======
}
break;
}
case SKT_SERVER:
if (async == 1) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"cannot set -async option for server sockets", -1));
return TCL_ERROR;
}
>>>>>>> upstream/master
server = 1;
a++;
if (a >= objc) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"no argument given for -server option", -1));
<<<<<<< HEAD
<<<<<<< HEAD
return TCL_ERROR;
}
<<<<<<< HEAD
script = TclGetString(objv[a]);
=======
script = objv[a];
>>>>>>> upstream/master
=======
server = 1;
a++;
if (a >= objc) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"no argument given for -server option", -1));
return TCL_ERROR;
}
script = objv[a];
>>>>>>> upstream/master
=======
server = 1;
a++;
if (a >= objc) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"no argument given for -server option", -1));
return TCL_ERROR;
}
script = objv[a];
break;
case SKT_REUSEADDR:
a++;
if (a >= objc) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"no argument given for -reuseaddr option", -1));
return TCL_ERROR;
}
if (Tcl_GetBooleanFromObj(interp, objv[a], &reusea) != TCL_OK) {
return TCL_ERROR;
}
break;
case SKT_REUSEPORT:
a++;
if (a >= objc) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"no argument given for -reuseport option", -1));
return TCL_ERROR;
}
if (Tcl_GetBooleanFromObj(interp, objv[a], &reusep) != TCL_OK) {
return TCL_ERROR;
}
>>>>>>> upstream/master
=======
return TCL_ERROR;
}
script = objv[a];
break;
case SKT_REUSEADDR:
a++;
if (a >= objc) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"no argument given for -reuseaddr option", -1));
return TCL_ERROR;
}
if (Tcl_GetBooleanFromObj(interp, objv[a], &reusea) != TCL_OK) {
return TCL_ERROR;
}
break;
case SKT_REUSEPORT:
a++;
if (a >= objc) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"no argument given for -reuseport option", -1));
return TCL_ERROR;
}
if (Tcl_GetBooleanFromObj(interp, objv[a], &reusep) != TCL_OK) {
return TCL_ERROR;
}
>>>>>>> upstream/master
=======
return TCL_ERROR;
}
script = objv[a];
break;
case SKT_REUSEADDR:
a++;
if (a >= objc) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"no argument given for -reuseaddr option", -1));
return TCL_ERROR;
}
if (Tcl_GetBooleanFromObj(interp, objv[a], &reusea) != TCL_OK) {
return TCL_ERROR;
}
break;
case SKT_REUSEPORT:
a++;
if (a >= objc) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"no argument given for -reuseport option", -1));
return TCL_ERROR;
}
if (Tcl_GetBooleanFromObj(interp, objv[a], &reusep) != TCL_OK) {
return TCL_ERROR;
}
>>>>>>> upstream/master
break;
default:
Tcl_Panic("Tcl_SocketObjCmd: bad option index to SocketOptions");
}
}
if (server) {
host = myaddr; /* NULL implies INADDR_ANY */
if (myport != 0) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"option -myport is not valid for servers", -1));
return TCL_ERROR;
}
} else if (a < objc) {
host = TclGetString(objv[a]);
a++;
} else {
Interp *iPtr;
wrongNumArgs:
iPtr = (Interp *) interp;
Tcl_WrongNumArgs(interp, 1, objv,
"?-myaddr addr? ?-myport myport? ?-async? host port");
iPtr->flags |= INTERP_ALTERNATE_WRONG_ARGS;
Tcl_WrongNumArgs(interp, 1, objv,
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
"-server command ?-myaddr addr? port");
return TCL_ERROR;
}
if (a == objc-1) {
if (TclSockGetPort(interp, TclGetString(objv[a]), "tcp",
&port) != TCL_OK) {
return TCL_ERROR;
}
} else {
=======
"-server command ?-reuseaddr boolean? ?-reuseport boolean? "
"?-myaddr addr? port");
return TCL_ERROR;
}
=======
"-server command ?-reuseaddr boolean? ?-reuseport boolean? "
"?-myaddr addr? port");
return TCL_ERROR;
}
>>>>>>> upstream/master
=======
"-server command ?-reuseaddr boolean? ?-reuseport boolean? "
"?-myaddr addr? port");
return TCL_ERROR;
}
>>>>>>> upstream/master
if (!server && (reusea != -1 || reusep != -1)) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"options -reuseaddr and -reuseport are only valid for servers",
-1));
return TCL_ERROR;
}
/*
* Set the options to their default value if the user didn't override
* their value.
*/
if (reusep == -1) {
reusep = 0;
}
if (reusea == -1) {
reusea = 1;
}
/*
* Build the bitset with the flags values.
*/
if (reusea) {
flags |= TCL_TCPSERVER_REUSEADDR;
}
if (reusep) {
flags |= TCL_TCPSERVER_REUSEPORT;
}
/*
* All the arguments should have been parsed by now, 'a' points to the
* last one, the port number.
*/
if (a != objc-1) {
<<<<<<< HEAD
<<<<<<< HEAD
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
goto wrongNumArgs;
}
port = TclGetString(objv[a]);
if (server) {
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
AcceptCallback *acceptCallbackPtr =
ckalloc(sizeof(AcceptCallback));
<<<<<<< HEAD
<<<<<<< HEAD
unsigned len = strlen(script) + 1;
char *copyScript = ckalloc(len);
memcpy(copyScript, script, len);
acceptCallbackPtr->script = copyScript;
=======
Tcl_IncrRefCount(script);
acceptCallbackPtr->script = script;
>>>>>>> upstream/master
=======
Tcl_IncrRefCount(script);
acceptCallbackPtr->script = script;
>>>>>>> upstream/master
=======
AcceptCallback *acceptCallbackPtr = ckalloc(sizeof(AcceptCallback));
=======
AcceptCallback *acceptCallbackPtr = Tcl_Alloc(sizeof(AcceptCallback));
>>>>>>> upstream/master
Tcl_IncrRefCount(script);
acceptCallbackPtr->script = script;
>>>>>>> upstream/master
=======
AcceptCallback *acceptCallbackPtr = Tcl_Alloc(sizeof(AcceptCallback));
Tcl_IncrRefCount(script);
acceptCallbackPtr->script = script;
>>>>>>> upstream/master
acceptCallbackPtr->interp = interp;
chan = Tcl_OpenTcpServerEx(interp, port, host, flags,
AcceptCallbackProc, acceptCallbackPtr);
if (chan == NULL) {
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
ckfree(copyScript);
=======
Tcl_DecrRefCount(script);
>>>>>>> upstream/master
=======
Tcl_DecrRefCount(script);
>>>>>>> upstream/master
=======
AcceptCallback *acceptCallbackPtr = ckalloc(sizeof(AcceptCallback));
=======
AcceptCallback *acceptCallbackPtr = (AcceptCallback *)Tcl_Alloc(sizeof(AcceptCallback));
>>>>>>> upstream/master
Tcl_IncrRefCount(script);
acceptCallbackPtr->script = script;
acceptCallbackPtr->interp = interp;
chan = Tcl_OpenTcpServerEx(interp, port, host, flags,
AcceptCallbackProc, acceptCallbackPtr);
if (chan == NULL) {
Tcl_DecrRefCount(script);
>>>>>>> upstream/master
=======
Tcl_DecrRefCount(script);
<<<<<<< HEAD
>>>>>>> upstream/master
ckfree(acceptCallbackPtr);
=======
Tcl_Free(acceptCallbackPtr);
>>>>>>> upstream/master
=======
Tcl_DecrRefCount(script);
Tcl_Free(acceptCallbackPtr);
>>>>>>> upstream/master
return TCL_ERROR;
}
/*
* Register with the interpreter to let us know when the interpreter
* is deleted (by having the callback set the interp field of the
* acceptCallbackPtr's structure to NULL). This is to avoid trying to
* eval the script in a deleted interpreter.
*/
RegisterTcpServerInterpCleanup(interp, acceptCallbackPtr);
/*
* Register a close callback. This callback will inform the
* interpreter (if it still exists) that this channel does not need to
* be informed when the interpreter is deleted.
*/
Tcl_CreateCloseHandler(chan, TcpServerCloseProc, acceptCallbackPtr);
} else {
<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
chan = Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async);
=======
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
int portNum;
if (TclSockGetPort(interp, port, "tcp", &portNum) != TCL_OK) {
return TCL_ERROR;
}
chan = Tcl_OpenTcpClient(interp, portNum, host, myaddr, myport, async);
<<<<<<< HEAD
<<<<<<< HEAD
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
=======
>>>>>>> upstream/master
if (chan == NULL) {
return TCL_ERROR;
}
}
Tcl_RegisterChannel(interp, chan);
Tcl_SetObjResult(interp, Tcl_NewStringObj(Tcl_GetChannelName(chan), -1));
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* Tcl_FcopyObjCmd --
*
* This function is invoked to process the "fcopy" Tcl command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* Moves data between two channels and possibly sets up a background copy
* handler.
*
*----------------------------------------------------------------------
*/
int
Tcl_FcopyObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel inChan, outChan;
int mode, i, index;
Tcl_WideInt toRead;
Tcl_Obj *cmdPtr;
static const char *const switches[] = { "-size", "-command", NULL };
enum { FcopySize, FcopyCommand };
if ((objc < 3) || (objc > 7) || (objc == 4) || (objc == 6)) {
Tcl_WrongNumArgs(interp, 1, objv,
"input output ?-size size? ?-command callback?");
return TCL_ERROR;
}
/*
* Parse the channel arguments and verify that they are readable or
* writable, as appropriate.
*/
if (TclGetChannelFromObj(interp, objv[1], &inChan, &mode, 0) != TCL_OK) {
return TCL_ERROR;
}
if (!(mode & TCL_READABLE)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"channel \"%s\" wasn't opened for reading",
TclGetString(objv[1])));
return TCL_ERROR;
}
if (TclGetChannelFromObj(interp, objv[2], &outChan, &mode, 0) != TCL_OK) {
return TCL_ERROR;
}
if (!(mode & TCL_WRITABLE)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"channel \"%s\" wasn't opened for writing",
TclGetString(objv[2])));
return TCL_ERROR;
}
toRead = -1;
cmdPtr = NULL;
for (i = 3; i < objc; i += 2) {
if (Tcl_GetIndexFromObj(interp, objv[i], switches, "option", 0,
&index) != TCL_OK) {
return TCL_ERROR;
}
switch (index) {
case FcopySize:
if (Tcl_GetWideIntFromObj(interp, objv[i+1], &toRead) != TCL_OK) {
return TCL_ERROR;
}
if (toRead < 0) {
/*
* Handle all negative sizes like -1, meaning 'copy all'. By
* resetting toRead we avoid changes in the core copying
* functions (which explicitly check for -1 and crash on any
* other negative value).
*/
toRead = -1;
}
break;
case FcopyCommand:
cmdPtr = objv[i+1];
break;
}
}
return TclCopyChannel(interp, inChan, outChan, toRead, cmdPtr);
}
/*
*---------------------------------------------------------------------------
*
* ChanPendingObjCmd --
*
* This function is invoked to process the Tcl "chan pending" command
* (TIP #287). See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* Sets interp's result to the number of bytes of buffered input or
* output (depending on whether the first argument is "input" or
* "output"), or -1 if the channel wasn't opened for that mode.
*
*---------------------------------------------------------------------------
*/
static int
ChanPendingObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel chan;
int index, mode;
static const char *const options[] = {"input", "output", NULL};
enum pendingOptionsEnum {PENDING_INPUT, PENDING_OUTPUT};
if (objc != 3) {
Tcl_WrongNumArgs(interp, 1, objv, "mode channelId");
return TCL_ERROR;
}
if (Tcl_GetIndexFromObj(interp, objv[1], options, "mode", 0,
&index) != TCL_OK) {
return TCL_ERROR;
}
if (TclGetChannelFromObj(interp, objv[2], &chan, &mode, 0) != TCL_OK) {
return TCL_ERROR;
}
switch ((enum pendingOptionsEnum) index) {
case PENDING_INPUT:
if (!(mode & TCL_READABLE)) {
Tcl_SetObjResult(interp, Tcl_NewWideIntObj(-1));
} else {
Tcl_SetObjResult(interp, Tcl_NewWideIntObj(Tcl_InputBuffered(chan)));
}
break;
case PENDING_OUTPUT:
if (!(mode & TCL_WRITABLE)) {
Tcl_SetObjResult(interp, Tcl_NewWideIntObj(-1));
} else {
Tcl_SetObjResult(interp, Tcl_NewWideIntObj(Tcl_OutputBuffered(chan)));
}
break;
}
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ChanTruncateObjCmd --
*
* This function is invoked to process the "chan truncate" Tcl command.
* See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* Truncates a channel (or rather a file underlying a channel).
*
*----------------------------------------------------------------------
*/
static int
ChanTruncateObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel chan;
Tcl_WideInt length;
if ((objc < 2) || (objc > 3)) {
Tcl_WrongNumArgs(interp, 1, objv, "channelId ?length?");
return TCL_ERROR;
}
if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
return TCL_ERROR;
}
if (objc == 3) {
/*
* User is supplying an explicit length.
*/
if (Tcl_GetWideIntFromObj(interp, objv[2], &length) != TCL_OK) {
return TCL_ERROR;
}
if (length < 0) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"cannot truncate to negative length of file", -1));
return TCL_ERROR;
}
} else {
/*
* User wants to truncate to the current file position.
*/
length = Tcl_Tell(chan);
if (length == -1) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"could not determine current location in \"%s\": %s",
TclGetString(objv[1]), Tcl_PosixError(interp)));
return TCL_ERROR;
}
}
if (Tcl_TruncateChannel(chan, length) != TCL_OK) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"error during truncate on \"%s\": %s",
TclGetString(objv[1]), Tcl_PosixError(interp)));
return TCL_ERROR;
}
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ChanPipeObjCmd --
*
* This function is invoked to process the "chan pipe" Tcl command.
* See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* Creates a pair of Tcl channels wrapping both ends of a new
* anonymous pipe.
*
*----------------------------------------------------------------------
*/
static int
ChanPipeObjCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Channel rchan, wchan;
const char *channelNames[2];
Tcl_Obj *resultPtr;
if (objc != 1) {
Tcl_WrongNumArgs(interp, 1, objv, "");
return TCL_ERROR;
}
if (Tcl_CreatePipe(interp, &rchan, &wchan, 0) != TCL_OK) {
return TCL_ERROR;
}
channelNames[0] = Tcl_GetChannelName(rchan);
channelNames[1] = Tcl_GetChannelName(wchan);
TclNewObj(resultPtr);
Tcl_ListObjAppendElement(NULL, resultPtr,
Tcl_NewStringObj(channelNames[0], -1));
Tcl_ListObjAppendElement(NULL, resultPtr,
Tcl_NewStringObj(channelNames[1], -1));
Tcl_SetObjResult(interp, resultPtr);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TclChannelNamesCmd --
*
* This function is invoked to process the "chan names" and "file
* channels" Tcl commands. See the user documentation for details on
* what they do.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
TclChannelNamesCmd(
TCL_UNUSED(ClientData),
Tcl_Interp *interp,
int objc,
Tcl_Obj *const objv[])
{
if (objc < 1 || objc > 2) {
Tcl_WrongNumArgs(interp, 1, objv, "?pattern?");
return TCL_ERROR;
}
return Tcl_GetChannelNamesEx(interp,
((objc == 1) ? NULL : TclGetString(objv[1])));
}
/*
*----------------------------------------------------------------------
*
* TclInitChanCmd --
*
* This function is invoked to create the "chan" Tcl command. See the
* user documentation for details on what it does.
*
* Results:
* A Tcl command handle.
*
* Side effects:
* None (since nothing is byte-compiled).
*
*----------------------------------------------------------------------
*/
Tcl_Command
TclInitChanCmd(
Tcl_Interp *interp)
{
/*
* Most commands are plugged directly together, but some are done via
* alias-like rewriting; [chan configure] is this way for security reasons
* (want overwriting of [fconfigure] to control that nicely), and [chan
* names] because the functionality isn't available as a separate command
* function at the moment.
*/
static const EnsembleImplMap initMap[] = {
{"blocked", Tcl_FblockedObjCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
{"close", Tcl_CloseObjCmd, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0},
{"copy", Tcl_FcopyObjCmd, NULL, NULL, NULL, 0},
{"create", TclChanCreateObjCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0}, /* TIP #219 */
{"eof", Tcl_EofObjCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
{"event", Tcl_FileEventObjCmd, TclCompileBasic2Or3ArgCmd, NULL, NULL, 0},
{"flush", Tcl_FlushObjCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
{"gets", Tcl_GetsObjCmd, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0},
{"names", TclChannelNamesCmd, TclCompileBasic0Or1ArgCmd, NULL, NULL, 0},
{"pending", ChanPendingObjCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0}, /* TIP #287 */
{"pipe", ChanPipeObjCmd, TclCompileBasic0ArgCmd, NULL, NULL, 0}, /* TIP #304 */
{"pop", TclChanPopObjCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0}, /* TIP #230 */
{"postevent", TclChanPostEventObjCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0}, /* TIP #219 */
{"push", TclChanPushObjCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0}, /* TIP #230 */
{"puts", Tcl_PutsObjCmd, NULL, NULL, NULL, 0},
{"read", Tcl_ReadObjCmd, NULL, NULL, NULL, 0},
{"seek", Tcl_SeekObjCmd, TclCompileBasic2Or3ArgCmd, NULL, NULL, 0},
{"tell", Tcl_TellObjCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
{"truncate", ChanTruncateObjCmd, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0}, /* TIP #208 */
{NULL, NULL, NULL, NULL, NULL, 0}
};
static const char *const extras[] = {
"configure", "::fconfigure",
NULL
};
Tcl_Command ensemble;
Tcl_Obj *mapObj;
int i;
ensemble = TclMakeEnsemble(interp, "chan", initMap);
Tcl_GetEnsembleMappingDict(NULL, ensemble, &mapObj);
for (i=0 ; extras[i] ; i+=2) {
/*
* Can assume that reference counts are all incremented.
*/
Tcl_DictObjPut(NULL, mapObj, Tcl_NewStringObj(extras[i], -1),
Tcl_NewStringObj(extras[i+1], -1));
}
Tcl_SetEnsembleMappingDict(interp, ensemble, mapObj);
return ensemble;
}
/*
* Local Variables:
* mode: c
* c-basic-offset: 4
* fill-column: 78
* End:
*/
|
115504.c | // Copyright 2018-2021, Collabora, Ltd.
// SPDX-License-Identifier: BSL-1.0
/*!
* @file
* @brief Holds swapchain related functions.
* @author Jakob Bornecrantz <[email protected]>
* @ingroup oxr_main
*/
#include <stdlib.h>
#include "xrt/xrt_gfx_xlib.h"
#include "util/u_debug.h"
#include "util/u_misc.h"
#include "oxr_objects.h"
#include "oxr_logger.h"
#include "oxr_handle.h"
static XrResult
oxr_swapchain_acquire_image(struct oxr_logger *log,
struct oxr_swapchain *sc,
const XrSwapchainImageAcquireInfo *acquireInfo,
uint32_t *out_index)
{
uint32_t index;
if (sc->acquired.num >= sc->swapchain->num_images) {
return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "All images have been acquired");
}
if (sc->is_static && (sc->released.yes || sc->waited.yes)) {
return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "Can only acquire once on a static swapchain");
}
struct xrt_swapchain *xsc = (struct xrt_swapchain *)sc->swapchain;
xrt_result_t res = xsc->acquire_image(xsc, &index);
if (res == XRT_ERROR_IPC_FAILURE) {
return oxr_error(log, XR_ERROR_INSTANCE_LOST, "Call to xsc->acquire_image failed");
}
if (res != XRT_SUCCESS) {
return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Call to xsc->acquire_image failed");
}
if (sc->images[index].state != OXR_IMAGE_STATE_READY) {
return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Internal acquire call returned non-ready image.");
}
sc->acquired.num++;
u_index_fifo_push(&sc->acquired.fifo, index);
sc->images[index].state = OXR_IMAGE_STATE_ACQUIRED;
// If the compositor is resuing the image,
// mark it as invalid to use in xrEndFrame.
if (sc->released.index == (int)index) {
sc->released.yes = false;
sc->released.index = -1;
}
*out_index = index;
return oxr_session_success_result(sc->sess);
}
static XrResult
oxr_swapchain_wait_image(struct oxr_logger *log, struct oxr_swapchain *sc, const XrSwapchainImageWaitInfo *waitInfo)
{
if (sc->waited.yes) {
return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "Swapchain has already been waited, call release");
}
if (u_index_fifo_is_empty(&sc->acquired.fifo)) {
return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "No image acquired");
}
uint32_t index;
u_index_fifo_pop(&sc->acquired.fifo, &index);
struct xrt_swapchain *xsc = (struct xrt_swapchain *)sc->swapchain;
xrt_result_t res = xsc->wait_image(xsc, waitInfo->timeout, index);
if (res == XRT_ERROR_IPC_FAILURE) {
return oxr_error(log, XR_ERROR_INSTANCE_LOST, "Call to xsc->wait_image failed");
}
if (res != XRT_SUCCESS) {
return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Call to xsc->wait_image failed");
}
// The app can only wait on one image.
sc->waited.yes = true;
sc->waited.index = index;
sc->images[index].state = OXR_IMAGE_STATE_WAITED;
return oxr_session_success_result(sc->sess);
}
static XrResult
oxr_swapchain_release_image(struct oxr_logger *log,
struct oxr_swapchain *sc,
const XrSwapchainImageReleaseInfo *releaseInfo)
{
if (!sc->waited.yes) {
return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "No swapchain images waited on");
}
sc->waited.yes = false;
uint32_t index = sc->waited.index;
struct xrt_swapchain *xsc = (struct xrt_swapchain *)sc->swapchain;
xrt_result_t res = xsc->release_image(xsc, index);
if (res == XRT_ERROR_IPC_FAILURE) {
return oxr_error(log, XR_ERROR_INSTANCE_LOST, "Call to xsc->release_image failed");
}
if (res != XRT_SUCCESS) {
return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Call to xsc->release_image failed");
}
// Only decerement here.
sc->acquired.num--;
// Overwrite the old released image, with new.
sc->released.yes = true;
sc->released.index = index;
sc->images[index].state = OXR_IMAGE_STATE_READY;
return oxr_session_success_result(sc->sess);
}
static XrResult
oxr_swapchain_destroy(struct oxr_logger *log, struct oxr_handle_base *hb)
{
struct oxr_swapchain *sc = (struct oxr_swapchain *)hb;
XrResult ret = sc->destroy(log, sc);
free(sc);
return ret;
}
static enum xrt_swapchain_create_flags
convert_create_flags(XrSwapchainCreateFlags xr_flags)
{
enum xrt_swapchain_create_flags flags = 0;
if ((xr_flags & XR_SWAPCHAIN_CREATE_PROTECTED_CONTENT_BIT) != 0) {
flags |= XRT_SWAPCHAIN_CREATE_PROTECTED_CONTENT;
}
if ((xr_flags & XR_SWAPCHAIN_CREATE_STATIC_IMAGE_BIT) != 0) {
flags |= XRT_SWAPCHAIN_CREATE_STATIC_IMAGE;
}
return flags;
}
static enum xrt_swapchain_usage_bits
convert_usage_bits(XrSwapchainUsageFlags xr_usage)
{
enum xrt_swapchain_usage_bits usage = 0;
if ((xr_usage & XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT) != 0) {
usage |= XRT_SWAPCHAIN_USAGE_COLOR;
}
if ((xr_usage & XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) != 0) {
usage |= XRT_SWAPCHAIN_USAGE_DEPTH_STENCIL;
}
if ((xr_usage & XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT) != 0) {
usage |= XRT_SWAPCHAIN_USAGE_UNORDERED_ACCESS;
}
if ((xr_usage & XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT) != 0) {
usage |= XRT_SWAPCHAIN_USAGE_TRANSFER_SRC;
}
if ((xr_usage & XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT) != 0) {
usage |= XRT_SWAPCHAIN_USAGE_TRANSFER_DST;
}
if ((xr_usage & XR_SWAPCHAIN_USAGE_SAMPLED_BIT) != 0) {
usage |= XRT_SWAPCHAIN_USAGE_SAMPLED;
}
if ((xr_usage & XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT) != 0) {
usage |= XRT_SWAPCHAIN_USAGE_MUTABLE_FORMAT;
}
if ((xr_usage & XR_SWAPCHAIN_USAGE_INPUT_ATTACHMENT_BIT_MND) != 0) {
usage |= XRT_SWAPCHAIN_USAGE_INPUT_ATTACHMENT;
}
return usage;
}
XrResult
oxr_create_swapchain(struct oxr_logger *log,
struct oxr_session *sess,
const XrSwapchainCreateInfo *createInfo,
struct oxr_swapchain **out_swapchain)
{
xrt_result_t xret = XRT_SUCCESS;
struct xrt_swapchain_create_info info;
info.create = convert_create_flags(createInfo->createFlags);
info.bits = convert_usage_bits(createInfo->usageFlags);
info.format = createInfo->format;
info.sample_count = createInfo->sampleCount;
info.width = createInfo->width;
info.height = createInfo->height;
info.face_count = createInfo->faceCount;
info.array_size = createInfo->arraySize;
info.mip_count = createInfo->mipCount;
struct xrt_swapchain *xsc = NULL; // Has to be NULL.
xret = xrt_comp_create_swapchain(sess->compositor, &info, &xsc);
if (xret == XRT_ERROR_SWAPCHAIN_FLAG_VALID_BUT_UNSUPPORTED) {
return oxr_error(log, XR_ERROR_FEATURE_UNSUPPORTED,
"Specified swapchain creation flag is valid, "
"but not supported");
} else if (xret == XRT_ERROR_SWAPCHAIN_FORMAT_UNSUPPORTED) {
return oxr_error(log, XR_ERROR_SWAPCHAIN_FORMAT_UNSUPPORTED,
"Specified swapchain format is not supported");
}
if (xret != XRT_SUCCESS) {
return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to create swapchain");
}
assert(xsc != NULL);
struct oxr_swapchain *sc = NULL;
OXR_ALLOCATE_HANDLE_OR_RETURN(log, sc, OXR_XR_DEBUG_SWAPCHAIN, oxr_swapchain_destroy, &sess->handle);
sc->sess = sess;
sc->swapchain = xsc;
sc->width = createInfo->width;
sc->height = createInfo->height;
sc->num_array_layers = createInfo->arraySize;
sc->acquire_image = oxr_swapchain_acquire_image;
sc->wait_image = oxr_swapchain_wait_image;
sc->release_image = oxr_swapchain_release_image;
sc->is_static = (createInfo->createFlags & XR_SWAPCHAIN_CREATE_STATIC_IMAGE_BIT) != 0;
*out_swapchain = sc;
return XR_SUCCESS;
}
|
24058.c | class ActionGiveSalineTargetCB : ActionContinuousBaseCB
{
override void CreateActionComponent()
{
m_ActionComponent = new CAContinuousTime(UATimeSpent.SALINE);
}
};
class ActionGiveSalineTarget: ActionContinuousBase
{
private const float PRECISE_SPECIALTY_WEIGHT = -0.02;
void ActionGiveSalineTarget()
{
m_CallbackClass = ActionGiveSalineTargetCB;
m_MessageStartFail = "Bag is empty.";
m_MessageStart = "Player started giving you saline.";
m_MessageSuccess = "Player finished giving you saline.";
m_MessageFail = "Player moved and giving you saline was canceled.";
m_MessageCancel = "You stopped giving saline.";
//m_Animation = "givesaline";
m_SpecialtyWeight = PRECISE_SPECIALTY_WEIGHT;
m_CommandUID = DayZPlayerConstants.CMD_ACTIONFB_SALINEBLOODBAGTARGET;
m_FullBody = true;
m_StanceMask = DayZPlayerConstants.STANCEMASK_ERECT | DayZPlayerConstants.STANCEMASK_CROUCH;
}
override void CreateConditionComponents()
{
m_ConditionItem = new CCINonRuined;
m_ConditionTarget = new CCTMan(UAMaxDistances.DEFAULT);
}
override int GetType()
{
return AT_GIVE_SALINE_T;
}
override string GetText()
{
return "give saline";
}
override void OnCompleteServer( PlayerBase player, ActionTarget target, ItemBase item, Param acdata )
{
//TODO Daniel: integrate ss 2.0
/*float efficiency = player.GetQuantityEfficiency( GetType() );
if ( efficiency == -1 )
{
efficiency = 1;
}*/
PlayerBase ntarget = PlayerBase.Cast( target.GetObject() );
Param1<float> nacdata = Param1<float>.Cast( acdata );
float delta = nacdata.param1;
//ntarget.AddHealth("", "Blood", delta);
//ntarget.m_PlayerStats.m_Blood.Add(nacdata.param1 * efficiency);//BLOOD_REPLACE
//float delta = nacdata.param1 * efficiency;
//player.SetHealth("GlobalHealth", "Blood", player.GetHealth("GlobalHealth", "Blood") + delta );
ntarget.GetModifiersManager().ActivateModifier(eModifiers.MDF_SALINE);
//this condition protects spamming UAs for exp without using items quantity
if ( nacdata.param1 != 0 )
{
player.GetSoftSkillManager().AddSpecialty( m_SpecialtyWeight );
}
item.Delete();
}
}; |
553028.c | /* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32f4xx_it.c
* @brief Interrupt Service Routines.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2021 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f4xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/* External variables --------------------------------------------------------*/
extern PCD_HandleTypeDef hpcd_USB_OTG_HS;
/* USER CODE BEGIN EV */
/* USER CODE END EV */
/******************************************************************************/
/* Cortex-M4 Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles Non maskable interrupt.
*/
void NMI_Handler(void)
{
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */
while (1)
{
}
/* USER CODE END NonMaskableInt_IRQn 1 */
}
/**
* @brief This function handles Hard fault interrupt.
*/
void HardFault_Handler(void)
{
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_HardFault_IRQn 0 */
/* USER CODE END W1_HardFault_IRQn 0 */
}
}
/**
* @brief This function handles Memory management fault.
*/
void MemManage_Handler(void)
{
/* USER CODE BEGIN MemoryManagement_IRQn 0 */
/* USER CODE END MemoryManagement_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
/* USER CODE END W1_MemoryManagement_IRQn 0 */
}
}
/**
* @brief This function handles Pre-fetch fault, memory access fault.
*/
void BusFault_Handler(void)
{
/* USER CODE BEGIN BusFault_IRQn 0 */
/* USER CODE END BusFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_BusFault_IRQn 0 */
/* USER CODE END W1_BusFault_IRQn 0 */
}
}
/**
* @brief This function handles Undefined instruction or illegal state.
*/
void UsageFault_Handler(void)
{
/* USER CODE BEGIN UsageFault_IRQn 0 */
/* USER CODE END UsageFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_UsageFault_IRQn 0 */
/* USER CODE END W1_UsageFault_IRQn 0 */
}
}
/**
* @brief This function handles System service call via SWI instruction.
*/
void SVC_Handler(void)
{
/* USER CODE BEGIN SVCall_IRQn 0 */
/* USER CODE END SVCall_IRQn 0 */
/* USER CODE BEGIN SVCall_IRQn 1 */
/* USER CODE END SVCall_IRQn 1 */
}
/**
* @brief This function handles Debug monitor.
*/
void DebugMon_Handler(void)
{
/* USER CODE BEGIN DebugMonitor_IRQn 0 */
/* USER CODE END DebugMonitor_IRQn 0 */
/* USER CODE BEGIN DebugMonitor_IRQn 1 */
/* USER CODE END DebugMonitor_IRQn 1 */
}
/**
* @brief This function handles Pendable request for system service.
*/
void PendSV_Handler(void)
{
/* USER CODE BEGIN PendSV_IRQn 0 */
/* USER CODE END PendSV_IRQn 0 */
/* USER CODE BEGIN PendSV_IRQn 1 */
/* USER CODE END PendSV_IRQn 1 */
}
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
/* USER CODE BEGIN SysTick_IRQn 0 */
/* USER CODE END SysTick_IRQn 0 */
HAL_IncTick();
/* USER CODE BEGIN SysTick_IRQn 1 */
/* USER CODE END SysTick_IRQn 1 */
}
/******************************************************************************/
/* STM32F4xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32f4xx.s). */
/******************************************************************************/
/**
* @brief This function handles USB On The Go HS End Point 1 Out global interrupt.
*/
//void OTG_HS_EP1_OUT_IRQHandler(void)
//{
// /* USER CODE BEGIN OTG_HS_EP1_OUT_IRQn 0 */
// /* USER CODE END OTG_HS_EP1_OUT_IRQn 0 */
// HAL_PCD_IRQHandler(&hpcd_USB_OTG_HS);
// /* USER CODE BEGIN OTG_HS_EP1_OUT_IRQn 1 */
// /* USER CODE END OTG_HS_EP1_OUT_IRQn 1 */
//}
///**
// * @brief This function handles USB On The Go HS End Point 1 In global interrupt.
// */
//void OTG_HS_EP1_IN_IRQHandler(void)
//{
// /* USER CODE BEGIN OTG_HS_EP1_IN_IRQn 0 */
// /* USER CODE END OTG_HS_EP1_IN_IRQn 0 */
// HAL_PCD_IRQHandler(&hpcd_USB_OTG_HS);
// /* USER CODE BEGIN OTG_HS_EP1_IN_IRQn 1 */
// /* USER CODE END OTG_HS_EP1_IN_IRQn 1 */
//}
///**
// * @brief This function handles USB On The Go HS global interrupt.
// */
//void OTG_HS_IRQHandler(void)
//{
// /* USER CODE BEGIN OTG_HS_IRQn 0 */
// /* USER CODE END OTG_HS_IRQn 0 */
// HAL_PCD_IRQHandler(&hpcd_USB_OTG_HS);
// /* USER CODE BEGIN OTG_HS_IRQn 1 */
// /* USER CODE END OTG_HS_IRQn 1 */
//}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
482311.c |
/* pngread.c - read a PNG file
*
* Last changed in libpng 1.4.10 [March 8, 2012]
* Copyright (c) 1998-2012 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*
* This file contains routines that an application calls directly to
* read a PNG file or stream.
*/
#define PNG_NO_PEDANTIC_WARNINGS
#include "png.h"
#ifdef PNG_READ_SUPPORTED
#include "pngpriv.h"
/* Create a PNG structure for reading, and allocate any memory needed. */
png_structp PNGAPI
png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn)
{
#ifdef PNG_USER_MEM_SUPPORTED
return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
warn_fn, NULL, NULL, NULL));
}
/* Alternate create PNG structure for reading, and allocate any memory
* needed.
*/
png_structp PNGAPI
png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
png_malloc_ptr malloc_fn, png_free_ptr free_fn)
{
#endif /* PNG_USER_MEM_SUPPORTED */
#ifdef PNG_SETJMP_SUPPORTED
volatile
#endif
png_structp png_ptr;
volatile int png_cleanup_needed = 0;
#ifdef PNG_SETJMP_SUPPORTED
#ifdef USE_FAR_KEYWORD
jmp_buf jmpbuf;
#endif
#endif
int i;
png_debug(1, "in png_create_read_struct");
#ifdef PNG_USER_MEM_SUPPORTED
png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
malloc_fn, mem_ptr);
#else
png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
#endif
if (png_ptr == NULL)
return (NULL);
/* Added at libpng-1.2.6 */
#ifdef PNG_USER_LIMITS_SUPPORTED
png_ptr->user_width_max = PNG_USER_WIDTH_MAX;
png_ptr->user_height_max = PNG_USER_HEIGHT_MAX;
/* Added at libpng-1.2.43 and 1.4.0 */
png_ptr->user_chunk_cache_max = PNG_USER_CHUNK_CACHE_MAX;
/* Added at libpng-1.4.1 */
png_ptr->user_chunk_malloc_max = PNG_USER_CHUNK_MALLOC_MAX;
#endif
#ifdef PNG_SETJMP_SUPPORTED
/* Applications that neglect to set up their own setjmp() and then
encounter a png_error() will longjmp here. Since the jmpbuf is
then meaningless we abort instead of returning. */
#ifdef USE_FAR_KEYWORD
if (setjmp(jmpbuf))
#else
if (setjmp(png_jmpbuf(png_ptr))) /* Sets longjmp to match setjmp */
#endif
PNG_ABORT();
#ifdef USE_FAR_KEYWORD
png_memcpy(png_jmpbuf(png_ptr), jmpbuf, png_sizeof(jmp_buf));
#endif
#endif /* PNG_SETJMP_SUPPORTED */
#ifdef PNG_USER_MEM_SUPPORTED
png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
#endif
png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
if (user_png_ver)
{
i = 0;
do
{
if (user_png_ver[i] != png_libpng_ver[i])
png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
} while (png_libpng_ver[i++]);
}
else
png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
{
/* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
* we must recompile any applications that use any older library version.
* For versions after libpng 1.0, we will be compatible, so we need
* only check the first digit.
*/
if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
(user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
(user_png_ver[0] == '0' && user_png_ver[2] < '9'))
{
#ifdef PNG_STDIO_SUPPORTED
char msg[80];
if (user_png_ver)
{
png_snprintf(msg, 80,
"Application was compiled with png.h from libpng-%.20s",
user_png_ver);
png_warning(png_ptr, msg);
}
png_snprintf(msg, 80,
"Application is running with png.c from libpng-%.20s",
png_libpng_ver);
png_warning(png_ptr, msg);
#endif
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
png_ptr->flags = 0;
#endif
png_warning(png_ptr,
"Incompatible libpng version in application and library");
png_cleanup_needed = 1;
}
}
if (!png_cleanup_needed)
{
/* Initialize zbuf - compression buffer */
png_ptr->zbuf_size = PNG_ZBUF_SIZE;
png_ptr->zbuf = (png_bytep)png_malloc_warn(png_ptr,
png_ptr->zbuf_size);
if (png_ptr->zbuf == NULL)
png_cleanup_needed = 1;
}
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zstream.zfree = png_zfree;
png_ptr->zstream.opaque = (voidpf)png_ptr;
if (!png_cleanup_needed)
{
switch (inflateInit(&png_ptr->zstream))
{
case Z_OK: /* Do nothing */ break;
case Z_MEM_ERROR:
case Z_STREAM_ERROR: png_warning(png_ptr, "zlib memory error");
png_cleanup_needed = 1; break;
case Z_VERSION_ERROR: png_warning(png_ptr, "zlib version error");
png_cleanup_needed = 1; break;
default: png_warning(png_ptr, "Unknown zlib error");
png_cleanup_needed = 1;
}
}
if (png_cleanup_needed)
{
/* Clean up PNG structure and deallocate any memory. */
png_free(png_ptr, png_ptr->zbuf);
png_ptr->zbuf = NULL;
#ifdef PNG_USER_MEM_SUPPORTED
png_destroy_struct_2((png_voidp)png_ptr,
(png_free_ptr)free_fn, (png_voidp)mem_ptr);
#else
png_destroy_struct((png_voidp)png_ptr);
#endif
return (NULL);
}
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_set_read_fn(png_ptr, NULL, NULL);
return (png_ptr);
}
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
/* Read the information before the actual image data. This has been
* changed in v0.90 to allow reading a file that already has the magic
* bytes read from the stream. You can tell libpng how many bytes have
* been read from the beginning of the stream (up to the maximum of 8)
* via png_set_sig_bytes(), and we will only check the remaining bytes
* here. The application can then have access to the signature bytes we
* read if it is determined that this isn't a valid PNG file.
*/
void PNGAPI
png_read_info(png_structp png_ptr, png_infop info_ptr)
{
png_debug(1, "in png_read_info");
if (png_ptr == NULL || info_ptr == NULL)
return;
/* Read and check the PNG file signature. */
png_read_sig(png_ptr, info_ptr);
for (;;)
{
PNG_IHDR;
PNG_IDAT;
PNG_IEND;
PNG_PLTE;
#ifdef PNG_READ_bKGD_SUPPORTED
PNG_bKGD;
#endif
#ifdef PNG_READ_cHRM_SUPPORTED
PNG_cHRM;
#endif
#ifdef PNG_READ_gAMA_SUPPORTED
PNG_gAMA;
#endif
#ifdef PNG_READ_hIST_SUPPORTED
PNG_hIST;
#endif
#ifdef PNG_READ_iCCP_SUPPORTED
PNG_iCCP;
#endif
#ifdef PNG_READ_iTXt_SUPPORTED
PNG_iTXt;
#endif
#ifdef PNG_READ_oFFs_SUPPORTED
PNG_oFFs;
#endif
#ifdef PNG_READ_pCAL_SUPPORTED
PNG_pCAL;
#endif
#ifdef PNG_READ_pHYs_SUPPORTED
PNG_pHYs;
#endif
#ifdef PNG_READ_sBIT_SUPPORTED
PNG_sBIT;
#endif
#ifdef PNG_READ_sCAL_SUPPORTED
PNG_sCAL;
#endif
#ifdef PNG_READ_sPLT_SUPPORTED
PNG_sPLT;
#endif
#ifdef PNG_READ_sRGB_SUPPORTED
PNG_sRGB;
#endif
#ifdef PNG_READ_tEXt_SUPPORTED
PNG_tEXt;
#endif
#ifdef PNG_READ_tIME_SUPPORTED
PNG_tIME;
#endif
#ifdef PNG_READ_tRNS_SUPPORTED
PNG_tRNS;
#endif
#ifdef PNG_READ_zTXt_SUPPORTED
PNG_zTXt;
#endif
png_uint_32 length = png_read_chunk_header(png_ptr);
PNG_CONST png_bytep chunk_name = png_ptr->chunk_name;
/* This should be a binary subdivision search or a hash for
* matching the chunk name rather than a linear search.
*/
if (!png_memcmp(chunk_name, png_IDAT, 4))
if (png_ptr->mode & PNG_AFTER_IDAT)
png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
if (!png_memcmp(chunk_name, png_IHDR, 4))
png_handle_IHDR(png_ptr, info_ptr, length);
else if (!png_memcmp(chunk_name, png_IEND, 4))
png_handle_IEND(png_ptr, info_ptr, length);
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
else if (png_handle_as_unknown(png_ptr, chunk_name))
{
if (!png_memcmp(chunk_name, png_IDAT, 4))
png_ptr->mode |= PNG_HAVE_IDAT;
png_handle_unknown(png_ptr, info_ptr, length);
if (!png_memcmp(chunk_name, png_PLTE, 4))
png_ptr->mode |= PNG_HAVE_PLTE;
else if (!png_memcmp(chunk_name, png_IDAT, 4))
{
if (!(png_ptr->mode & PNG_HAVE_IHDR))
png_error(png_ptr, "Missing IHDR before IDAT");
else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
!(png_ptr->mode & PNG_HAVE_PLTE))
png_error(png_ptr, "Missing PLTE before IDAT");
break;
}
}
#endif
else if (!png_memcmp(chunk_name, png_PLTE, 4))
png_handle_PLTE(png_ptr, info_ptr, length);
else if (!png_memcmp(chunk_name, png_IDAT, 4))
{
if (!(png_ptr->mode & PNG_HAVE_IHDR))
png_error(png_ptr, "Missing IHDR before IDAT");
else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
!(png_ptr->mode & PNG_HAVE_PLTE))
png_error(png_ptr, "Missing PLTE before IDAT");
png_ptr->idat_size = length;
png_ptr->mode |= PNG_HAVE_IDAT;
break;
}
#ifdef PNG_READ_bKGD_SUPPORTED
else if (!png_memcmp(chunk_name, png_bKGD, 4))
png_handle_bKGD(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_cHRM_SUPPORTED
else if (!png_memcmp(chunk_name, png_cHRM, 4))
png_handle_cHRM(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_gAMA_SUPPORTED
else if (!png_memcmp(chunk_name, png_gAMA, 4))
png_handle_gAMA(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_hIST_SUPPORTED
else if (!png_memcmp(chunk_name, png_hIST, 4))
png_handle_hIST(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_oFFs_SUPPORTED
else if (!png_memcmp(chunk_name, png_oFFs, 4))
png_handle_oFFs(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_pCAL_SUPPORTED
else if (!png_memcmp(chunk_name, png_pCAL, 4))
png_handle_pCAL(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_sCAL_SUPPORTED
else if (!png_memcmp(chunk_name, png_sCAL, 4))
png_handle_sCAL(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_pHYs_SUPPORTED
else if (!png_memcmp(chunk_name, png_pHYs, 4))
png_handle_pHYs(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_sBIT_SUPPORTED
else if (!png_memcmp(chunk_name, png_sBIT, 4))
png_handle_sBIT(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_sRGB_SUPPORTED
else if (!png_memcmp(chunk_name, png_sRGB, 4))
png_handle_sRGB(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_iCCP_SUPPORTED
else if (!png_memcmp(chunk_name, png_iCCP, 4))
png_handle_iCCP(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_sPLT_SUPPORTED
else if (!png_memcmp(chunk_name, png_sPLT, 4))
png_handle_sPLT(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_tEXt_SUPPORTED
else if (!png_memcmp(chunk_name, png_tEXt, 4))
png_handle_tEXt(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_tIME_SUPPORTED
else if (!png_memcmp(chunk_name, png_tIME, 4))
png_handle_tIME(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_tRNS_SUPPORTED
else if (!png_memcmp(chunk_name, png_tRNS, 4))
png_handle_tRNS(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_zTXt_SUPPORTED
else if (!png_memcmp(chunk_name, png_zTXt, 4))
png_handle_zTXt(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_iTXt_SUPPORTED
else if (!png_memcmp(chunk_name, png_iTXt, 4))
png_handle_iTXt(png_ptr, info_ptr, length);
#endif
else
png_handle_unknown(png_ptr, info_ptr, length);
}
}
#endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
/* Optional call to update the users info_ptr structure */
void PNGAPI
png_read_update_info(png_structp png_ptr, png_infop info_ptr)
{
png_debug(1, "in png_read_update_info");
if (png_ptr == NULL)
return;
if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
png_read_start_row(png_ptr);
else
png_warning(png_ptr,
"Ignoring extra png_read_update_info() call; row buffer not reallocated");
png_read_transform_info(png_ptr, info_ptr);
}
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
/* Initialize palette, background, etc, after transformations
* are set, but before any reading takes place. This allows
* the user to obtain a gamma-corrected palette, for example.
* If the user doesn't call this, we will do it ourselves.
*/
void PNGAPI
png_start_read_image(png_structp png_ptr)
{
png_debug(1, "in png_start_read_image");
if (png_ptr == NULL)
return;
if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
png_read_start_row(png_ptr);
}
#endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
void PNGAPI
png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
{
PNG_IDAT;
#ifdef PNG_READ_INTERLACING_SUPPORTED
PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
0xff};
PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
int ret;
#endif
if (png_ptr == NULL)
return;
png_debug2(1, "in png_read_row (row %lu, pass %d)",
(unsigned long) png_ptr->row_number, png_ptr->pass);
if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
png_read_start_row(png_ptr);
if (png_ptr->row_number == 0 && png_ptr->pass == 0)
{
/* Check for transforms that have been set but were defined out */
#if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
if (png_ptr->transformations & PNG_INVERT_MONO)
png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined");
#endif
#if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
if (png_ptr->transformations & PNG_FILLER)
png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined");
#endif
#if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
!defined(PNG_READ_PACKSWAP_SUPPORTED)
if (png_ptr->transformations & PNG_PACKSWAP)
png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined");
#endif
#if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
if (png_ptr->transformations & PNG_PACK)
png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined");
#endif
#if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
if (png_ptr->transformations & PNG_SHIFT)
png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined");
#endif
#if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
if (png_ptr->transformations & PNG_BGR)
png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined");
#endif
#if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
if (png_ptr->transformations & PNG_SWAP_BYTES)
png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined");
#endif
}
#ifdef PNG_READ_INTERLACING_SUPPORTED
/* If interlaced and we do not need a new row, combine row and return */
if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
{
switch (png_ptr->pass)
{
case 0:
if (png_ptr->row_number & 0x07)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 1:
if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 2:
if ((png_ptr->row_number & 0x07) != 4)
{
if (dsp_row != NULL && (png_ptr->row_number & 4))
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 3:
if ((png_ptr->row_number & 3) || png_ptr->width < 3)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 4:
if ((png_ptr->row_number & 3) != 2)
{
if (dsp_row != NULL && (png_ptr->row_number & 2))
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 5:
if ((png_ptr->row_number & 1) || png_ptr->width < 2)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
default:
case 6:
if (!(png_ptr->row_number & 1))
{
png_read_finish_row(png_ptr);
return;
}
break;
}
}
#endif
if (!(png_ptr->mode & PNG_HAVE_IDAT))
png_error(png_ptr, "Invalid attempt to read row data");
png_ptr->zstream.next_out = png_ptr->row_buf;
png_ptr->zstream.avail_out =
(uInt)(PNG_ROWBYTES(png_ptr->pixel_depth,
png_ptr->iwidth) + 1);
do
{
if (!(png_ptr->zstream.avail_in))
{
while (!png_ptr->idat_size)
{
png_crc_finish(png_ptr, 0);
png_ptr->idat_size = png_read_chunk_header(png_ptr);
if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
png_error(png_ptr, "Not enough image data");
}
png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_in = png_ptr->zbuf;
if (png_ptr->zbuf_size > png_ptr->idat_size)
png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
png_crc_read(png_ptr, png_ptr->zbuf,
(png_size_t)png_ptr->zstream.avail_in);
png_ptr->idat_size -= png_ptr->zstream.avail_in;
}
ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
if (ret == Z_STREAM_END)
{
if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
png_ptr->idat_size)
png_benign_error(png_ptr, "Extra compressed data");
png_ptr->mode |= PNG_AFTER_IDAT;
png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
break;
}
if (ret != Z_OK)
png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
"Decompression error");
} while (png_ptr->zstream.avail_out);
png_ptr->row_info.color_type = png_ptr->color_type;
png_ptr->row_info.width = png_ptr->iwidth;
png_ptr->row_info.channels = png_ptr->channels;
png_ptr->row_info.bit_depth = png_ptr->bit_depth;
png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
png_ptr->row_info.width);
if (png_ptr->row_buf[0])
png_read_filter_row(png_ptr, &(png_ptr->row_info),
png_ptr->row_buf + 1, png_ptr->prev_row + 1,
(int)(png_ptr->row_buf[0]));
png_memcpy(png_ptr->prev_row, png_ptr->row_buf, png_ptr->rowbytes + 1);
#ifdef PNG_MNG_FEATURES_SUPPORTED
if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
(png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
{
/* Intrapixel differencing */
png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
}
#endif
if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
png_do_read_transformations(png_ptr);
#ifdef PNG_READ_INTERLACING_SUPPORTED
/* Blow up interlaced rows to full size */
if (png_ptr->interlaced &&
(png_ptr->transformations & PNG_INTERLACE))
{
if (png_ptr->pass < 6)
/* Old interface (pre-1.0.9):
* png_do_read_interlace(&(png_ptr->row_info),
* png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
*/
png_do_read_interlace(png_ptr);
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
if (row != NULL)
png_combine_row(png_ptr, row,
png_pass_mask[png_ptr->pass]);
}
else
#endif
{
if (row != NULL)
png_combine_row(png_ptr, row, 0xff);
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row, 0xff);
}
png_read_finish_row(png_ptr);
if (png_ptr->read_row_fn != NULL)
(*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
}
#endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
/* Read one or more rows of image data. If the image is interlaced,
* and png_set_interlace_handling() has been called, the rows need to
* contain the contents of the rows from the previous pass. If the
* image has alpha or transparency, and png_handle_alpha()[*] has been
* called, the rows contents must be initialized to the contents of the
* screen.
*
* "row" holds the actual image, and pixels are placed in it
* as they arrive. If the image is displayed after each pass, it will
* appear to "sparkle" in. "display_row" can be used to display a
* "chunky" progressive image, with finer detail added as it becomes
* available. If you do not want this "chunky" display, you may pass
* NULL for display_row. If you do not want the sparkle display, and
* you have not called png_handle_alpha(), you may pass NULL for rows.
* If you have called png_handle_alpha(), and the image has either an
* alpha channel or a transparency chunk, you must provide a buffer for
* rows. In this case, you do not have to provide a display_row buffer
* also, but you may. If the image is not interlaced, or if you have
* not called png_set_interlace_handling(), the display_row buffer will
* be ignored, so pass NULL to it.
*
* [*] png_handle_alpha() does not exist yet, as of this version of libpng
*/
void PNGAPI
png_read_rows(png_structp png_ptr, png_bytepp row,
png_bytepp display_row, png_uint_32 num_rows)
{
png_uint_32 i;
png_bytepp rp;
png_bytepp dp;
png_debug(1, "in png_read_rows");
if (png_ptr == NULL)
return;
rp = row;
dp = display_row;
if (rp != NULL && dp != NULL)
for (i = 0; i < num_rows; i++)
{
png_bytep rptr = *rp++;
png_bytep dptr = *dp++;
png_read_row(png_ptr, rptr, dptr);
}
else if (rp != NULL)
for (i = 0; i < num_rows; i++)
{
png_bytep rptr = *rp;
png_read_row(png_ptr, rptr, NULL);
rp++;
}
else if (dp != NULL)
for (i = 0; i < num_rows; i++)
{
png_bytep dptr = *dp;
png_read_row(png_ptr, NULL, dptr);
dp++;
}
}
#endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
/* Read the entire image. If the image has an alpha channel or a tRNS
* chunk, and you have called png_handle_alpha()[*], you will need to
* initialize the image to the current image that PNG will be overlaying.
* We set the num_rows again here, in case it was incorrectly set in
* png_read_start_row() by a call to png_read_update_info() or
* png_start_read_image() if png_set_interlace_handling() wasn't called
* prior to either of these functions like it should have been. You can
* only call this function once. If you desire to have an image for
* each pass of a interlaced image, use png_read_rows() instead.
*
* [*] png_handle_alpha() does not exist yet, as of this version of libpng
*/
void PNGAPI
png_read_image(png_structp png_ptr, png_bytepp image)
{
png_uint_32 i, image_height;
int pass, j;
png_bytepp rp;
png_debug(1, "in png_read_image");
if (png_ptr == NULL)
return;
#ifdef PNG_READ_INTERLACING_SUPPORTED
pass = png_set_interlace_handling(png_ptr);
#else
if (png_ptr->interlaced)
png_error(png_ptr,
"Cannot read interlaced image -- interlace handler disabled");
pass = 1;
#endif
image_height=png_ptr->height;
png_ptr->num_rows = image_height; /* Make sure this is set correctly */
for (j = 0; j < pass; j++)
{
rp = image;
for (i = 0; i < image_height; i++)
{
png_read_row(png_ptr, *rp, NULL);
rp++;
}
}
}
#endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
/* Read the end of the PNG file. Will not read past the end of the
* file, will verify the end is accurate, and will read any comments
* or time information at the end of the file, if info is not NULL.
*/
void PNGAPI
png_read_end(png_structp png_ptr, png_infop info_ptr)
{
png_debug(1, "in png_read_end");
if (png_ptr == NULL)
return;
png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
do
{
PNG_IHDR;
PNG_IDAT;
PNG_IEND;
PNG_PLTE;
#ifdef PNG_READ_bKGD_SUPPORTED
PNG_bKGD;
#endif
#ifdef PNG_READ_cHRM_SUPPORTED
PNG_cHRM;
#endif
#ifdef PNG_READ_gAMA_SUPPORTED
PNG_gAMA;
#endif
#ifdef PNG_READ_hIST_SUPPORTED
PNG_hIST;
#endif
#ifdef PNG_READ_iCCP_SUPPORTED
PNG_iCCP;
#endif
#ifdef PNG_READ_iTXt_SUPPORTED
PNG_iTXt;
#endif
#ifdef PNG_READ_oFFs_SUPPORTED
PNG_oFFs;
#endif
#ifdef PNG_READ_pCAL_SUPPORTED
PNG_pCAL;
#endif
#ifdef PNG_READ_pHYs_SUPPORTED
PNG_pHYs;
#endif
#ifdef PNG_READ_sBIT_SUPPORTED
PNG_sBIT;
#endif
#ifdef PNG_READ_sCAL_SUPPORTED
PNG_sCAL;
#endif
#ifdef PNG_READ_sPLT_SUPPORTED
PNG_sPLT;
#endif
#ifdef PNG_READ_sRGB_SUPPORTED
PNG_sRGB;
#endif
#ifdef PNG_READ_tEXt_SUPPORTED
PNG_tEXt;
#endif
#ifdef PNG_READ_tIME_SUPPORTED
PNG_tIME;
#endif
#ifdef PNG_READ_tRNS_SUPPORTED
PNG_tRNS;
#endif
#ifdef PNG_READ_zTXt_SUPPORTED
PNG_zTXt;
#endif
png_uint_32 length = png_read_chunk_header(png_ptr);
PNG_CONST png_bytep chunk_name = png_ptr->chunk_name;
if (!png_memcmp(chunk_name, png_IHDR, 4))
png_handle_IHDR(png_ptr, info_ptr, length);
else if (!png_memcmp(chunk_name, png_IEND, 4))
png_handle_IEND(png_ptr, info_ptr, length);
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
else if (png_handle_as_unknown(png_ptr, chunk_name))
{
if (!png_memcmp(chunk_name, png_IDAT, 4))
{
if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
png_benign_error(png_ptr, "Too many IDATs found");
}
png_handle_unknown(png_ptr, info_ptr, length);
if (!png_memcmp(chunk_name, png_PLTE, 4))
png_ptr->mode |= PNG_HAVE_PLTE;
}
#endif
else if (!png_memcmp(chunk_name, png_IDAT, 4))
{
/* Zero length IDATs are legal after the last IDAT has been
* read, but not after other chunks have been read.
*/
if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
png_benign_error(png_ptr, "Too many IDATs found");
png_crc_finish(png_ptr, length);
}
else if (!png_memcmp(chunk_name, png_PLTE, 4))
png_handle_PLTE(png_ptr, info_ptr, length);
#ifdef PNG_READ_bKGD_SUPPORTED
else if (!png_memcmp(chunk_name, png_bKGD, 4))
png_handle_bKGD(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_cHRM_SUPPORTED
else if (!png_memcmp(chunk_name, png_cHRM, 4))
png_handle_cHRM(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_gAMA_SUPPORTED
else if (!png_memcmp(chunk_name, png_gAMA, 4))
png_handle_gAMA(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_hIST_SUPPORTED
else if (!png_memcmp(chunk_name, png_hIST, 4))
png_handle_hIST(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_oFFs_SUPPORTED
else if (!png_memcmp(chunk_name, png_oFFs, 4))
png_handle_oFFs(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_pCAL_SUPPORTED
else if (!png_memcmp(chunk_name, png_pCAL, 4))
png_handle_pCAL(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_sCAL_SUPPORTED
else if (!png_memcmp(chunk_name, png_sCAL, 4))
png_handle_sCAL(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_pHYs_SUPPORTED
else if (!png_memcmp(chunk_name, png_pHYs, 4))
png_handle_pHYs(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_sBIT_SUPPORTED
else if (!png_memcmp(chunk_name, png_sBIT, 4))
png_handle_sBIT(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_sRGB_SUPPORTED
else if (!png_memcmp(chunk_name, png_sRGB, 4))
png_handle_sRGB(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_iCCP_SUPPORTED
else if (!png_memcmp(chunk_name, png_iCCP, 4))
png_handle_iCCP(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_sPLT_SUPPORTED
else if (!png_memcmp(chunk_name, png_sPLT, 4))
png_handle_sPLT(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_tEXt_SUPPORTED
else if (!png_memcmp(chunk_name, png_tEXt, 4))
png_handle_tEXt(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_tIME_SUPPORTED
else if (!png_memcmp(chunk_name, png_tIME, 4))
png_handle_tIME(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_tRNS_SUPPORTED
else if (!png_memcmp(chunk_name, png_tRNS, 4))
png_handle_tRNS(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_zTXt_SUPPORTED
else if (!png_memcmp(chunk_name, png_zTXt, 4))
png_handle_zTXt(png_ptr, info_ptr, length);
#endif
#ifdef PNG_READ_iTXt_SUPPORTED
else if (!png_memcmp(chunk_name, png_iTXt, 4))
png_handle_iTXt(png_ptr, info_ptr, length);
#endif
else
png_handle_unknown(png_ptr, info_ptr, length);
} while (!(png_ptr->mode & PNG_HAVE_IEND));
}
#endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
/* Free all memory used by the read */
void PNGAPI
png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
png_infopp end_info_ptr_ptr)
{
png_structp png_ptr = NULL;
png_infop info_ptr = NULL, end_info_ptr = NULL;
#ifdef PNG_USER_MEM_SUPPORTED
png_free_ptr free_fn = NULL;
png_voidp mem_ptr = NULL;
#endif
png_debug(1, "in png_destroy_read_struct");
if (png_ptr_ptr != NULL)
png_ptr = *png_ptr_ptr;
if (png_ptr == NULL)
return;
#ifdef PNG_USER_MEM_SUPPORTED
free_fn = png_ptr->free_fn;
mem_ptr = png_ptr->mem_ptr;
#endif
if (info_ptr_ptr != NULL)
info_ptr = *info_ptr_ptr;
if (end_info_ptr_ptr != NULL)
end_info_ptr = *end_info_ptr_ptr;
png_read_destroy(png_ptr, info_ptr, end_info_ptr);
if (info_ptr != NULL)
{
#ifdef PNG_TEXT_SUPPORTED
png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
#endif
#ifdef PNG_USER_MEM_SUPPORTED
png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
(png_voidp)mem_ptr);
#else
png_destroy_struct((png_voidp)info_ptr);
#endif
*info_ptr_ptr = NULL;
}
if (end_info_ptr != NULL)
{
#ifdef PNG_READ_TEXT_SUPPORTED
png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
#endif
#ifdef PNG_USER_MEM_SUPPORTED
png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
(png_voidp)mem_ptr);
#else
png_destroy_struct((png_voidp)end_info_ptr);
#endif
*end_info_ptr_ptr = NULL;
}
if (png_ptr != NULL)
{
#ifdef PNG_USER_MEM_SUPPORTED
png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
(png_voidp)mem_ptr);
#else
png_destroy_struct((png_voidp)png_ptr);
#endif
*png_ptr_ptr = NULL;
}
}
/* Free all memory used by the read (old method) */
void /* PRIVATE */
png_read_destroy(png_structp png_ptr, png_infop info_ptr,
png_infop end_info_ptr)
{
#ifdef PNG_SETJMP_SUPPORTED
jmp_buf tmp_jmp;
#endif
png_error_ptr error_fn;
png_error_ptr warning_fn;
png_voidp error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
png_free_ptr free_fn;
#endif
png_debug(1, "in png_read_destroy");
if (info_ptr != NULL)
png_info_destroy(png_ptr, info_ptr);
if (end_info_ptr != NULL)
png_info_destroy(png_ptr, end_info_ptr);
png_free(png_ptr, png_ptr->zbuf);
png_free(png_ptr, png_ptr->big_row_buf);
png_free(png_ptr, png_ptr->prev_row);
png_free(png_ptr, png_ptr->chunkdata);
#ifdef PNG_READ_QUANTIZE_SUPPORTED
png_free(png_ptr, png_ptr->palette_lookup);
png_free(png_ptr, png_ptr->quantize_index);
#endif
#ifdef PNG_READ_GAMMA_SUPPORTED
png_free(png_ptr, png_ptr->gamma_table);
#endif
#ifdef PNG_READ_BACKGROUND_SUPPORTED
png_free(png_ptr, png_ptr->gamma_from_1);
png_free(png_ptr, png_ptr->gamma_to_1);
#endif
if (png_ptr->free_me & PNG_FREE_PLTE)
png_zfree(png_ptr, png_ptr->palette);
png_ptr->free_me &= ~PNG_FREE_PLTE;
#if defined(PNG_tRNS_SUPPORTED) || \
defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
if (png_ptr->free_me & PNG_FREE_TRNS)
png_free(png_ptr, png_ptr->trans_alpha);
png_ptr->free_me &= ~PNG_FREE_TRNS;
#endif
#ifdef PNG_READ_hIST_SUPPORTED
if (png_ptr->free_me & PNG_FREE_HIST)
png_free(png_ptr, png_ptr->hist);
png_ptr->free_me &= ~PNG_FREE_HIST;
#endif
#ifdef PNG_READ_GAMMA_SUPPORTED
if (png_ptr->gamma_16_table != NULL)
{
int i;
int istop = (1 << (8 - png_ptr->gamma_shift));
for (i = 0; i < istop; i++)
{
png_free(png_ptr, png_ptr->gamma_16_table[i]);
}
png_free(png_ptr, png_ptr->gamma_16_table);
}
#ifdef PNG_READ_BACKGROUND_SUPPORTED
if (png_ptr->gamma_16_from_1 != NULL)
{
int i;
int istop = (1 << (8 - png_ptr->gamma_shift));
for (i = 0; i < istop; i++)
{
png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
}
png_free(png_ptr, png_ptr->gamma_16_from_1);
}
if (png_ptr->gamma_16_to_1 != NULL)
{
int i;
int istop = (1 << (8 - png_ptr->gamma_shift));
for (i = 0; i < istop; i++)
{
png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
}
png_free(png_ptr, png_ptr->gamma_16_to_1);
}
#endif
#endif
#ifdef PNG_TIME_RFC1123_SUPPORTED
png_free(png_ptr, png_ptr->time_buffer);
#endif
inflateEnd(&png_ptr->zstream);
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
png_free(png_ptr, png_ptr->save_buffer);
#endif
/* Save the important info out of the png_struct, in case it is
* being used again.
*/
#ifdef PNG_SETJMP_SUPPORTED
png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
#endif
error_fn = png_ptr->error_fn;
warning_fn = png_ptr->warning_fn;
error_ptr = png_ptr->error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
free_fn = png_ptr->free_fn;
#endif
png_memset(png_ptr, 0, png_sizeof(png_struct));
png_ptr->error_fn = error_fn;
png_ptr->warning_fn = warning_fn;
png_ptr->error_ptr = error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
png_ptr->free_fn = free_fn;
#endif
#ifdef PNG_SETJMP_SUPPORTED
png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
#endif
}
void PNGAPI
png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
{
if (png_ptr == NULL)
return;
png_ptr->read_row_fn = read_row_fn;
}
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
#ifdef PNG_INFO_IMAGE_SUPPORTED
void PNGAPI
png_read_png(png_structp png_ptr, png_infop info_ptr,
int transforms,
voidp params)
{
int row;
if (png_ptr == NULL)
return;
/* png_read_info() gives us all of the information from the
* PNG file before the first IDAT (image data chunk).
*/
png_read_info(png_ptr, info_ptr);
if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
png_error(png_ptr, "Image is too high to process with png_read_png()");
/* -------------- image transformations start here ------------------- */
#ifdef PNG_READ_16_TO_8_SUPPORTED
/* Tell libpng to strip 16 bit/color files down to 8 bits per color.
*/
if (transforms & PNG_TRANSFORM_STRIP_16)
png_set_strip_16(png_ptr);
#endif
#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
/* Strip alpha bytes from the input data without combining with
* the background (not recommended).
*/
if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
png_set_strip_alpha(png_ptr);
#endif
#if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
/* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
* byte into separate bytes (useful for paletted and grayscale images).
*/
if (transforms & PNG_TRANSFORM_PACKING)
png_set_packing(png_ptr);
#endif
#ifdef PNG_READ_PACKSWAP_SUPPORTED
/* Change the order of packed pixels to least significant bit first
* (not useful if you are using png_set_packing).
*/
if (transforms & PNG_TRANSFORM_PACKSWAP)
png_set_packswap(png_ptr);
#endif
#ifdef PNG_READ_EXPAND_SUPPORTED
/* Expand paletted colors into true RGB triplets
* Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
* Expand paletted or RGB images with transparency to full alpha
* channels so the data will be available as RGBA quartets.
*/
if (transforms & PNG_TRANSFORM_EXPAND)
if ((png_ptr->bit_depth < 8) ||
(png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
(png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
png_set_expand(png_ptr);
#endif
/* We don't handle background color or gamma transformation or quantizing.
*/
#ifdef PNG_READ_INVERT_SUPPORTED
/* Invert monochrome files to have 0 as white and 1 as black
*/
if (transforms & PNG_TRANSFORM_INVERT_MONO)
png_set_invert_mono(png_ptr);
#endif
#ifdef PNG_READ_SHIFT_SUPPORTED
/* If you want to shift the pixel values from the range [0,255] or
* [0,65535] to the original [0,7] or [0,31], or whatever range the
* colors were originally in:
*/
if ((transforms & PNG_TRANSFORM_SHIFT)
&& png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
{
png_color_8p sig_bit;
png_get_sBIT(png_ptr, info_ptr, &sig_bit);
png_set_shift(png_ptr, sig_bit);
}
#endif
#ifdef PNG_READ_BGR_SUPPORTED
/* Flip the RGB pixels to BGR (or RGBA to BGRA)
*/
if (transforms & PNG_TRANSFORM_BGR)
png_set_bgr(png_ptr);
#endif
#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
/* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
*/
if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
png_set_swap_alpha(png_ptr);
#endif
#ifdef PNG_READ_SWAP_SUPPORTED
/* Swap bytes of 16 bit files to least significant byte first
*/
if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
png_set_swap(png_ptr);
#endif
/* Added at libpng-1.2.41 */
#ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
/* Invert the alpha channel from opacity to transparency
*/
if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
png_set_invert_alpha(png_ptr);
#endif
/* Added at libpng-1.2.41 */
#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
/* Expand grayscale image to RGB
*/
if (transforms & PNG_TRANSFORM_GRAY_TO_RGB)
png_set_gray_to_rgb(png_ptr);
#endif
/* We don't handle adding filler bytes */
/* Optional call to gamma correct and add the background to the palette
* and update info structure. REQUIRED if you are expecting libpng to
* update the palette for you (i.e., you selected such a transform above).
*/
png_read_update_info(png_ptr, info_ptr);
/* -------------- image transformations end here ------------------- */
png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
if (info_ptr->row_pointers == NULL)
{
png_uint_32 iptr;
info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
info_ptr->height * png_sizeof(png_bytep));
for (iptr=0; iptr<info_ptr->height; iptr++)
info_ptr->row_pointers[iptr] = NULL;
info_ptr->free_me |= PNG_FREE_ROWS;
for (row = 0; row < (int)info_ptr->height; row++)
info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
png_get_rowbytes(png_ptr, info_ptr));
}
png_read_image(png_ptr, info_ptr->row_pointers);
info_ptr->valid |= PNG_INFO_IDAT;
/* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
png_read_end(png_ptr, info_ptr);
PNG_UNUSED(transforms) /* Quiet compiler warnings */
PNG_UNUSED(params)
}
#endif /* PNG_INFO_IMAGE_SUPPORTED */
#endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
#endif /* PNG_READ_SUPPORTED */
|
917769.c | /*
* Copyright (c) 2007 - 2020 Joseph Gaeddert
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
// test spectral periodogram (spgram) objects
#include <stdlib.h>
#include "autotest/autotest.h"
#include "liquid.h"
void testbench_spgramcf_noise(unsigned int _nfft,
int _wtype,
float _noise_floor)
{
unsigned int num_samples = 2000*_nfft; // number of samples to generate
float nstd = powf(10.0f,_noise_floor/20.0f); // noise std. dev.
float tol = 0.5f; // error tolerance [dB]
if (liquid_autotest_verbose)
printf(" spgramcf test (noise): nfft=%6u, wtype=%24s, noise floor=%6.1f\n", _nfft, liquid_window_str[_wtype][1], _noise_floor);
// create spectral periodogram
spgramcf q = _wtype == LIQUID_WINDOW_UNKNOWN ? spgramcf_create_default(_nfft) :
spgramcf_create(_nfft, _wtype, _nfft/2, _nfft/4);
unsigned int i;
for (i=0; i<num_samples; i++)
spgramcf_push(q, nstd*( randnf() + _Complex_I*randnf() ) * M_SQRT1_2);
// verify number of samples processed
CONTEND_EQUALITY(spgramcf_get_num_samples(q), num_samples);
CONTEND_EQUALITY(spgramcf_get_num_samples_total(q), num_samples);
// compute power spectral density output
float psd[_nfft];
spgramcf_get_psd(q, psd);
// verify result
for (i=0; i<_nfft; i++)
CONTEND_DELTA(psd[i], _noise_floor, tol)
// destroy objects
spgramcf_destroy(q);
}
// test different transform sizes
void autotest_spgramcf_noise_400() { testbench_spgramcf_noise( 440, 0, -80.0); }
void autotest_spgramcf_noise_1024() { testbench_spgramcf_noise(1024, 0, -80.0); }
void autotest_spgramcf_noise_1200() { testbench_spgramcf_noise(1200, 0, -80.0); }
void autotest_spgramcf_noise_8400() { testbench_spgramcf_noise(8400, 0, -80.0); }
// test different window types
void autotest_spgramcf_noise_hamming () { testbench_spgramcf_noise(800, LIQUID_WINDOW_HAMMING, -80.0); }
void autotest_spgramcf_noise_hann () { testbench_spgramcf_noise(800, LIQUID_WINDOW_HANN, -80.0); }
void autotest_spgramcf_noise_blackmanharris () { testbench_spgramcf_noise(800, LIQUID_WINDOW_BLACKMANHARRIS, -80.0); }
void autotest_spgramcf_noise_blackmanharris7() { testbench_spgramcf_noise(800, LIQUID_WINDOW_BLACKMANHARRIS7,-80.0); }
void autotest_spgramcf_noise_kaiser () { testbench_spgramcf_noise(800, LIQUID_WINDOW_KAISER, -80.0); }
void autotest_spgramcf_noise_flattop () { testbench_spgramcf_noise(800, LIQUID_WINDOW_FLATTOP, -80.0); }
void autotest_spgramcf_noise_triangular () { testbench_spgramcf_noise(800, LIQUID_WINDOW_TRIANGULAR, -80.0); }
void autotest_spgramcf_noise_rcostaper () { testbench_spgramcf_noise(800, LIQUID_WINDOW_RCOSTAPER, -80.0); }
void autotest_spgramcf_noise_kbd () { testbench_spgramcf_noise(800, LIQUID_WINDOW_KBD, -80.0); }
void testbench_spgramcf_signal(unsigned int _nfft, int _wtype, float _fc, float _SNRdB)
{
unsigned int k = 4, m = 12;
float beta = 0.2f, noise_floor = -80.0f, tol = 0.5f;
if (liquid_autotest_verbose)
printf(" spgramcf test (signal): nfft=%6u, wtype=%24s, fc=%6.2f Fs, snr=%6.1f dB\n", _nfft, liquid_window_str[_wtype][1], _fc, _SNRdB);
// create objects
spgramcf q = spgramcf_create(_nfft, _wtype, _nfft/2, _nfft/4);
symstreamcf gen = symstreamcf_create_linear(LIQUID_FIRFILT_KAISER,k,m,beta,LIQUID_MODEM_QPSK);
nco_crcf mixer = nco_crcf_create(LIQUID_VCO);
// set parameters
float nstd = powf(10.0f,noise_floor/20.0f); // noise std. dev.
symstreamcf_set_gain(gen, powf(10.0f, (noise_floor + _SNRdB - 10*log10f(k))/20.0f));
nco_crcf_set_frequency(mixer, 2*M_PI*_fc);
// generate samples and push through spgram object
unsigned int i, buf_len = 256, num_samples = 0;
float complex buf[buf_len];
while (num_samples < 2000*_nfft) {
// generate block of samples
symstreamcf_write_samples(gen, buf, buf_len);
// mix to desired frequency and add noise
nco_crcf_mix_block_up(mixer, buf, buf, buf_len);
for (i=0; i<buf_len; i++)
buf[i] += nstd*(randnf()+_Complex_I*randnf())*M_SQRT1_2;
// run samples through the spgram object
spgramcf_write(q, buf, buf_len);
num_samples += buf_len;
}
// determine appropriate indices
unsigned int i0 = ((unsigned int)roundf((_fc+0.5f)*_nfft)) % _nfft;
unsigned int ns = (unsigned int)roundf(_nfft*(1.0f-beta)/(float)k); // numer of samples to observe
float psd_target = 10*log10f(powf(10.0f,noise_floor/10.0f) + powf(10.0f,(noise_floor+_SNRdB)/10.0f));
//printf("i0=%u, ns=%u (nfft=%u), target=%.3f dB\n", i0, ns, _nfft, psd_target);
// verify result
float psd[_nfft];
spgramcf_get_psd(q, psd);
//for (i=0; i<_nfft; i++) { printf("%6u %8.2f\n", i, psd[i]); }
for (i=0; i<ns; i++) {
unsigned int index = (i0 + i + _nfft - ns/2) % _nfft;
CONTEND_DELTA(psd[index], psd_target, tol)
}
// destroy objects
spgramcf_destroy(q);
symstreamcf_destroy(gen);
nco_crcf_destroy(mixer);
}
void autotest_spgramcf_signal_00() { testbench_spgramcf_signal(800,LIQUID_WINDOW_HAMMING, 0.0f,30.0f); }
void autotest_spgramcf_signal_01() { testbench_spgramcf_signal(800,LIQUID_WINDOW_HAMMING, 0.2f,10.0f); }
void autotest_spgramcf_signal_02() { testbench_spgramcf_signal(800,LIQUID_WINDOW_HANN, 0.2f,10.0f); }
void autotest_spgramcf_signal_03() { testbench_spgramcf_signal(400,LIQUID_WINDOW_KAISER, -0.3f,50.0f); }
void autotest_spgramcf_signal_04() { testbench_spgramcf_signal(640,LIQUID_WINDOW_HAMMING,-0.5f, 0.0f); }
void autotest_spgramcf_signal_05() { testbench_spgramcf_signal(640,LIQUID_WINDOW_HAMMING, 0.1f,-3.0f); }
void autotest_spgramcf_counters()
{
// create spectral periodogram with specific parameters
unsigned int nfft=1200, wlen=400, delay=200;
int wtype = LIQUID_WINDOW_HAMMING;
float alpha = 0.0123456f;
spgramcf q = spgramcf_create(nfft, wtype, wlen, delay);
// check setting bandwidth
CONTEND_EQUALITY ( spgramcf_set_alpha(q, 0.1), 0 ); // valid
CONTEND_DELTA ( spgramcf_get_alpha(q), 0.1, 1e-6f);
CONTEND_EQUALITY ( spgramcf_set_alpha(q,-7.0), -1 ); // invalid
CONTEND_DELTA ( spgramcf_get_alpha(q), 0.1, 1e-6f);
CONTEND_EQUALITY ( spgramcf_set_alpha(q,alpha), 0); // valid
CONTEND_DELTA ( spgramcf_get_alpha(q), alpha, 1e-6f);
spgramcf_print(q); // test for code coverage
// check parameters
CONTEND_EQUALITY( spgramcf_get_nfft(q), nfft );
CONTEND_EQUALITY( spgramcf_get_window_len(q), wlen );
CONTEND_EQUALITY( spgramcf_get_delay(q), delay);
CONTEND_EQUALITY( spgramcf_get_alpha(q), alpha);
unsigned int block_len = 1117, num_blocks = 1123;
unsigned int i, num_samples = block_len * num_blocks;
unsigned int num_transforms = num_samples / delay;
for (i=0; i<num_samples; i++)
spgramcf_push(q, randnf() + _Complex_I*randnf());
// verify number of samples and transforms processed
CONTEND_EQUALITY(spgramcf_get_num_samples(q), num_samples);
CONTEND_EQUALITY(spgramcf_get_num_samples_total(q), num_samples);
CONTEND_EQUALITY(spgramcf_get_num_transforms(q), num_transforms);
CONTEND_EQUALITY(spgramcf_get_num_transforms_total(q), num_transforms);
// clear object and run in blocks
spgramcf_clear(q);
float complex block[block_len];
for (i=0; i<block_len; i++)
block[i] = randnf() + _Complex_I*randnf();
for (i=0; i<num_blocks; i++)
spgramcf_write(q, block, block_len);
// re-verify number of samples and transforms processed
CONTEND_EQUALITY(spgramcf_get_num_samples(q), num_samples);
CONTEND_EQUALITY(spgramcf_get_num_samples_total(q), num_samples * 2);
CONTEND_EQUALITY(spgramcf_get_num_transforms(q), num_transforms);
CONTEND_EQUALITY(spgramcf_get_num_transforms_total(q), num_transforms * 2);
// reset object and ensure counters are zero
spgramcf_reset(q);
CONTEND_EQUALITY(spgramcf_get_num_samples(q), 0);
CONTEND_EQUALITY(spgramcf_get_num_samples_total(q), 0);
CONTEND_EQUALITY(spgramcf_get_num_transforms(q), 0);
CONTEND_EQUALITY(spgramcf_get_num_transforms_total(q), 0);
// destroy object(s)
spgramcf_destroy(q);
}
void autotest_spgramcf_config_errors()
{
// check that object returns NULL for invalid configurations
fprintf(stderr,"warning: ignore potential errors here; checking for invalid configurations\n");
CONTEND_EQUALITY(spgramcf_create( 0, LIQUID_WINDOW_HAMMING, 200, 200)==NULL,1); // nfft too small
CONTEND_EQUALITY(spgramcf_create( 1, LIQUID_WINDOW_HAMMING, 200, 200)==NULL,1); // nfft too small
CONTEND_EQUALITY(spgramcf_create( 2, LIQUID_WINDOW_HAMMING, 200, 200)==NULL,1); // window length too large
CONTEND_EQUALITY(spgramcf_create(400, LIQUID_WINDOW_HAMMING, 0, 200)==NULL,1); // window length too small
CONTEND_EQUALITY(spgramcf_create(400, LIQUID_WINDOW_UNKNOWN, 200, 200)==NULL,1); // invalid window type
CONTEND_EQUALITY(spgramcf_create(400, LIQUID_WINDOW_NUM_FUNCTIONS, 200, 200)==NULL,1); // invalid window type
CONTEND_EQUALITY(spgramcf_create(400, LIQUID_WINDOW_KBD, 201, 200)==NULL,1); // KBD must be even
CONTEND_EQUALITY(spgramcf_create(400, LIQUID_WINDOW_HAMMING, 200, 0)==NULL,1); // delay too small
// check that object returns NULL for invalid configurations (default)
CONTEND_EQUALITY(spgramcf_create_default(0)==NULL,1); // nfft too small
CONTEND_EQUALITY(spgramcf_create_default(1)==NULL,1); // nfft too small
}
void autotest_spgramcf_standalone()
{
unsigned int nfft = 1200;
unsigned int num_samples = 20*nfft; // number of samples to generate
float noise_floor = -20.0f;
float nstd = powf(10.0f,noise_floor/20.0f); // noise std. dev.
float complex * buf = (float complex*)malloc(num_samples*sizeof(float complex));
unsigned int i;
for (i=0; i<num_samples; i++)
buf[i] = 0.1f + nstd*(randnf()+_Complex_I*randnf())*M_SQRT1_2;
float psd[nfft];
spgramcf_estimate_psd(nfft, buf, num_samples, psd);
// check mask
for (i=0; i<nfft; i++) {
float mask_lo = i ==nfft/2 ? 2.0f : noise_floor - 3.0f;
float mask_hi = i > nfft/2-10 && i < nfft/2+10 ? 8.0f : noise_floor + 3.0f;
if (liquid_autotest_verbose)
printf("%6u : %8.2f < %8.2f < %8.2f\n", i, mask_lo, psd[i], mask_hi);
CONTEND_GREATER_THAN( psd[i], mask_lo );
CONTEND_LESS_THAN ( psd[i], mask_hi );
}
// free memory
free(buf);
}
// check spectral periodogram operation where the input size is much shorter
// than the transform size
void autotest_spgramcf_short()
{
unsigned int nfft = 1200; // transform size
unsigned int num_samples = 200; // number of samples to generate
float noise_floor = -20.0f;
float nstd = powf(10.0f,noise_floor/20.0f); // noise std. dev.
float complex * buf = (float complex*)malloc(num_samples*sizeof(float complex));
unsigned int i;
for (i=0; i<num_samples; i++)
buf[i] = 1.0f + nstd*(randnf()+_Complex_I*randnf())*M_SQRT1_2;
float psd[nfft];
spgramcf_estimate_psd(nfft, buf, num_samples, psd);
// use a very loose upper mask as we have only computed a few hundred samples
for (i=0; i<nfft; i++) {
float f = (float)i / (float)nfft - 0.5f;
float mask_hi = fabsf(f) < 0.2f ? 15.0f - 30*fabsf(f)/0.2f : -15.0f;
if (liquid_autotest_verbose)
printf("%6u : f=%6.3f, %8.2f < %8.2f\n", i, f, psd[i], mask_hi);
CONTEND_LESS_THAN( psd[i], mask_hi );
}
// consider lower mask only for DC term
float mask_lo = 0.0f;
unsigned int nfft_2 = nfft/2;
if (liquid_autotest_verbose)
printf(" DC : f=%6.3f, %8.2f > %8.2f\n", 0.0f, psd[nfft_2], mask_lo);
CONTEND_GREATER_THAN( psd[nfft_2], mask_lo );
// free memory
free(buf);
}
// check spectral periodogram behavior on null input (zero samples)
void autotest_spgramcf_null()
{
unsigned int nfft = 1200; // transform size
float psd[nfft];
spgramcf_estimate_psd(nfft, NULL, 0, psd);
// value should be exactly minimum
float psd_val = 10*log10f(LIQUID_SPGRAM_PSD_MIN);
unsigned int i;
for (i=0; i<nfft; i++)
CONTEND_EQUALITY(psd[i], psd_val);
}
|
444299.c | /* Expands a blossom. Fixes up LINK and MATE. */
void
UNPAIR (int oldbase, int oldmate)
{ int e, newbase, u;
#ifdef DEBUG
printf("Unpair oldbase, oldmate=%d %d\n",oldbase, oldmate);
#endif
UNLINK (oldbase);
newbase = BMATE (oldmate);
if (newbase != oldbase) {
LINK [oldbase] = -DUMMYEDGE;
REMATCH (newbase, MATE[oldbase]);
if (f == LASTEDGE[1])
LINK[secondmate] = -LASTEDGE[2];
else LINK[secondmate] = -LASTEDGE[1];
}
e = LINK[oldmate];
u = BEND (OPPEDGE (e));
if (u == newbase) {
POINTER (newbase, oldmate, e);
return;
}
LINK[BMATE (u)] = -e;
do {
e = -LINK[u];
v = BMATE (u);
POINTER (u, v, -LINK[v]);
u = BEND (e);
} while (u != newbase);
e = OPPEDGE (e);
POINTER (newbase, oldmate, e);
}
/* changes the matching along an alternating path */
/* firstmate is the first base vertex on the path */
/* edge e is the new matched edge for firstmate */
void
REMATCH (int firstmate, int e)
{
#ifdef DEBUG
printf("Rematch firstmate=%d e=%d-%d\n",firstmate, END[OPPEDGE(e)], END[e]);
#endif
MATE[firstmate] = e;
nexte = -LINK[firstmate];
while (nexte != DUMMYEDGE) {
e = nexte;
f = OPPEDGE (e);
firstmate = BEND (e);
secondmate = BEND (f);
nexte = -LINK[firstmate];
LINK[firstmate] = -MATE[secondmate];
LINK[secondmate] = -MATE[firstmate];
MATE[firstmate] = f;
MATE[secondmate] = e;
}
}
/* unlinks subblossoms in a blossom. oldbase is the base of the blossom to */
/* be unlinked. */
void
UNLINK (int oldbase)
{ int k, j=1;
#ifdef DEBUG
printf("Unlink oldbase=%d\n",oldbase);
#endif
i = NEXTVTX[oldbase];
newbase = NEXTVTX[oldbase];
nextbase = NEXTVTX[LASTVTX[newbase]];
e = LINK[nextbase];
UL2:
do {
nextedge = OPPEDGE (LINK[newbase]);
for (k=1; k <= 2; ++k) {
LINK[newbase] = -LINK[newbase];
BASE[i] = newbase;
i = NEXTVTX[i];
while (i != nextbase) {
BASE[i] = newbase;
i = NEXTVTX[i];
}
newbase = nextbase;
nextbase = NEXTVTX[LASTVTX[newbase]];
}
} while (LINK[nextbase] == nextedge);
if (j==1) {
LASTEDGE[1] = nextedge;
j++;
nextedge = OPPEDGE (e);
if (LINK[nextbase] == nextedge) {
goto UL2;
}
}
LASTEDGE[2] = nextedge;
if (BASE[LASTVTX[oldbase]] == oldbase)
NEXTVTX[oldbase] = newbase;
else {
NEXTVTX[oldbase] = DUMMYVERTEX;
LASTVTX[oldbase] = oldbase;
}
}
|
764974.c | /**
* \file
*
* \brief Chip-specific system clock manager configuration
*
* Copyright (c) 2011-2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* 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. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \asf_license_stop
*
*/
/*
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#ifndef CONF_CLOCK_H_INCLUDED
#define CONF_CLOCK_H_INCLUDED
//#define CONFIG_SYSCLK_SOURCE SYSCLK_SRC_RC2MHZ
//#define CONFIG_SYSCLK_SOURCE SYSCLK_SRC_RC32MHZ
//#define CONFIG_SYSCLK_SOURCE SYSCLK_SRC_RC32KHZ
//#define CONFIG_SYSCLK_SOURCE SYSCLK_SRC_XOSC
#define CONFIG_SYSCLK_SOURCE SYSCLK_SRC_PLL
/* Fbus = Fsys / (2 ^ BUS_div) */
#define CONFIG_SYSCLK_PSADIV SYSCLK_PSADIV_1
#define CONFIG_SYSCLK_PSBCDIV SYSCLK_PSBCDIV_1_1
#define CONFIG_PLL0_SOURCE PLL_SRC_XOSC
//#define CONFIG_PLL0_SOURCE PLL_SRC_RC2MHZ
//#define CONFIG_PLL0_SOURCE PLL_SRC_RC32MHZ
/* Fpll = (Fclk * PLL_mul) / PLL_div */
//#define CONFIG_PLL0_MUL (24000000UL / BOARD_XOSC_HZ)
#define CONFIG_PLL0_DIV 1
#define CONFIG_PLL0_MUL 3
#define BOARD_XOSC_HZ 16000000UL
#define BOARD_XOSC_STARTUP_US 1000
#define BOARD_XOSC_TYPE XOSC_TYPE_XTAL
//#define CONFIG_XOSC_STARTUP
/* External oscillator frequency range */
/** 0.4 to 2 MHz frequency range */
//#define CONFIG_XOSC_RANGE XOSC_RANGE_04TO2
/** 2 to 9 MHz frequency range */
//#define CONFIG_XOSC_RANGE XOSC_RANGE_2TO9
/** 9 to 12 MHz frequency range */
//#define CONFIG_XOSC_RANGE XOSC_RANGE_9TO12
/** 12 to 16 MHz frequency range */
#define CONFIG_XOSC_RANGE XOSC_RANGE_12TO16
/* DFLL autocalibration */
//#define CONFIG_OSC_AUTOCAL_RC2MHZ_REF_OSC OSC_ID_RC32KHZ
//#define CONFIG_OSC_AUTOCAL_RC32MHZ_REF_OSC OSC_ID_XOSC
/* The following example clock configuration definitions can be used in XMEGA
* devices that contain a USB controller. It configures the USB controller clock
* source to use the internal (nominally) 32MHz RC oscillator, up-calibrated to
* run at 48MHz via the periodic 1ms USB Start Of Frame packets sent by the
* host. The USB controller requires 48MHz for Full Speed operation, or 6MHz
* for USB Low Speed operation.
*
* Note that when the 32MHz RC oscillator is tuned to 48MHz, it cannot be used
* directly as the system clock source; it must either be prescaled down to a
* speed below the maximum operating frequency given in the datasheet, or an
* alternative clock source (e.g. the internal 2MHz RC Oscillator, multiplied
* to a higher frequency via the internal PLL module) must be used instead.
*/
#define CONFIG_USBCLK_SOURCE USBCLK_SRC_PLL
//#define CONFIG_OSC_RC32_CAL 48000000UL
//#define CONFIG_OSC_AUTOCAL_RC32MHZ_REF_OSC OSC_ID_USBSOF
/* Use to enable and select RTC clock source */
//#define CONFIG_RTC_SOURCE SYSCLK_RTCSRC_ULP
#endif /* CONF_CLOCK_H_INCLUDED */
|
850990.c | /*
* -----------------------------------------------------------------
* $Revision: 1.6 $
* $Date: 2009/02/17 02:42:29 $
* -----------------------------------------------------------------
* Programmer(s): Scott D. Cohen, Alan C. Hindmarsh and
* Radu Serban @ LLNL
* -----------------------------------------------------------------
* Copyright (c) 2002, The Regents of the University of California.
* Produced at the Lawrence Livermore National Laboratory.
* All rights reserved.
* For details, see the LICENSE file.
* -----------------------------------------------------------------
* This is the implementation file for a generic package of dense
* matrix operations.
* -----------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <sundials_dense.h>
#include <sundials_math.h>
#define ZERO RCONST(0.0)
#define ONE RCONST(1.0)
#define TWO RCONST(2.0)
/*
* -----------------------------------------------------
* Functions working on DlsMat
* -----------------------------------------------------
*/
int DenseGETRF(DlsMat A, int *p)
{
return(denseGETRF(A->cols, A->M, A->N, p));
}
void DenseGETRS(DlsMat A, int *p, realtype *b)
{
denseGETRS(A->cols, A->N, p, b);
}
int DensePOTRF(DlsMat A)
{
return(densePOTRF(A->cols, A->M));
}
void DensePOTRS(DlsMat A, realtype *b)
{
densePOTRS(A->cols, A->M, b);
}
int DenseGEQRF(DlsMat A, realtype *beta, realtype *wrk)
{
return(denseGEQRF(A->cols, A->M, A->N, beta, wrk));
}
int DenseORMQR(DlsMat A, realtype *beta, realtype *vn, realtype *vm, realtype *wrk)
{
return(denseORMQR(A->cols, A->M, A->N, beta, vn, vm, wrk));
}
void DenseCopy(DlsMat A, DlsMat B)
{
denseCopy(A->cols, B->cols, A->M, A->N);
}
void DenseScale(realtype c, DlsMat A)
{
denseScale(c, A->cols, A->M, A->N);
}
int denseGETRF(realtype **a, int m, int n, int *p)
{
int i, j, k, l;
realtype *col_j, *col_k;
realtype temp, mult, a_kj;
/* k-th elimination step number */
for (k=0; k < n; k++) {
col_k = a[k];
/* find l = pivot row number */
l=k;
for (i=k+1; i < m; i++)
if (ABS(col_k[i]) > ABS(col_k[l])) l=i;
p[k] = l;
/* check for zero pivot element */
if (col_k[l] == ZERO) return(k+1);
/* swap a(k,1:n) and a(l,1:n) if necessary */
if ( l!= k ) {
for (i=0; i<n; i++) {
temp = a[i][l];
a[i][l] = a[i][k];
a[i][k] = temp;
}
}
/* Scale the elements below the diagonal in
* column k by 1.0/a(k,k). After the above swap
* a(k,k) holds the pivot element. This scaling
* stores the pivot row multipliers a(i,k)/a(k,k)
* in a(i,k), i=k+1, ..., m-1.
*/
mult = ONE/col_k[k];
for(i=k+1; i < m; i++) col_k[i] *= mult;
/* row_i = row_i - [a(i,k)/a(k,k)] row_k, i=k+1, ..., m-1 */
/* row k is the pivot row after swapping with row l. */
/* The computation is done one column at a time, */
/* column j=k+1, ..., n-1. */
for (j=k+1; j < n; j++) {
col_j = a[j];
a_kj = col_j[k];
/* a(i,j) = a(i,j) - [a(i,k)/a(k,k)]*a(k,j) */
/* a_kj = a(k,j), col_k[i] = - a(i,k)/a(k,k) */
if (a_kj != ZERO) {
for (i=k+1; i < m; i++)
col_j[i] -= a_kj * col_k[i];
}
}
}
/* return 0 to indicate success */
return(0);
}
void denseGETRS(realtype **a, int n, int *p, realtype *b)
{
int i, k, pk;
realtype *col_k, tmp;
/* Permute b, based on pivot information in p */
for (k=0; k<n; k++) {
pk = p[k];
if(pk != k) {
tmp = b[k];
b[k] = b[pk];
b[pk] = tmp;
}
}
/* Solve Ly = b, store solution y in b */
for (k=0; k<n-1; k++) {
col_k = a[k];
for (i=k+1; i<n; i++) b[i] -= col_k[i]*b[k];
}
/* Solve Ux = y, store solution x in b */
for (k = n-1; k > 0; k--) {
col_k = a[k];
b[k] /= col_k[k];
for (i=0; i<k; i++) b[i] -= col_k[i]*b[k];
}
b[0] /= a[0][0];
}
/*
* Cholesky decomposition of a symmetric positive-definite matrix
* A = C^T*C: gaxpy version.
* Only the lower triangle of A is accessed and it is overwritten with
* the lower triangle of C.
*/
int densePOTRF(realtype **a, int m)
{
realtype *a_col_j, *a_col_k;
realtype a_diag;
int i, j, k;
for (j=0; j<m; j++) {
a_col_j = a[j];
if (j>0) {
for(i=j; i<m; i++) {
for(k=0;k<j;k++) {
a_col_k = a[k];
a_col_j[i] -= a_col_k[i]*a_col_k[j];
}
}
}
a_diag = a_col_j[j];
if (a_diag <= ZERO) return(j);
a_diag = RSqrt(a_diag);
for(i=j; i<m; i++) a_col_j[i] /= a_diag;
}
return(0);
}
/*
* Solution of Ax=b, with A s.p.d., based on the Cholesky decomposition
* obtained with denPOTRF.; A = C*C^T, C lower triangular
*
*/
void densePOTRS(realtype **a, int m, realtype *b)
{
realtype *col_j, *col_i;
int i, j;
/* Solve C y = b, forward substitution - column version.
Store solution y in b */
for (j=0; j < m-1; j++) {
col_j = a[j];
b[j] /= col_j[j];
for (i=j+1; i < m; i++)
b[i] -= b[j]*col_j[i];
}
col_j = a[m-1];
b[m-1] /= col_j[m-1];
/* Solve C^T x = y, backward substitution - row version.
Store solution x in b */
col_j = a[m-1];
b[m-1] /= col_j[m-1];
for (i=m-2; i>=0; i--) {
col_i = a[i];
for (j=i+1; j<m; j++)
b[i] -= col_i[j]*b[j];
b[i] /= col_i[i];
}
}
/*
* QR factorization of a rectangular matrix A of size m by n (m >= n)
* using Householder reflections.
*
* On exit, the elements on and above the diagonal of A contain the n by n
* upper triangular matrix R; the elements below the diagonal, with the array beta,
* represent the orthogonal matrix Q as a product of elementary reflectors .
*
* v (of length m) must be provided as workspace.
*
*/
int denseGEQRF(realtype **a, int m, int n, realtype *beta, realtype *v)
{
realtype ajj, s, mu, v1, v1_2;
realtype *col_j, *col_k;
int i, j, k;
/* For each column...*/
for(j=0; j<n; j++) {
col_j = a[j];
ajj = col_j[j];
/* Compute the j-th Householder vector (of length m-j) */
v[0] = ONE;
s = ZERO;
for(i=1; i<m-j; i++) {
v[i] = col_j[i+j];
s += v[i]*v[i];
}
if(s != ZERO) {
mu = RSqrt(ajj*ajj+s);
v1 = (ajj <= ZERO) ? ajj-mu : -s/(ajj+mu);
v1_2 = v1*v1;
beta[j] = TWO * v1_2 / (s + v1_2);
for(i=1; i<m-j; i++) v[i] /= v1;
} else {
beta[j] = ZERO;
}
/* Update upper triangle of A (load R) */
for(k=j; k<n; k++) {
col_k = a[k];
s = ZERO;
for(i=0; i<m-j; i++) s += col_k[i+j]*v[i];
s *= beta[j];
for(i=0; i<m-j; i++) col_k[i+j] -= s*v[i];
}
/* Update A (load Householder vector) */
if(j<m-1) {
for(i=1; i<m-j; i++) col_j[i+j] = v[i];
}
}
return(0);
}
/*
* Computes vm = Q * vn, where the orthogonal matrix Q is stored as
* elementary reflectors in the m by n matrix A and in the vector beta.
* (NOTE: It is assumed that an QR factorization has been previously
* computed with denGEQRF).
*
* vn (IN) has length n, vm (OUT) has length m, and it's assumed that m >= n.
*
* v (of length m) must be provided as workspace.
*/
int denseORMQR(realtype **a, int m, int n, realtype *beta,
realtype *vn, realtype *vm, realtype *v)
{
realtype *col_j, s;
int i, j;
/* Initialize vm */
for(i=0; i<n; i++) vm[i] = vn[i];
for(i=n; i<m; i++) vm[i] = ZERO;
/* Accumulate (backwards) corrections into vm */
for(j=n-1; j>=0; j--) {
col_j = a[j];
v[0] = ONE;
s = vm[j];
for(i=1; i<m-j; i++) {
v[i] = col_j[i+j];
s += v[i]*vm[i+j];
}
s *= beta[j];
for(i=0; i<m-j; i++) vm[i+j] -= s * v[i];
}
return(0);
}
void denseCopy(realtype **a, realtype **b, int m, int n)
{
int i, j;
realtype *a_col_j, *b_col_j;
for (j=0; j < n; j++) {
a_col_j = a[j];
b_col_j = b[j];
for (i=0; i < m; i++)
b_col_j[i] = a_col_j[i];
}
}
void denseScale(realtype c, realtype **a, int m, int n)
{
int i, j;
realtype *col_j;
for (j=0; j < n; j++) {
col_j = a[j];
for (i=0; i < m; i++)
col_j[i] *= c;
}
}
void denseAddIdentity(realtype **a, int n)
{
int i;
for (i=0; i < n; i++) a[i][i] += ONE;
}
|
896818.c | #include "varints.h"
#define VARINT_SEGMENT 0x7F
#define VARINT_CONTINUE 0x80
inline i32 varint_size(u64 value)
{
i32 size = 1;
while (value > VARINT_SEGMENT)
{
value >>= 7;
size++;
}
return size;
}
inline void varlong_encode(u8 *buffer, u64 value)
{
do {
u8 byte = value & VARINT_SEGMENT;
value >>= 7;
if (value != 0) byte |= VARINT_CONTINUE;
*buffer++ = byte;
} while (value != 0);
}
inline i64 varlong_decode(const u8 *buffer)
{
u64 value = 0;
u64 shift = 0;
u8 byte = 0;
do {
byte = *buffer++;
value |= (u64) (byte & VARINT_SEGMENT) << shift;
shift += 7;
} while (byte & VARINT_CONTINUE);
return value;
}
|
445111.c | #include <stdio.h>
#include <stdlib.h>
#include "../inc/stack.h"
struct Stack_t
{
int num_stack[MAX_STACK_SIZE];
int ptr;
};
typedef struct Stack_t Stack_t;
typedef struct Stack_t * pStack_t;
pStack_t pgGameStack;
int stack_init(void)
{
int result = -1;
pgGameStack = (pStack_t)malloc(sizeof(Stack_t));
if (pgGameStack)
{
pgGameStack->ptr = 0;
result = 0;
}
return result;
}
void stack_deinit(void)
{
free(pgGameStack);
}
void stack_clear(void)
{
if (pgGameStack)
{
pgGameStack->ptr = 0;
}
}
int stack_pop(void)
{
int result = -1;
if (pgGameStack)
{
if (pgGameStack->ptr)
{
result = pgGameStack->num_stack[--pgGameStack->ptr];
{
int i;
printf("\n");
for (i = 0; i < pgGameStack->ptr; i++)
{
printf("%-2d ", pgGameStack->num_stack[i]);
}
}
}
}
return result;
}
int stack_push(int n)
{
int result = -1;
if (pgGameStack)
{
if (pgGameStack->ptr < MAX_STACK_SIZE)
{
pgGameStack->num_stack[pgGameStack->ptr++] = n;
printf("%-2d ", n);
result = 0;
}
}
return result;
}
void print_spacetilltop(void)
{
if (pgGameStack)
{
int i;
for (i = 0; i < pgGameStack->ptr; i++)
{
printf(" ");
}
}
}
int stack_first(void)
{
if (pgGameStack)
{
if (pgGameStack->ptr)
{
return pgGameStack->num_stack[0];
}
}
return -1;
}
int stack_last(void)
{
if (pgGameStack)
{
if (pgGameStack->ptr)
{
return pgGameStack->num_stack[pgGameStack->ptr - 1];
}
}
return -1;
}
|
462657.c | /*-
* Copyright 2016 Vsevolod Stakhov
*
* 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 "config.h"
#include "libutil/util.h"
#include "libutil/http_connection.h"
#include "libutil/http_private.h"
#include "rspamdclient.h"
#include "utlist.h"
#include "unix-std.h"
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#define DEFAULT_PORT 11333
#define DEFAULT_CONTROL_PORT 11334
static gchar *connect_str = "localhost";
static gchar *password = NULL;
static gchar *ip = NULL;
static gchar *from = NULL;
static gchar *deliver_to = NULL;
static gchar **rcpts = NULL;
static gchar *user = NULL;
static gchar *helo = NULL;
static gchar *hostname = NULL;
static gchar *classifier = NULL;
static gchar *local_addr = NULL;
static gchar *execute = NULL;
static gchar *sort = NULL;
static gchar **http_headers = NULL;
static gchar **exclude_patterns = NULL;
static gint weight = 0;
static gint flag = 0;
static gchar *fuzzy_symbol = NULL;
static gchar *dictionary = NULL;
static gint max_requests = 8;
static gdouble timeout = 10.0;
static gboolean pass_all;
static gboolean tty = FALSE;
static gboolean verbose = FALSE;
static gboolean print_commands = FALSE;
static gboolean json = FALSE;
static gboolean compact = FALSE;
static gboolean headers = FALSE;
static gboolean raw = FALSE;
static gboolean extended_urls = FALSE;
static gboolean mime_output = FALSE;
static gboolean empty_input = FALSE;
static gboolean compressed = FALSE;
static gboolean profile = FALSE;
static gboolean skip_images = FALSE;
static gboolean skip_attachments = FALSE;
static gchar *key = NULL;
static gchar *user_agent = "rspamc";
static GList *children;
static GPatternSpec **exclude_compiled = NULL;
static struct rspamd_http_context *http_ctx;
static gint retcode = EXIT_SUCCESS;
#define ADD_CLIENT_HEADER(o, n, v) do { \
struct rspamd_http_client_header *nh; \
nh = g_malloc (sizeof (*nh)); \
nh->name = g_strdup (n); \
nh->value = g_strdup (v); \
g_queue_push_tail ((o), nh); \
} while (0)
#define ADD_CLIENT_FLAG(str, n) do { \
g_string_append ((str), (n)); \
} while (0)
static gboolean rspamc_password_callback (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error);
static GOptionEntry entries[] =
{
{ "connect", 'h', 0, G_OPTION_ARG_STRING, &connect_str,
"Specify host and port", NULL },
{ "password", 'P', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK,
&rspamc_password_callback, "Specify control password", NULL },
{ "classifier", 'c', 0, G_OPTION_ARG_STRING, &classifier,
"Classifier to learn spam or ham", NULL },
{ "weight", 'w', 0, G_OPTION_ARG_INT, &weight,
"Weight for fuzzy operations", NULL },
{ "flag", 'f', 0, G_OPTION_ARG_INT, &flag, "Flag for fuzzy operations",
NULL },
{ "pass-all", 'p', 0, G_OPTION_ARG_NONE, &pass_all, "Pass all filters",
NULL },
{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "More verbose output",
NULL },
{ "ip", 'i', 0, G_OPTION_ARG_STRING, &ip,
"Emulate that message was received from specified ip address",
NULL },
{ "user", 'u', 0, G_OPTION_ARG_STRING, &user,
"Emulate that message was received from specified authenticated user", NULL },
{ "deliver", 'd', 0, G_OPTION_ARG_STRING, &deliver_to,
"Emulate that message is delivered to specified user (for LDA/statistics)", NULL },
{ "from", 'F', 0, G_OPTION_ARG_STRING, &from,
"Emulate that message has specified SMTP FROM address", NULL },
{ "rcpt", 'r', 0, G_OPTION_ARG_STRING_ARRAY, &rcpts,
"Emulate that message has specified SMTP RCPT address", NULL },
{ "helo", 0, 0, G_OPTION_ARG_STRING, &helo,
"Imitate SMTP HELO passing from MTA", NULL },
{ "hostname", 0, 0, G_OPTION_ARG_STRING, &hostname,
"Imitate hostname passing from MTA", NULL },
{ "timeout", 't', 0, G_OPTION_ARG_DOUBLE, &timeout,
"Time in seconds to wait for a reply", NULL },
{ "bind", 'b', 0, G_OPTION_ARG_STRING, &local_addr,
"Bind to specified ip address", NULL },
{ "commands", 0, 0, G_OPTION_ARG_NONE, &print_commands,
"List available commands", NULL },
{ "json", 'j', 0, G_OPTION_ARG_NONE, &json, "Output json reply", NULL },
{ "compact", '\0', 0, G_OPTION_ARG_NONE, &compact, "Output compact json reply", NULL},
{ "headers", 0, 0, G_OPTION_ARG_NONE, &headers, "Output HTTP headers",
NULL },
{ "raw", 0, 0, G_OPTION_ARG_NONE, &raw, "Output raw reply from rspamd",
NULL },
{ "ucl", 0, 0, G_OPTION_ARG_NONE, &raw, "Output ucl reply from rspamd",
NULL },
{ "max-requests", 'n', 0, G_OPTION_ARG_INT, &max_requests,
"Maximum count of parallel requests to rspamd", NULL },
{ "extended-urls", 0, 0, G_OPTION_ARG_NONE, &extended_urls,
"Output urls in extended format", NULL },
{ "key", 0, 0, G_OPTION_ARG_STRING, &key,
"Use specified pubkey to encrypt request", NULL },
{ "exec", 'e', 0, G_OPTION_ARG_STRING, &execute,
"Execute the specified command and pass output to it", NULL },
{ "mime", 'm', 0, G_OPTION_ARG_NONE, &mime_output,
"Write mime body of message with headers instead of just a scan's result", NULL },
{"header", 0, 0, G_OPTION_ARG_STRING_ARRAY, &http_headers,
"Add custom HTTP header to query (can be repeated)", NULL},
{"exclude", 0, 0, G_OPTION_ARG_STRING_ARRAY, &exclude_patterns,
"Exclude specific glob patterns in file names (can be repeated)", NULL},
{"sort", 0, 0, G_OPTION_ARG_STRING, &sort,
"Sort output in a specific order (name, weight, frequency, hits)", NULL},
{ "empty", 'E', 0, G_OPTION_ARG_NONE, &empty_input,
"Allow empty input instead of reading from stdin", NULL },
{ "fuzzy-symbol", 'S', 0, G_OPTION_ARG_STRING, &fuzzy_symbol,
"Learn the specified fuzzy symbol", NULL },
{ "compressed", 'z', 0, G_OPTION_ARG_NONE, &compressed,
"Enable zstd compression", NULL },
{ "profile", '\0', 0, G_OPTION_ARG_NONE, &profile,
"Profile symbols execution time", NULL },
{ "dictionary", 'D', 0, G_OPTION_ARG_FILENAME, &dictionary,
"Use dictionary to compress data", NULL },
{ "skip-images", '\0', 0, G_OPTION_ARG_NONE, &skip_images,
"Skip images when learning/unlearning fuzzy", NULL },
{ "skip-attachments", '\0', 0, G_OPTION_ARG_NONE, &skip_attachments,
"Skip attachments when learning/unlearning fuzzy", NULL },
{ "user-agent", 'U', 0, G_OPTION_ARG_STRING, &user_agent,
"Use specific User-Agent instead of \"rspamc\"", NULL },
{ NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL }
};
/* Copy to avoid linking with librspamdserver */
enum rspamd_action_type {
METRIC_ACTION_REJECT = 0,
METRIC_ACTION_SOFT_REJECT,
METRIC_ACTION_REWRITE_SUBJECT,
METRIC_ACTION_ADD_HEADER,
METRIC_ACTION_GREYLIST,
METRIC_ACTION_NOACTION,
METRIC_ACTION_MAX
};
static void rspamc_symbols_output (FILE *out, ucl_object_t *obj);
static void rspamc_uptime_output (FILE *out, ucl_object_t *obj);
static void rspamc_counters_output (FILE *out, ucl_object_t *obj);
static void rspamc_stat_output (FILE *out, ucl_object_t *obj);
enum rspamc_command_type {
RSPAMC_COMMAND_UNKNOWN = 0,
RSPAMC_COMMAND_CHECK,
RSPAMC_COMMAND_SYMBOLS,
RSPAMC_COMMAND_LEARN_SPAM,
RSPAMC_COMMAND_LEARN_HAM,
RSPAMC_COMMAND_FUZZY_ADD,
RSPAMC_COMMAND_FUZZY_DEL,
RSPAMC_COMMAND_FUZZY_DELHASH,
RSPAMC_COMMAND_STAT,
RSPAMC_COMMAND_STAT_RESET,
RSPAMC_COMMAND_COUNTERS,
RSPAMC_COMMAND_UPTIME,
RSPAMC_COMMAND_ADD_SYMBOL,
RSPAMC_COMMAND_ADD_ACTION
};
struct rspamc_command {
enum rspamc_command_type cmd;
const char *name;
const char *description;
const char *path;
gboolean is_controller;
gboolean is_privileged;
gboolean need_input;
void (*command_output_func)(FILE *, ucl_object_t *obj);
} rspamc_commands[] = {
{
.cmd = RSPAMC_COMMAND_SYMBOLS,
.name = "symbols",
.path = "checkv2",
.description = "scan message and show symbols (default command)",
.is_controller = FALSE,
.is_privileged = FALSE,
.need_input = TRUE,
.command_output_func = rspamc_symbols_output
},
{
.cmd = RSPAMC_COMMAND_LEARN_SPAM,
.name = "learn_spam",
.path = "learnspam",
.description = "learn message as spam",
.is_controller = TRUE,
.is_privileged = TRUE,
.need_input = TRUE,
.command_output_func = NULL
},
{
.cmd = RSPAMC_COMMAND_LEARN_HAM,
.name = "learn_ham",
.path = "learnham",
.description = "learn message as ham",
.is_controller = TRUE,
.is_privileged = TRUE,
.need_input = TRUE,
.command_output_func = NULL
},
{
.cmd = RSPAMC_COMMAND_FUZZY_ADD,
.name = "fuzzy_add",
.path = "fuzzyadd",
.description =
"add hashes from a message to the fuzzy storage (check -f and -w options for this command)",
.is_controller = TRUE,
.is_privileged = TRUE,
.need_input = TRUE,
.command_output_func = NULL
},
{
.cmd = RSPAMC_COMMAND_FUZZY_DEL,
.name = "fuzzy_del",
.path = "fuzzydel",
.description =
"delete hashes from a message from the fuzzy storage (check -f option for this command)",
.is_controller = TRUE,
.is_privileged = TRUE,
.need_input = TRUE,
.command_output_func = NULL
},
{
.cmd = RSPAMC_COMMAND_FUZZY_DELHASH,
.name = "fuzzy_delhash",
.path = "fuzzydelhash",
.description =
"delete a hash from fuzzy storage (check -f option for this command)",
.is_controller = TRUE,
.is_privileged = TRUE,
.need_input = FALSE,
.command_output_func = NULL
},
{
.cmd = RSPAMC_COMMAND_STAT,
.name = "stat",
.path = "stat",
.description = "show rspamd statistics",
.is_controller = TRUE,
.is_privileged = FALSE,
.need_input = FALSE,
.command_output_func = rspamc_stat_output,
},
{
.cmd = RSPAMC_COMMAND_STAT_RESET,
.name = "stat_reset",
.path = "statreset",
.description = "show and reset rspamd statistics (useful for graphs)",
.is_controller = TRUE,
.is_privileged = TRUE,
.need_input = FALSE,
.command_output_func = rspamc_stat_output
},
{
.cmd = RSPAMC_COMMAND_COUNTERS,
.name = "counters",
.path = "counters",
.description = "display rspamd symbols statistics",
.is_controller = TRUE,
.is_privileged = FALSE,
.need_input = FALSE,
.command_output_func = rspamc_counters_output
},
{
.cmd = RSPAMC_COMMAND_UPTIME,
.name = "uptime",
.path = "auth",
.description = "show rspamd uptime",
.is_controller = TRUE,
.is_privileged = FALSE,
.need_input = FALSE,
.command_output_func = rspamc_uptime_output
},
{
.cmd = RSPAMC_COMMAND_ADD_SYMBOL,
.name = "add_symbol",
.path = "addsymbol",
.description = "add or modify symbol settings in rspamd",
.is_controller = TRUE,
.is_privileged = TRUE,
.need_input = FALSE,
.command_output_func = NULL
},
{
.cmd = RSPAMC_COMMAND_ADD_ACTION,
.name = "add_action",
.path = "addaction",
.description = "add or modify action settings",
.is_controller = TRUE,
.is_privileged = TRUE,
.need_input = FALSE,
.command_output_func = NULL
}
};
struct rspamc_callback_data {
struct rspamc_command *cmd;
gchar *filename;
};
gboolean
rspamc_password_callback (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
guint plen = 8192;
guint8 *map, *end;
gsize sz;
if (value != NULL) {
if (value[0] == '/' || value[0] == '.') {
/* Try to open file */
map = rspamd_file_xmap (value, PROT_READ, &sz, 0);
if (map == NULL) {
/* Just use it as a string */
password = g_strdup (value);
}
else {
/* Strip trailing spaces */
g_assert (sz > 0);
end = map + sz - 1;
while (g_ascii_isspace (*end) && end > map) {
end --;
}
end ++;
password = g_malloc (end - map + 1);
rspamd_strlcpy (password, map, end - map + 1);
munmap (map, sz);
}
}
else {
password = g_strdup (value);
}
}
else {
/* Read password from console */
password = g_malloc0 (plen);
plen = rspamd_read_passphrase (password, plen, 0, NULL);
}
if (plen == 0) {
rspamd_fprintf (stderr, "Invalid password\n");
exit (EXIT_FAILURE);
}
return TRUE;
}
/*
* Parse command line
*/
static void
read_cmd_line (gint *argc, gchar ***argv)
{
GError *error = NULL;
GOptionContext *context;
/* Prepare parser */
context = g_option_context_new ("- run rspamc client");
g_option_context_set_summary (context,
"Summary:\n Rspamd client version " RVERSION "\n Release id: " RID);
g_option_context_add_main_entries (context, entries, NULL);
/* Parse options */
if (!g_option_context_parse (context, argc, argv, &error)) {
fprintf (stderr, "option parsing failed: %s\n", error->message);
exit (EXIT_FAILURE);
}
if (json || compact) {
raw = TRUE;
}
/* Argc and argv are shifted after this function */
}
static gboolean
rspamd_action_from_str_rspamc (const gchar *data, gint *result)
{
if (strcmp (data, "reject") == 0) {
*result = METRIC_ACTION_REJECT;
}
else if (strcmp (data, "greylist") == 0) {
*result = METRIC_ACTION_GREYLIST;
}
else if (strcmp (data, "add_header") == 0) {
*result = METRIC_ACTION_ADD_HEADER;
}
else if (strcmp (data, "rewrite_subject") == 0) {
*result = METRIC_ACTION_REWRITE_SUBJECT;
}
else if (strcmp (data, "add header") == 0) {
*result = METRIC_ACTION_ADD_HEADER;
}
else if (strcmp (data, "rewrite subject") == 0) {
*result = METRIC_ACTION_REWRITE_SUBJECT;
}
else if (strcmp (data, "soft_reject") == 0) {
*result = METRIC_ACTION_SOFT_REJECT;
}
else if (strcmp (data, "soft reject") == 0) {
*result = METRIC_ACTION_SOFT_REJECT;
}
else if (strcmp (data, "no_action") == 0) {
*result = METRIC_ACTION_NOACTION;
}
else if (strcmp (data, "no action") == 0) {
*result = METRIC_ACTION_NOACTION;
}
else {
return FALSE;
}
return TRUE;
}
/*
* Check rspamc command from string (used for arguments parsing)
*/
static struct rspamc_command *
check_rspamc_command (const gchar *cmd)
{
enum rspamc_command_type ct = 0;
guint i;
if (g_ascii_strcasecmp (cmd, "SYMBOLS") == 0 ||
g_ascii_strcasecmp (cmd, "CHECK") == 0 ||
g_ascii_strcasecmp (cmd, "REPORT") == 0) {
/* These all are symbols, don't use other commands */
ct = RSPAMC_COMMAND_SYMBOLS;
}
else if (g_ascii_strcasecmp (cmd, "LEARN_SPAM") == 0) {
ct = RSPAMC_COMMAND_LEARN_SPAM;
}
else if (g_ascii_strcasecmp (cmd, "LEARN_HAM") == 0) {
ct = RSPAMC_COMMAND_LEARN_HAM;
}
else if (g_ascii_strcasecmp (cmd, "FUZZY_ADD") == 0) {
ct = RSPAMC_COMMAND_FUZZY_ADD;
}
else if (g_ascii_strcasecmp (cmd, "FUZZY_DEL") == 0) {
ct = RSPAMC_COMMAND_FUZZY_DEL;
}
else if (g_ascii_strcasecmp (cmd, "FUZZY_DELHASH") == 0) {
ct = RSPAMC_COMMAND_FUZZY_DELHASH;
}
else if (g_ascii_strcasecmp (cmd, "STAT") == 0) {
ct = RSPAMC_COMMAND_STAT;
}
else if (g_ascii_strcasecmp (cmd, "STAT_RESET") == 0) {
ct = RSPAMC_COMMAND_STAT_RESET;
}
else if (g_ascii_strcasecmp (cmd, "COUNTERS") == 0) {
ct = RSPAMC_COMMAND_COUNTERS;
}
else if (g_ascii_strcasecmp (cmd, "UPTIME") == 0) {
ct = RSPAMC_COMMAND_UPTIME;
}
else if (g_ascii_strcasecmp (cmd, "ADD_SYMBOL") == 0) {
ct = RSPAMC_COMMAND_ADD_SYMBOL;
}
else if (g_ascii_strcasecmp (cmd, "ADD_ACTION") == 0) {
ct = RSPAMC_COMMAND_ADD_ACTION;
}
for (i = 0; i < G_N_ELEMENTS (rspamc_commands); i++) {
if (rspamc_commands[i].cmd == ct) {
return &rspamc_commands[i];
}
}
return NULL;
}
static void
print_commands_list (void)
{
guint i;
guint cmd_len = 0;
gchar fmt_str[32];
rspamd_fprintf (stdout, "Rspamc commands summary:\n");
for (i = 0; i < G_N_ELEMENTS (rspamc_commands); i++) {
gsize clen = strlen (rspamc_commands[i].name);
if (clen > cmd_len) {
cmd_len = clen;
}
}
rspamd_snprintf (fmt_str, sizeof (fmt_str), " %%%ds (%%7s%%1s)\t%%s\n",
cmd_len);
for (i = 0; i < G_N_ELEMENTS (rspamc_commands); i++) {
fprintf (stdout,
fmt_str,
rspamc_commands[i].name,
rspamc_commands[i].is_controller ? "control" : "normal",
rspamc_commands[i].is_privileged ? "*" : "",
rspamc_commands[i].description);
}
rspamd_fprintf (stdout,
"\n* is for privileged commands that may need password (see -P option)\n");
rspamd_fprintf (stdout,
"control commands use port 11334 while normal use 11333 by default (see -h option)\n");
}
static void
add_options (GQueue *opts)
{
GString *numbuf;
gchar **hdr, **rcpt;
GString *flagbuf = g_string_new (NULL);
if (ip != NULL) {
rspamd_inet_addr_t *addr = NULL;
if (!rspamd_parse_inet_address (&addr, ip, strlen (ip))) {
/* Try to resolve */
struct addrinfo hints, *res, *cur;
gint r;
memset (&hints, 0, sizeof (hints));
hints.ai_socktype = SOCK_STREAM; /* Type of the socket */
#ifdef AI_IDN
hints.ai_flags = AI_NUMERICSERV|AI_IDN;
#else
hints.ai_flags = AI_NUMERICSERV;
#endif
hints.ai_family = AF_UNSPEC;
if ((r = getaddrinfo (ip, "25", &hints, &res)) == 0) {
cur = res;
while (cur) {
addr = rspamd_inet_address_from_sa (cur->ai_addr,
cur->ai_addrlen);
if (addr != NULL) {
ip = g_strdup (rspamd_inet_address_to_string (addr));
rspamd_inet_address_free (addr);
break;
}
cur = cur->ai_next;
}
freeaddrinfo (res);
}
else {
rspamd_fprintf (stderr, "address resolution for %s failed: %s\n",
ip,
gai_strerror (r));
}
}
else {
rspamd_inet_address_free (addr);
}
ADD_CLIENT_HEADER (opts, "Ip", ip);
}
if (from != NULL) {
ADD_CLIENT_HEADER (opts, "From", from);
}
if (user != NULL) {
ADD_CLIENT_HEADER (opts, "User", user);
}
if (rcpts != NULL) {
for (rcpt = rcpts; *rcpt != NULL; rcpt ++) {
ADD_CLIENT_HEADER (opts, "Rcpt", *rcpt);
}
}
if (deliver_to != NULL) {
ADD_CLIENT_HEADER (opts, "Deliver-To", deliver_to);
}
if (helo != NULL) {
ADD_CLIENT_HEADER (opts, "Helo", helo);
}
if (hostname != NULL) {
ADD_CLIENT_HEADER (opts, "Hostname", hostname);
}
if (password != NULL) {
ADD_CLIENT_HEADER (opts, "Password", password);
}
if (pass_all) {
ADD_CLIENT_FLAG (flagbuf, "pass_all");
}
if (classifier) {
ADD_CLIENT_HEADER (opts, "Classifier", classifier);
}
if (weight != 0) {
numbuf = g_string_sized_new (8);
rspamd_printf_gstring (numbuf, "%d", weight);
ADD_CLIENT_HEADER (opts, "Weight", numbuf->str);
g_string_free (numbuf, TRUE);
}
if (fuzzy_symbol != NULL) {
ADD_CLIENT_HEADER (opts, "Symbol", fuzzy_symbol);
}
if (flag != 0) {
numbuf = g_string_sized_new (8);
rspamd_printf_gstring (numbuf, "%d", flag);
ADD_CLIENT_HEADER (opts, "Flag", numbuf->str);
g_string_free (numbuf, TRUE);
}
if (extended_urls) {
ADD_CLIENT_HEADER (opts, "URL-Format", "extended");
}
if (profile) {
ADD_CLIENT_FLAG (flagbuf, "profile");
}
if (skip_images) {
ADD_CLIENT_HEADER (opts, "Skip-Images", "true");
}
if (skip_attachments) {
ADD_CLIENT_HEADER (opts, "Skip-Attachments", "true");
}
hdr = http_headers;
while (hdr != NULL && *hdr != NULL) {
gchar **kv = g_strsplit_set (*hdr, ":=", 2);
if (kv == NULL || kv[1] == NULL) {
ADD_CLIENT_HEADER (opts, *hdr, "");
}
else {
ADD_CLIENT_HEADER (opts, kv[0], kv[1]);
}
if (kv) {
g_strfreev (kv);
}
hdr ++;
}
if (flagbuf->len > 0) {
goffset last = flagbuf->len - 1;
if (flagbuf->str[last] == ',') {
flagbuf->str[last] = '\0';
flagbuf->len --;
}
ADD_CLIENT_HEADER (opts, "Flags", flagbuf->str);
}
g_string_free (flagbuf, TRUE);
}
static void
rspamc_symbol_output (FILE *out, const ucl_object_t *obj)
{
const ucl_object_t *val, *cur;
ucl_object_iter_t it = NULL;
gboolean first = TRUE;
rspamd_fprintf (out, "Symbol: %s ", ucl_object_key (obj));
val = ucl_object_lookup (obj, "score");
if (val != NULL) {
rspamd_fprintf (out, "(%.2f)", ucl_object_todouble (val));
}
val = ucl_object_lookup (obj, "options");
if (val != NULL && val->type == UCL_ARRAY) {
rspamd_fprintf (out, "[");
while ((cur = ucl_object_iterate (val, &it, TRUE)) != NULL) {
if (first) {
rspamd_fprintf (out, "%s", ucl_object_tostring (cur));
first = FALSE;
}
else {
rspamd_fprintf (out, ", %s", ucl_object_tostring (cur));
}
}
rspamd_fprintf (out, "]");
}
rspamd_fprintf (out, "\n");
}
static gint
rspamc_symbols_sort_func (gconstpointer a, gconstpointer b)
{
ucl_object_t * const *ua = a, * const *ub = b;
return strcmp (ucl_object_key (*ua), ucl_object_key (*ub));
}
#define PRINT_PROTOCOL_STRING(ucl_name, output_message) do { \
elt = ucl_object_lookup (obj, (ucl_name)); \
if (elt) { \
rspamd_fprintf (out, output_message ": %s\n", ucl_object_tostring (elt)); \
} \
} while (0)
static void
rspamc_metric_output (FILE *out, const ucl_object_t *obj)
{
ucl_object_iter_t it = NULL;
const ucl_object_t *cur, *elt;
gdouble score = 0, required_score = 0;
gint got_scores = 0, action = METRIC_ACTION_MAX;
GPtrArray *sym_ptr;
guint i;
sym_ptr = g_ptr_array_new ();
rspamd_fprintf (out, "[Metric: default]\n");
elt = ucl_object_lookup (obj, "required_score");
if (elt) {
required_score = ucl_object_todouble (elt);
got_scores++;
}
elt = ucl_object_lookup (obj, "score");
if (elt) {
score = ucl_object_todouble (elt);
got_scores++;
}
PRINT_PROTOCOL_STRING ("action", "Action");
/* Defined by previous macro */
if (elt && rspamd_action_from_str_rspamc (ucl_object_tostring (elt), &action)) {
rspamd_fprintf (out, "Spam: %s\n", action < METRIC_ACTION_GREYLIST ?
"true" : "false");
}
PRINT_PROTOCOL_STRING ("subject", "Subject");
if (got_scores == 2) {
rspamd_fprintf (out,
"Score: %.2f / %.2f\n",
score,
required_score);
}
elt = ucl_object_lookup (obj, "symbols");
while (elt && (cur = ucl_object_iterate (elt, &it, true)) != NULL) {
if (cur->type == UCL_OBJECT) {
g_ptr_array_add (sym_ptr, (void *)cur);
}
}
g_ptr_array_sort (sym_ptr, rspamc_symbols_sort_func);
for (i = 0; i < sym_ptr->len; i ++) {
cur = (const ucl_object_t *)g_ptr_array_index (sym_ptr, i);
rspamc_symbol_output (out, cur);
}
g_ptr_array_free (sym_ptr, TRUE);
}
static gint
rspamc_profile_sort_func (gconstpointer a, gconstpointer b)
{
ucl_object_t * const *ua = a, * const *ub = b;
return ucl_object_compare (*ua, *ub);
}
static void
rspamc_profile_output (FILE *out, const ucl_object_t *obj)
{
ucl_object_iter_t it = NULL;
const ucl_object_t *cur;
guint i;
GPtrArray *ar;
ar = g_ptr_array_sized_new (obj->len);
while ((cur = ucl_object_iterate (obj, &it, true)) != NULL) {
g_ptr_array_add (ar, (void *)cur);
}
g_ptr_array_sort (ar, rspamc_profile_sort_func);
for (i = 0; i < ar->len; i ++) {
cur = (const ucl_object_t *)g_ptr_array_index (ar, i);
rspamd_fprintf (out, "\t%s: %.3f usec\n",
ucl_object_key (cur), ucl_object_todouble (cur));
}
g_ptr_array_free (ar, TRUE);
}
static void
rspamc_symbols_output (FILE *out, ucl_object_t *obj)
{
ucl_object_iter_t mit = NULL;
const ucl_object_t *cmesg, *elt;
gchar *emitted;
rspamc_metric_output (out, obj);
PRINT_PROTOCOL_STRING ("message-id", "Message-ID");
PRINT_PROTOCOL_STRING ("queue-id", "Queue-ID");
elt = ucl_object_lookup (obj, "urls");
if (elt) {
if (!extended_urls || compact) {
emitted = ucl_object_emit (elt, UCL_EMIT_JSON_COMPACT);
}
else {
emitted = ucl_object_emit (elt, UCL_EMIT_JSON);
}
rspamd_fprintf (out, "Urls: %s\n", emitted);
free (emitted);
}
elt = ucl_object_lookup (obj, "emails");
if (elt) {
if (!extended_urls || compact) {
emitted = ucl_object_emit (elt, UCL_EMIT_JSON_COMPACT);
}
else {
emitted = ucl_object_emit (elt, UCL_EMIT_JSON);
}
rspamd_fprintf (out, "Emails: %s\n", emitted);
free (emitted);
}
PRINT_PROTOCOL_STRING ("error", "Scan error");
elt = ucl_object_lookup (obj, "messages");
if (elt && elt->type == UCL_OBJECT) {
mit = NULL;
while ((cmesg = ucl_object_iterate (elt, &mit, true)) != NULL) {
rspamd_fprintf (out, "Message - %s: %s\n",
ucl_object_key (cmesg), ucl_object_tostring (cmesg));
}
}
elt = ucl_object_lookup (obj, "dkim-signature");
if (elt && elt->type == UCL_STRING) {
rspamd_fprintf (out, "DKIM-Signature: %s\n", ucl_object_tostring (elt));
} else if (elt && elt->type == UCL_ARRAY) {
mit = NULL;
while ((cmesg = ucl_object_iterate (elt, &mit, true)) != NULL) {
rspamd_fprintf (out, "DKIM-Signature: %s\n", ucl_object_tostring (cmesg));
}
}
elt = ucl_object_lookup (obj, "profile");
if (elt) {
rspamd_fprintf (out, "Profile data:\n");
rspamc_profile_output (out, elt);
}
}
static void
rspamc_uptime_output (FILE *out, ucl_object_t *obj)
{
const ucl_object_t *elt;
int64_t seconds, days, hours, minutes;
elt = ucl_object_lookup (obj, "version");
if (elt != NULL) {
rspamd_fprintf (out, "Rspamd version: %s\n", ucl_object_tostring (
elt));
}
elt = ucl_object_lookup (obj, "uptime");
if (elt != NULL) {
rspamd_printf ("Uptime: ");
seconds = ucl_object_toint (elt);
if (seconds >= 2 * 3600) {
days = seconds / 86400;
hours = seconds / 3600 - days * 24;
minutes = seconds / 60 - hours * 60 - days * 1440;
rspamd_printf ("%L day%s %L hour%s %L minute%s\n", days,
days > 1 ? "s" : "", hours, hours > 1 ? "s" : "",
minutes, minutes > 1 ? "s" : "");
}
/* If uptime is less than 1 minute print only seconds */
else if (seconds / 60 == 0) {
rspamd_printf ("%L second%s\n", seconds,
(gint)seconds > 1 ? "s" : "");
}
/* Else print the minutes and seconds. */
else {
hours = seconds / 3600;
minutes = seconds / 60 - hours * 60;
seconds -= hours * 3600 + minutes * 60;
rspamd_printf ("%L hour %L minute%s %L second%s\n", hours,
minutes, minutes > 1 ? "s" : "",
seconds, seconds > 1 ? "s" : "");
}
}
}
static gint
rspamc_counters_sort (const ucl_object_t **o1, const ucl_object_t **o2)
{
gint order1 = 0, order2 = 0, c;
const ucl_object_t *elt1, *elt2;
gboolean inverse = FALSE;
gchar **args;
if (sort != NULL) {
args = g_strsplit_set (sort, ":", 2);
if (args && args[0]) {
if (args[1] && g_ascii_strcasecmp (args[1], "desc") == 0) {
inverse = TRUE;
}
if (g_ascii_strcasecmp (args[0], "name") == 0) {
elt1 = ucl_object_lookup (*o1, "symbol");
elt2 = ucl_object_lookup (*o2, "symbol");
if (elt1 && elt2) {
c = strcmp (ucl_object_tostring (elt1),
ucl_object_tostring (elt2));
order1 = c > 0 ? 1 : 0;
order2 = c < 0 ? 1 : 0;
}
}
else if (g_ascii_strcasecmp (args[0], "weight") == 0) {
elt1 = ucl_object_lookup (*o1, "weight");
elt2 = ucl_object_lookup (*o2, "weight");
if (elt1 && elt2) {
order1 = ucl_object_todouble (elt1) * 1000.0;
order2 = ucl_object_todouble (elt2) * 1000.0;
}
}
else if (g_ascii_strcasecmp (args[0], "frequency") == 0) {
elt1 = ucl_object_lookup (*o1, "frequency");
elt2 = ucl_object_lookup (*o2, "frequency");
if (elt1 && elt2) {
order1 = ucl_object_todouble (elt1) * 100000;
order2 = ucl_object_todouble (elt2) * 100000;
}
}
else if (g_ascii_strcasecmp (args[0], "time") == 0) {
elt1 = ucl_object_lookup (*o1, "time");
elt2 = ucl_object_lookup (*o2, "time");
if (elt1 && elt2) {
order1 = ucl_object_todouble (elt1) * 1000000;
order2 = ucl_object_todouble (elt2) * 1000000;
}
}
else if (g_ascii_strcasecmp (args[0], "hits") == 0) {
elt1 = ucl_object_lookup (*o1, "hits");
elt2 = ucl_object_lookup (*o2, "hits");
if (elt1 && elt2) {
order1 = ucl_object_toint (elt1);
order2 = ucl_object_toint (elt2);
}
}
}
g_strfreev (args);
}
return (inverse ? (order2 - order1) : (order1 - order2));
}
static void
rspamc_counters_output (FILE *out, ucl_object_t *obj)
{
const ucl_object_t *cur, *sym, *weight, *freq, *freq_dev, *nhits;
ucl_object_iter_t iter = NULL;
gchar fmt_buf[64], dash_buf[82], sym_buf[82];
gint l, max_len = INT_MIN, i;
static const gint dashes = 44;
if (obj->type != UCL_ARRAY) {
rspamd_printf ("Bad output\n");
return;
}
/* Sort symbols by their order */
if (sort != NULL) {
ucl_object_array_sort (obj, rspamc_counters_sort);
}
/* Find maximum width of symbol's name */
while ((cur = ucl_object_iterate (obj, &iter, true)) != NULL) {
sym = ucl_object_lookup (cur, "symbol");
if (sym != NULL) {
l = sym->len;
if (l > max_len) {
max_len = MIN (sizeof (dash_buf) - dashes - 1, l);
}
}
}
rspamd_snprintf (fmt_buf, sizeof (fmt_buf),
"| %%3s | %%%ds | %%7s | %%13s | %%7s |\n", max_len);
memset (dash_buf, '-', dashes + max_len);
dash_buf[dashes + max_len] = '\0';
printf ("Symbols cache\n");
printf (" %s \n", dash_buf);
if (tty) {
printf ("\033[1m");
}
printf (fmt_buf, "Pri", "Symbol", "Weight", "Frequency", "Hits");
printf (" %s \n", dash_buf);
printf (fmt_buf, "", "", "", "hits/min", "");
if (tty) {
printf ("\033[0m");
}
rspamd_snprintf (fmt_buf, sizeof (fmt_buf),
"| %%3d | %%%ds | %%7.1f | %%6.3f(%%5.3f) | %%7ju |\n", max_len);
iter = NULL;
i = 0;
while ((cur = ucl_object_iterate (obj, &iter, true)) != NULL) {
printf (" %s \n", dash_buf);
sym = ucl_object_lookup (cur, "symbol");
weight = ucl_object_lookup (cur, "weight");
freq = ucl_object_lookup (cur, "frequency");
freq_dev = ucl_object_lookup (cur, "frequency_stddev");
nhits = ucl_object_lookup (cur, "hits");
if (sym && weight && freq && nhits) {
const gchar *sym_name;
if (sym->len > max_len) {
rspamd_snprintf (sym_buf, sizeof (sym_buf), "%*s...",
(max_len - 3), ucl_object_tostring (sym));
sym_name = sym_buf;
}
else {
sym_name = ucl_object_tostring (sym);
}
printf (fmt_buf, i,
sym_name,
ucl_object_todouble (weight),
ucl_object_todouble (freq) * 60.0,
ucl_object_todouble (freq_dev) * 60.0,
(uintmax_t)ucl_object_toint (nhits));
}
i++;
}
printf (" %s \n", dash_buf);
}
static void
rspamc_stat_actions (ucl_object_t *obj, GString *out, gint64 scanned)
{
const ucl_object_t *actions = ucl_object_lookup (obj, "actions"), *cur;
ucl_object_iter_t iter = NULL;
gint64 spam, ham;
if (actions && ucl_object_type (actions) == UCL_OBJECT) {
while ((cur = ucl_object_iterate (actions, &iter, true)) != NULL) {
gint64 cnt = ucl_object_toint (cur);
rspamd_printf_gstring (out, "Messages with action %s: %L"
", %.2f%%\n", ucl_object_key (cur), cnt,
((gdouble)cnt / (gdouble)scanned) * 100.);
}
}
spam = ucl_object_toint (ucl_object_lookup (obj, "spam_count"));
ham = ucl_object_toint (ucl_object_lookup (obj, "ham_count"));
rspamd_printf_gstring (out, "Messages treated as spam: %L, %.2f%%\n", spam,
((gdouble)spam / (gdouble)scanned) * 100.);
rspamd_printf_gstring (out, "Messages treated as ham: %L, %.2f%%\n", ham,
((gdouble)ham / (gdouble)scanned) * 100.);
}
static void
rspamc_stat_statfile (const ucl_object_t *obj, GString *out)
{
gint64 version, size, blocks, used_blocks, nlanguages, nusers;
const gchar *label, *symbol, *type;
version = ucl_object_toint (ucl_object_lookup (obj, "revision"));
size = ucl_object_toint (ucl_object_lookup (obj, "size"));
blocks = ucl_object_toint (ucl_object_lookup (obj, "total"));
used_blocks = ucl_object_toint (ucl_object_lookup (obj, "used"));
label = ucl_object_tostring (ucl_object_lookup (obj, "label"));
symbol = ucl_object_tostring (ucl_object_lookup (obj, "symbol"));
type = ucl_object_tostring (ucl_object_lookup (obj, "type"));
nlanguages = ucl_object_toint (ucl_object_lookup (obj, "languages"));
nusers = ucl_object_toint (ucl_object_lookup (obj, "users"));
if (label) {
rspamd_printf_gstring (out, "Statfile: %s <%s> type: %s; ", symbol,
label, type);
}
else {
rspamd_printf_gstring (out, "Statfile: %s type: %s; ", symbol, type);
}
rspamd_printf_gstring (out, "length: %hL; free blocks: %hL; total blocks: %hL; "
"free: %.2f%%; learned: %L; users: %L; languages: %L\n",
size,
blocks - used_blocks, blocks,
blocks > 0 ? (blocks - used_blocks) * 100.0 / (gdouble)blocks : 0,
version,
nusers, nlanguages);
}
static void
rspamc_stat_output (FILE *out, ucl_object_t *obj)
{
GString *out_str;
ucl_object_iter_t iter = NULL;
const ucl_object_t *st, *cur;
gint64 scanned;
out_str = g_string_sized_new (BUFSIZ);
scanned = ucl_object_toint (ucl_object_lookup (obj, "scanned"));
rspamd_printf_gstring (out_str, "Messages scanned: %L\n",
scanned);
if (scanned > 0) {
rspamc_stat_actions (obj, out_str, scanned);
}
rspamd_printf_gstring (out_str, "Messages learned: %L\n",
ucl_object_toint (ucl_object_lookup (obj, "learned")));
rspamd_printf_gstring (out_str, "Connections count: %L\n",
ucl_object_toint (ucl_object_lookup (obj, "connections")));
rspamd_printf_gstring (out_str, "Control connections count: %L\n",
ucl_object_toint (ucl_object_lookup (obj, "control_connections")));
/* Pools */
rspamd_printf_gstring (out_str, "Pools allocated: %L\n",
ucl_object_toint (ucl_object_lookup (obj, "pools_allocated")));
rspamd_printf_gstring (out_str, "Pools freed: %L\n",
ucl_object_toint (ucl_object_lookup (obj, "pools_freed")));
rspamd_printf_gstring (out_str, "Bytes allocated: %HL\n",
ucl_object_toint (ucl_object_lookup (obj, "bytes_allocated")));
rspamd_printf_gstring (out_str, "Memory chunks allocated: %L\n",
ucl_object_toint (ucl_object_lookup (obj, "chunks_allocated")));
rspamd_printf_gstring (out_str, "Shared chunks allocated: %L\n",
ucl_object_toint (ucl_object_lookup (obj, "shared_chunks_allocated")));
rspamd_printf_gstring (out_str, "Chunks freed: %L\n",
ucl_object_toint (ucl_object_lookup (obj, "chunks_freed")));
rspamd_printf_gstring (out_str, "Oversized chunks: %L\n",
ucl_object_toint (ucl_object_lookup (obj, "chunks_oversized")));
/* Fuzzy */
st = ucl_object_lookup (obj, "fuzzy_hashes");
if (st) {
ucl_object_iter_t it = NULL;
const ucl_object_t *cur;
gint64 stored = 0;
while ((cur = ucl_iterate_object (st, &it, true)) != NULL) {
rspamd_printf_gstring (out_str, "Fuzzy hashes in storage \"%s\": %L\n",
ucl_object_key (cur),
ucl_object_toint (cur));
stored += ucl_object_toint (cur);
}
rspamd_printf_gstring (out_str, "Fuzzy hashes stored: %L\n",
stored);
}
st = ucl_object_lookup (obj, "fuzzy_checked");
if (st != NULL && ucl_object_type (st) == UCL_ARRAY) {
rspamd_printf_gstring (out_str, "Fuzzy hashes checked: ");
iter = NULL;
while ((cur = ucl_object_iterate (st, &iter, true)) != NULL) {
rspamd_printf_gstring (out_str, "%hL ", ucl_object_toint (cur));
}
rspamd_printf_gstring (out_str, "\n");
}
st = ucl_object_lookup (obj, "fuzzy_found");
if (st != NULL && ucl_object_type (st) == UCL_ARRAY) {
rspamd_printf_gstring (out_str, "Fuzzy hashes found: ");
iter = NULL;
while ((cur = ucl_object_iterate (st, &iter, true)) != NULL) {
rspamd_printf_gstring (out_str, "%hL ", ucl_object_toint (cur));
}
rspamd_printf_gstring (out_str, "\n");
}
st = ucl_object_lookup (obj, "statfiles");
if (st != NULL && ucl_object_type (st) == UCL_ARRAY) {
iter = NULL;
while ((cur = ucl_object_iterate (st, &iter, true)) != NULL) {
rspamc_stat_statfile (cur, out_str);
}
}
rspamd_printf_gstring (out_str, "Total learns: %L\n",
ucl_object_toint (ucl_object_lookup (obj, "total_learns")));
rspamd_fprintf (out, "%v", out_str);
}
static void
rspamc_output_headers (FILE *out, struct rspamd_http_message *msg)
{
struct rspamd_http_header *h, *htmp;
HASH_ITER (hh, msg->headers, h, htmp) {
rspamd_fprintf (out, "%T: %T\n", &h->name, &h->value);
}
rspamd_fprintf (out, "\n");
}
static void
rspamc_mime_output (FILE *out, ucl_object_t *result, GString *input,
gdouble time, GError *err)
{
const ucl_object_t *cur, *res, *syms;
ucl_object_iter_t it = NULL;
const gchar *action = "no action", *line_end = "\r\n", *p;
gchar scorebuf[32];
GString *symbuf, *folded_symbuf, *added_headers;
gint act = 0;
goffset headers_pos;
gdouble score = 0.0, required_score = 0.0;
gboolean is_spam = FALSE;
gchar *json_header, *json_header_encoded, *sc;
enum rspamd_newlines_type nl_type = RSPAMD_TASK_NEWLINES_CRLF;
headers_pos = rspamd_string_find_eoh (input, NULL);
if (headers_pos == -1) {
rspamd_fprintf (stderr,"cannot find end of headers position");
return;
}
p = input->str + headers_pos;
if (headers_pos > 1 && *(p - 1) == '\n') {
if (headers_pos > 2 && *(p - 2) == '\r') {
line_end = "\r\n";
nl_type = RSPAMD_TASK_NEWLINES_CRLF;
}
else {
line_end = "\n";
nl_type = RSPAMD_TASK_NEWLINES_LF;
}
}
else if (headers_pos > 1 && *(p - 1) == '\r') {
line_end = "\r";
nl_type = RSPAMD_TASK_NEWLINES_CR;
}
added_headers = g_string_sized_new (127);
if (result) {
res = ucl_object_lookup (result, "action");
if (res) {
action = ucl_object_tostring (res);
}
res = ucl_object_lookup (result, "score");
if (res) {
score = ucl_object_todouble (res);
}
res = ucl_object_lookup (result, "required_score");
if (res) {
required_score = ucl_object_todouble (res);
}
rspamd_action_from_str_rspamc (action, &act);
if (act < METRIC_ACTION_GREYLIST) {
is_spam = TRUE;
}
rspamd_printf_gstring (added_headers, "X-Spam-Scanner: %s%s",
"rspamc " RVERSION, line_end);
rspamd_printf_gstring (added_headers, "X-Spam-Scan-Time: %.3f%s",
time, line_end);
/*
* TODO: add rmilter_headers support here
*/
if (is_spam) {
rspamd_printf_gstring (added_headers, "X-Spam: yes%s", line_end);
}
rspamd_printf_gstring (added_headers, "X-Spam-Action: %s%s",
action, line_end);
rspamd_printf_gstring (added_headers, "X-Spam-Score: %.2f / %.2f%s",
score, required_score, line_end);
/* SA style stars header */
for (sc = scorebuf; sc < scorebuf + sizeof (scorebuf) - 1 && score > 0;
sc ++, score -= 1.0) {
*sc = '*';
}
*sc = '\0';
rspamd_printf_gstring (added_headers, "X-Spam-Level: %s%s",
scorebuf, line_end);
/* Short description of all symbols */
symbuf = g_string_sized_new (64);
syms = ucl_object_lookup (result, "symbols");
while (syms && (cur = ucl_object_iterate (syms, &it, true)) != NULL) {
if (ucl_object_type (cur) == UCL_OBJECT) {
rspamd_printf_gstring (symbuf, "%s,", ucl_object_key (cur));
}
}
/* Trim the last comma */
if (symbuf->str[symbuf->len - 1] == ',') {
g_string_erase (symbuf, symbuf->len - 1, 1);
}
folded_symbuf = rspamd_header_value_fold ("X-Spam-Symbols",
symbuf->str,
0, nl_type, ",");
rspamd_printf_gstring (added_headers, "X-Spam-Symbols: %v%s",
folded_symbuf, line_end);
g_string_free (folded_symbuf, TRUE);
g_string_free (symbuf, TRUE);
res = ucl_object_lookup (result, "dkim-signature");
if (res && res->type == UCL_STRING) {
rspamd_printf_gstring (added_headers, "DKIM-Signature: %s%s",
ucl_object_tostring (res), line_end);
} else if (res && res->type == UCL_ARRAY) {
it = NULL;
while ((cur = ucl_object_iterate (res, &it, true)) != NULL) {
rspamd_printf_gstring (added_headers, "DKIM-Signature: %s%s",
ucl_object_tostring (cur), line_end);
}
}
if (json || raw || compact) {
/* We also append json data as a specific header */
if (json) {
json_header = ucl_object_emit (result,
compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON);
}
else {
json_header = ucl_object_emit (result,
compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG);
}
json_header_encoded = rspamd_encode_base64_fold (json_header,
strlen (json_header), 60, NULL, nl_type);
free (json_header);
rspamd_printf_gstring (added_headers,
"X-Spam-Result: %s%s",
json_header_encoded, line_end);
g_free (json_header_encoded);
}
ucl_object_unref (result);
}
else {
rspamd_printf_gstring (added_headers, "X-Spam-Scanner: %s%s",
"rspamc " RVERSION, line_end);
rspamd_printf_gstring (added_headers, "X-Spam-Scan-Time: %.3f%s",
time, line_end);
rspamd_printf_gstring (added_headers, "X-Spam-Error: %e%s",
err, line_end);
}
/* Write message */
if (rspamd_fprintf (out, "%*s", (gint)headers_pos, input->str)
== headers_pos) {
if (rspamd_fprintf (out, "%v", added_headers)
== (gint)added_headers->len) {
rspamd_fprintf (out, "%s", input->str + headers_pos);
}
}
g_string_free (added_headers, TRUE);
}
static void
rspamc_client_execute_cmd (struct rspamc_command *cmd, ucl_object_t *result,
GString *input, gdouble time, GError *err)
{
gchar **eargv;
gint eargc, infd, outfd, errfd;
GError *exec_err = NULL;
GPid cld;
FILE *out;
gchar *ucl_out;
if (!g_shell_parse_argv (execute, &eargc, &eargv, &err)) {
rspamd_fprintf (stderr, "Cannot execute %s: %e", execute, err);
g_error_free (err);
return;
}
if (!g_spawn_async_with_pipes (NULL, eargv, NULL,
G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &cld,
&infd, &outfd, &errfd, &exec_err)) {
rspamd_fprintf (stderr, "Cannot execute %s: %e", execute, exec_err);
g_error_free (exec_err);
exit (EXIT_FAILURE);
}
else {
children = g_list_prepend (children, GSIZE_TO_POINTER (cld));
out = fdopen (infd, "w");
if (cmd->cmd == RSPAMC_COMMAND_SYMBOLS && mime_output && input) {
rspamc_mime_output (out, result, input, time, err);
}
else if (result) {
if (raw || cmd->command_output_func == NULL) {
if (json) {
ucl_out = ucl_object_emit (result,
compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON);
}
else {
ucl_out = ucl_object_emit (result,
compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG);
}
rspamd_fprintf (out, "%s", ucl_out);
free (ucl_out);
}
else {
cmd->command_output_func (out, result);
}
ucl_object_unref (result);
}
else {
rspamd_fprintf (out, "%e\n", err);
}
fflush (out);
fclose (out);
}
g_strfreev (eargv);
}
static void
rspamc_client_cb (struct rspamd_client_connection *conn,
struct rspamd_http_message *msg,
const gchar *name, ucl_object_t *result, GString *input,
gpointer ud, gdouble start_time, gdouble send_time,
const gchar *body, gsize bodylen,
GError *err)
{
gchar *ucl_out;
struct rspamc_callback_data *cbdata = (struct rspamc_callback_data *)ud;
struct rspamc_command *cmd;
FILE *out = stdout;
gdouble finish = rspamd_get_ticks (FALSE), diff;
cmd = cbdata->cmd;
if (send_time > 0) {
diff = finish - send_time;
}
else {
diff = finish - start_time;
}
if (execute) {
/* Pass all to the external command */
rspamc_client_execute_cmd (cmd, result, input, diff, err);
}
else {
if (cmd->cmd == RSPAMC_COMMAND_SYMBOLS && mime_output && input) {
rspamc_mime_output (out, result, input, diff, err);
}
else {
if (cmd->need_input) {
if (!compact) {
rspamd_fprintf (out, "Results for file: %s (%.3f seconds)\n",
cbdata->filename, diff);
}
}
else {
if (!compact) {
rspamd_fprintf (out, "Results for command: %s (%.3f seconds)\n",
cmd->name, diff);
}
}
if (result != NULL) {
if (headers && msg != NULL) {
rspamc_output_headers (out, msg);
}
if (raw || cmd->command_output_func == NULL) {
if (cmd->need_input) {
ucl_object_insert_key (result,
ucl_object_fromstring (cbdata->filename),
"filename", 0,
false);
}
ucl_object_insert_key (result,
ucl_object_fromdouble (diff),
"scan_time", 0,
false);
if (json) {
ucl_out = ucl_object_emit (result,
compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON);
}
else {
ucl_out = ucl_object_emit (result,
compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG);
}
rspamd_fprintf (out, "%s", ucl_out);
free (ucl_out);
}
else {
cmd->command_output_func (out, result);
}
ucl_object_unref (result);
}
else if (err != NULL) {
rspamd_fprintf (out, "%s\n", err->message);
if (json && msg != NULL) {
const gchar *raw;
gsize rawlen;
raw = rspamd_http_message_get_body (msg, &rawlen);
if (raw) {
/* We can also output the resulting json */
rspamd_fprintf (out, "%*s\n", (gint)(rawlen - bodylen),
raw);
}
}
}
rspamd_fprintf (out, "\n");
}
fflush (out);
}
rspamd_client_destroy (conn);
g_free (cbdata->filename);
g_free (cbdata);
if (err) {
retcode = EXIT_FAILURE;
}
}
static void
rspamc_process_input (struct ev_loop *ev_base, struct rspamc_command *cmd,
FILE *in, const gchar *name, GQueue *attrs)
{
struct rspamd_client_connection *conn;
gchar *hostbuf = NULL, *p;
guint16 port;
GError *err = NULL;
struct rspamc_callback_data *cbdata;
if (connect_str[0] == '[') {
p = strrchr (connect_str, ']');
if (p != NULL) {
hostbuf = g_malloc (p - connect_str);
rspamd_strlcpy (hostbuf, connect_str + 1, p - connect_str);
p ++;
}
else {
p = connect_str;
}
}
else {
p = connect_str;
}
p = strrchr (p, ':');
if (!hostbuf) {
if (p != NULL) {
hostbuf = g_malloc (p - connect_str + 1);
rspamd_strlcpy (hostbuf, connect_str, p - connect_str + 1);
}
else {
hostbuf = g_strdup (connect_str);
}
}
if (p != NULL) {
port = strtoul (p + 1, NULL, 10);
}
else {
/*
* If we connect to localhost, 127.0.0.1 or ::1, then try controller
* port first
*/
if (strcmp (hostbuf, "localhost") == 0 ||
strcmp (hostbuf, "127.0.0.1") == 0 ||
strcmp (hostbuf, "::1") == 0 ||
strcmp (hostbuf, "[::1]") == 0) {
port = DEFAULT_CONTROL_PORT;
}
else {
port = cmd->is_controller ? DEFAULT_CONTROL_PORT : DEFAULT_PORT;
}
}
conn = rspamd_client_init (http_ctx, ev_base, hostbuf, port, timeout, key);
if (conn != NULL) {
cbdata = g_malloc0 (sizeof (struct rspamc_callback_data));
cbdata->cmd = cmd;
if (name) {
cbdata->filename = g_strdup (name);
}
if (cmd->need_input) {
rspamd_client_command (conn, cmd->path, attrs, in, rspamc_client_cb,
cbdata, compressed, dictionary, cbdata->filename, &err);
}
else {
rspamd_client_command (conn,
cmd->path,
attrs,
NULL,
rspamc_client_cb,
cbdata,
compressed,
dictionary,
cbdata->filename,
&err);
}
}
else {
rspamd_fprintf (stderr, "cannot connect to %s\n", connect_str);
exit (EXIT_FAILURE);
}
g_free (hostbuf);
}
static gsize
rspamd_dirent_size (DIR * dirp)
{
goffset name_max;
gsize name_end;
#if defined(HAVE_FPATHCONF) && defined(HAVE_DIRFD) \
&& defined(_PC_NAME_MAX)
name_max = fpathconf (dirfd (dirp), _PC_NAME_MAX);
# if defined(NAME_MAX)
if (name_max == -1) {
name_max = (NAME_MAX > 255) ? NAME_MAX : 255;
}
# else
if (name_max == -1) {
return (size_t)(-1);
}
# endif
#else
# if defined(NAME_MAX)
name_max = (NAME_MAX > 255) ? NAME_MAX : 255;
# else
# error "buffer size for readdir_r cannot be determined"
# endif
#endif
name_end = G_STRUCT_OFFSET (struct dirent, d_name) + name_max + 1;
return (name_end > sizeof (struct dirent) ? name_end : sizeof(struct dirent));
}
static void
rspamc_process_dir (struct ev_loop *ev_base, struct rspamc_command *cmd,
const gchar *name, GQueue *attrs)
{
DIR *d;
GPatternSpec **ex;
struct dirent *pentry;
gint cur_req = 0, r;
gchar fpath[PATH_MAX];
FILE *in;
struct stat st;
gboolean is_reg, is_dir, skip;
d = opendir (name);
if (d != NULL) {
while ((pentry = readdir (d))!= NULL) {
if (pentry->d_name[0] == '.') {
continue;
}
r = rspamd_snprintf (fpath, sizeof (fpath), "%s%c%s",
name, G_DIR_SEPARATOR,
pentry->d_name);
/* Check exclude */
ex = exclude_compiled;
skip = FALSE;
while (ex != NULL && *ex != NULL) {
if (g_pattern_match (*ex, r, fpath, NULL)) {
skip = TRUE;
break;
}
ex ++;
}
if (skip) {
continue;
}
is_reg = FALSE;
is_dir = FALSE;
#if (defined(_DIRENT_HAVE_D_TYPE) || defined(__APPLE__)) && defined(DT_UNKNOWN)
if (pentry->d_type == DT_UNKNOWN) {
/* Fallback to lstat */
if (lstat (fpath, &st) == -1) {
rspamd_fprintf (stderr, "cannot stat file %s: %s\n",
fpath, strerror (errno));
continue;
}
is_dir = S_ISDIR (st.st_mode);
is_reg = S_ISREG (st.st_mode);
}
else {
if (pentry->d_type == DT_REG) {
is_reg = TRUE;
}
else if (pentry->d_type == DT_DIR) {
is_dir = TRUE;
}
}
#else
if (lstat (fpath, &st) == -1) {
rspamd_fprintf (stderr, "cannot stat file %s: %s\n",
fpath, strerror (errno));
continue;
}
is_dir = S_ISDIR (st.st_mode);
is_reg = S_ISREG (st.st_mode);
#endif
if (is_dir) {
rspamc_process_dir (ev_base, cmd, fpath, attrs);
continue;
}
else if (is_reg) {
in = fopen (fpath, "r");
if (in == NULL) {
rspamd_fprintf (stderr, "cannot open file %s: %s\n",
fpath, strerror (errno));
continue;
}
rspamc_process_input (ev_base, cmd, in, fpath, attrs);
cur_req++;
fclose (in);
if (cur_req >= max_requests) {
cur_req = 0;
/* Wait for completion */
ev_loop (ev_base, 0);
}
}
}
}
else {
fprintf (stderr, "cannot open directory %s: %s\n", name, strerror (errno));
exit (EXIT_FAILURE);
}
closedir (d);
ev_loop (ev_base, 0);
}
static void
rspamc_kwattr_free (gpointer p)
{
struct rspamd_http_client_header *h = (struct rspamd_http_client_header *)p;
g_free (h->value);
g_free (h->name);
g_free (h);
}
gint
main (gint argc, gchar **argv, gchar **env)
{
gint i, start_argc, cur_req = 0, res, ret, npatterns;
GQueue *kwattrs;
GList *cur;
GPid cld;
struct rspamc_command *cmd;
FILE *in = NULL;
struct ev_loop *event_loop;
struct stat st;
struct sigaction sigpipe_act;
gchar **exclude_pattern;
kwattrs = g_queue_new ();
read_cmd_line (&argc, &argv);
tty = isatty (STDOUT_FILENO);
if (print_commands) {
print_commands_list ();
exit (EXIT_SUCCESS);
}
/* Deal with exclude patterns */
exclude_pattern = exclude_patterns;
npatterns = 0;
while (exclude_pattern && *exclude_pattern) {
exclude_pattern ++;
npatterns ++;
}
if (npatterns > 0) {
exclude_compiled = g_malloc0 (sizeof (*exclude_compiled) * (npatterns + 1));
for (i = 0; i < npatterns; i ++) {
exclude_compiled[i] = g_pattern_spec_new (exclude_patterns[i]);
if (exclude_compiled[i] == NULL) {
rspamd_fprintf (stderr, "Invalid glob pattern: %s\n",
exclude_patterns[i]);
exit (EXIT_FAILURE);
}
}
}
rspamd_init_libs ();
event_loop = ev_loop_new (EVFLAG_SIGNALFD|EVBACKEND_ALL);
struct rspamd_http_context_cfg http_config;
memset (&http_config, 0, sizeof (http_config));
http_config.kp_cache_size_client = 32;
http_config.kp_cache_size_server = 0;
http_config.user_agent = user_agent;
http_ctx = rspamd_http_context_create_config (&http_config,
event_loop, NULL);
/* Ignore sigpipe */
sigemptyset (&sigpipe_act.sa_mask);
sigaddset (&sigpipe_act.sa_mask, SIGPIPE);
sigpipe_act.sa_handler = SIG_IGN;
sigpipe_act.sa_flags = 0;
sigaction (SIGPIPE, &sigpipe_act, NULL);
/* Now read other args from argc and argv */
if (argc == 1) {
start_argc = argc;
in = stdin;
cmd = check_rspamc_command ("symbols");
}
else if (argc == 2) {
/* One argument is whether command or filename */
if ((cmd = check_rspamc_command (argv[1])) != NULL) {
start_argc = argc;
in = stdin;
}
else {
cmd = check_rspamc_command ("symbols"); /* Symbols command */
start_argc = 1;
}
}
else {
if ((cmd = check_rspamc_command (argv[1])) != NULL) {
/* In case of command read arguments starting from 2 */
if (cmd->cmd == RSPAMC_COMMAND_ADD_SYMBOL || cmd->cmd ==
RSPAMC_COMMAND_ADD_ACTION) {
if (argc < 4 || argc > 5) {
fprintf (stderr, "invalid arguments\n");
exit (EXIT_FAILURE);
}
if (argc == 5) {
ADD_CLIENT_HEADER (kwattrs, "metric", argv[2]);
ADD_CLIENT_HEADER (kwattrs, "name", argv[3]);
ADD_CLIENT_HEADER (kwattrs, "value", argv[4]);
}
else {
ADD_CLIENT_HEADER (kwattrs, "name", argv[2]);
ADD_CLIENT_HEADER (kwattrs, "value", argv[3]);
}
start_argc = argc;
}
else {
start_argc = 2;
}
}
else {
cmd = check_rspamc_command ("symbols");
start_argc = 1;
}
}
add_options (kwattrs);
if (start_argc == argc) {
/* Do command without input or with stdin */
if (empty_input) {
rspamc_process_input (event_loop, cmd, NULL, "empty", kwattrs);
}
else {
rspamc_process_input (event_loop, cmd, in, "stdin", kwattrs);
}
}
else {
for (i = start_argc; i < argc; i++) {
if (cmd->cmd == RSPAMC_COMMAND_FUZZY_DELHASH) {
ADD_CLIENT_HEADER (kwattrs, "Hash", argv[i]);
}
else {
if (stat (argv[i], &st) == -1) {
fprintf (stderr, "cannot stat file %s\n", argv[i]);
exit (EXIT_FAILURE);
}
if (S_ISDIR (st.st_mode)) {
/* Directories are processed with a separate limit */
rspamc_process_dir (event_loop, cmd, argv[i], kwattrs);
cur_req = 0;
}
else {
in = fopen (argv[i], "r");
if (in == NULL) {
fprintf (stderr, "cannot open file %s\n", argv[i]);
exit (EXIT_FAILURE);
}
rspamc_process_input (event_loop, cmd, in, argv[i], kwattrs);
cur_req++;
fclose (in);
}
if (cur_req >= max_requests) {
cur_req = 0;
/* Wait for completion */
ev_loop (event_loop, 0);
}
}
}
if (cmd->cmd == RSPAMC_COMMAND_FUZZY_DELHASH) {
rspamc_process_input (event_loop, cmd, NULL, "hashes", kwattrs);
}
}
ev_loop (event_loop, 0);
g_queue_free_full (kwattrs, rspamc_kwattr_free);
/* Wait for children processes */
cur = children ? g_list_first (children) : NULL;
ret = 0;
while (cur) {
cld = GPOINTER_TO_SIZE (cur->data);
if (waitpid (cld, &res, 0) == -1) {
fprintf (stderr, "Cannot wait for %d: %s", (gint)cld,
strerror (errno));
ret = errno;
}
if (ret == 0) {
/* Check return code */
if (WIFSIGNALED (res)) {
ret = WTERMSIG (res);
}
else if (WIFEXITED (res)) {
ret = WEXITSTATUS (res);
}
}
cur = g_list_next (cur);
}
if (children != NULL) {
g_list_free (children);
}
for (i = 0; i < npatterns; i ++) {
g_pattern_spec_free (exclude_compiled[i]);
}
/* Mix retcode (return from Rspamd side) and ret (return from subprocess) */
return ret | retcode;
}
|
622405.c | /*
* progress.c - Numeric progress meter
*
* Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
* 2003, 2004, 2005 by Theodore Ts'o.
*
* %Begin-Header%
* This file may be redistributed under the terms of the GNU Public
* License.
* %End-Header%
*/
#include "config.h"
#include <time.h>
#include "ext2fs.h"
#include "ext2fsP.h"
static char spaces[80], backspaces[80];
static time_t last_update;
struct ext2fs_progress_ops ext2fs_numeric_progress_ops = {
.init = ext2fs_numeric_progress_init,
.update = ext2fs_numeric_progress_update,
.close = ext2fs_numeric_progress_close,
};
static int int_log10(unsigned int arg)
{
int l;
for (l = 0; arg; l++)
arg = arg / 10;
return l;
}
void ext2fs_numeric_progress_init(
ext2_filsys fs, struct ext2fs_numeric_progress_struct* progress,
const char* label, __u64 max)
{
/*
* The PRINT_PROGRESS flag turns on or off ALL
* progress-related messages, whereas the SKIP_PROGRESS
* environment variable prints the start and end messages but
* not the numeric countdown in the middle.
*/
if (!(fs->flags & EXT2_FLAG_PRINT_PROGRESS))
return;
memset(spaces, ' ', sizeof(spaces) - 1);
spaces[sizeof(spaces) - 1] = 0;
memset(backspaces, '\b', sizeof(backspaces) - 1);
backspaces[sizeof(backspaces) - 1] = 0;
memset(progress, 0, sizeof(*progress));
if (getenv("E2FSPROGS_SKIP_PROGRESS"))
progress->skip_progress++;
/*
* Figure out how many digits we need
*/
progress->max = max;
progress->log_max = int_log10(max);
if (label)
{
fputs(label, stdout);
fflush(stdout);
}
last_update = 0;
}
void ext2fs_numeric_progress_update(
ext2_filsys fs, struct ext2fs_numeric_progress_struct* progress, __u64 val)
{
time_t now;
if (!(fs->flags & EXT2_FLAG_PRINT_PROGRESS))
return;
if (progress->skip_progress)
return;
now = time(0);
if (now == last_update)
return;
last_update = now;
printf("%*llu/%*llu", progress->log_max, val, progress->log_max,
progress->max);
fprintf(stdout, "%.*s", (2 * progress->log_max) + 1, backspaces);
}
void ext2fs_numeric_progress_close(
ext2_filsys fs, struct ext2fs_numeric_progress_struct* progress,
const char* message)
{
if (!(fs->flags & EXT2_FLAG_PRINT_PROGRESS))
return;
fprintf(stdout, "%.*s", (2 * progress->log_max) + 1, spaces);
fprintf(stdout, "%.*s", (2 * progress->log_max) + 1, backspaces);
if (message)
fputs(message, stdout);
}
|
483099.c | //#############################################################################
//! \file /2837x_vcu2_rifft_256/main.c
//!
//! \brief Demo code for the 256 sample RFFT(VCU) and RIFFT(VCU)
//!
//! \date July 23, 2013
//!
//! This example shows how to use the vcu2 supported CFFT and utility routines
//! from the library to perform an FFT of an N point real sequence
//!
//
// Group: C2000
// Target Family: F2837x
//
//#############################################################################
// $TI Release: C28x VCU Library V2.10.00.00 $
// $Release Date: Oct 18, 2018 $
// $Copyright: Copyright (C) 2018 Texas Instruments Incorporated -
// http://www.ti.com/ ALL RIGHTS RESERVED $
//#############################################################################
//*****************************************************************************
// includes
//*****************************************************************************
#include "vcu2_types.h"
#include "vcu2_fft.h"
#include "examples_setup.h"
//!
//! \addtogroup RFFT_EXAMPLES Real Fast Fourier Transform 256 point Sequence
// @{
//*****************************************************************************
// defines
//*****************************************************************************
#define NSTAGES 8
#define NSAMPLES 1<<NSTAGES
#define ERR_EPSILON 10
//*****************************************************************************
// globals
//*****************************************************************************
#ifdef __cplusplus
#pragma DATA_SECTION("buffer1")
#else
#pragma DATA_SECTION(buffer1Q15,"buffer1")
#endif //__cplusplus
// \brief Test Input Data
//
int16_t buffer1Q15[2*NSAMPLES] = {
#include "data_input.h"
};
// \brief Expected Output
//
const int16_t goldenOutputQ15[2*NSAMPLES] = {
#include "data_output.h"
};
// \brief Error Vector
//
int16_t errorQ15[2*NSAMPLES];
#ifdef __cplusplus
#pragma DATA_SECTION("buffer2")
#else
#pragma DATA_SECTION(buffer2Q15,"buffer2")
#endif
// \brief Test Output Data
//
int16_t buffer2Q15[2*NSAMPLES];
// \brief CFFT Object
//
CFFT_Obj CFFT;
// \brief Handle to the CFFT object
//
CFFT_Handle handleCFFT;
uint16_t pass = 0;
uint16_t fail = 0;
//*****************************************************************************
// Function Prototypes
//*****************************************************************************
//*****************************************************************************
// function definitions
//*****************************************************************************
//!
//! \brief main routine for the 256-sample RFFT example
//! \return returns a 1
//!
//! This example shows how to use the vcu2 supported CFFT routines from the
//! library. The input is placed in a section buffer1 that needs to be
//! aligned to the size of the input in words to allow the bit reverse
//! addressing in stage 1 of the FFT to work properly. The output, however, need
//! not be aligned to any boundary
//!
int main( void )
{
// Locals
int16_t i;
#ifdef FLASH
EALLOW;
Flash0EccRegs.ECC_ENABLE.bit.ENABLE = 0;
memcpy((uint32_t *)&RamfuncsRunStart, (uint32_t *)&RamfuncsLoadStart,
(uint32_t)&RamfuncsLoadSize );
VCU2_initFlash();
#endif //FLASH
VCU2_initSystemClocks();
VCU2_initEpie();
//*************************************************************************
// Running the RIFFT
//*************************************************************************
//! \b Running \b the \b RIFFT
//! The user starts by initializing the CFFT Object with the appropriate
//! init() and run().The init() accepts pointers to the input and output
//! buffers and will initialize the other object elements appropriately.
//! For the F2837xD devices, the twiddle factor tables are already present
//! in bootrom.
//! For an N-point real FFT, the input was treated as an N/2 point
//! complex data set and an N/2 point complex FFT was run on it, and its
//! output unpacked. Therefore, the user must perform the inverse operations
//! i.e. "pack" the data and then run it through the same N/2 complex FFT
//! and finally conjugate the output to get the correct result
//!
//! The user need not re-initialize the CFFT object if done before (during
//! a forward run of the RFFT). The user must take care that the pInBuffer
//! pointer points to the input. If running through the forward RFFT first,
//! the pointers pInBuffer and pOutBuffer should be switched first
//! \code
//*************************************************************************
// Step 1: Initialize CFFT object
CFFT.pInBuffer = buffer1Q15;
CFFT.pOutBuffer = buffer2Q15;
CFFT.init = (void (*)(void *))CFFT_init256Pt;
CFFT.run = (void (*)(void *))CFFT_run256Pt;
// Step 2: Initialize the handle
handleCFFT = &CFFT;
// Step 3: Run the init first, then pack routine, followed by the IFFT
CFFT.init(handleCFFT);
CFFT_pack(handleCFFT);
CFFT.run(handleCFFT);
CFFT_conjugate(handleCFFT->pOutBuffer, handleCFFT->nSamples);
//*************************************************************************
//!
//! \endcode
//!
//*************************************************************************
// Step 4: Verify the result
for(i = 0; i < CFFT.nSamples*2; i++){
errorQ15[i] = abs(CFFT.pOutBuffer[i] - goldenOutputQ15[i]);
if( errorQ15[i] > ERR_EPSILON ){
fail++;
}else{
pass++;
}
}
// End of test
done();
// Execution never reaches this point
return 1;
}
// End of main
// @} //addtogroup
// End of file
|
605343.c | /*-------------------------------------------------------------------------
*
* parse_agg.c
* handle aggregates in parser
*
* Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/parser/parse_agg.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_type.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/tlist.h"
#include "optimizer/walkers.h"
#include "parser/parse_agg.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_expr.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "optimizer/walkers.h"
typedef struct
{
ParseState *pstate;
int min_varlevel;
int min_agglevel;
int sublevels_up;
} check_agg_arguments_context;
typedef struct
{
ParseState *pstate;
Query *qry;
PlannerInfo *root;
List *groupClauses;
List *groupClauseCommonVars;
bool have_non_var_grouping;
List **func_grouped_rels;
int sublevels_up;
bool in_agg_direct_args;
} check_ungrouped_columns_context;
typedef struct
{
int sublevels_up;
} checkHasGroupExtFuncs_context;
static int check_agg_arguments(ParseState *pstate,
List *directargs,
List *args,
Expr *filter);
static bool check_agg_arguments_walker(Node *node,
check_agg_arguments_context *context);
static void check_ungrouped_columns(Node *node, ParseState *pstate, Query *qry,
List *groupClauses, List *groupClauseVars,
bool have_non_var_grouping,
List **func_grouped_rels);
static bool check_ungrouped_columns_walker(Node *node,
check_ungrouped_columns_context *context);
static void finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry,
List *groupClauses, PlannerInfo *root,
bool have_non_var_grouping);
static bool finalize_grouping_exprs_walker(Node *node,
check_ungrouped_columns_context *context);
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr);
static List *expand_groupingset_node(GroupingSet *gs);
static Node *make_agg_arg(Oid argtype, Oid argcollation);
/*
* transformAggregateCall -
* Finish initial transformation of an aggregate call
*
* parse_func.c has recognized the function as an aggregate, and has set up
* all the fields of the Aggref except aggdirectargs, args, aggorder,
* aggdistinct and agglevelsup. The passed-in args list has been through
* standard expression transformation and type coercion to match the agg's
* declared arg types, while the passed-in aggorder list hasn't been
* transformed at all.
*
* Here we separate the args list into direct and aggregated args, storing the
* former in agg->aggdirectargs and the latter in agg->args. The regular
* args, but not the direct args, are converted into a targetlist by inserting
* TargetEntry nodes. We then transform the aggorder and agg_distinct
* specifications to produce lists of SortGroupClause nodes for agg->aggorder
* and agg->aggdistinct. (For a regular aggregate, this might result in
* adding resjunk expressions to the targetlist; but for ordered-set
* aggregates the aggorder list will always be one-to-one with the aggregated
* args.)
*
* We must also determine which query level the aggregate actually belongs to,
* set agglevelsup accordingly, and mark p_hasAggs true in the corresponding
* pstate level.
*/
void
transformAggregateCall(ParseState *pstate, Aggref *agg,
List *args, List *aggorder, bool agg_distinct)
{
List *tlist = NIL;
List *torder = NIL;
List *tdistinct = NIL;
AttrNumber attno = 1;
int save_next_resno;
ListCell *lc;
if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
{
/*
* For an ordered-set agg, the args list includes direct args and
* aggregated args; we must split them apart.
*/
int numDirectArgs = list_length(args) - list_length(aggorder);
List *aargs;
ListCell *lc2;
Assert(numDirectArgs >= 0);
aargs = list_copy_tail(args, numDirectArgs);
agg->aggdirectargs = list_truncate(args, numDirectArgs);
/*
* Build a tlist from the aggregated args, and make a sortlist entry
* for each one. Note that the expressions in the SortBy nodes are
* ignored (they are the raw versions of the transformed args); we are
* just looking at the sort information in the SortBy nodes.
*/
forboth(lc, aargs, lc2, aggorder)
{
Expr *arg = (Expr *) lfirst(lc);
SortBy *sortby = (SortBy *) lfirst(lc2);
TargetEntry *tle;
/* We don't bother to assign column names to the entries */
tle = makeTargetEntry(arg, attno++, NULL, false);
tlist = lappend(tlist, tle);
torder = addTargetToSortList(pstate, tle,
torder, tlist, sortby,
true /* fix unknowns */ );
}
/* Never any DISTINCT in an ordered-set agg */
Assert(!agg_distinct);
}
else
{
/* Regular aggregate, so it has no direct args */
agg->aggdirectargs = NIL;
/*
* Transform the plain list of Exprs into a targetlist.
*/
foreach(lc, args)
{
Expr *arg = (Expr *) lfirst(lc);
TargetEntry *tle;
/* We don't bother to assign column names to the entries */
tle = makeTargetEntry(arg, attno++, NULL, false);
tlist = lappend(tlist, tle);
}
/*
* If we have an ORDER BY, transform it. This will add columns to the
* tlist if they appear in ORDER BY but weren't already in the arg
* list. They will be marked resjunk = true so we can tell them apart
* from regular aggregate arguments later.
*
* We need to mess with p_next_resno since it will be used to number
* any new targetlist entries.
*/
save_next_resno = pstate->p_next_resno;
pstate->p_next_resno = attno;
torder = transformSortClause(pstate,
aggorder,
&tlist,
EXPR_KIND_ORDER_BY,
true /* fix unknowns */ ,
true /* force SQL99 rules */ );
/*
* If we have DISTINCT, transform that to produce a distinctList.
*/
if (agg_distinct)
{
tdistinct = transformDistinctClause(pstate, &tlist, torder, true);
/*
* Remove this check if executor support for hashed distinct for
* aggregates is ever added.
*/
foreach(lc, tdistinct)
{
SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc);
if (!OidIsValid(sortcl->sortop))
{
Node *expr = get_sortgroupclause_expr(sortcl, tlist);
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("could not identify an ordering operator for type %s",
format_type_be(exprType(expr))),
errdetail("Aggregates with DISTINCT must be able to sort their inputs."),
parser_errposition(pstate, exprLocation(expr))));
}
}
}
pstate->p_next_resno = save_next_resno;
}
/* Update the Aggref with the transformation results */
agg->args = tlist;
agg->aggorder = torder;
agg->aggdistinct = tdistinct;
check_agglevels_and_constraints(pstate, (Node *) agg);
}
/*
* transformGroupingFunc
* Transform a GROUPING expression
*
* GROUPING() behaves very like an aggregate. Processing of levels and nesting
* is done as for aggregates. We set p_hasAggs for these expressions too.
*/
Node *
transformGroupingFunc(ParseState *pstate, GroupingFunc *p)
{
ListCell *lc;
List *args = p->args;
List *result_list = NIL;
GroupingFunc *result = makeNode(GroupingFunc);
if (list_length(args) > 31)
ereport(ERROR,
(errcode(ERRCODE_TOO_MANY_ARGUMENTS),
errmsg("GROUPING must have fewer than 32 arguments"),
parser_errposition(pstate, p->location)));
foreach(lc, args)
{
Node *current_result;
current_result = transformExpr(pstate, (Node *) lfirst(lc), pstate->p_expr_kind);
/* acceptability of expressions is checked later */
result_list = lappend(result_list, current_result);
}
result->args = result_list;
result->location = p->location;
check_agglevels_and_constraints(pstate, (Node *) result);
return (Node *) result;
}
/*
* transformGroupingFunc
* Transform a GROUPING expression
*
* GROUP_ID() behaves very like an aggregate. Processing of levels and nesting
* is done as for aggregates. We set p_hasAggs for these expressions too.
*/
Node *
transformGroupId(ParseState *pstate, GroupId *p)
{
GroupId *result = makeNode(GroupId);
result->location = p->location;
check_agglevels_and_constraints(pstate, (Node *) result);
return (Node *) result;
}
/*
* Aggregate functions and grouping operations (which are combined in the spec
* as <set function specification>) are very similar with regard to level and
* nesting restrictions (though we allow a lot more things than the spec does).
* Centralise those restrictions here.
*/
static void
check_agglevels_and_constraints(ParseState *pstate, Node *expr)
{
List *directargs = NIL;
List *args = NIL;
Expr *filter = NULL;
int min_varlevel;
int location = -1;
Index *p_levelsup;
const char *err;
bool errkind;
bool isAgg = IsA(expr, Aggref);
if (isAgg)
{
Aggref *agg = (Aggref *) expr;
directargs = agg->aggdirectargs;
args = agg->args;
filter = agg->aggfilter;
location = agg->location;
p_levelsup = &agg->agglevelsup;
}
else if (IsA(expr, GroupId))
{
GroupId *grp = (GroupId *) expr;
args = NIL;
location = grp->location;
p_levelsup = &grp->agglevelsup;
}
else
{
GroupingFunc *grp = (GroupingFunc *) expr;
args = grp->args;
location = grp->location;
p_levelsup = &grp->agglevelsup;
}
/*
* Check the arguments to compute the aggregate's level and detect
* improper nesting.
*/
min_varlevel = check_agg_arguments(pstate,
directargs,
args,
filter);
*p_levelsup = min_varlevel;
/* Mark the correct pstate level as having aggregates */
while (min_varlevel-- > 0)
pstate = pstate->parentParseState;
pstate->p_hasAggs = true;
/*
* Check to see if the aggregate function is in an invalid place within
* its aggregation query.
*
* For brevity we support two schemes for reporting an error here: set
* "err" to a custom message, or set "errkind" true if the error context
* is sufficiently identified by what ParseExprKindName will return, *and*
* what it will return is just a SQL keyword. (Otherwise, use a custom
* message to avoid creating translation problems.)
*/
err = NULL;
errkind = false;
switch (pstate->p_expr_kind)
{
case EXPR_KIND_NONE:
Assert(false); /* can't happen */
break;
case EXPR_KIND_OTHER:
/*
* Accept aggregate/grouping here; caller must throw error if
* wanted
*/
break;
case EXPR_KIND_JOIN_ON:
case EXPR_KIND_JOIN_USING:
if (isAgg)
err = _("aggregate functions are not allowed in JOIN conditions");
else
err = _("grouping operations are not allowed in JOIN conditions");
break;
case EXPR_KIND_FROM_SUBSELECT:
/* Should only be possible in a LATERAL subquery */
Assert(pstate->p_lateral_active);
/*
* Aggregate/grouping scope rules make it worth being explicit
* here
*/
if (isAgg)
err = _("aggregate functions are not allowed in FROM clause of their own query level");
else
err = _("grouping operations are not allowed in FROM clause of their own query level");
break;
case EXPR_KIND_FROM_FUNCTION:
if (isAgg)
err = _("aggregate functions are not allowed in functions in FROM");
else
err = _("grouping operations are not allowed in functions in FROM");
break;
case EXPR_KIND_WHERE:
errkind = true;
break;
case EXPR_KIND_HAVING:
/* okay */
break;
case EXPR_KIND_FILTER:
errkind = true;
break;
case EXPR_KIND_WINDOW_PARTITION:
/* okay */
break;
case EXPR_KIND_WINDOW_ORDER:
/* okay */
break;
case EXPR_KIND_WINDOW_FRAME_RANGE:
if (isAgg)
err = _("aggregate functions are not allowed in window RANGE");
else
err = _("grouping operations are not allowed in window RANGE");
break;
case EXPR_KIND_WINDOW_FRAME_ROWS:
if (isAgg)
err = _("aggregate functions are not allowed in window ROWS");
else
err = _("grouping operations are not allowed in window ROWS");
break;
case EXPR_KIND_SELECT_TARGET:
/* okay */
break;
case EXPR_KIND_INSERT_TARGET:
case EXPR_KIND_UPDATE_SOURCE:
case EXPR_KIND_UPDATE_TARGET:
errkind = true;
break;
case EXPR_KIND_GROUP_BY:
errkind = true;
break;
case EXPR_KIND_ORDER_BY:
/* okay */
break;
case EXPR_KIND_DISTINCT_ON:
/* okay */
break;
case EXPR_KIND_LIMIT:
case EXPR_KIND_OFFSET:
errkind = true;
break;
case EXPR_KIND_RETURNING:
errkind = true;
break;
case EXPR_KIND_VALUES:
errkind = true;
break;
case EXPR_KIND_CHECK_CONSTRAINT:
case EXPR_KIND_DOMAIN_CHECK:
if (isAgg)
err = _("aggregate functions are not allowed in check constraints");
else
err = _("grouping operations are not allowed in check constraints");
break;
case EXPR_KIND_COLUMN_DEFAULT:
case EXPR_KIND_FUNCTION_DEFAULT:
if (isAgg)
err = _("aggregate functions are not allowed in DEFAULT expressions");
else
err = _("grouping operations are not allowed in DEFAULT expressions");
break;
case EXPR_KIND_INDEX_EXPRESSION:
if (isAgg)
err = _("aggregate functions are not allowed in index expressions");
else
err = _("grouping operations are not allowed in index expressions");
break;
case EXPR_KIND_INDEX_PREDICATE:
if (isAgg)
err = _("aggregate functions are not allowed in index predicates");
else
err = _("grouping operations are not allowed in index predicates");
break;
case EXPR_KIND_ALTER_COL_TRANSFORM:
if (isAgg)
err = _("aggregate functions are not allowed in transform expressions");
else
err = _("grouping operations are not allowed in transform expressions");
break;
case EXPR_KIND_EXECUTE_PARAMETER:
if (isAgg)
err = _("aggregate functions are not allowed in EXECUTE parameters");
else
err = _("grouping operations are not allowed in EXECUTE parameters");
break;
case EXPR_KIND_TRIGGER_WHEN:
if (isAgg)
err = _("aggregate functions are not allowed in trigger WHEN conditions");
else
err = _("grouping operations are not allowed in trigger WHEN conditions");
break;
case EXPR_KIND_PARTITION_EXPRESSION:
err = _("aggregate functions are not allowed in partition key expression");
case EXPR_KIND_SCATTER_BY:
/* okay */
break;
/*
* There is intentionally no default: case here, so that the
* compiler will warn if we add a new ParseExprKind without
* extending this switch. If we do see an unrecognized value at
* runtime, the behavior will be the same as for EXPR_KIND_OTHER,
* which is sane anyway.
*/
}
if (err)
ereport(ERROR,
(errcode(ERRCODE_GROUPING_ERROR),
errmsg_internal("%s", err),
parser_errposition(pstate, location)));
if (errkind)
{
if (isAgg)
/* translator: %s is name of a SQL construct, eg GROUP BY */
err = _("aggregate functions are not allowed in %s");
else
/* translator: %s is name of a SQL construct, eg GROUP BY */
err = _("grouping operations are not allowed in %s");
ereport(ERROR,
(errcode(ERRCODE_GROUPING_ERROR),
errmsg_internal(err,
ParseExprKindName(pstate->p_expr_kind)),
parser_errposition(pstate, location)));
}
}
/*
* check_agg_arguments
* Scan the arguments of an aggregate function to determine the
* aggregate's semantic level (zero is the current select's level,
* one is its parent, etc).
*
* The aggregate's level is the same as the level of the lowest-level variable
* or aggregate in its aggregated arguments (including any ORDER BY columns)
* or filter expression; or if it contains no variables at all, we presume it
* to be local.
*
* Vars/Aggs in direct arguments are *not* counted towards determining the
* agg's level, as those arguments aren't evaluated per-row but only
* per-group, and so in some sense aren't really agg arguments. However,
* this can mean that we decide an agg is upper-level even when its direct
* args contain lower-level Vars/Aggs, and that case has to be disallowed.
* (This is a little strange, but the SQL standard seems pretty definite that
* direct args are not to be considered when setting the agg's level.)
*
* We also take this opportunity to detect any aggregates or window functions
* nested within the arguments. We can throw error immediately if we find
* a window function. Aggregates are a bit trickier because it's only an
* error if the inner aggregate is of the same semantic level as the outer,
* which we can't know until we finish scanning the arguments.
*/
static int
check_agg_arguments(ParseState *pstate,
List *directargs,
List *args,
Expr *filter)
{
int agglevel;
check_agg_arguments_context context;
context.pstate = pstate;
context.min_varlevel = -1; /* signifies nothing found yet */
context.min_agglevel = -1;
context.sublevels_up = 0;
(void) expression_tree_walker((Node *) args,
check_agg_arguments_walker,
(void *) &context);
(void) expression_tree_walker((Node *) filter,
check_agg_arguments_walker,
(void *) &context);
/*
* If we found no vars nor aggs at all, it's a level-zero aggregate;
* otherwise, its level is the minimum of vars or aggs.
*/
if (context.min_varlevel < 0)
{
if (context.min_agglevel < 0)
agglevel = 0;
else
agglevel = context.min_agglevel;
}
else if (context.min_agglevel < 0)
agglevel = context.min_varlevel;
else
agglevel = Min(context.min_varlevel, context.min_agglevel);
/*
* If there's a nested aggregate of the same semantic level, complain.
*/
if (agglevel == context.min_agglevel)
{
int aggloc;
aggloc = locate_agg_of_level((Node *) args, agglevel);
if (aggloc < 0)
aggloc = locate_agg_of_level((Node *) filter, agglevel);
ereport(ERROR,
(errcode(ERRCODE_GROUPING_ERROR),
errmsg("aggregate function calls cannot be nested"),
parser_errposition(pstate, aggloc)));
}
/*
* Now check for vars/aggs in the direct arguments, and throw error if
* needed. Note that we allow a Var of the agg's semantic level, but not
* an Agg of that level. In principle such Aggs could probably be
* supported, but it would create an ordering dependency among the
* aggregates at execution time. Since the case appears neither to be
* required by spec nor particularly useful, we just treat it as a
* nested-aggregate situation.
*/
if (directargs)
{
context.min_varlevel = -1;
context.min_agglevel = -1;
(void) expression_tree_walker((Node *) directargs,
check_agg_arguments_walker,
(void *) &context);
if (context.min_varlevel >= 0 && context.min_varlevel < agglevel)
ereport(ERROR,
(errcode(ERRCODE_GROUPING_ERROR),
errmsg("outer-level aggregate cannot contain a lower-level variable in its direct arguments"),
parser_errposition(pstate,
locate_var_of_level((Node *) directargs,
context.min_varlevel))));
if (context.min_agglevel >= 0 && context.min_agglevel <= agglevel)
ereport(ERROR,
(errcode(ERRCODE_GROUPING_ERROR),
errmsg("aggregate function calls cannot be nested"),
parser_errposition(pstate,
locate_agg_of_level((Node *) directargs,
context.min_agglevel))));
}
return agglevel;
}
static bool
check_agg_arguments_walker(Node *node,
check_agg_arguments_context *context)
{
if (node == NULL)
return false;
if (IsA(node, Var))
{
int varlevelsup = ((Var *) node)->varlevelsup;
/* convert levelsup to frame of reference of original query */
varlevelsup -= context->sublevels_up;
/* ignore local vars of subqueries */
if (varlevelsup >= 0)
{
if (context->min_varlevel < 0 ||
context->min_varlevel > varlevelsup)
context->min_varlevel = varlevelsup;
}
return false;
}
if (IsA(node, Aggref))
{
int agglevelsup = ((Aggref *) node)->agglevelsup;
/* convert levelsup to frame of reference of original query */
agglevelsup -= context->sublevels_up;
/* ignore local aggs of subqueries */
if (agglevelsup >= 0)
{
if (context->min_agglevel < 0 ||
context->min_agglevel > agglevelsup)
context->min_agglevel = agglevelsup;
}
/* no need to examine args of the inner aggregate */
return false;
}
if (IsA(node, GroupingFunc))
{
int agglevelsup = ((GroupingFunc *) node)->agglevelsup;
/* convert levelsup to frame of reference of original query */
agglevelsup -= context->sublevels_up;
/* ignore local aggs of subqueries */
if (agglevelsup >= 0)
{
if (context->min_agglevel < 0 ||
context->min_agglevel > agglevelsup)
context->min_agglevel = agglevelsup;
}
/* Continue and descend into subtree */
}
if (IsA(node, GroupId))
{
int agglevelsup = ((GroupId *) node)->agglevelsup;
/* convert levelsup to frame of reference of original query */
agglevelsup -= context->sublevels_up;
/* ignore local aggs of subqueries */
if (agglevelsup >= 0)
{
if (context->min_agglevel < 0 ||
context->min_agglevel > agglevelsup)
context->min_agglevel = agglevelsup;
}
/* Continue and descend into subtree */
}
/* We can throw error on sight for a window function */
if (IsA(node, WindowFunc) && context->sublevels_up == 0)
ereport(ERROR,
(errcode(ERRCODE_GROUPING_ERROR),
errmsg("aggregate function calls cannot contain window function calls"),
parser_errposition(context->pstate,
((WindowFunc *) node)->location)));
if (IsA(node, Query))
{
/* Recurse into subselects */
bool result;
context->sublevels_up++;
result = query_tree_walker((Query *) node,
check_agg_arguments_walker,
(void *) context,
0);
context->sublevels_up--;
return result;
}
return expression_tree_walker(node,
check_agg_arguments_walker,
(void *) context);
}
/*
* transformWindowFuncCall -
* Finish initial transformation of a window function call
*
* parse_func.c has recognized the function as a window function, and has set
* up all the fields of the WindowFunc except winref. Here we must (1) add
* the WindowDef to the pstate (if not a duplicate of one already present) and
* set winref to link to it; and (2) mark p_hasWindowFuncs true in the pstate.
* Unlike aggregates, only the most closely nested pstate level need be
* considered --- there are no "outer window functions" per SQL spec.
*/
void
transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
WindowDef *windef)
{
const char *err;
bool errkind;
char *name;
/*
* A window function call can't contain another one (but aggs are OK). XXX
* is this required by spec, or just an unimplemented feature?
*
* Note: we don't need to check the filter expression here, because the
* context checks done below and in transformAggregateCall would have
* already rejected any window funcs or aggs within the filter.
*/
if (pstate->p_hasWindowFuncs &&
contain_windowfuncs((Node *) wfunc->args))
ereport(ERROR,
(errcode(ERRCODE_WINDOWING_ERROR),
errmsg("window function calls cannot be nested"),
parser_errposition(pstate,
locate_windowfunc((Node *) wfunc->args))));
/*
* Check to see if the window function is in an invalid place within the
* query.
*
* For brevity we support two schemes for reporting an error here: set
* "err" to a custom message, or set "errkind" true if the error context
* is sufficiently identified by what ParseExprKindName will return, *and*
* what it will return is just a SQL keyword. (Otherwise, use a custom
* message to avoid creating translation problems.)
*/
err = NULL;
errkind = false;
switch (pstate->p_expr_kind)
{
case EXPR_KIND_NONE:
Assert(false); /* can't happen */
break;
case EXPR_KIND_OTHER:
/* Accept window func here; caller must throw error if wanted */
break;
case EXPR_KIND_JOIN_ON:
case EXPR_KIND_JOIN_USING:
err = _("window functions are not allowed in JOIN conditions");
break;
case EXPR_KIND_FROM_SUBSELECT:
/* can't get here, but just in case, throw an error */
errkind = true;
break;
case EXPR_KIND_FROM_FUNCTION:
err = _("window functions are not allowed in functions in FROM");
break;
case EXPR_KIND_WHERE:
errkind = true;
break;
case EXPR_KIND_HAVING:
errkind = true;
break;
case EXPR_KIND_FILTER:
errkind = true;
break;
case EXPR_KIND_WINDOW_PARTITION:
case EXPR_KIND_WINDOW_ORDER:
case EXPR_KIND_WINDOW_FRAME_RANGE:
case EXPR_KIND_WINDOW_FRAME_ROWS:
err = _("window functions are not allowed in window definitions");
break;
case EXPR_KIND_SELECT_TARGET:
/* okay */
break;
case EXPR_KIND_INSERT_TARGET:
case EXPR_KIND_UPDATE_SOURCE:
case EXPR_KIND_UPDATE_TARGET:
errkind = true;
break;
case EXPR_KIND_GROUP_BY:
errkind = true;
break;
case EXPR_KIND_ORDER_BY:
/* okay */
break;
case EXPR_KIND_DISTINCT_ON:
/* okay */
break;
case EXPR_KIND_LIMIT:
case EXPR_KIND_OFFSET:
errkind = true;
break;
case EXPR_KIND_RETURNING:
errkind = true;
break;
case EXPR_KIND_VALUES:
errkind = true;
break;
case EXPR_KIND_CHECK_CONSTRAINT:
case EXPR_KIND_DOMAIN_CHECK:
err = _("window functions are not allowed in check constraints");
break;
case EXPR_KIND_COLUMN_DEFAULT:
case EXPR_KIND_FUNCTION_DEFAULT:
err = _("window functions are not allowed in DEFAULT expressions");
break;
case EXPR_KIND_INDEX_EXPRESSION:
err = _("window functions are not allowed in index expressions");
break;
case EXPR_KIND_INDEX_PREDICATE:
err = _("window functions are not allowed in index predicates");
break;
case EXPR_KIND_ALTER_COL_TRANSFORM:
err = _("window functions are not allowed in transform expressions");
break;
case EXPR_KIND_EXECUTE_PARAMETER:
err = _("window functions are not allowed in EXECUTE parameters");
break;
case EXPR_KIND_TRIGGER_WHEN:
err = _("window functions are not allowed in trigger WHEN conditions");
break;
case EXPR_KIND_PARTITION_EXPRESSION:
err = _("window functions are not allowed in partition key expression");
break;
case EXPR_KIND_SCATTER_BY:
/* okay */
break;
/*
* There is intentionally no default: case here, so that the
* compiler will warn if we add a new ParseExprKind without
* extending this switch. If we do see an unrecognized value at
* runtime, the behavior will be the same as for EXPR_KIND_OTHER,
* which is sane anyway.
*/
}
if (err)
ereport(ERROR,
(errcode(ERRCODE_WINDOWING_ERROR),
errmsg_internal("%s", err),
parser_errposition(pstate, wfunc->location)));
if (errkind)
ereport(ERROR,
(errcode(ERRCODE_WINDOWING_ERROR),
/* translator: %s is name of a SQL construct, eg GROUP BY */
errmsg("window functions are not allowed in %s",
ParseExprKindName(pstate->p_expr_kind)),
parser_errposition(pstate, wfunc->location)));
/*
* If the OVER clause just specifies a window name, find that WINDOW
* clause (which had better be present). Otherwise, try to match all the
* properties of the OVER clause, and make a new entry in the p_windowdefs
* list if no luck.
*
* In PostgreSQL, the syntax for this is "agg() OVER w". In GPDB, we also
* accept "agg() OVER (w)", with the extra parens.
*/
if (windef->name)
{
name = windef->name;
Assert(windef->refname == NULL &&
windef->partitionClause == NIL &&
windef->orderClause == NIL &&
windef->frameOptions == FRAMEOPTION_DEFAULTS);
}
else if (windef->refname &&
!windef->partitionClause &&
!windef->orderClause &&
(windef->frameOptions & FRAMEOPTION_NONDEFAULT) == 0)
{
/* This is "agg() OVER (w)" */
name = windef->refname;
}
else
name = NULL;
if (name)
{
Index winref = 0;
ListCell *lc;
foreach(lc, pstate->p_windowdefs)
{
WindowDef *refwin = (WindowDef *) lfirst(lc);
winref++;
if (refwin->name && strcmp(refwin->name, name) == 0)
{
wfunc->winref = winref;
break;
}
}
if (lc == NULL) /* didn't find it? */
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("window \"%s\" does not exist", name),
parser_errposition(pstate, windef->location)));
}
else
{
Index winref = 0;
ListCell *lc;
foreach(lc, pstate->p_windowdefs)
{
WindowDef *refwin = (WindowDef *) lfirst(lc);
winref++;
if (refwin->refname && windef->refname &&
strcmp(refwin->refname, windef->refname) == 0)
/* matched on refname */ ;
else if (!refwin->refname && !windef->refname)
/* matched, no refname */ ;
else
continue;
if (equal(refwin->partitionClause, windef->partitionClause) &&
equal(refwin->orderClause, windef->orderClause) &&
refwin->frameOptions == windef->frameOptions &&
equal(refwin->startOffset, windef->startOffset) &&
equal(refwin->endOffset, windef->endOffset))
{
/* found a duplicate window specification */
wfunc->winref = winref;
break;
}
}
if (lc == NULL) /* didn't find it? */
{
pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
wfunc->winref = list_length(pstate->p_windowdefs);
}
}
pstate->p_hasWindowFuncs = true;
}
/*
* parseCheckAggregates
* Check for aggregates where they shouldn't be and improper grouping.
* This function should be called after the target list and qualifications
* are finalized.
*
* Misplaced aggregates are now mostly detected in transformAggregateCall,
* but it seems more robust to check for aggregates in recursive queries
* only after everything is finalized. In any case it's hard to detect
* improper grouping on-the-fly, so we have to make another pass over the
* query for that.
*/
void
parseCheckAggregates(ParseState *pstate, Query *qry)
{
List *gset_common = NIL;
List *groupClauses = NIL;
List *groupClauseCommonVars = NIL;
bool have_non_var_grouping;
List *func_grouped_rels = NIL;
ListCell *l;
bool hasJoinRTEs;
bool hasSelfRefRTEs;
PlannerInfo *root = NULL;
Node *clause;
/* This should only be called if we found aggregates or grouping */
Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets);
/*
* If we have grouping sets, expand them and find the intersection of all
* sets.
*/
if (qry->groupingSets)
{
/*
* The limit of 4096 is arbitrary and exists simply to avoid resource
* issues from pathological constructs.
*/
List *gsets = expand_grouping_sets(qry->groupingSets, 4096);
if (!gsets)
ereport(ERROR,
(errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
errmsg("too many grouping sets present (max 4096)"),
parser_errposition(pstate,
qry->groupClause
? exprLocation((Node *) qry->groupClause)
: exprLocation((Node *) qry->groupingSets))));
/*
* The intersection will often be empty, so help things along by
* seeding the intersect with the smallest set.
*/
gset_common = linitial(gsets);
if (gset_common)
{
for_each_cell(l, lnext(list_head(gsets)))
{
gset_common = list_intersection_int(gset_common, lfirst(l));
if (!gset_common)
break;
}
}
/*
* If there was only one grouping set in the expansion, AND if the
* groupClause is non-empty (meaning that the grouping set is not
* empty either), then we can ditch the grouping set and pretend we
* just had a normal GROUP BY.
*/
if (list_length(gsets) == 1 && qry->groupClause)
qry->groupingSets = NIL;
}
/*
* Scan the range table to see if there are JOIN or self-reference CTE
* entries. We'll need this info below.
*/
hasJoinRTEs = hasSelfRefRTEs = false;
foreach(l, pstate->p_rtable)
{
RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
if (rte->rtekind == RTE_JOIN)
hasJoinRTEs = true;
else if (rte->rtekind == RTE_CTE && rte->self_reference)
hasSelfRefRTEs = true;
}
/*
* Build a list of the acceptable GROUP BY expressions for use by
* check_ungrouped_columns().
*
* We get the TLE, not just the expr, because GROUPING wants to know the
* sortgroupref.
*/
foreach(l, qry->groupClause)
{
SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
TargetEntry *expr;
expr = get_sortgroupclause_tle(grpcl, qry->targetList);
if (expr == NULL)
continue; /* probably cannot happen */
groupClauses = lcons(expr, groupClauses);
}
/*
* If there are join alias vars involved, we have to flatten them to the
* underlying vars, so that aliased and unaliased vars will be correctly
* taken as equal. We can skip the expense of doing this if no rangetable
* entries are RTE_JOIN kind. We use the planner's flatten_join_alias_vars
* routine to do the flattening; it wants a PlannerInfo root node, which
* fortunately can be mostly dummy.
*/
if (hasJoinRTEs)
{
root = makeNode(PlannerInfo);
root->parse = qry;
root->planner_cxt = CurrentMemoryContext;
root->hasJoinRTEs = true;
groupClauses = (List *) flatten_join_alias_vars(root,
(Node *) groupClauses);
}
/*
* Detect whether any of the grouping expressions aren't simple Vars; if
* they're all Vars then we don't have to work so hard in the recursive
* scans. (Note we have to flatten aliases before this.)
*
* Track Vars that are included in all grouping sets separately in
* groupClauseCommonVars, since these are the only ones we can use to
* check for functional dependencies.
*/
have_non_var_grouping = false;
foreach(l, groupClauses)
{
TargetEntry *tle = lfirst(l);
if (!IsA(tle->expr, Var))
{
have_non_var_grouping = true;
}
else if (!qry->groupingSets ||
list_member_int(gset_common, tle->ressortgroupref))
{
groupClauseCommonVars = lappend(groupClauseCommonVars, tle->expr);
}
}
/*
* Check the targetlist and HAVING clause for ungrouped variables.
*
* Note: because we check resjunk tlist elements as well as regular ones,
* this will also find ungrouped variables that came from ORDER BY and
* WINDOW clauses. For that matter, it's also going to examine the
* grouping expressions themselves --- but they'll all pass the test ...
*
* We also finalize GROUPING expressions, but for that we need to traverse
* the original (unflattened) clause in order to modify nodes.
*/
clause = (Node *) qry->targetList;
finalize_grouping_exprs(clause, pstate, qry,
groupClauses, root,
have_non_var_grouping);
if (hasJoinRTEs)
clause = flatten_join_alias_vars(root, clause);
check_ungrouped_columns(clause, pstate, qry,
groupClauses, groupClauseCommonVars,
have_non_var_grouping,
&func_grouped_rels);
clause = (Node *) qry->havingQual;
finalize_grouping_exprs(clause, pstate, qry,
groupClauses, root,
have_non_var_grouping);
if (hasJoinRTEs)
clause = flatten_join_alias_vars(root, clause);
check_ungrouped_columns(clause, pstate, qry,
groupClauses, groupClauseCommonVars,
have_non_var_grouping,
&func_grouped_rels);
/*
* Per spec, aggregates can't appear in a recursive term.
*/
if (pstate->p_hasAggs && hasSelfRefRTEs)
ereport(ERROR,
(errcode(ERRCODE_INVALID_RECURSION),
errmsg("aggregate functions are not allowed in a recursive query's recursive term"),
parser_errposition(pstate,
locate_agg_of_level((Node *) qry, 0))));
}
/*
* check_ungrouped_columns -
* Scan the given expression tree for ungrouped variables (variables
* that are not listed in the groupClauses list and are not within
* the arguments of aggregate functions). Emit a suitable error message
* if any are found.
*
* NOTE: we assume that the given clause has been transformed suitably for
* parser output. This means we can use expression_tree_walker.
*
* NOTE: we recognize grouping expressions in the main query, but only
* grouping Vars in subqueries. For example, this will be rejected,
* although it could be allowed:
* SELECT
* (SELECT x FROM bar where y = (foo.a + foo.b))
* FROM foo
* GROUP BY a + b;
* The difficulty is the need to account for different sublevels_up.
* This appears to require a whole custom version of equal(), which is
* way more pain than the feature seems worth.
*/
static void
check_ungrouped_columns(Node *node, ParseState *pstate, Query *qry,
List *groupClauses, List *groupClauseCommonVars,
bool have_non_var_grouping,
List **func_grouped_rels)
{
check_ungrouped_columns_context context;
context.pstate = pstate;
context.qry = qry;
context.root = NULL;
context.groupClauses = groupClauses;
context.groupClauseCommonVars = groupClauseCommonVars;
context.have_non_var_grouping = have_non_var_grouping;
context.func_grouped_rels = func_grouped_rels;
context.sublevels_up = 0;
context.in_agg_direct_args = false;
check_ungrouped_columns_walker(node, &context);
}
static bool
check_ungrouped_columns_walker(Node *node,
check_ungrouped_columns_context *context)
{
ListCell *gl;
if (node == NULL)
return false;
if (IsA(node, Const) ||
IsA(node, Param))
return false; /* constants are always acceptable */
if (IsA(node, Aggref))
{
Aggref *agg = (Aggref *) node;
if ((int) agg->agglevelsup == context->sublevels_up)
{
/*
* If we find an aggregate call of the original level, do not
* recurse into its normal arguments, ORDER BY arguments, or
* filter; ungrouped vars there are not an error. But we should
* check direct arguments as though they weren't in an aggregate.
* We set a special flag in the context to help produce a useful
* error message for ungrouped vars in direct arguments.
*/
bool result;
Assert(!context->in_agg_direct_args);
context->in_agg_direct_args = true;
result = check_ungrouped_columns_walker((Node *) agg->aggdirectargs,
context);
context->in_agg_direct_args = false;
return result;
}
/*
* We can skip recursing into aggregates of higher levels altogether,
* since they could not possibly contain Vars of concern to us (see
* transformAggregateCall). We do need to look at aggregates of lower
* levels, however.
*/
if ((int) agg->agglevelsup > context->sublevels_up)
return false;
}
if (IsA(node, GroupingFunc))
{
GroupingFunc *grp = (GroupingFunc *) node;
/* handled GroupingFunc separately, no need to recheck at this level */
if ((int) grp->agglevelsup >= context->sublevels_up)
return false;
}
if (IsA(node, GroupId))
{
GroupId *grp = (GroupId *) node;
/* handled GroupId separately, no need to recheck at this level */
if ((int) grp->agglevelsup >= context->sublevels_up)
return false;
}
/*
* If we have any GROUP BY items that are not simple Vars, check to see if
* subexpression as a whole matches any GROUP BY item. We need to do this
* at every recursion level so that we recognize GROUPed-BY expressions
* before reaching variables within them. But this only works at the outer
* query level, as noted above.
*/
if (context->have_non_var_grouping && context->sublevels_up == 0)
{
foreach(gl, context->groupClauses)
{
TargetEntry *tle = lfirst(gl);
if (equal(node, tle->expr))
return false; /* acceptable, do not descend more */
}
}
/*
* If we have an ungrouped Var of the original query level, we have a
* failure. Vars below the original query level are not a problem, and
* neither are Vars from above it. (If such Vars are ungrouped as far as
* their own query level is concerned, that's someone else's problem...)
*/
if (IsA(node, Var))
{
Var *var = (Var *) node;
RangeTblEntry *rte;
const char *attname;
if (var->varlevelsup != context->sublevels_up)
return false; /* it's not local to my query, ignore */
/*
* Check for a match, if we didn't do it above.
*/
if (!context->have_non_var_grouping || context->sublevels_up != 0)
{
foreach(gl, context->groupClauses)
{
Var *gvar = (Var *) ((TargetEntry *) lfirst(gl))->expr;
if (IsA(gvar, Var) &&
gvar->varno == var->varno &&
gvar->varattno == var->varattno &&
gvar->varlevelsup == 0)
return false; /* acceptable, we're okay */
}
}
/*
* Check whether the Var is known functionally dependent on the GROUP
* BY columns. If so, we can allow the Var to be used, because the
* grouping is really a no-op for this table. However, this deduction
* depends on one or more constraints of the table, so we have to add
* those constraints to the query's constraintDeps list, because it's
* not semantically valid anymore if the constraint(s) get dropped.
* (Therefore, this check must be the last-ditch effort before raising
* error: we don't want to add dependencies unnecessarily.)
*
* Because this is a pretty expensive check, and will have the same
* outcome for all columns of a table, we remember which RTEs we've
* already proven functional dependency for in the func_grouped_rels
* list. This test also prevents us from adding duplicate entries to
* the constraintDeps list.
*/
if (list_member_int(*context->func_grouped_rels, var->varno))
return false; /* previously proven acceptable */
Assert(var->varno > 0 &&
(int) var->varno <= list_length(context->pstate->p_rtable));
rte = rt_fetch(var->varno, context->pstate->p_rtable);
if (rte->rtekind == RTE_RELATION)
{
if (check_functional_grouping(rte->relid,
var->varno,
0,
context->groupClauseCommonVars,
&context->qry->constraintDeps))
{
*context->func_grouped_rels =
lappend_int(*context->func_grouped_rels, var->varno);
return false; /* acceptable */
}
}
/* Found an ungrouped local variable; generate error message */
attname = get_rte_attribute_name(rte, var->varattno);
if (context->sublevels_up == 0)
ereport(ERROR,
(errcode(ERRCODE_GROUPING_ERROR),
errmsg("column \"%s.%s\" must appear in the GROUP BY clause or be used in an aggregate function",
rte->eref->aliasname, attname),
context->in_agg_direct_args ?
errdetail("Direct arguments of an ordered-set aggregate must use only grouped columns.") : 0,
parser_errposition(context->pstate, var->location)));
else
ereport(ERROR,
(errcode(ERRCODE_GROUPING_ERROR),
errmsg("subquery uses ungrouped column \"%s.%s\" from outer query",
rte->eref->aliasname, attname),
parser_errposition(context->pstate, var->location)));
}
if (IsA(node, Query))
{
/* Recurse into subselects */
bool result;
context->sublevels_up++;
result = query_tree_walker((Query *) node,
check_ungrouped_columns_walker,
(void *) context,
0);
context->sublevels_up--;
return result;
}
return expression_tree_walker(node, check_ungrouped_columns_walker,
(void *) context);
}
/*
* finalize_grouping_exprs -
* Scan the given expression tree for GROUPING() and related calls,
* and validate and process their arguments.
*
* This is split out from check_ungrouped_columns above because it needs
* to modify the nodes (which it does in-place, not via a mutator) while
* check_ungrouped_columns may see only a copy of the original thanks to
* flattening of join alias vars. So here, we flatten each individual
* GROUPING argument as we see it before comparing it.
*/
static void
finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry,
List *groupClauses, PlannerInfo *root,
bool have_non_var_grouping)
{
check_ungrouped_columns_context context;
context.pstate = pstate;
context.qry = qry;
context.root = root;
context.groupClauses = groupClauses;
context.groupClauseCommonVars = NIL;
context.have_non_var_grouping = have_non_var_grouping;
context.func_grouped_rels = NULL;
context.sublevels_up = 0;
context.in_agg_direct_args = false;
finalize_grouping_exprs_walker(node, &context);
}
static bool
finalize_grouping_exprs_walker(Node *node,
check_ungrouped_columns_context *context)
{
ListCell *gl;
if (node == NULL)
return false;
if (IsA(node, Const) ||
IsA(node, Param))
return false; /* constants are always acceptable */
if (IsA(node, Aggref))
{
Aggref *agg = (Aggref *) node;
if ((int) agg->agglevelsup == context->sublevels_up)
{
/*
* If we find an aggregate call of the original level, do not
* recurse into its normal arguments, ORDER BY arguments, or
* filter; GROUPING exprs of this level are not allowed there. But
* check direct arguments as though they weren't in an aggregate.
*/
bool result;
Assert(!context->in_agg_direct_args);
context->in_agg_direct_args = true;
result = finalize_grouping_exprs_walker((Node *) agg->aggdirectargs,
context);
context->in_agg_direct_args = false;
return result;
}
/*
* We can skip recursing into aggregates of higher levels altogether,
* since they could not possibly contain exprs of concern to us (see
* transformAggregateCall). We do need to look at aggregates of lower
* levels, however.
*/
if ((int) agg->agglevelsup > context->sublevels_up)
return false;
}
if (IsA(node, GroupingFunc))
{
GroupingFunc *grp = (GroupingFunc *) node;
/*
* We only need to check GroupingFunc nodes at the exact level to
* which they belong, since they cannot mix levels in arguments.
*/
if ((int) grp->agglevelsup == context->sublevels_up)
{
ListCell *lc;
List *ref_list = NIL;
foreach(lc, grp->args)
{
Node *expr = lfirst(lc);
Index ref = 0;
if (context->root)
expr = flatten_join_alias_vars(context->root, expr);
/*
* Each expression must match a grouping entry at the current
* query level. Unlike the general expression case, we don't
* allow functional dependencies or outer references.
*/
if (IsA(expr, Var))
{
Var *var = (Var *) expr;
if (var->varlevelsup == context->sublevels_up)
{
foreach(gl, context->groupClauses)
{
TargetEntry *tle = lfirst(gl);
Var *gvar = (Var *) tle->expr;
if (IsA(gvar, Var) &&
gvar->varno == var->varno &&
gvar->varattno == var->varattno &&
gvar->varlevelsup == 0)
{
ref = tle->ressortgroupref;
break;
}
}
}
}
else if (context->have_non_var_grouping &&
context->sublevels_up == 0)
{
foreach(gl, context->groupClauses)
{
TargetEntry *tle = lfirst(gl);
if (equal(expr, tle->expr))
{
ref = tle->ressortgroupref;
break;
}
}
}
if (ref == 0)
ereport(ERROR,
(errcode(ERRCODE_GROUPING_ERROR),
errmsg("arguments to GROUPING must be grouping expressions of the associated query level"),
parser_errposition(context->pstate,
exprLocation(expr))));
ref_list = lappend_int(ref_list, ref);
}
grp->refs = ref_list;
}
if ((int) grp->agglevelsup > context->sublevels_up)
return false;
}
if (IsA(node, Query))
{
/* Recurse into subselects */
bool result;
context->sublevels_up++;
result = query_tree_walker((Query *) node,
finalize_grouping_exprs_walker,
(void *) context,
0);
context->sublevels_up--;
return result;
}
return expression_tree_walker(node, finalize_grouping_exprs_walker,
(void *) context);
}
/*
* Given a GroupingSet node, expand it and return a list of lists.
*
* For EMPTY nodes, return a list of one empty list.
*
* For SIMPLE nodes, return a list of one list, which is the node content.
*
* For CUBE and ROLLUP nodes, return a list of the expansions.
*
* For SET nodes, recursively expand contained CUBE and ROLLUP.
*/
static List *
expand_groupingset_node(GroupingSet *gs)
{
List *result = NIL;
switch (gs->kind)
{
case GROUPING_SET_EMPTY:
result = list_make1(NIL);
break;
case GROUPING_SET_SIMPLE:
result = list_make1(gs->content);
break;
case GROUPING_SET_ROLLUP:
{
List *rollup_val = gs->content;
ListCell *lc;
int curgroup_size = list_length(gs->content);
while (curgroup_size > 0)
{
List *current_result = NIL;
int i = curgroup_size;
foreach(lc, rollup_val)
{
GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
Assert(gs_current->kind == GROUPING_SET_SIMPLE);
current_result
= list_concat(current_result,
list_copy(gs_current->content));
/* If we are done with making the current group, break */
if (--i == 0)
break;
}
result = lappend(result, current_result);
--curgroup_size;
}
result = lappend(result, NIL);
}
break;
case GROUPING_SET_CUBE:
{
List *cube_list = gs->content;
int number_bits = list_length(cube_list);
uint32 num_sets;
uint32 i;
/* parser should cap this much lower */
Assert(number_bits < 31);
num_sets = (1U << number_bits);
for (i = 0; i < num_sets; i++)
{
List *current_result = NIL;
ListCell *lc;
uint32 mask = 1U;
foreach(lc, cube_list)
{
GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
Assert(gs_current->kind == GROUPING_SET_SIMPLE);
if (mask & i)
{
current_result
= list_concat(current_result,
list_copy(gs_current->content));
}
mask <<= 1;
}
result = lappend(result, current_result);
}
}
break;
case GROUPING_SET_SETS:
{
ListCell *lc;
foreach(lc, gs->content)
{
List *current_result = expand_groupingset_node(lfirst(lc));
result = list_concat(result, current_result);
}
}
break;
}
return result;
}
static int
cmp_list_len_asc(const void *a, const void *b)
{
int la = list_length(*(List *const *) a);
int lb = list_length(*(List *const *) b);
return (la > lb) ? 1 : (la == lb) ? 0 : -1;
}
/*
* Expand a groupingSets clause to a flat list of grouping sets.
* The returned list is sorted by length, shortest sets first.
*
* This is mainly for the planner, but we use it here too to do
* some consistency checks.
*/
List *
expand_grouping_sets(List *groupingSets, int limit)
{
List *expanded_groups = NIL;
List *result = NIL;
double numsets = 1;
ListCell *lc;
if (groupingSets == NIL)
return NIL;
foreach(lc, groupingSets)
{
List *current_result = NIL;
GroupingSet *gs = lfirst(lc);
current_result = expand_groupingset_node(gs);
Assert(current_result != NIL);
numsets *= list_length(current_result);
if (limit >= 0 && numsets > limit)
return NIL;
expanded_groups = lappend(expanded_groups, current_result);
}
/*
* Do cartesian product between sublists of expanded_groups. While at it,
* remove any duplicate elements from individual grouping sets (we must
* NOT change the number of sets though)
*/
foreach(lc, (List *) linitial(expanded_groups))
{
result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
}
for_each_cell(lc, lnext(list_head(expanded_groups)))
{
List *p = lfirst(lc);
List *new_result = NIL;
ListCell *lc2;
foreach(lc2, result)
{
List *q = lfirst(lc2);
ListCell *lc3;
foreach(lc3, p)
{
new_result = lappend(new_result,
list_union_int(q, (List *) lfirst(lc3)));
}
}
result = new_result;
}
if (list_length(result) > 1)
{
int result_len = list_length(result);
List **buf = palloc(sizeof(List *) * result_len);
List **ptr = buf;
foreach(lc, result)
{
*ptr++ = lfirst(lc);
}
qsort(buf, result_len, sizeof(List *), cmp_list_len_asc);
result = NIL;
ptr = buf;
while (result_len-- > 0)
result = lappend(result, *ptr++);
pfree(buf);
}
return result;
}
/*
* get_aggregate_argtypes
* Identify the specific datatypes passed to an aggregate call.
*
* Given an Aggref, extract the actual datatypes of the input arguments.
* The input datatypes are reported in a way that matches up with the
* aggregate's declaration, ie, any ORDER BY columns attached to a plain
* aggregate are ignored, but we report both direct and aggregated args of
* an ordered-set aggregate.
*
* Datatypes are returned into inputTypes[], which must reference an array
* of length FUNC_MAX_ARGS.
*
* The function result is the number of actual arguments.
*/
int
get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
{
int numArguments = 0;
ListCell *lc;
/* Any direct arguments of an ordered-set aggregate come first */
foreach(lc, aggref->aggdirectargs)
{
Node *expr = (Node *) lfirst(lc);
inputTypes[numArguments] = exprType(expr);
numArguments++;
}
/* Now get the regular (aggregated) arguments */
foreach(lc, aggref->args)
{
TargetEntry *tle = (TargetEntry *) lfirst(lc);
/* Ignore ordering columns of a plain aggregate */
if (tle->resjunk)
continue;
inputTypes[numArguments] = exprType((Node *) tle->expr);
numArguments++;
}
return numArguments;
}
/*
* resolve_aggregate_transtype
* Identify the transition state value's datatype for an aggregate call.
*
* This function resolves a polymorphic aggregate's state datatype.
* It must be passed the aggtranstype from the aggregate's catalog entry,
* as well as the actual argument types extracted by get_aggregate_argtypes.
* (We could fetch these values internally, but for all existing callers that
* would just duplicate work the caller has to do too, so we pass them in.)
*/
Oid
resolve_aggregate_transtype(Oid aggfuncid,
Oid aggtranstype,
Oid *inputTypes,
int numArguments)
{
/* resolve actual type of transition state, if polymorphic */
if (IsPolymorphicType(aggtranstype))
{
/* have to fetch the agg's declared input types... */
Oid *declaredArgTypes;
int agg_nargs;
(void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
/*
* VARIADIC ANY aggs could have more actual than declared args, but
* such extra args can't affect polymorphic type resolution.
*/
Assert(agg_nargs <= numArguments);
aggtranstype = enforce_generic_type_consistency(inputTypes,
declaredArgTypes,
agg_nargs,
aggtranstype,
false);
pfree(declaredArgTypes);
}
return aggtranstype;
}
/*
* Create expression trees for the transition and final functions
* of an aggregate. These are needed so that polymorphic functions
* can be used within an aggregate --- without the expression trees,
* such functions would not know the datatypes they are supposed to use.
* (The trees will never actually be executed, however, so we can skimp
* a bit on correctness.)
*
* agg_input_types, agg_state_type, agg_result_type identify the input,
* transition, and result types of the aggregate. These should all be
* resolved to actual types (ie, none should ever be ANYELEMENT etc).
* agg_input_collation is the aggregate function's input collation.
*
* For an ordered-set aggregate, remember that agg_input_types describes
* the direct arguments followed by the aggregated arguments.
*
* transfn_oid, invtransfn_oid and finalfn_oid identify the funcs to be
* called; the latter two may be InvalidOid.
*
* Pointers to the constructed trees are returned into *transfnexpr,
* *invtransfnexpr and *finalfnexpr. If there is no invtransfn or finalfn,
* the respective pointers are set to NULL. Since use of the invtransfn is
* optional, NULL may be passed for invtransfnexpr.
*/
void
build_aggregate_fnexprs(Oid *agg_input_types,
int agg_num_inputs,
int agg_num_direct_inputs,
int num_finalfn_inputs,
bool agg_variadic,
Oid agg_state_type,
Oid agg_result_type,
Oid agg_input_collation,
Oid transfn_oid,
Oid invtransfn_oid,
Oid finalfn_oid,
Oid combinefn_oid,
Expr **transfnexpr,
Expr **invtransfnexpr,
Expr **finalfnexpr,
Expr **combinefnexpr)
{
Param *argp;
List *args;
FuncExpr *fexpr;
int i;
/*
* Build arg list to use in the transfn FuncExpr node. We really only care
* that transfn can discover the actual argument types at runtime using
* get_fn_expr_argtype(), so it's okay to use Param nodes that don't
* correspond to any real Param.
*/
argp = makeNode(Param);
argp->paramkind = PARAM_EXEC;
argp->paramid = -1;
argp->paramtype = agg_state_type;
argp->paramtypmod = -1;
argp->paramcollid = agg_input_collation;
argp->location = -1;
args = list_make1(argp);
for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
{
argp = makeNode(Param);
argp->paramkind = PARAM_EXEC;
argp->paramid = -1;
argp->paramtype = agg_input_types[i];
argp->paramtypmod = -1;
argp->paramcollid = agg_input_collation;
argp->location = -1;
args = lappend(args, argp);
}
fexpr = makeFuncExpr(transfn_oid,
agg_state_type,
args,
InvalidOid,
agg_input_collation,
COERCE_EXPLICIT_CALL);
fexpr->funcvariadic = agg_variadic;
*transfnexpr = (Expr *) fexpr;
/*
* Build invtransfn expression if requested, with same args as transfn
*/
if (invtransfnexpr != NULL)
{
if (OidIsValid(invtransfn_oid))
{
fexpr = makeFuncExpr(invtransfn_oid,
agg_state_type,
args,
InvalidOid,
agg_input_collation,
COERCE_EXPLICIT_CALL);
fexpr->funcvariadic = agg_variadic;
*invtransfnexpr = (Expr *) fexpr;
}
else
*invtransfnexpr = NULL;
}
/* see if we have a final function */
if (!OidIsValid(finalfn_oid))
{
*finalfnexpr = NULL;
}
else
{
/*
* Build expr tree for final function
*/
argp = makeNode(Param);
argp->paramkind = PARAM_EXEC;
argp->paramid = -1;
argp->paramtype = agg_state_type;
argp->paramtypmod = -1;
argp->location = -1;
args = list_make1(argp);
/* finalfn may take additional args, which match agg's input types */
for (i = 0; i < num_finalfn_inputs - 1; i++)
{
argp = makeNode(Param);
argp->paramkind = PARAM_EXEC;
argp->paramid = -1;
argp->paramtype = agg_input_types[i];
argp->paramtypmod = -1;
argp->paramcollid = agg_input_collation;
argp->location = -1;
args = lappend(args, argp);
}
*finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
agg_result_type,
args,
InvalidOid,
agg_input_collation,
COERCE_EXPLICIT_CALL);
/* finalfn is currently never treated as variadic */
}
/* combine function */
if (OidIsValid(combinefn_oid))
{
/*
* Build expr tree for combine function
*/
argp = makeNode(Param);
argp->paramkind = PARAM_EXEC;
argp->paramid = -1;
argp->paramtype = agg_state_type;
argp->paramtypmod = -1;
argp->location = -1;
args = list_make1(argp);
/* XXX: is agg_state_type correct here? */
*combinefnexpr = (Expr *) makeFuncExpr(combinefn_oid,
agg_state_type,
args,
InvalidOid,
agg_input_collation,
COERCE_EXPLICIT_CALL);
}
}
/*
* Like build_aggregate_transfn_expr, but creates an expression tree for the
* serialization function of an aggregate.
*/
void
build_aggregate_serialfn_expr(Oid serialfn_oid,
Expr **serialfnexpr)
{
List *args;
FuncExpr *fexpr;
/* serialfn always takes INTERNAL and returns BYTEA */
args = list_make1(make_agg_arg(INTERNALOID, InvalidOid));
fexpr = makeFuncExpr(serialfn_oid,
BYTEAOID,
args,
InvalidOid,
InvalidOid,
COERCE_EXPLICIT_CALL);
*serialfnexpr = (Expr *) fexpr;
}
/*
* Like build_aggregate_transfn_expr, but creates an expression tree for the
* deserialization function of an aggregate.
*/
void
build_aggregate_deserialfn_expr(Oid deserialfn_oid,
Expr **deserialfnexpr)
{
List *args;
FuncExpr *fexpr;
/* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
make_agg_arg(INTERNALOID, InvalidOid));
fexpr = makeFuncExpr(deserialfn_oid,
INTERNALOID,
args,
InvalidOid,
InvalidOid,
COERCE_EXPLICIT_CALL);
*deserialfnexpr = (Expr *) fexpr;
}
/*
* Convenience function to build dummy argument expressions for aggregates.
*
* We really only care that an aggregate support function can discover its
* actual argument types at runtime using get_fn_expr_argtype(), so it's okay
* to use Param nodes that don't correspond to any real Param.
*/
static Node *
make_agg_arg(Oid argtype, Oid argcollation)
{
Param *argp = makeNode(Param);
argp->paramkind = PARAM_EXEC;
argp->paramid = -1;
argp->paramtype = argtype;
argp->paramtypmod = -1;
argp->paramcollid = argcollation;
argp->location = -1;
return (Node *) argp;
}
|
304896.c | /*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/rand.h>
#include "rand_lcl.h"
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
# include <windows.h>
/* On Windows 7 or higher use BCrypt instead of the legacy CryptoAPI */
# if defined(_MSC_VER) && defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0601
# define RAND_WINDOWS_USE_BCRYPT
# endif
# ifdef RAND_WINDOWS_USE_BCRYPT
# include <bcrypt.h>
# pragma comment(lib, "bcrypt.lib")
# ifndef STATUS_SUCCESS
# define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
# endif
# else
# include <wincrypt.h>
/*
* Intel hardware RNG CSP -- available from
* http://developer.intel.com/design/security/rng/redist_license.htm
*/
# define PROV_INTEL_SEC 22
# define INTEL_DEF_PROV L"Intel Hardware Cryptographic Service Provider"
# endif
static void readtimer(void);
int RAND_poll(void)
{
MEMORYSTATUS mst;
# ifndef RAND_WINDOWS_USE_BCRYPT
HCRYPTPROV hProvider;
# endif
DWORD w;
BYTE buf[64];
# ifdef RAND_WINDOWS_USE_BCRYPT
if (BCryptGenRandom(NULL, buf, (ULONG)sizeof(buf), BCRYPT_USE_SYSTEM_PREFERRED_RNG) == STATUS_SUCCESS) {
RAND_add(buf, sizeof(buf), sizeof(buf));
}
# else
/* poll the CryptoAPI PRNG */
/* The CryptoAPI returns sizeof(buf) bytes of randomness */
if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
if (CryptGenRandom(hProvider, (DWORD)sizeof(buf), buf) != 0) {
RAND_add(buf, sizeof(buf), sizeof(buf));
}
CryptReleaseContext(hProvider, 0);
}
/* poll the Pentium PRG with CryptoAPI */
if (CryptAcquireContextW(&hProvider, NULL, INTEL_DEF_PROV, PROV_INTEL_SEC, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
if (CryptGenRandom(hProvider, (DWORD)sizeof(buf), buf) != 0) {
RAND_add(buf, sizeof(buf), sizeof(buf));
}
CryptReleaseContext(hProvider, 0);
}
# endif
/* timer data */
readtimer();
/* memory usage statistics */
GlobalMemoryStatus(&mst);
RAND_add(&mst, sizeof(mst), 1);
/* process ID */
w = GetCurrentProcessId();
RAND_add(&w, sizeof(w), 1);
return (1);
}
#if OPENSSL_API_COMPAT < 0x00101000L
int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam)
{
RAND_poll();
return RAND_status();
}
void RAND_screen(void)
{
RAND_poll();
}
#endif
/* feed timing information to the PRNG */
static void readtimer(void)
{
DWORD w;
LARGE_INTEGER l;
static int have_perfc = 1;
# if defined(_MSC_VER) && defined(_M_X86)
static int have_tsc = 1;
DWORD cyclecount;
if (have_tsc) {
__try {
__asm {
_emit 0x0f _emit 0x31 mov cyclecount, eax}
RAND_add(&cyclecount, sizeof(cyclecount), 1);
}
__except(EXCEPTION_EXECUTE_HANDLER) {
have_tsc = 0;
}
}
# else
# define have_tsc 0
# endif
if (have_perfc) {
if (QueryPerformanceCounter(&l) == 0)
have_perfc = 0;
else
RAND_add(&l, sizeof(l), 0);
}
if (!have_tsc && !have_perfc) {
w = GetTickCount();
RAND_add(&w, sizeof(w), 0);
}
}
#endif
|
94956.c | //
// sc-42-circlegencount.c
// sec
//
// Created by Richard Murphy on 9/10/14.
//
//
#include <Security/SecBase.h>
#include <Security/SecItem.h>
#include <Security/SecKey.h>
#include <SecureObjectSync/SOSCircle.h>
#include <SecureObjectSync/SOSCloudCircle.h>
#include <SecureObjectSync/SOSPeerInfo.h>
#include <SecureObjectSync/SOSInternal.h>
#include <SecureObjectSync/SOSUserKeygen.h>
#include <utilities/SecCFWrappers.h>
#include <CoreFoundation/CoreFoundation.h>
#include <stdlib.h>
#include <unistd.h>
#include <securityd/SOSCloudCircleServer.h>
#include "SOSCircle_regressions.h"
#include "SOSRegressionUtilities.h"
static int kTestTestCount = 5;
static void tests(void)
{
uint64_t beginvalue;
uint64_t incvalue;
SOSCircleRef circle = SOSCircleCreate(NULL, CFSTR("TEST DOMAIN"), NULL);
ok(NULL != circle, "Circle creation");
ok(0 == SOSCircleCountPeers(circle), "Zero peers");
ok(0 != (beginvalue = SOSCircleGetGenerationSint(circle))); // New circles should never be 0
SOSCircleGenerationSetValue(circle, 0);
ok(0 == SOSCircleGetGenerationSint(circle)); // Know we're starting out with a zero value (forced)
SOSCircleGenerationIncrement(circle);
ok(beginvalue < (incvalue = SOSCircleGetGenerationSint(circle))); // incremented value should be greater than where we began
CFReleaseNull(circle);
}
int sc_42_circlegencount(int argc, char *const *argv)
{
plan_tests(kTestTestCount);
tests();
return 0;
}
|
264129.c | #include "../inc/libmx.h"
int mx_binary_search(char **arr, int size, const char *s, int *count) {
int max = size - 1, min = 0, mid;
if (!s) return -1;
while(min <= max) {
mid = min + (max - min) / 2;
if(mx_strcmp(arr[mid], s) == 0) {
*count += 1;
return mid;
}
else {
if(mx_strcmp(arr[mid], s) < 0) {
*count += 1;
min = mid + 1;
}
else {
*count += 1;
max = mid - 1;
}
}
}
*count = 0;
return -1;
}
|