file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/10931.c
|
/* bitstring.c -- Builtins for HSAIL bitstring instructions.
Copyright (C) 2015-2020 Free Software Foundation, Inc.
Contributed by Pekka Jaaskelainen <[email protected]>
for General Processor Tech.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdint.h>
#include <limits.h>
#define BITEXTRACT(DEST_TYPE, SRC0, SRC1, SRC2) \
uint32_t offset = SRC1 & (sizeof (DEST_TYPE) * 8 - 1); \
uint32_t width = SRC2 & (sizeof (DEST_TYPE) * 8 - 1); \
if (width == 0) \
return 0; \
else \
return (SRC0 << (sizeof (DEST_TYPE) * 8 - width - offset)) \
>> (sizeof (DEST_TYPE) * 8 - width)
uint32_t
__hsail_bitextract_u32 (uint32_t src0, uint32_t src1, uint32_t src2)
{
BITEXTRACT (uint32_t, src0, src1, src2);
}
int32_t
__hsail_bitextract_s32 (int32_t src0, uint32_t src1, uint32_t src2)
{
BITEXTRACT (int32_t, src0, src1, src2);
}
uint64_t
__hsail_bitextract_u64 (uint64_t src0, uint32_t src1, uint32_t src2)
{
BITEXTRACT (uint64_t, src0, src1, src2);
}
int64_t
__hsail_bitextract_s64 (int64_t src0, uint32_t src1, uint32_t src2)
{
BITEXTRACT (int64_t, src0, src1, src2);
}
#define BITINSERT(DEST_TYPE, SRC0, SRC1, SRC2, SRC3) \
uint32_t offset = SRC2 & (sizeof (DEST_TYPE) * 8 - 1); \
uint32_t width = SRC3 & (sizeof (DEST_TYPE) * 8 - 1); \
DEST_TYPE mask = ((DEST_TYPE) 1 << width) - 1; \
return (SRC0 & ~(mask << offset)) | ((SRC1 & mask) << offset)
uint32_t
__hsail_bitinsert_u32 (uint32_t src0, uint32_t src1, uint32_t src2,
uint32_t src3)
{
BITINSERT (uint32_t, src0, src1, src2, src3);
}
int64_t
__hsail_bitinsert_u64 (uint64_t src0, uint64_t src1, uint32_t src2,
uint32_t src3)
{
BITINSERT (uint64_t, src0, src1, src2, src3);
}
#define BITMASK(DEST_TYPE, SRC0, SRC1) \
uint32_t offset = SRC0 & (sizeof (DEST_TYPE) * 8 - 1); \
uint32_t width = SRC1 & (sizeof (DEST_TYPE) * 8 - 1); \
DEST_TYPE mask = ((DEST_TYPE) 1 << width) - 1; \
return mask << offset
uint32_t
__hsail_bitmask_u32 (uint32_t src0, uint32_t src1)
{
BITMASK (uint32_t, src0, src1);
}
uint64_t
__hsail_bitmask_u64 (uint32_t src0, uint32_t src1)
{
BITMASK (uint64_t, src0, src1);
}
/* The dummy, but readable version from
http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious
This (also) often maps to a single instruction in DSPs. */
#define BITREV(DEST_TYPE, SRC) \
DEST_TYPE v = SRC; \
DEST_TYPE r = v; \
int s = sizeof (SRC) * CHAR_BIT - 1; \
\
for (v >>= 1; v; v >>= 1) \
{ \
r <<= 1; \
r |= v & 1; \
s--; \
} \
return r << s
uint32_t
__hsail_bitrev_u32 (uint32_t src0)
{
BITREV (uint32_t, src0);
}
uint64_t
__hsail_bitrev_u64 (uint64_t src0)
{
BITREV (uint64_t, src0);
}
uint32_t
__hsail_bitselect_u32 (uint32_t src0, uint32_t src1, uint32_t src2)
{
return (src1 & src0) | (src2 & ~src0);
}
uint64_t
__hsail_bitselect_u64 (uint64_t src0, uint64_t src1, uint64_t src2)
{
return (src1 & src0) | (src2 & ~src0);
}
/* Due to the defined behavior with 0, we cannot use the gcc builtin
__builtin_clz* () directly. __builtin_ffs () has defined behavior, but
returns 0 while HSAIL requires to return -1. */
uint32_t
__hsail_firstbit_u32 (uint32_t src0)
{
if (src0 == 0)
return -1;
return __builtin_clz (src0);
}
uint32_t
__hsail_firstbit_s32 (int32_t src0)
{
uint32_t converted = src0 >= 0 ? src0 : ~src0;
return __hsail_firstbit_u32 (converted);
}
uint32_t
__hsail_firstbit_u64 (uint64_t src0)
{
if (src0 == 0)
return -1;
return __builtin_clzl (src0);
}
uint32_t
__hsail_firstbit_s64 (int64_t src0)
{
uint64_t converted = src0 >= 0 ? src0 : ~src0;
return __hsail_firstbit_u64 (converted);
}
uint32_t
__hsail_lastbit_u32 (uint32_t src0)
{
if (src0 == 0)
return -1;
return __builtin_ctz (src0);
}
uint32_t
__hsail_lastbit_u64 (uint64_t src0)
{
if (src0 == 0)
return -1;
return __builtin_ctzl (src0);
}
|
the_stack_data/98635.c
|
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#define False 0
#define True 1
volatile sig_atomic_t stopflag = 0;
void abrt_handler(int sig);
extern int rep(char *, const char *, const char *, const char *);
int main(int argc, char* argv[]) {
const char* optstring = "vmsti:c:";
int sd;
struct sockaddr_in addr;
socklen_t sin_size;
struct sockaddr_in from_addr;
char buf[2048]; // 受信バッファ
char dbuf[2048]; // 表示バッファ
char ipa[30]; // IPアドレスのマッチング
char ccm[30]; // CCMのマッチング
char ddd[11],tod[9];
int cnt; // 受信カウンタ
int rc;
int c;
int opt_m,opt_s,opt_t,opt_i,opt_c;
u_int yes = 1;
time_t now;
struct tm *tm_now;
opt_m = False;
opt_s = False;
opt_t = False;
opt_i = False;
opt_c = False;
while((c=getopt(argc,argv,optstring))!=-1) {
// printf("opt=%c ",c);
if (c=='m') {
opt_m = True;
} else if (c=='s') {
opt_s = True;
} else if (c=='t') {
opt_t = True;
} else if (c=='i') {
opt_i = True;
sprintf(ipa,"<IP>%s</IP>",optarg);
} else if (c=='c') {
opt_c = True;
sprintf(ccm,"type=\"%s\"",optarg);
} else if (c=='v') {
printf("uecsrxdump UECS CCM packet Dump Version 1.00\n");
exit(0);
}
}
if ( signal(SIGINT, abrt_handler) == SIG_ERR ) {
exit(1);
}
// IPv4 UDP のソケットを作成
if((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket");
return -1;
}
// 待ち受けるIPとポート番号を設定
addr.sin_family = AF_INET;
addr.sin_port = htons(16520);
addr.sin_addr.s_addr = INADDR_ANY; // すべてのアドレス宛のパケットを受信する
// バインドする
setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
if(bind(sd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind");
return -1;
}
// 受信バッファの初期化
memset(buf, 0, sizeof(buf));
while(!stopflag) {
// 受信 パケットが到着するまでブロック
// from_addr には、送信元アドレスが格納される
rc = recvfrom(sd, buf, sizeof(buf), MSG_DONTWAIT,
(struct sockaddr *)&from_addr, &sin_size);
if ( rc > 0 ) {
buf[rc] = (char)NULL;
if (opt_i) {
if (strstr(buf,ipa)==NULL) continue;
}
if (opt_c) {
if (strstr(buf,ccm)==NULL) continue;
}
// 日時生成
if (opt_t) {
now = time(NULL);
tm_now = localtime(&now);
sprintf(ddd,"%04d-%02d-%02d",tm_now->tm_year+1900,tm_now->tm_mon+1,tm_now->tm_mday);
sprintf(tod,"%02d:%02d:%02d",tm_now->tm_hour,tm_now->tm_min,tm_now->tm_sec);
}
// 不要フィールド削除
if ((opt_m)||(opt_s)) {
rep(dbuf,buf,"<?xml version=\"1.0\"?><UECS ver=\"1.00-E10\">","");
rep(buf,dbuf,"</UECS>","");
}
if (opt_s) {
rep(dbuf,buf,"<DATA type=\"","");
rep(buf,dbuf,"\" room=\"",",");
rep(dbuf,buf,"\" region=\"",",");
rep(buf,dbuf,"\" order=\"",",");
rep(dbuf,buf,"\" priority=\"",",");
rep(buf,dbuf,"</DATA><IP>",",");
rep(dbuf,buf,"</IP>","");
rep(buf,dbuf,"\">",",");
}
strcpy(dbuf,buf);
// 受信データの出力
if (opt_t) {
printf("%s %s %s\n",ddd,tod,dbuf);
} else {
printf("%s\n",dbuf);
}
} else {
if ( errno == EAGAIN ) continue;
perror("recvfrom");
}
}
// ソケットのクローズ
close(sd);
return 0;
}
void abrt_handler(int sig) {
stopflag = 1;
}
|
the_stack_data/6387531.c
|
/**
* Example of openmp parallel region
*
* To compile, enter:
*
* gcc -fopenmp openmp.c
*
* You should see the message "I am a parallel region" for each
* processing core on your system.
*
* For those using a virtual machine, make sure you set the number of
* processing cores > 1 to see parallel execution of the parallel region.
*/
#include <omp.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
/* sequential code */
#pragma omp parallel
{
printf("I am a parallel region\n");
}
/* sequential code */
return 0;
}
|
the_stack_data/5861.c
|
#include<stdio.h>
#include<assert.h>
int main()
{
int rd, result;
result = 0x01BF01BF;
__asm
("repl.ph %0, 0x1BF\n\t"
: "=r"(rd)
);
assert(rd == result);
result = 0x01FF01FF;
__asm
("repl.ph %0, 0x01FF\n\t"
: "=r"(rd)
);
assert(rd == result);
return 0;
}
|
the_stack_data/87638741.c
|
#include<stdio.h>
//求出勒德多多项式
double toSolvethe(double x,int n){
if (n==0)
{
return 1.00;
}else if (n==1)
{
return x;
}else if (n>1)
{
return (((double)(2*n-1)/n)*x*toSolvethe(x,(n-1))-((double)(n-1)/n)*toSolvethe(x,n-2));
}
}
int main(int argc, char const *argv[])
{
double x,pn;
int n;
scanf("%lf %d",&x,&n);
if(n==0){
printf("%.2lf",1.00);
}else if (n==1)
{
printf("%.2lf",x);
}else if (n>1)
{
pn=toSolvethe(x,n);
printf("%.2lf",pn);
}
return 0;
}
|
the_stack_data/159515007.c
|
// https://www.cprogramming.com/challenges/integer-to-english.html
// Solution by Kai#9999
/*
Integer to english number conversion
Write a program that takes an integer and displays the English name of that value.
You should support both positive and negative numbers, in the range supported by a 32-bit integer (approximately -2 billion to 2 billion).
Examples:
10 -> ten
121 -> one hundred twenty one
1032 -> one thousand thirty two
11043 -> eleven thousand forty three
1200000 -> one million two hundred thousand
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
// Set up our English constants
const char *ENG_BELOW_TWENTY[] = {
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
const char *ENG_BELOW_HUNDRED[] = {
"twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"
};
const char *ENG_BASE_MAGNITUDES[] = {
"thousand", "million", "billion", "trillion", "quadrillion", "quintillion"
};
const char *ENG_HUNDRED = "hundred";
const char *ENG_ZERO = "zero";
const char *ENG_NEGATIVE = "negative";
void wpush(char **words, int *n_words, const char *string)
{
words[(*n_words)++] = (char *)string;
}
void get_hundred(int num, char **words, int *n_words)
{
int hundreds = num / 100;
if (hundreds > 0)
{
wpush(words, n_words, ENG_BELOW_TWENTY[hundreds - 1]);
wpush(words, n_words, ENG_HUNDRED);
}
num %= 100;
int tens = num / 10;
if (tens > 1)
{
wpush(words, n_words, ENG_BELOW_HUNDRED[tens - 2]);
num %= 10;
if (num > 0)
wpush(words, n_words, ENG_BELOW_TWENTY[num - 1]);
}
else
{
if (num > 0)
wpush(words, n_words, ENG_BELOW_TWENTY[num - 1]);
}
}
const char *int_to_english(signed int num)
{
int magnitude = (int)log10((double)abs(num)) / 3;
char *ret = (char *)calloc(1000, sizeof(char));
char **words = (char **)calloc(1 + ((magnitude + 1) * 4), sizeof(char *));
int n_words = 0;
if (num < 0)
wpush(words, &n_words, ENG_NEGATIVE);
if (num != 0)
{
num = abs(num);
int *magnitudes = (int *)calloc(magnitude + 1, sizeof(int));
int n_magnitudes = 0;
// Get each magnitude in reverse
while (num != 0)
{
magnitudes[n_magnitudes++] = num % 1000;
num /= 1000;
}
// Traverse backwards
for (int i = 0; i < n_magnitudes; ++i)
{
--magnitude;
int j = n_magnitudes - 1 - i;
get_hundred(magnitudes[j], words, &n_words);
if (magnitudes[j] != 0 && magnitude >= 0)
{
wpush(words, &n_words, ENG_BASE_MAGNITUDES[magnitude]);
}
}
}
else
{
wpush(words, &n_words, ENG_ZERO);
}
// Compile words list into return string
for (int i = 0; i < n_words; ++i)
{
strcat(ret, words[i]);
strcat(ret, " ");
}
size_t len = strlen(ret);
if (len > 0)
ret[len - 1] = '\0';
ret = (char *)realloc(ret, len * sizeof(char));
return (const char *)ret;
}
void prthelp()
{
printf("IntegerToEnglish by Kai#9999\n");
printf("-h or --help: Displays this help page\n");
printf("-n x: Outputs English number to stdout\n");
}
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i)
{
char *v = argv[i];
if (!strcmp(v, "-h") || !strcmp(v, "--help"))
{
prthelp();
return 0;
}
else if (!strcmp(v, "-n"))
{
if (argc != 3)
{
printf("Incorrect number of arguments\n");
return -1;
}
int n = atoi(argv[i + 1]);
const char *ret = int_to_english(n);
printf("%s", ret);
return 0;
}
}
prthelp();
return 0;
}
|
the_stack_data/12462.c
|
/*
* matrizFork.c
*
* Created on: 12/04/2009
* Author: marcotulio
*/
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
//criando ponteiros para elementos da diag princi e secundaria
int diagPrinc, diagSec;
int matriz[4];//criando uma matriz de 4 elementos
int main()
{
system("clear");
//lendo os elementos da matriz
printf("\tSistemas Operacionais - N1(Matriz)\n\n");
int elemento;
//pegando os valores da matriz
int i;
for(i=0; i<4; i++)
{
printf("\nDigite o elemento da posicao %i do vetor:",i);
scanf("%i",&elemento);
//printf("\nelemento: %i",elemento);
matriz[i]=elemento;
}//fim for
//imprimindo a matriz digitada
printf("A seguinte matriz foi digitada: \n");
for(i=0; i<4; i++)
{
if(i==0) printf("\n %i ",matriz[i]);
if(i==1) printf(" %i \n",matriz[i]);
if(i==2) printf(" %i ",matriz[i]);
if(i==3) printf(" %i \n",matriz[i]);
}//fim for
//criando o processo
pid_t pid1,pid2;
//vfork cria um processo filho compartilhando blocos, trocando valores entre eles
pid1=vfork();
//verificando se pid1 foi criado, se foi cria o pid2
if(pid1>0)pid2=vfork();
if(pid1<0)
{ //houve erro-- nao foi possivel criar outro processo
fprintf(stderr, "ERROR: FALHA NA EXECUÇÃO DO PID1");
exit(-1);
}//fim verif erros do pid1
else if(pid1==0)
{ //processo filho criado
diagPrinc = matriz[0]*matriz[3];
exit(0);
}//fim da execucao do pid1
//verificando se n houver erros na criacao do PID2
if(pid2<0)
{ //houve erro-- nao foi possivel criar outro processo
fprintf(stderr, "ERROR: FALHA NA EXECUÇÃO DO PID2");
exit(-1);
}//fim verif a criacao do 2 vfork
else if(pid2==0)
{ //processo filho criado pid2
diagSec=matriz[1]*matriz[2];
exit(0);
}//fim execucao do 2 fork
else
{ //processo pai, espera o processamento das diag principais
wait(NULL);
int determinante=0;//determinante
//calculando o determinante
determinante=diagPrinc-diagSec;
printf("\n\tDeterminante: %i\n\n",determinante);
}//fim else de espera da execucao do 2 processo
}//fim programa principal
|
the_stack_data/35324.c
|
/*
* 显然,这个规模用多重背包会萎。
* 因为这是容斥的套题所以考虑到用容斥来解决。
*
* 如果是完全背包,没有硬币数量限制,方案数可以做一次完全背包求出来。这一步整个
* 程序只要做一次。
*
* 设 c_i 为硬币 i 的价值。
* 设 d_i 为硬币 i 的数量限制。
* 设 f(x) 为不考虑硬币数量限制,用 4 种硬币得到 x 的方案数。
* 设 总价为 s 。
*
* 如果仅硬币 i 数量超过限制,那么产生的不合法的方案数为 f(s - c_i(d_i+1))
* 然后进行容斥。
*/
#include <stdio.h>
#include <string.h>
#define SMAX 100009
#define CNUM 4
struct {
int c[CNUM];
long long f[SMAX];
} E;
int solve_main(void)
{
int *c = E.c;
long long *f = E.f;
int d[4];
int s;
long long ans = 0;
scanf("%d%d%d%d%d", &d[0], &d[1], &d[2], &d[3], &s);
#define magic(expr, sign) if ((expr) >= 0) ans += (sign) * f[expr]
#define ff(expr) c[expr] * (d[expr] + 1)
magic(s, 1);
magic(s - ff(0), -1);
magic(s - ff(1), -1);
magic(s - ff(2), -1);
magic(s - ff(3), -1);
magic(s - ff(0) - ff(1), 1);
magic(s - ff(0) - ff(2), 1);
magic(s - ff(0) - ff(3), 1);
magic(s - ff(1) - ff(2), 1);
magic(s - ff(1) - ff(3), 1);
magic(s - ff(2) - ff(3), 1);
magic(s - ff(3) - ff(2) - ff(1), -1);
magic(s - ff(3) - ff(2) - ff(0), -1);
magic(s - ff(3) - ff(0) - ff(1), -1);
magic(s - ff(0) - ff(2) - ff(1), -1);
magic(s - ff(0) - ff(1) - ff(2) - ff(3), 1);
#undef ff
#undef magic
printf("%lld\n", ans);
return 0;
}
int solve_start(void)
{
return solve_main();
}
int main(void)
{
int tot;
int *c = E.c;
long long *f = E.f;
int i, j;
#ifdef DEBUG
freopen("in", "r", stdin);
#endif
scanf("%d%d%d%d%d", &c[0], &c[1], &c[2], &c[3], &tot);
f[0] = 1;
for (i = 0; i < 4; ++i)
for (j = c[i]; j < SMAX; ++j)
f[j] += f[j - c[i]];
while (tot--)
solve_start();
#ifdef DEBUG
fclose(stdin);
#endif
return 0;
}
|
the_stack_data/72012935.c
|
/* This testcase is part of GDB, the GNU debugger.
Copyright 2014-2020 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
struct dynamic_struct
{
int dynamic_field[0];
} use_dynamic_struct;
|
the_stack_data/140766126.c
|
// Find out the largest and smallest number in a given array.
#include <stdio.h>
void findLargestSmallest()
{
int n, array[100], largest, smallest;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements: ");
for (int i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
largest = array[0];
smallest = array[0];
for (int i = 0; i < n; i++)
{
if (array[i] > largest)
{
largest = array[i];
}
if (array[i] < smallest)
{
smallest = array[i];
}
}
printf("Largest number is %d\n", largest);
printf("Smallest number is %d\n", smallest);
}
void main()
{
findLargestSmallest();
}
|
the_stack_data/104317.c
|
#include<stdio.h>
int ways(int coins[], int m , int sum) {
if(sum == 0) {
return 1;
}
if(m<=0 || sum < 0) {
return 0;
}
/* 1. Exclude current coin. - note we only move to next coin here. Sum is unchanged.
2. Include current coin - note ony sum chnages, means we use the coin, but we do not move to next coin, as we want to use it again!!
*/
return ways(coins, m-1, sum) + ways(coins, m, sum - coins[m]);
}
void main() {
int coins[] = {1, 5, 10, 25, 50};
int m = sizeof(coins)/sizeof(coins[0]);
int res = ways(coins, m, 4);
printf("Number of ways are %d", res);
}
|
the_stack_data/192329571.c
|
/*
* This software is Copyright (c) 2015 Sayantan Datta <std2048 at gmail dot com>
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
* Based on paper 'Perfect Spatial Hashing' by Lefebvre & Hoppe
*/
#ifdef HAVE_OPENCL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#include "misc.h" // error()
#include "bt_twister.h"
#include "bt_hash_types.h"
#if _OPENMP > 201107
#define MAYBE_PARALLEL_FOR _Pragma("omp for")
#define MAYBE_ATOMIC_WRITE _Pragma("omp atomic write")
#define MAYBE_ATOMIC_CAPTURE _Pragma("omp atomic capture")
#else
#define MAYBE_PARALLEL_FOR _Pragma("omp single")
#define MAYBE_ATOMIC_WRITE
#define MAYBE_ATOMIC_CAPTURE
#endif
typedef struct {
/* List of indexes linked to offset_data_idx */
unsigned int *hash_location_list;
unsigned short collisions;
unsigned short iter;
unsigned int offset_table_idx;
} auxilliary_offset_data;
/* Interface pointers */
static unsigned int (*zero_check_ht)(unsigned int);
static void (*assign_ht)(unsigned int, unsigned int);
static void (*assign0_ht)(unsigned int);
static unsigned int (*calc_ht_idx)(unsigned int, unsigned int);
static unsigned int (*get_offset)(unsigned int, unsigned int);
static void (*allocate_ht)(unsigned int, unsigned int);
static int (*test_tables)(unsigned int, OFFSET_TABLE_WORD *, unsigned int, unsigned int, unsigned int, unsigned int);
static unsigned int (*remove_duplicates)(unsigned int, unsigned int, unsigned int);
static void *loaded_hashes;
static unsigned int hash_type = 0;
static unsigned int binary_size_actual = 0;
static unsigned int num_loaded_hashes = 0;
unsigned int hash_table_size = 0, shift64_ht_sz = 0, shift128_ht_sz = 0;
static OFFSET_TABLE_WORD *offset_table = NULL;
static unsigned int offset_table_size = 0, shift64_ot_sz = 0, shift128_ot_sz = 0;
static auxilliary_offset_data *offset_data = NULL;
unsigned long long total_memory_in_bytes = 0;
static volatile sig_atomic_t signal_stop = 0;
static unsigned int verbosity;
static void alarm_handler(int sig)
{
if (sig == SIGALRM)
signal_stop = 1;
}
static unsigned int coprime_check(unsigned int m,unsigned int n)
{
unsigned int rem;
while (n != 0) {
rem = m % n;
m = n;
n = rem;
}
return m;
}
static void release_all_lists()
{
unsigned int i;
for (i = 0; i < offset_table_size; i++)
bt_free((void **)&(offset_data[i].hash_location_list));
}
int bt_malloc(void **ptr, size_t size)
{
*ptr = mem_alloc(size);
if (*ptr || !size)
return 0;
return 1;
}
int bt_calloc(void **ptr, size_t num, size_t size)
{
*ptr = mem_calloc(num, size);
if (*ptr || !num)
return 0;
return 1;
}
int bt_memalign_alloc(void **ptr, size_t alignment, size_t size)
{
*ptr = mem_alloc_align(size, alignment);
if (*ptr || !size)
return 0;
return 1;
}
void bt_free(void **ptr)
{
MEM_FREE((*ptr));
*ptr = NULL;
}
void bt_error_fn(const char *str, char *file, int line)
{
fprintf(stderr, "%s in file:%s, line:%d.\n", str, file, line);
error();
}
void bt_warn_fn(const char *str, char *file, int line)
{
fprintf(stderr, "%s in file:%s, line:%d.\n", str, file, line);
}
static unsigned int modulo_op(void * hash, unsigned int N, uint64_t shift64, uint64_t shift128)
{
if (hash_type == 64)
return modulo64_31b(*(uint64_t *)hash, N);
else if (hash_type == 128)
return modulo128_31b(*(uint128_t *)hash, N, shift64);
else if (hash_type == 192)
return modulo192_31b(*(uint192_t *)hash, N, shift64, shift128);
else
fprintf(stderr, "modulo op error\n");
return 0;
}
/* Exploits the fact that sorting with a bucket is not essential. */
static void in_place_bucket_sort(unsigned int num_buckets)
{
unsigned int *histogram;
unsigned int *histogram_empty;
unsigned int *prefix_sum;
unsigned int i;
if (bt_calloc((void **)&histogram, num_buckets + 1, sizeof(unsigned int)))
bt_error("Failed to allocate memory: histogram.");
if (bt_calloc((void **)&histogram_empty, num_buckets + 1, sizeof(unsigned int)))
bt_error("Failed to allocate memory: histogram_empty.");
if (bt_calloc((void **)&prefix_sum, num_buckets + 10, sizeof(unsigned int)))
bt_error("Failed to allocate memory: prefix_sum.");
i = 0;
while (i < offset_table_size)
histogram[num_buckets - offset_data[i++].collisions]++;
for (i = 1; i <= num_buckets; i++)
prefix_sum[i] = prefix_sum[i - 1] + histogram[i - 1];
i = 0;
while (i < prefix_sum[num_buckets]) {
unsigned int histogram_index = num_buckets - offset_data[i].collisions;
if (i >= prefix_sum[histogram_index] &&
histogram_index < num_buckets &&
i < prefix_sum[histogram_index + 1]) {
histogram_empty[histogram_index]++;
i++;
}
else {
auxilliary_offset_data tmp;
unsigned int swap_index = prefix_sum[histogram_index] + histogram_empty[histogram_index];
histogram_empty[histogram_index]++;
tmp = offset_data[i];
offset_data[i] = offset_data[swap_index];
offset_data[swap_index] = tmp;
}
}
bt_free((void **)&histogram);
bt_free((void **)&histogram_empty);
bt_free((void **)&prefix_sum);
}
static void init_tables(unsigned int approx_offset_table_sz, unsigned int approx_hash_table_sz)
{
unsigned int i, max_collisions, offset_data_idx;
uint64_t shift128;
if (verbosity > 1)
fprintf(stdout, "\nInitialing Tables...");
total_memory_in_bytes = 0;
approx_hash_table_sz |= 1;
/* Repeat until two sizes are coprimes */
while (coprime_check(approx_offset_table_sz, approx_hash_table_sz) != 1)
approx_offset_table_sz++;
offset_table_size = approx_offset_table_sz;
hash_table_size = approx_hash_table_sz;
if (hash_table_size > 0x7fffffff || offset_table_size > 0x7fffffff)
bt_error("Reduce the number of loaded hashes to < 0x7fffffff.");
shift64_ht_sz = (((1ULL << 63) % hash_table_size) * 2) % hash_table_size;
shift64_ot_sz = (((1ULL << 63) % offset_table_size) * 2) % offset_table_size;
shift128 = (uint64_t)shift64_ht_sz * shift64_ht_sz;
shift128_ht_sz = shift128 % hash_table_size;
shift128 = (uint64_t)shift64_ot_sz * shift64_ot_sz;
shift128_ot_sz = shift128 % offset_table_size;
if (bt_malloc((void **)&offset_table, offset_table_size * sizeof(OFFSET_TABLE_WORD)))
bt_error("Failed to allocate memory: offset_table.");
total_memory_in_bytes += offset_table_size * sizeof(OFFSET_TABLE_WORD);
if (bt_malloc((void **)&offset_data, offset_table_size * sizeof(auxilliary_offset_data)))
bt_error("Failed to allocate memory: offset_data.");
total_memory_in_bytes += offset_table_size * sizeof(auxilliary_offset_data);
max_collisions = 0;
#if _OPENMP
#pragma omp parallel private(i, offset_data_idx)
#endif
{
#if _OPENMP
#pragma omp for
#endif
for (i = 0; i < offset_table_size; i++) {
//memset(&offset_data[i], 0, sizeof(auxilliary_offset_data));
offset_data[i].offset_table_idx = 0;
offset_data[i].collisions = 0;
offset_data[i].hash_location_list = NULL;
offset_data[i].iter = 0;
offset_table[i] = 0;
}
#if _OPENMP
#pragma omp barrier
#endif
/* Build Auxilliary data structure for offset_table. */
#if _OPENMP
#pragma omp for
#endif
for (i = 0; i < num_loaded_hashes; i++) {
offset_data_idx = modulo_op(loaded_hashes + i * binary_size_actual, offset_table_size, shift64_ot_sz, shift128_ot_sz);
#if _OPENMP
#pragma omp atomic
#endif
offset_data[offset_data_idx].collisions++;
}
#if _OPENMP
#pragma omp barrier
#pragma omp single
#endif
for (i = 0; i < offset_table_size; i++)
if (offset_data[i].collisions) {
if (bt_malloc((void **)&offset_data[i].hash_location_list, offset_data[i].collisions * sizeof(unsigned int)))
bt_error("Failed to allocate memory: offset_data[i].hash_location_list.");
if (offset_data[i].collisions > max_collisions)
max_collisions = offset_data[i].collisions;
}
#if _OPENMP
#pragma omp barrier
MAYBE_PARALLEL_FOR
#endif
for (i = 0; i < num_loaded_hashes; i++) {
unsigned int iter;
offset_data_idx = modulo_op(loaded_hashes + i * binary_size_actual, offset_table_size, shift64_ot_sz, shift128_ot_sz);
#if _OPENMP
MAYBE_ATOMIC_WRITE
#endif
offset_data[offset_data_idx].offset_table_idx = offset_data_idx;
#if _OPENMP
MAYBE_ATOMIC_CAPTURE
#endif
iter = offset_data[offset_data_idx].iter++;
offset_data[offset_data_idx].hash_location_list[iter] = i;
}
#if _OPENMP
#pragma omp barrier
#endif
}
total_memory_in_bytes += num_loaded_hashes * sizeof(unsigned int);
//qsort((void *)offset_data, offset_table_size, sizeof(auxilliary_offset_data), qsort_compare);
in_place_bucket_sort(max_collisions);
if (verbosity > 1)
fprintf(stdout, "Done\n");
allocate_ht(num_loaded_hashes, verbosity);
if (verbosity > 2) {
fprintf(stdout, "Offset Table Size %Lf %% of Number of Loaded Hashes.\n", ((long double)offset_table_size / (long double)num_loaded_hashes) * 100.00);
fprintf(stdout, "Offset Table Size(in GBs):%Lf\n", ((long double)offset_table_size * sizeof(OFFSET_TABLE_WORD)) / ((long double)1024 * 1024 * 1024));
fprintf(stdout, "Offset Table Aux Data Size(in GBs):%Lf\n", ((long double)offset_table_size * sizeof(auxilliary_offset_data)) / ((long double)1024 * 1024 * 1024));
fprintf(stdout, "Offset Table Aux List Size(in GBs):%Lf\n", ((long double)num_loaded_hashes * sizeof(unsigned int)) / ((long double)1024 * 1024 * 1024));
for (i = 0; i < offset_table_size && offset_data[i].collisions; i++)
;
fprintf (stdout, "Unused Slots in Offset Table:%Lf %%\n", 100.00 * (long double)(offset_table_size - i) / (long double)(offset_table_size));
fprintf(stdout, "Total Memory Use(in GBs):%Lf\n", ((long double)total_memory_in_bytes) / ((long double) 1024 * 1024 * 1024));
}
}
static unsigned int check_n_insert_into_hash_table(unsigned int offset, auxilliary_offset_data * ptr, unsigned int *hash_table_idxs, unsigned int *store_hash_modulo_table_sz)
{
unsigned int i;
i = 0;
while (i < ptr -> collisions) {
hash_table_idxs[i] = store_hash_modulo_table_sz[i] + offset;
if (hash_table_idxs[i] >= hash_table_size)
hash_table_idxs[i] -= hash_table_size;
if (zero_check_ht(hash_table_idxs[i++]))
return 0;
}
i = 0;
while (i < ptr -> collisions) {
if (zero_check_ht(hash_table_idxs[i])) {
unsigned int j = 0;
while (j < i)
assign0_ht(hash_table_idxs[j++]);
return 0;
}
assign_ht(hash_table_idxs[i], ptr -> hash_location_list[i]);
i++;
}
return 1;
}
static void calc_hash_mdoulo_table_size(unsigned int *store, auxilliary_offset_data * ptr) {
unsigned int i = 0;
while (i < ptr -> collisions) {
store[i] = modulo_op(loaded_hashes + (ptr -> hash_location_list[i]) * binary_size_actual, hash_table_size, shift64_ht_sz, shift128_ht_sz);
i++;
}
}
static unsigned int create_tables()
{
unsigned int i;
unsigned int bitmap = ((1ULL << (sizeof(OFFSET_TABLE_WORD) * 8)) - 1) & 0xFFFFFFFF;
unsigned int limit = bitmap % hash_table_size + 1;
unsigned int hash_table_idx;
unsigned int *store_hash_modulo_table_sz;
unsigned int *hash_table_idxs;
#ifdef ENABLE_BACKTRACKING
OFFSET_TABLE_WORD last_offset;
unsigned int backtracking = 0;
#endif
unsigned int trigger;
long double done = 0;
struct timeval t;
if (bt_malloc((void **)&store_hash_modulo_table_sz, offset_data[0].collisions * sizeof(unsigned int)))
bt_error("Failed to allocate memory: store_hash_modulo_table_sz.");
if (bt_malloc((void **)&hash_table_idxs, offset_data[0].collisions * sizeof(unsigned int)))
bt_error("Failed to allocate memory: hash_table_idxs.");
gettimeofday(&t, NULL);
seedMT(t.tv_sec + t.tv_usec);
i = 0;
trigger = 0;
while (offset_data[i].collisions > 1) {
OFFSET_TABLE_WORD offset;
unsigned int num_iter;
done += offset_data[i].collisions;
calc_hash_mdoulo_table_size(store_hash_modulo_table_sz, &offset_data[i]);
offset = (OFFSET_TABLE_WORD)(randomMT() & bitmap) % hash_table_size;
#ifdef ENABLE_BACKTRACKING
if (backtracking) {
offset = (last_offset + 1) % hash_table_size;
backtracking = 0;
}
#endif
alarm(3);
num_iter = 0;
while (!check_n_insert_into_hash_table((unsigned int)offset, &offset_data[i], hash_table_idxs, store_hash_modulo_table_sz) && num_iter < limit) {
offset++;
if (offset >= hash_table_size) offset = 0;
num_iter++;
}
offset_table[offset_data[i].offset_table_idx] = offset;
if ((trigger & 0xffff) == 0) {
trigger = 0;
if (verbosity > 0) {
fprintf(stdout, "\rProgress:%Lf %%, Number of collisions:%u", done / (long double)num_loaded_hashes * 100.00, offset_data[i].collisions);
fflush(stdout);
}
alarm(0);
}
if (signal_stop) {
alarm(0);
signal_stop = 0;
fprintf(stderr, "\nProgress is too slow!! trying next table size.\n");
bt_free((void **)&hash_table_idxs);
bt_free((void **)&store_hash_modulo_table_sz);
return 0;
}
trigger++;
if (num_iter == limit) {
#ifdef ENABLE_BACKTRACKING
if (num_loaded_hashes > 1000000) {
unsigned int j, backtrack_steps, iter;
done -= offset_data[i].collisions;
offset_table[offset_data[i].offset_table_idx] = 0;
backtrack_steps = 1;
j = 1;
while (j <= backtrack_steps && (int)(i - j) >= 0) {
last_offset = offset_table[offset_data[i - j].offset_table_idx];
iter = 0;
while (iter < offset_data[i - j].collisions) {
hash_table_idx =
calc_ht_idx(offset_data[i - j].hash_location_list[iter],
last_offset);
assign0_ht(hash_table_idx);
iter++;
}
offset_table[offset_data[i - j].offset_table_idx] = 0;
done -= offset_data[i - j].collisions;
j++;
}
i -= (j - 1);
backtracking = 1;
continue;
}
#endif
bt_free((void **)&hash_table_idxs);
bt_free((void **)&store_hash_modulo_table_sz);
return 0;
}
i++;
}
alarm(0);
hash_table_idx = 0;
while (offset_data[i].collisions > 0) {
done++;
while (hash_table_idx < hash_table_size) {
if (!zero_check_ht(hash_table_idx)) {
assign_ht(hash_table_idx, offset_data[i].hash_location_list[0]);
break;
}
hash_table_idx++;
}
offset_table[offset_data[i].offset_table_idx] = get_offset(hash_table_idx, offset_data[i].hash_location_list[0]);
if ((trigger & 0xffff) == 0) {
trigger = 0;
if (verbosity > 0) {
fprintf(stdout, "\rProgress:%Lf %%, Number of collisions:%u", done / (long double)num_loaded_hashes * 100.00, offset_data[i].collisions);
fflush(stdout);
}
}
trigger++;
i++;
}
bt_free((void **)&hash_table_idxs);
bt_free((void **)&store_hash_modulo_table_sz);
return 1;
}
static unsigned int next_prime(unsigned int num)
{
if (num == 1)
return 2;
else if (num == 2)
return 3;
else if (num == 3 || num == 4)
return 5;
else if (num == 5 || num == 6)
return 7;
else if (num >= 7 && num <= 9)
return 1;
/* else if (num == 11 || num == 12)
return 13;
else if (num >= 13 && num < 17)
return 17;
else if (num == 17 || num == 18)
return 19;
else if (num >= 19 && num < 23)
return 23;
else if (num >= 23 && num < 29)
return 29;
else if (num == 29 || num == 30 )
return 31;
else if (num >= 31 && num < 37)
return 37;
else if (num >= 37 && num < 41)
return 41;
else if (num == 41 || num == 42 )
return 43;
else if (num >= 43 && num < 47)
return 47;
else if (num >= 47 && num < 53)
return 53;
else if (num >= 53 && num < 59)
return 59;
else if (num == 59 || num == 60)
return 61;
else if (num >= 61 && num < 67)
return 67;
else if (num >= 67 && num < 71)
return 71;
else if (num == 71 || num == 72)
return 73;
else if (num >= 73 && num < 79)
return 79;
else if (num >= 79 && num < 83)
return 83;
else if (num >= 83 && num < 89)
return 89;
else if (num >= 89 && num < 97)
return 97;
else
return 1;*/
return 1;
}
unsigned int create_perfect_hash_table(int htype, void *loaded_hashes_ptr,
unsigned int num_ld_hashes,
OFFSET_TABLE_WORD **offset_table_ptr,
unsigned int *offset_table_sz_ptr,
unsigned int *hash_table_sz_ptr,
unsigned int verb)
{
long double multiplier_ht, multiplier_ot, inc_ht, inc_ot;
unsigned int approx_hash_table_sz, approx_offset_table_sz, i, dupe_remove_ht_sz;
struct sigaction new_action, old_action;
struct itimerval old_it;
total_memory_in_bytes = 0;
hash_type = htype;
loaded_hashes = loaded_hashes_ptr;
verbosity = verb;
if (hash_type == 64) {
zero_check_ht = zero_check_ht_64;
assign_ht = assign_ht_64;
assign0_ht = assign0_ht_64;
calc_ht_idx = calc_ht_idx_64;
get_offset = get_offset_64;
allocate_ht = allocate_ht_64;
test_tables = test_tables_64;
remove_duplicates = remove_duplicates_64;
loaded_hashes_64 = (uint64_t *)loaded_hashes;
binary_size_actual = 8;
if (verbosity > 1)
fprintf(stdout, "Using Hash type 64.\n");
}
else if (hash_type == 128) {
zero_check_ht = zero_check_ht_128;
assign_ht = assign_ht_128;
assign0_ht = assign0_ht_128;
calc_ht_idx = calc_ht_idx_128;
get_offset = get_offset_128;
allocate_ht = allocate_ht_128;
test_tables = test_tables_128;
remove_duplicates = remove_duplicates_128;
loaded_hashes_128 = (uint128_t *)loaded_hashes;
binary_size_actual = 16;
if (verbosity > 1)
fprintf(stdout, "Using Hash type 128.\n");
}
else if (hash_type == 192) {
zero_check_ht = zero_check_ht_192;
assign_ht = assign_ht_192;
assign0_ht = assign0_ht_192;
calc_ht_idx = calc_ht_idx_192;
get_offset = get_offset_192;
allocate_ht = allocate_ht_192;
test_tables = test_tables_192;
remove_duplicates = remove_duplicates_192;
loaded_hashes_192 = (uint192_t *)loaded_hashes;
binary_size_actual = 24;
if (verbosity > 1)
fprintf(stdout, "Using Hash type 192.\n");
}
new_action.sa_handler = alarm_handler;
sigemptyset(&new_action.sa_mask);
new_action.sa_flags = 0;
if (sigaction(SIGALRM, NULL, &old_action) < 0)
bt_error("Error retriving signal info.");
if (sigaction(SIGALRM, &new_action, NULL) < 0)
bt_error("Error setting new signal handler.");
if (getitimer(ITIMER_REAL, &old_it) < 0)
bt_error("Error retriving timer info.");
inc_ht = 0.005;
inc_ot = 0.05;
if (num_ld_hashes <= 100) {
multiplier_ot = 1.501375173;
inc_ht = 0.05;
inc_ot = 0.5;
dupe_remove_ht_sz = 128;
}
else if (num_ld_hashes <= 1000) {
multiplier_ot = 1.101375173;
dupe_remove_ht_sz = 1024;
}
else if (num_ld_hashes <= 10000) {
multiplier_ot = 1.151375173;
dupe_remove_ht_sz = 16384;
}
else if (num_ld_hashes <= 100000) {
multiplier_ot = 1.20375173;
dupe_remove_ht_sz = 131072;
}
else if (num_ld_hashes <= 1000000) {
multiplier_ot = 1.25375173;
dupe_remove_ht_sz = 1048576;
}
else if (num_ld_hashes <= 10000000) {
multiplier_ot = 1.31375173;
dupe_remove_ht_sz = 16777216;
}
else if (num_ld_hashes <= 20000000) {
multiplier_ot = 1.35375173;
dupe_remove_ht_sz = 33554432;
}
else if (num_ld_hashes <= 50000000) {
multiplier_ot = 1.41375173;
dupe_remove_ht_sz = 67108864;
}
else if (num_ld_hashes <= 110000000) {
multiplier_ot = 1.51375173;
dupe_remove_ht_sz = 134217728;
}
else if (num_ld_hashes <= 200000000) {
multiplier_ot = 1.61375173;
dupe_remove_ht_sz = 134217728 * 2;
}
else {
fprintf(stderr, "This many number of hashes have never been tested before and might not succeed!!\n");
multiplier_ot = 3.01375173;
dupe_remove_ht_sz = 134217728 * 4;
}
num_loaded_hashes = remove_duplicates(num_ld_hashes, dupe_remove_ht_sz, verbosity);
if (!num_loaded_hashes)
bt_error("Failed to remove duplicates.");
multiplier_ht = 1.001097317;
approx_offset_table_sz = (((long double)num_loaded_hashes / 4.0) * multiplier_ot + 10.00);
approx_hash_table_sz = ((long double)num_loaded_hashes * multiplier_ht);
i = 0;
do {
unsigned int temp;
init_tables(approx_offset_table_sz, approx_hash_table_sz);
if (create_tables()) {
if (verbosity > 0)
fprintf(stdout, "\n");
break;
}
if (verbosity > 0)
fprintf(stdout, "\n");
release_all_lists();
bt_free((void **)&offset_data);
bt_free((void **)&offset_table);
if (hash_type == 64)
bt_free((void **)&hash_table_64);
else if (hash_type == 128)
bt_free((void **)&hash_table_128);
else if (hash_type == 192)
bt_free((void **)&hash_table_192);
temp = next_prime(approx_offset_table_sz % 10);
approx_offset_table_sz /= 10;
approx_offset_table_sz *= 10;
approx_offset_table_sz += temp;
i++;
if (!(i % 5)) {
multiplier_ot += inc_ot;
multiplier_ht += inc_ht;
approx_offset_table_sz = (((long double)num_loaded_hashes / 4.0) * multiplier_ot + 10.00);
approx_hash_table_sz = ((long double)num_loaded_hashes * multiplier_ht);
}
} while(1);
release_all_lists();
bt_free((void **)&offset_data);
*offset_table_ptr = offset_table;
*hash_table_sz_ptr = hash_table_size;
*offset_table_sz_ptr = offset_table_size;
if (sigaction(SIGALRM, &old_action, NULL) < 0)
bt_error("Error restoring previous signal handler.");
if (setitimer(ITIMER_REAL, &old_it, NULL) < 0)
bt_error("Error restoring previous timer.");
if (!test_tables(num_loaded_hashes, offset_table, offset_table_size, shift64_ot_sz, shift128_ot_sz, verbosity))
return 0;
return num_loaded_hashes;
}
/*static int qsort_compare(const void *p1, const void *p2)
{
auxilliary_offset_data *a = (auxilliary_offset_data *)p1;
auxilliary_offset_data *b = (auxilliary_offset_data *)p2;
if (a[0].collisions > b[0].collisions) return -1;
if (a[0].collisions == b[0].collisions) return 0;
return 1;
}*/
#endif
|
the_stack_data/123451.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strncmp.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yaziz <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/11 03:46:12 by yaziz #+# #+# */
/* Updated: 2020/02/01 20:16:17 by yaziz ### ########.fr */
/* */
/* ************************************************************************** */
#include <string.h>
int ft_strncmp(const char *s1, const char *s2, size_t n)
{
size_t i;
i = 0;
while (i < n && ((unsigned char *)s1)[i] && ((unsigned char *)s2)[i])
{
if (((unsigned char *)s1)[i] != ((unsigned char *)s2)[i])
return (((unsigned char *)s1)[i] - ((unsigned char *)s2)[i]);
i++;
}
return (i == n ? 0 : ((unsigned char *)s1)[i] - ((unsigned char *)s2)[i]);
}
|
the_stack_data/231393107.c
|
#include "stdio.h"
#define max_arr_length 100
void merge (int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int tmp_left[n1];
int tmp_right[n2];
for (int i = 0; i < n1; i++) tmp_left[i] = arr[l + i];
for (int i = 0; i < n2; i++) tmp_right[i] = arr[m + 1 + i];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (tmp_left[i] <= tmp_right[j]) {
arr[k] = tmp_left[i];
i++;
} else {
arr[k] = tmp_right[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = tmp_left[i];
i++;
k++;
}
while (j < n2) {
arr[k] = tmp_right[j];
j++;
k++;
}
return;
}
void mergesort(int arr[], int l, int r) {
if (l < r) {
int m = (r + l) / 2;
mergesort(arr, l, m);
mergesort(arr, m + 1, r);
merge(arr, l, m, r);
}
return;
}
int arr[max_arr_length];
int main () {
freopen("mergesort.in", "r", stdin);
freopen("mergesort.ans", "w", stdout);
int loc = 0;
int n;
do {
scanf("%d", &n);
if (n != -1) {
arr[loc] = n;
loc++;
}
} while (n != -1);
for (int i = 0; i < loc; i++) printf("%d ", arr[i]);
mergesort(arr, 0, loc - 1);
printf("\n");
for (int i = 0; i < loc; i++) printf("%d ", arr[i]);
return 0;
fclose(stdin);
fclose(stdout);
}
|
the_stack_data/181394572.c
|
/* This function initialise the MMU with the following mapping */
/* Physical 0x00000000 - 0x20000000, virtual 0x00000000 - 0x20000000, RWX user, RWX super, write-back, no write allocate */
/* RPI1 Physical 0x20000000 - 0x21000000, virtual 0x20000000 - 0x21000000, RWX user, RWX super, write-back, no-cacheable */
/* RPI2&3 Physical 0x3F000000 - 0x40000000, virtual 0x20000000 - 0x21000000, RWX user, RWX super, write-back, no-cacheable */
/* Physical 0x00000000 - 0x40000000, virtual 0x40000000 - 0x80000000, RWX user, RWX super, write-back, no-cacheable */
/* The CPU RAM size is limited to 512 to fit almost all raspberry */
/* The Whole RAM is accessible in non-cacheable mode from 0x40000000 to be able to access video RAM */
#define RPI1_IO_BASE_ADDRESS 0x20000000
#define RPI2_IO_BASE_ADDRESS 0x3F000000
#define RPI3_IO_BASE_ADDRESS 0x3F000000
/* number of 1M section in 4 GB address space */
#define NB_1M_SECTION (0x100000000LL / 0x00100000)
extern unsigned int CPU_init_page_table[NB_1M_SECTION];
/* */
#define ONE_MB (1024 * 1024)
#define K_RAM_SIZE (512 *K_1M)
extern unsigned int CPU_init_read_main_id();
extern void CPU_init_stop_mmu();
extern void CPU_init_start_mmu(unsigned int * page_table,unsigned int control_register_or_mask);
extern void CPU_init_enable_vfp();
extern void CPU_init_invalidate_tlb();
extern void CPU_init_clean_and_invalidate_data_cache();
extern void CPU_init_invalidate_instruction_cache();
extern void CPU_init_disable_caches();
void CPU_init_map_section(
unsigned int *page_table,
unsigned int virtual_address,
unsigned int physical_address,
unsigned int flags)
{
unsigned int *entry;
entry = &(page_table[virtual_address >> 20]);
*entry = (physical_address & 0xFFF00000) | flags | 2 |0xC00;
return;
}
void CPU_init()
{
unsigned int main_id;
unsigned int physical_io_address;
unsigned int i;
/* reading CPU id to known RPI version */
main_id = CPU_init_read_main_id();
/* rpi1 armv6 */
if ((main_id & 0xF000) == 0xB000)
{
physical_io_address = RPI1_IO_BASE_ADDRESS;
}
/* rpi2 armv7 */
else if ((main_id & 0xF000) == 0xC000)
{
physical_io_address = RPI2_IO_BASE_ADDRESS;
}
/* rpi3 armv8 */
else if ((main_id & 0xF000) == 0xD000)
{
physical_io_address = RPI3_IO_BASE_ADDRESS;
}
/* clear page table */
for (i = 0;i < NB_1M_SECTION; i++)
{
CPU_init_page_table[i] = 0;
}
/* map Physical 0x00000000 - 0x20000000, virtual 0x00000000 - 0x20000000, RWX user, RWX super, write-back, no write allocate */
for (i = 0x00000000; i < (512 * ONE_MB); i+= ONE_MB)
{
CPU_init_map_section(CPU_init_page_table,i,i,0x0c); // cacheable no write allocate
}
/* RPI1 Physical 0x20000000 - 0x21000000, virtual 0x20000000 - 0x21000000, RWX user, RWX super, write-back, no-cacheable */
/* RPI2&3 Physical 0x3F000000 - 0x40000000, virtual 0x20000000 - 0x21000000, RWX user, RWX super, write-back, no-cacheable */
for (i = 0; i < (16 * ONE_MB) ; i+= ONE_MB)
{
CPU_init_map_section(CPU_init_page_table,RPI1_IO_BASE_ADDRESS + i,physical_io_address + i,0); // not cacheable
}
/* Map Physical 0x00000000 - 0x40000000, virtual 0x40000000 - 0x80000000, RWX user, RWX super, write-back, no-cacheable */
for (i = 0x00000000; i < 0x40000000; i+= ONE_MB)
{
CPU_init_map_section(CPU_init_page_table,0x40000000 + i,i,0x0); // not cacheable
}
// clean_and_invalidate_data_cache();
// invalidate_instruction_cache();
// disable_caches();
CPU_init_stop_mmu();
CPU_init_invalidate_tlb();
CPU_init_start_mmu((unsigned int *)((unsigned int)CPU_init_page_table),0x1005); /* ICACHE DCACHE and MMU ON */
CPU_init_enable_vfp();
return;
}
|
the_stack_data/838713.c
|
int brack_(int *, float *, float *, int *);
int hermit_(float *, float *, float *, float *, float *, float *,
float *, float *, float *);
/* NAME */
/* interp -- Hermite cubic interpolation. */
/* FILE */
/* interp.f */
/* SYNOPSIS */
/* Hermite cubic interpolation routine for function y(x). */
/* DESCRIPTION */
/* Subroutine. Hermitian cubic interpolation routine to act on a */
/* function, y(x). */
/* ---- Indexing ---- */
/* i = 1, n; */
/* ---- On entry ---- */
/* n: Number of function samples */
/* x(i): Sample values of independent variable */
/* y(i): Value of function at x(i); y(x(i)) */
/* yp(i): Value of derivative at x(i); y'(x(i)) */
/* x0: Value of independent variable for interpolation */
/* ---- On return ---- */
/* y0: Interpolated value of function at x0 */
/* yp0: Interpolated value of derivative at x0 */
/* ierr: Error flag; */
/* = 0, No error */
/* = 1, x0 out of range. yp0 and y0 are then defined */
/* through linear extrapolation of function */
/* ---- Subroutines called ---- */
/* Local */
/* - Calls hermit */
/* DIAGNOSTICS */
/* FILES */
/* NOTES */
/* SEE ALSO */
/* AUTHOR */
int interp_(int *n, float *x, float *y, float *yp, float *x0, float *y0, float *yp0, int *ierr) {
int ileft, i1, i2;
/* K.S. 1-Dec-97, changed 'undefined' to 'none' */
/* ---- On entry ---- */
/* ---- On return ---- */
/* ---- Internal variables ---- */
/* Binary search for samples bounding x0 */
/* Parameter adjustments */
--yp;
--y;
--x;
/* Function Body */
brack_(n, &x[1], x0, &ileft);
/* x0 < x(1) */
if (ileft < 1) {
*ierr = 1;
*yp0 = yp[1];
*y0 = y[1] + *yp0 * (*x0 - x[1]);
return 0;
}
/* x0 > x(n) */
if (ileft >= *n) {
*ierr = 1;
*yp0 = yp[*n];
*y0 = y[*n] + *yp0 * (*x0 - x[*n]);
return 0;
}
/* Normal case */
i1 = ileft;
i2 = ileft + 1;
hermit_(&x[i1], &x[i2], &y[i1], &y[i2], &yp[i1], &yp[i2], x0, y0, yp0);
*ierr = 0;
return 0;
}
|
the_stack_data/322899.c
|
// Compilation Instructions
// gcc bmi.c && ./a.out
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main() {
char weight_c[SIZE], height_c[SIZE];
double weight, height, bmi;
printf("Enter you weight: ");
fgets(weight_c, SIZE, stdin);
weight = atof(weight_c);
printf("Enter you height: ");
fgets(height_c, SIZE, stdin);
height = atof(height_c);
bmi = weight / (height * height);
printf("weight is %2f, height is %2f\n", weight, height);
printf("You bmi is %2f\n", bmi);
}
|
the_stack_data/1195596.c
|
/* Ray-Triangle Intersection Test Routines */
/* Different optimizations of my and Ben Trumbore's */
/* code from journals of graphics tools (JGT) */
/* http://www.acm.org/jgt/ */
/* by Tomas Moller, May 2000 */
#include <math.h>
#define EPSILON 1e-6
#define CROSS(dest,v1,v2) \
dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; \
dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; \
dest[2]=v1[0]*v2[1]-v1[1]*v2[0];
#define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2])
#define SUB(dest,v1,v2) \
dest[0]=v1[0]-v2[0]; \
dest[1]=v1[1]-v2[1]; \
dest[2]=v1[2]-v2[2];
/* the original jgt code */
int intersect_triangle(double orig[3], double dir[3],
double vert0[3], double vert1[3], double vert2[3],
double *t, double *u, double *v)
{
double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
double det,inv_det;
/* find vectors for two edges sharing vert0 */
SUB(edge1, vert1, vert0);
SUB(edge2, vert2, vert0);
/* begin calculating determinant - also used to calculate U parameter */
CROSS(pvec, dir, edge2);
/* if determinant is near zero, ray lies in plane of triangle */
det = DOT(edge1, pvec);
if (det > -EPSILON && det < EPSILON)
return 0;
inv_det = 1.0 / det;
/* calculate distance from vert0 to ray origin */
SUB(tvec, orig, vert0);
/* calculate U parameter and test bounds */
*u = DOT(tvec, pvec) * inv_det;
if (*u < 0.0 || *u > 1.0)
return 0;
/* prepare to test V parameter */
CROSS(qvec, tvec, edge1);
/* calculate V parameter and test bounds */
*v = DOT(dir, qvec) * inv_det;
if (*v < 0.0 || *u + *v > 1.0)
return 0;
/* calculate t, ray intersects triangle */
*t = DOT(edge2, qvec) * inv_det;
return 1;
}
/* code rewritten to do tests on the sign of the determinant */
/* the division is at the end in the code */
int intersect_triangle1(double orig[3], double dir[3],
double vert0[3], double vert1[3], double vert2[3],
double *t, double *u, double *v)
{
double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
double det,inv_det;
/* find vectors for two edges sharing vert0 */
SUB(edge1, vert1, vert0);
SUB(edge2, vert2, vert0);
/* begin calculating determinant - also used to calculate U parameter */
CROSS(pvec, dir, edge2);
/* if determinant is near zero, ray lies in plane of triangle */
det = DOT(edge1, pvec);
if (det > EPSILON)
{
/* calculate distance from vert0 to ray origin */
SUB(tvec, orig, vert0);
/* calculate U parameter and test bounds */
*u = DOT(tvec, pvec);
if (*u < 0.0 || *u > det)
return 0;
/* prepare to test V parameter */
CROSS(qvec, tvec, edge1);
/* calculate V parameter and test bounds */
*v = DOT(dir, qvec);
if (*v < 0.0 || *u + *v > det)
return 0;
}
else if(det < -EPSILON)
{
/* calculate distance from vert0 to ray origin */
SUB(tvec, orig, vert0);
/* calculate U parameter and test bounds */
*u = DOT(tvec, pvec);
/* printf("*u=%f\n",(float)*u); */
/* printf("det=%f\n",det); */
if (*u > 0.0 || *u < det)
return 0;
/* prepare to test V parameter */
CROSS(qvec, tvec, edge1);
/* calculate V parameter and test bounds */
*v = DOT(dir, qvec) ;
if (*v > 0.0 || *u + *v < det)
return 0;
}
else return 0; /* ray is parallell to the plane of the triangle */
inv_det = 1.0 / det;
/* calculate t, ray intersects triangle */
*t = DOT(edge2, qvec) * inv_det;
(*u) *= inv_det;
(*v) *= inv_det;
return 1;
}
/* code rewritten to do tests on the sign of the determinant */
/* the division is before the test of the sign of the det */
int intersect_triangle2(double orig[3], double dir[3],
double vert0[3], double vert1[3], double vert2[3],
double *t, double *u, double *v)
{
double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
double det,inv_det;
/* find vectors for two edges sharing vert0 */
SUB(edge1, vert1, vert0);
SUB(edge2, vert2, vert0);
/* begin calculating determinant - also used to calculate U parameter */
CROSS(pvec, dir, edge2);
/* if determinant is near zero, ray lies in plane of triangle */
det = DOT(edge1, pvec);
/* calculate distance from vert0 to ray origin */
SUB(tvec, orig, vert0);
inv_det = 1.0 / det;
if (det > EPSILON)
{
/* calculate U parameter and test bounds */
*u = DOT(tvec, pvec);
if (*u < 0.0 || *u > det)
return 0;
/* prepare to test V parameter */
CROSS(qvec, tvec, edge1);
/* calculate V parameter and test bounds */
*v = DOT(dir, qvec);
if (*v < 0.0 || *u + *v > det)
return 0;
}
else if(det < -EPSILON)
{
/* calculate U parameter and test bounds */
*u = DOT(tvec, pvec);
if (*u > 0.0 || *u < det)
return 0;
/* prepare to test V parameter */
CROSS(qvec, tvec, edge1);
/* calculate V parameter and test bounds */
*v = DOT(dir, qvec) ;
if (*v > 0.0 || *u + *v < det)
return 0;
}
else return 0; /* ray is parallell to the plane of the triangle */
/* calculate t, ray intersects triangle */
*t = DOT(edge2, qvec) * inv_det;
(*u) *= inv_det;
(*v) *= inv_det;
return 1;
}
/* code rewritten to do tests on the sign of the determinant */
/* the division is before the test of the sign of the det */
/* and one CROSS has been moved out from the if-else if-else */
int intersect_triangle3(double orig[3], double dir[3],
double vert0[3], double vert1[3], double vert2[3],
double *t, double *u, double *v)
{
double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
double det,inv_det;
/* find vectors for two edges sharing vert0 */
SUB(edge1, vert1, vert0);
SUB(edge2, vert2, vert0);
/* begin calculating determinant - also used to calculate U parameter */
CROSS(pvec, dir, edge2);
/* if determinant is near zero, ray lies in plane of triangle */
det = DOT(edge1, pvec);
/* calculate distance from vert0 to ray origin */
SUB(tvec, orig, vert0);
inv_det = 1.0 / det;
CROSS(qvec, tvec, edge1);
if (det > EPSILON)
{
*u = DOT(tvec, pvec);
if (*u < 0.0 || *u > det)
return 0;
/* calculate V parameter and test bounds */
*v = DOT(dir, qvec);
if (*v < 0.0 || *u + *v > det)
return 0;
}
else if(det < -EPSILON)
{
/* calculate U parameter and test bounds */
*u = DOT(tvec, pvec);
if (*u > 0.0 || *u < det)
return 0;
/* calculate V parameter and test bounds */
*v = DOT(dir, qvec) ;
if (*v > 0.0 || *u + *v < det)
return 0;
}
else return 0; /* ray is parallell to the plane of the triangle */
*t = DOT(edge2, qvec) * inv_det;
(*u) *= inv_det;
(*v) *= inv_det;
return 1;
}
/* Sueda: inclusive borders */
#define ZERO -EPSILON
int intersect_triangle3_inc(
const double *orig, const double *dir,
const double *vert0, const double *vert1, const double *vert2,
double *t, double *u, double *v)
{
double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
double det,inv_det;
/* find vectors for two edges sharing vert0 */
SUB(edge1, vert1, vert0);
SUB(edge2, vert2, vert0);
/* begin calculating determinant - also used to calculate U parameter */
CROSS(pvec, dir, edge2);
/* if determinant is near zero, ray lies in plane of triangle */
det = DOT(edge1, pvec);
/* calculate distance from vert0 to ray origin */
SUB(tvec, orig, vert0);
inv_det = 1.0 / det;
CROSS(qvec, tvec, edge1);
if (det > EPSILON)
{
*u = DOT(tvec, pvec);
if (*u < -ZERO || *u > det + ZERO)
return 0;
/* calculate V parameter and test bounds */
*v = DOT(dir, qvec);
if (*v < -ZERO || *u + *v > det + ZERO)
return 0;
}
else if(det < -EPSILON)
{
/* calculate U parameter and test bounds */
*u = DOT(tvec, pvec);
if (*u > ZERO || *u < det - ZERO)
return 0;
/* calculate V parameter and test bounds */
*v = DOT(dir, qvec) ;
if (*v > ZERO || *u + *v < det - ZERO)
return 0;
}
else return 0; /* ray is parallell to the plane of the triangle */
*t = DOT(edge2, qvec) * inv_det;
(*u) *= inv_det;
(*v) *= inv_det;
return 1;
}
|
the_stack_data/89199754.c
|
float f (float x)
{
return sin (x);
}
void main()
{
float a,b,d,S;
int i = 0;
d = 1e-2;
S = 0;
getid (a);
getid (b);
while (a + i * d < b)
{
S += d * f(a + i * d);
i++;
}
printid (S);
}
|
the_stack_data/86076376.c
|
#ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/THLabLapack.c"
#else
TH_API void THLab_(gesv)(THTensor *a_, THTensor *b_)
{
int n, nrhs, lda, ldb, info;
THIntTensor *ipiv;
THTensor *A, *B;
THArgCheck(a_->nDimension == 2, 2, "A should be 2 dimensional");
THArgCheck(a_->size[0] == a_->size[1], 2, "A should be symmetric");
n = (int)a_->size[1];
lda = n;
ldb = n;
if (b_->nDimension == 1)
{
nrhs = 1;
THArgCheck(n == b_->size[0], 1, "size incompatible A,b");
}
else
{
nrhs = b_->size[0];
THArgCheck(n == b_->size[1], 1, "size incompatible A,b");
}
A = THTensor_(newContiguous)(a_);
B = THTensor_(newContiguous)(b_);
ipiv = THIntTensor_newWithSize1d((long)n);
THLapack_(gesv)(n, nrhs,
THTensor_(data)(A), lda, THIntTensor_data(ipiv),
THTensor_(data)(B), ldb, &info);
if(!THTensor_(isContiguous)(b_))
{
THTensor_(copy)(b_,B);
}
if (info < 0)
{
THError("Lapack gesv : Argument %d : illegal value", -info);
}
else if (info > 0)
{
THError("Lapack gesv : U(%d,%d) is zero, singular U.", info,info);
}
THIntTensor_free(ipiv);
THTensor_(free)(A);
THTensor_(free)(B);
}
TH_API void THLab_(gels)(THTensor *a_, THTensor *b_)
{
int m, n, nrhs, lda, ldb, info, lwork;
char transpose;
THTensor *A, *B;
THTensor *work;
real wkopt;
THArgCheck(a_->nDimension == 2, 2, "A should be 2 dimensional");
A = THTensor_(newContiguous)(a_);
B = THTensor_(newContiguous)(b_);
m = A->size[1];
n = A->size[0];
lda = m;
ldb = m;
if (b_->nDimension == 1)
{
nrhs = 1;
THArgCheck(m == b_->size[0], 1, "size incompatible A,b");
}
else
{
nrhs = b_->size[0];
THArgCheck(m == b_->size[1], 1, "size incompatible A,b");
}
// get optimal workspace size
THLapack_(gels)('N', m, n, nrhs, THTensor_(data)(A), lda,
THTensor_(data)(B), ldb,
&wkopt, -1, &info);
lwork = (int)wkopt;
work = THTensor_(newWithSize1d)(lwork);
THLapack_(gels)('N', m, n, nrhs, THTensor_(data)(A), lda,
THTensor_(data)(B), ldb,
THTensor_(data)(work), lwork, &info);
//printf("lwork = %d,%g\n",lwork,THTensor_(data)(work)[0]);
if (info != 0)
{
THError("Lapack gels : Argument %d : illegal value", -info);
}
THTensor_(free)(A);
THTensor_(free)(B);
THTensor_(free)(work);
}
TH_API void THLab_(syev)(THTensor *a_, THTensor *w_, const char *jobz, const char *uplo)
{
int n, lda, lwork, info;
THTensor *A;
THTensor *work;
real wkopt;
THArgCheck(a_->nDimension == 2, 2, "A should be 2 dimensional");
A = THTensor_(newContiguous)(a_);
n = A->size[1];
lda = n;
THTensor_(resize1d)(w_,n);
// get optimal workspace size
THLapack_(syev)(jobz[0], uplo[0], n, THTensor_(data)(A), lda,
THTensor_(data)(w_), &wkopt, -1, &info);
lwork = (int)wkopt;
work = THTensor_(newWithSize1d)(lwork);
THLapack_(syev)(jobz[0], uplo[0], n, THTensor_(data)(A), lda,
THTensor_(data)(w_), THTensor_(data)(work), lwork, &info);
if (info > 0)
{
THError(" Lapack syev : Failed to converge. %d off-diagonal elements of an didn't converge to zero",info);
}
else if (info < 0)
{
THError("Lapack syev : Argument %d : illegal value", -info);
}
THTensor_(free)(A);
THTensor_(free)(work);
}
TH_API void THLab_(gesvd)(THTensor *a_, THTensor *s_, THTensor *u_, THTensor *vt_, char jobu)
{
int k,m, n, lda, ldu, ldvt, lwork, info;
THTensor *A, *work;
real wkopt;
char jobvt = jobu;
THArgCheck(a_->nDimension == 2, 2, "A should be 2 dimensional");
THArgCheck(jobu == 'A' || jobu == 'S',4, "jobu can be 'A' or 'S'");
A = THTensor_(newContiguous)(a_);
m = A->size[1];
n = A->size[0];
k = (m < n ? m : n);
lda = m;
ldu = m;
ldvt = n;
THTensor_(resize1d)(s_,k);
THTensor_(resize2d)(vt_,n,ldvt);
if (jobu == 'A')
{
THTensor_(resize2d)(u_,m,ldu);
}
else
{
THTensor_(resize2d)(u_,k,ldu);
}
THLapack_(gesvd)(jobu,jobvt,
m,n,THTensor_(data)(A),lda,
THTensor_(data)(s_),
THTensor_(data)(u_),
ldu,
THTensor_(data)(vt_), ldvt,
&wkopt, -1, &info);
lwork = (int)wkopt;
work = THTensor_(newWithSize1d)(lwork);
THLapack_(gesvd)(jobu,jobvt,
m,n,THTensor_(data)(A),lda,
THTensor_(data)(s_),
THTensor_(data)(u_),
ldu,
THTensor_(data)(vt_), ldvt,
THTensor_(data)(work),lwork, &info);
if (info > 0)
{
THError(" Lapack gesvd : %d superdiagonals failed to converge.",info);
}
else if (info < 0)
{
THError("Lapack gesvd : Argument %d : illegal value", -info);
}
THTensor_(free)(A);
THTensor_(free)(work);
}
#endif
|
the_stack_data/45450428.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
#define PORT 9010
int server (int client_socket)
{
while(1)
{
int lenght;
char *text;
if (read(client_socket, &lenght, sizeof(lenght)) == 0)
return 0;
text = (char*)malloc(lenght);
read(client_socket, text, lenght);
printf("%s\n", text);
if (!strcmp(text, "quit"))
{
free(text);
return 1;
} else {
free(text);
}
}
}
int main(int argc, char* argv[])
{
char* socket_name = argv[1];
int socket_fd;
struct sockaddr_in name;
int client_sent_quit_message;
socket_fd = socket(PF_INET, SOCK_STREAM, 0);
name.sin_family = AF_INET;
name.sin_port = htons(PORT);
bind(socket_fd, (struct sockaddr*) &name, sizeof(struct sockaddr_in)); //vincular o descritor de arquivos com o endereço
listen(socket_fd, 5);
do{
struct sockaddr_in client_name;
socklen_t client_name_len;
int client_socket_fd;
//função que bloqueia no descriptor de arquivo?
client_name_len = sizeof(client_name);
client_socket_fd = accept(socket_fd, (struct sockaddr*) &client_name, &client_name_len);
client_sent_quit_message = server(client_socket_fd);
close (client_socket_fd);
}while(!client_sent_quit_message);
close(socket_fd);
unlink(socket_name);
return 0;
}
|
the_stack_data/132683.c
|
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#define READ_END 0
#define WRITE_END 1
int main(int argc, char** argv) {
int fd[2];
int errnum;
printf("Iniciando proceso padre, pid '%d'.\n", getpid());
if (pipe(fd) < 0) {
fprintf(stderr, "Error al crear pipe!\n");
exit(EXIT_FAILURE);
}
int child = fork();
if (child == -1) {
fprintf(stderr, "Error creando proceso hijo!\n");
exit(EXIT_FAILURE);
}
if (!child) {
char arg[17];
sprintf(arg, "%d", fd[READ_END]);
char* args[] = { "./child", arg, NULL };
execv("./child", args);
errnum = errno;
perror("Error: ");
fprintf(stderr, "Valor de errno: %d\n", errno);
}
else {
char buff[128];
int rc = 0;
close(fd[READ_END]);
while ((rc = read(STDIN_FILENO, buff, 128)) > 0) {
write(fd[WRITE_END], buff, rc);
}
wait(&child);
printf("Proceso padre ha terminado.\n");
}
exit(EXIT_SUCCESS);
}
|
the_stack_data/59512153.c
|
int* y;
int z[4];
int main() {
int* a;
int b;
int x[5];
b = 33;
*a = 44;
x[0] = 5;
x[1] = 6;
x[2] = 7;
y = malloc(5 * 4);
z[2] = *(x + 2) * 7; // 49
*y = 15 + x[0]; // 20
*(y + 1) = 16 + *(x + 1); // 22
*(y + 2) = y[0] + y[1] + *(z + 2); // 91
return *(y + 2);
}
|
the_stack_data/150140590.c
|
#include <stdio.h>
#include <stdlib.h>
struct queue_record
{
unsigned int queue_max_size;
int queue_front;
int queue_rear;
unsigned int queue_size;
int *queue_array;
};
typedef struct queue_record *QUEUE;
QUEUE CreateQueue(unsigned int max_size)
{
QUEUE Q;
Q = (QUEUE)malloc(sizeof(struct queue_record));
Q->queue_max_size = max_size;
Q->queue_front = Q->queue_rear = -1;
Q->queue_size = 0;
Q->queue_array = (int *)malloc(sizeof(int) * max_size);
return Q;
}
int succ(int num, QUEUE Q)
{
return num % Q->queue_max_size;
}
int is_empty(QUEUE Q)
{
if (Q == NULL)
{
printf("\nError");
return 0;
}
return Q->queue_size == 0;
}
int is_full(QUEUE Q)
{
if (Q == NULL)
{
printf("\nError");
return 0;
}
return Q->queue_size == Q->queue_max_size;
}
void Enqueue(int x, QUEUE Q)
{
if (Q == NULL)
{
printf("\nError");
return;
}
if (is_full(Q))
{
printf("\nFull queue");
return;
}
else if (is_empty(Q))
{
Q->queue_front = Q->queue_rear = 0;
Q->queue_array[Q->queue_front] = x;
Q->queue_size++;
}
else
{
Q->queue_rear = succ(++Q->queue_rear, Q);
Q->queue_array[Q->queue_rear] = x;
Q->queue_size++;
}
}
int Dequeue(QUEUE Q)
{
if (Q == NULL)
{
printf("\nError");
return 0;
}
if (is_empty(Q))
{
printf("\nEmpty queue");
return 0;
}
else
{
Q->queue_front = succ(++Q->queue_front, Q);
Q->queue_size--;
}
}
void PrintQueue(QUEUE Q)
{
int i;
if (Q == NULL)
{
printf("\nError");
return;
}
if (is_empty(Q))
{
printf("\nEmpty queue");
return;
}
else
{
i = Q->queue_front;
printf("\n%d",Q->queue_array[i]);
while (i != Q->queue_rear)
{
i = succ(++i, Q);
printf("\t%d",Q->queue_array[i]);
}
}
}
void main()
{
QUEUE Q;
Q = CreateQueue(30);
Enqueue(1,Q);
Enqueue(3,Q);
PrintQueue(Q);
Enqueue(5,Q);
Dequeue(Q);
PrintQueue(Q);
Dequeue(Q);
Dequeue(Q);
PrintQueue(Q);
}
|
the_stack_data/87637757.c
|
/*
* iof_try.c
* Buggy demo for the IoF (integer overflow) bug..
*
* Author(s) :
* Kaiwan N Billimoria
* <kaiwan -at- kaiwantech -dot- com>
* License(s): MIT permissive
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char **argv)
{
off_t fsz = 5000, len = 2000;
int off = 0;
if (argc < 2) {
fprintf(stderr, "Usage: %s offset\n", argv[0]);
exit(EXIT_FAILURE);
}
/*
IoF Poc:
A signed integer on 64-bit ranges from (min,max) (-2,147,483,648, +2,147,483,647).
So, if you pass a positive offset within the max it works.
However, just pass the number 2,147,483,649 and see! It wraps around to
the negative side and the validity check below passes. Whoops!
*/
off = atoi(argv[1]);
printf("off = %d\n", off);
if (off+len > fsz) {
fprintf(stderr,
"%s: invalid offset or offset/length combination, aborting...\n", argv[0]);
exit(1);
}
printf("Ok, proceed !\n");
// do_foo(off);
exit(EXIT_SUCCESS);
}
|
the_stack_data/6388527.c
|
/**
******************************************************************************
* @file Templates/Src/stm32f1xx_hal_msp.c
* @author MCD Application Team
* @version V1.4.0
* @date 29-April-2016
* @brief HAL MSP module.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
/** @addtogroup STM32F1xx_HAL_Examples
* @{
*/
/** @addtogroup Templates
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup HAL_MSP_Private_Functions
* @{
*/
/**
* @brief Initializes the Global MSP.
* @param None
* @retval None
*/
void HAL_MspInit(void)
{
}
/**
* @brief DeInitializes the Global MSP.
* @param None
* @retval None
*/
void HAL_MspDeInit(void)
{
}
/**
* @brief Initializes the PPP MSP.
* @param None
* @retval None
*/
/*void HAL_PPP_MspInit(void)
{*/
/*}*/
/**
* @brief DeInitializes the PPP MSP.
* @param None
* @retval None
*/
/*void HAL_PPP_MspDeInit(void)
{*/
/*}*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/373759.c
|
// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck %s
// END.
// CHECK: private unnamed_addr constant [8 x i8] c"v_ann_{{.}}\00", section "llvm.metadata"
// CHECK: private unnamed_addr constant [8 x i8] c"v_ann_{{.}}\00", section "llvm.metadata"
struct foo {
int v __attribute__((annotate("v_ann_0"))) __attribute__((annotate("v_ann_1")));
};
static struct foo gf;
int main(int argc, char **argv) {
struct foo f;
f.v = argc;
// CHECK: getelementptr inbounds %struct.foo* %f, i32 0, i32 0
// CHECK-NEXT: bitcast i32* {{.*}} to i8*
// CHECK-NEXT: call i8* @llvm.ptr.annotation.p0i8({{.*}}str{{.*}}str{{.*}}i32 8)
// CHECK-NEXT: bitcast i8* {{.*}} to i32*
// CHECK-NEXT: bitcast i32* {{.*}} to i8*
// CHECK-NEXT: call i8* @llvm.ptr.annotation.p0i8({{.*}}str{{.*}}str{{.*}}i32 8)
// CHECK-NEXT: bitcast i8* {{.*}} to i32*
gf.v = argc;
// CHECK: bitcast i32* getelementptr inbounds (%struct.foo* @gf, i32 0, i32 0) to i8*
// CHECK-NEXT: call i8* @llvm.ptr.annotation.p0i8({{.*}}str{{.*}}str{{.*}}i32 8)
return 0;
}
|
the_stack_data/52970.c
|
int main(void){
int long long bignum = (- 0x7FFFFFFFFFFFFFFF - 1);
return bignum + 4;
}
|
the_stack_data/64200351.c
|
#include<stdio.h> //header file
int main(void) //main function
{
printf("Hello World"); //print statement
return 0; //return value
}
|
the_stack_data/132953232.c
|
int main()
{
int a, b;
printf("Entre com uma fracao (numerador e denominador): ");
scanf("%d %d", &a, &b);
if (b != 0)
printf("A fracao em decimal eh %f\n", 1.0 * a / b);
return 0;
}
|
the_stack_data/150141618.c
|
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int no1, no2, ans;
printf("\n Enter no1 =");
scanf("%d",&no1);
printf("\n Enter no2 =");
scanf("%d",&no2);
ans=0;
ans=no1+no2;
printf("\n %d +%d =%d\n", no1,no2, ans);
return 0;
}
|
the_stack_data/167330734.c
|
/* Test that the correct data prefetch instructions are generated for i386
variants that use SSE prefetch instructions. */
/* { dg-do compile { target { { i?86-*-* x86_64-*-* } && ia32 } } } */
extern void exit (int);
char *msg = "howdy there";
void foo (char *p)
{
__builtin_prefetch (p, 0, 0);
__builtin_prefetch (p, 0, 1);
__builtin_prefetch (p, 0, 2);
__builtin_prefetch (p, 0, 3);
__builtin_prefetch (p, 1, 0);
__builtin_prefetch (p, 1, 1);
__builtin_prefetch (p, 1, 2);
__builtin_prefetch (p, 1, 3);
}
int main ()
{
foo (msg);
exit (0);
}
/* { dg-final { scan-assembler "prefetchnta" } } */
/* { dg-final { scan-assembler "prefetcht0" } } */
/* { dg-final { scan-assembler "prefetcht1" } } */
/* { dg-final { scan-assembler "prefetcht2" } } */
/* { dg-final { scan-assembler-not "prefetchw" } } */
|
the_stack_data/97623.c
|
#include <stdio.h>
unsigned invert(unsigned x, int p, int n)
{
unsigned m;
m = ~(~0 << n) << (p - n + 1);
return x ^ m;
}
int main(void)
{
printf("%x\n", invert(0xaa, 4, 3));
return 0;
}
|
the_stack_data/220457002.c
|
/* Contest Scoreboard */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NPROBLEMS 9
#define NCONTESTANTS 101
/* The 0th position of each field of the structure below is: total time and
total solved respectively. */
typedef struct {
int time[NPROBLEMS + 1];
char solved[NPROBLEMS + 1];
} problems;
typedef struct {
int team;
problems p;
} contestant;
contestant contestants[NCONTESTANTS];
int num_cont;
int search(int team) {
int i;
for (i = 0; i < num_cont; i++)
if (team == contestants[i].team)
return i;
return -1;
}
int compare(const void *x, const void *y) {
contestant *a = (contestant *) x;
contestant *b = (contestant *) y;
if (a -> p.solved[0] != b -> p.solved[0])
return (b -> p.solved[0] - a -> p.solved[0]);
else if (a -> p.time[0] != b -> p.time[0])
return (a -> p.time[0] - b -> p.time[0]);
else
return (a -> team - b -> team);
}
int main() {
int cases;
char line[82];
int i, j, team, problem, time, pos;
scanf("%d", &cases);
getchar();
getchar();
while (cases) {
num_cont = 0;
while(fgets(line, 82, stdin)) {
if (*line == '\n')
break;
for (i = strlen(line) - 1; (line[i] == ' ') || (line[i] == '\n'); i--);
sscanf(line, "%d %d %d", &team, &problem, &time);
if ((pos = search(team)) == -1) {
contestants[num_cont].team = team;
for (j = 0; j < 10; j++) {
contestants[num_cont].p.time[j] = 0;
contestants[num_cont].p.solved[j] = 0;
}
pos = num_cont;
num_cont++;
}
if ((line[i] == 'R') || (line[i] == 'U') || (line[i] == 'E'))
continue;
if (!(contestants[pos].p.solved[problem])) {
if (line[i] == 'I')
contestants[pos].p.time[problem] += 20;
else {
contestants[pos].p.solved[problem] = 1;
contestants[pos].p.time[problem] += time;
contestants[pos].p.solved[0]++;
contestants[pos].p.time[0] += contestants[pos].p.time[problem];
}
}
}
qsort(contestants, num_cont, sizeof(contestant), compare);
for (i = 0; i < num_cont; i++)
printf("%d %d %d\n", contestants[i].team, contestants[i].p.solved[0],
contestants[i].p.time[0]);
if (cases > 1)
putchar('\n');
cases--;
}
return 0;
}
|
the_stack_data/671257.c
|
/*
* This file contrains the definitions that add file IO
* to the UserProfile Project. Essentially It is used
* for persistance of user data across program usages.
*
* MIT License
* Copyright (C) 2018 ElliePenguin
*/
#include <stdio.h>
#include <string.h>
// TODO: define functions.
|
the_stack_data/154827039.c
|
/* $OpenBSD: rsa_ssl.c,v 1.14 2014/10/22 13:02:04 jsing Exp $ */
/* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/rsa.h>
int
RSA_padding_add_SSLv23(unsigned char *to, int tlen, const unsigned char *from,
int flen)
{
int i, j;
unsigned char *p;
if (flen > tlen - 11) {
RSAerror(RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
return 0;
}
p = (unsigned char *)to;
*(p++) = 0;
*(p++) = 2; /* Public Key BT (Block Type) */
/* pad out with non-zero random data */
j = tlen - 3 - 8 - flen;
arc4random_buf(p, j);
for (i = 0; i < j; i++) {
while (*p == '\0')
arc4random_buf(p, 1);
p++;
}
memset(p, 3, 8);
p += 8;
*(p++) = '\0';
memcpy(p, from, flen);
return 1;
}
int
RSA_padding_check_SSLv23(unsigned char *to, int tlen, const unsigned char *from,
int flen, int num)
{
int i, j, k;
const unsigned char *p;
p = from;
if (flen < 10) {
RSAerror(RSA_R_DATA_TOO_SMALL);
return -1;
}
if (num != flen + 1 || *(p++) != 02) {
RSAerror(RSA_R_BLOCK_TYPE_IS_NOT_02);
return -1;
}
/* scan over padding data */
j = flen - 1; /* one for type */
for (i = 0; i < j; i++)
if (*(p++) == 0)
break;
if (i == j || i < 8) {
RSAerror(RSA_R_NULL_BEFORE_BLOCK_MISSING);
return -1;
}
for (k = -9; k < -1; k++) {
if (p[k] != 0x03)
break;
}
if (k == -1) {
RSAerror(RSA_R_SSLV3_ROLLBACK_ATTACK);
return -1;
}
i++; /* Skip over the '\0' */
j -= i;
if (j > tlen) {
RSAerror(RSA_R_DATA_TOO_LARGE);
return -1;
}
memcpy(to, p, j);
return j;
}
|
the_stack_data/62637358.c
|
/*
* --- ZyXEL header format ---
* Original Version by Benjamin Berg <[email protected]>
* C implementation based on generation-script by Christian Lamparter <[email protected]>
*
* The firmware image prefixed with a header (which is written into the MTD device).
* The header is one erase block (~64KiB) in size, but the checksum only convers the
* first 2KiB. Padding is 0xff. All integers are in big-endian.
*
* The checksum is always a 16-Bit System V checksum (sum -s) stored in a 32-Bit integer.
*
* 4 bytes: checksum of the rootfs image
* 4 bytes: length of the contained rootfs image file (big endian)
* 32 bytes: Firmware Version string (NUL terminated, 0xff padded)
* 4 bytes: checksum over the header partition (big endian - see below)
* 64 bytes: Model (e.g. "NBG6617", NUL termiated, 0xff padded)
* 4 bytes: checksum of the kernel partition
* 4 bytes: length of the contained kernel image file (big endian)
* rest: 0xff padding (To erase block size)
*
* The kernel partition checksum and length is not used for every device.
* If it's notused, pad those 8 bytes with 0xFF.
*
* The checksums are calculated by adding up all bytes and if a 16bit
* overflow occurs, one is added and the sum is masked to 16 bit:
* csum = csum + databyte; if (csum > 0xffff) { csum += 1; csum &= 0xffff };
* Should the file have an odd number of bytes then the byte len-0x800 is
* used additionally.
*
* The checksum for the header is calculated over the first 2048 bytes with
* the rootfs image checksum as the placeholder during calculation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
*/
#include <fcntl.h>
#include <getopt.h>
#include <libgen.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#define VERSION_STRING_LEN 31
#define ROOTFS_HEADER_LEN 40
#define KERNEL_HEADER_LEN 8
#define BOARD_NAME_LEN 64
#define BOARD_HEADER_LEN 68
#define HEADER_PARTITION_CALC_LENGTH 2048
#define HEADER_PARTITION_LENGTH 0x10000
struct file_info {
char *name; /* name of the file */
char *data; /* file content */
size_t size; /* length of the file */
};
static char *progname;
static char *board_name = 0;
static char *version_name = 0;
static unsigned int rootfs_size = 0;
static unsigned int header_length = HEADER_PARTITION_LENGTH;
static struct file_info kernel = { NULL, NULL, 0 };
static struct file_info rootfs = { NULL, NULL, 0 };
static struct file_info rootfs_out = { NULL, NULL, 0 };
static struct file_info out = { NULL, NULL, 0 };
#define ERR(fmt, ...) do { \
fprintf(stderr, "[%s] *** error: " fmt "\n", \
progname, ## __VA_ARGS__ ); \
} while (0)
void map_file(struct file_info *finfo)
{
struct stat file_stat = {0};
int fd;
fd = open(finfo->name, O_RDONLY, (mode_t)0600);
if (fd == -1) {
ERR("Error while opening file %s.", finfo->name);
exit(EXIT_FAILURE);
}
if (fstat(fd, &file_stat) == -1) {
ERR("Error getting file size for %s.", finfo->name);
exit(EXIT_FAILURE);
}
finfo->size = file_stat.st_size;
finfo->data = mmap(0, finfo->size, PROT_READ, MAP_SHARED, fd, 0);
if (finfo->data == MAP_FAILED) {
ERR("Error mapping file %s.", finfo->name);
exit(EXIT_FAILURE);
}
close(fd);
}
void unmap_file(struct file_info *finfo)
{
if(munmap(finfo->data, finfo->size) == -1) {
ERR("Error unmapping file %s.", finfo->name);
exit(EXIT_FAILURE);
}
}
void write_file(struct file_info *finfo)
{
FILE *fout = fopen(finfo->name, "w");
fwrite(finfo->data, finfo->size, 1, fout);
if (ferror(fout)) {
ERR("Wanted to write, but something went wrong.");
exit(EXIT_FAILURE);
}
fclose(fout);
}
void usage(int status)
{
FILE *stream = (status != EXIT_SUCCESS) ? stderr : stdout;
fprintf(stream, "Usage: %s [OPTIONS...]\n", progname);
fprintf(stream,
"\n"
"Options:\n"
" -k <kernel> path for kernel image\n"
" -r <rootfs> path for rootfs image\n"
" -s <rfssize> size of output rootfs\n"
" -v <version> version string\n"
" -b <boardname> name of board to generate image for\n"
" -o <out_name> name of output image\n"
" -l <hdr_length> length of header, default 65536\n"
" -h show this screen\n"
);
exit(status);
}
static int sysv_chksm(const unsigned char *data, int size)
{
int r;
int checksum;
unsigned int s = 0; /* The sum of all the input bytes, modulo (UINT_MAX + 1). */
for (int i = 0; i < size; i++) {
s += data[i];
}
r = (s & 0xffff) + ((s & 0xffffffff) >> 16);
checksum = (r & 0xffff) + (r >> 16);
return checksum;
}
static int zyxel_chksm(const unsigned char *data, int size)
{
return htonl(sysv_chksm(data, size));
}
char *generate_rootfs_header(struct file_info filesystem, char *version)
{
size_t version_string_length;
unsigned int chksm, size;
char *rootfs_header;
size_t ptr = 0;
rootfs_header = malloc(ROOTFS_HEADER_LEN);
if (!rootfs_header) {
ERR("Couldn't allocate memory for rootfs header!");
exit(EXIT_FAILURE);
}
/* Prepare padding for firmware-version string here */
memset(rootfs_header, 0xff, ROOTFS_HEADER_LEN);
chksm = zyxel_chksm((const unsigned char *)filesystem.data, filesystem.size);
size = htonl(filesystem.size);
/* 4 bytes: checksum of the rootfs image */
memcpy(rootfs_header + ptr, &chksm, 4);
ptr += 4;
/* 4 bytes: length of the contained rootfs image file (big endian) */
memcpy(rootfs_header + ptr, &size, 4);
ptr += 4;
/* 32 bytes: Firmware Version string (NUL terminated, 0xff padded) */
version_string_length = strlen(version) <= VERSION_STRING_LEN ? strlen(version) : VERSION_STRING_LEN;
memcpy(rootfs_header + ptr, version, version_string_length);
ptr += version_string_length;
/* Add null-terminator */
rootfs_header[ptr] = 0x0;
return rootfs_header;
}
char *generate_kernel_header(struct file_info kernel)
{
unsigned int chksm, size;
char *kernel_header;
size_t ptr = 0;
kernel_header = malloc(KERNEL_HEADER_LEN);
if (!kernel_header) {
ERR("Couldn't allocate memory for kernel header!");
exit(EXIT_FAILURE);
}
chksm = zyxel_chksm((const unsigned char *)kernel.data, kernel.size);
size = htonl(kernel.size);
/* 4 bytes: checksum of the kernel image */
memcpy(kernel_header + ptr, &chksm, 4);
ptr += 4;
/* 4 bytes: length of the contained kernel image file (big endian) */
memcpy(kernel_header + ptr, &size, 4);
return kernel_header;
}
unsigned int generate_board_header_checksum(char *kernel_hdr, char *rootfs_hdr, char *boardname)
{
char *board_hdr_tmp;
unsigned int sum;
size_t ptr = 0;
/*
* The checksum of the board header is calculated over the first 2048 bytes of
* the header partition with the rootfs checksum used as a placeholder for then
* board checksum we calculate in this step. The checksum gained from this step
* is then used for the final board header partition.
*/
board_hdr_tmp = malloc(HEADER_PARTITION_CALC_LENGTH);
if (!board_hdr_tmp) {
ERR("Couldn't allocate memory for temporary board header!");
exit(EXIT_FAILURE);
}
memset(board_hdr_tmp, 0xff, HEADER_PARTITION_CALC_LENGTH);
/* 40 bytes: RootFS header */
memcpy(board_hdr_tmp, rootfs_hdr, ROOTFS_HEADER_LEN);
ptr += ROOTFS_HEADER_LEN;
/* 4 bytes: RootFS checksum (BE) as placeholder for board-header checksum */
memcpy(board_hdr_tmp + ptr, rootfs_hdr, 4);
ptr += 4;
/* 32 bytes: Model (e.g. "NBG6617", NUL termiated, 0xff padded) */
memcpy(board_hdr_tmp + ptr, boardname, strlen(boardname));
ptr += strlen(boardname);
/* Add null-terminator */
board_hdr_tmp[ptr] = 0x0;
ptr = ROOTFS_HEADER_LEN + 4 + BOARD_NAME_LEN;
/* 8 bytes: Kernel header */
if (kernel_hdr)
memcpy(board_hdr_tmp + ptr, kernel_hdr, 8);
/* Calculate the checksum over the first 2048 bytes */
sum = zyxel_chksm((const unsigned char *)board_hdr_tmp, HEADER_PARTITION_CALC_LENGTH);
free(board_hdr_tmp);
return sum;
}
char *generate_board_header(char *kernel_hdr, char *rootfs_hdr, char *boardname)
{
unsigned int board_checksum;
char *board_hdr;
board_hdr = malloc(BOARD_HEADER_LEN);
if (!board_hdr) {
ERR("Couldn't allocate memory for board header!");
exit(EXIT_FAILURE);
}
memset(board_hdr, 0xff, BOARD_HEADER_LEN);
/* 4 bytes: checksum over the header partition (big endian) */
board_checksum = generate_board_header_checksum(kernel_hdr, rootfs_hdr, boardname);
memcpy(board_hdr, &board_checksum, 4);
/* 32 bytes: Model (e.g. "NBG6617", NUL termiated, 0xff padded) */
memcpy(board_hdr + 4, boardname, strlen(boardname));
board_hdr[4 + strlen(boardname)] = 0x0;
return board_hdr;
}
int build_image()
{
char *rootfs_header = NULL;
char *kernel_header = NULL;
char *board_header = NULL;
size_t ptr;
/* Load files */
if (kernel.name)
map_file(&kernel);
map_file(&rootfs);
/*
* Allocate memory and copy input rootfs for temporary output rootfs.
* This is important as we have to generate the rootfs checksum over the
* entire rootfs partition. As we might have to pad the partition to allow
* for flashing via ZyXEL's Web-GUI, we prepare the rootfs partition for the
* output image here (and also use it for calculating the rootfs checksum).
*
* The roofs padding has to be done with 0x00.
*/
rootfs_out.data = calloc(rootfs_out.size, sizeof(char));
memcpy(rootfs_out.data, rootfs.data, rootfs.size);
/* Prepare headers */
rootfs_header = generate_rootfs_header(rootfs_out, version_name);
if (kernel.name)
kernel_header = generate_kernel_header(kernel);
board_header = generate_board_header(kernel_header, rootfs_header, board_name);
/* Prepare output file */
out.size = header_length + rootfs_out.size;
if (kernel.name)
out.size += kernel.size;
out.data = malloc(out.size);
memset(out.data, 0xFF, out.size);
/* Build output image */
memcpy(out.data, rootfs_header, ROOTFS_HEADER_LEN);
memcpy(out.data + ROOTFS_HEADER_LEN, board_header, BOARD_HEADER_LEN);
if (kernel.name)
memcpy(out.data + ROOTFS_HEADER_LEN + BOARD_HEADER_LEN, kernel_header, KERNEL_HEADER_LEN);
ptr = header_length;
memcpy(out.data + ptr, rootfs_out.data, rootfs_out.size);
ptr += rootfs_out.size;
if (kernel.name)
memcpy(out.data + ptr, kernel.data, kernel.size);
/* Write back output image */
write_file(&out);
/* Free allocated memory */
if (kernel.name)
unmap_file(&kernel);
unmap_file(&rootfs);
free(out.data);
free(rootfs_out.data);
free(rootfs_header);
if (kernel.name)
free(kernel_header);
free(board_header);
return 0;
}
int check_options()
{
if (!rootfs.name) {
ERR("No rootfs filename supplied");
return -2;
}
if (!out.name) {
ERR("No output filename supplied");
return -3;
}
if (!board_name) {
ERR("No board-name supplied");
return -4;
}
if (!version_name) {
ERR("No version supplied");
return -5;
}
if (rootfs_size <= 0) {
ERR("Invalid rootfs size supplied");
return -6;
}
if (strlen(board_name) > 31) {
ERR("Board name is to long");
return -7;
}
return 0;
}
int main(int argc, char *argv[])
{
int ret;
progname = basename(argv[0]);
while (1) {
int c;
c = getopt(argc, argv, "b:k:o:r:s:v:l:h");
if (c == -1)
break;
switch (c) {
case 'b':
board_name = optarg;
break;
case 'h':
usage(EXIT_SUCCESS);
break;
case 'k':
kernel.name = optarg;
break;
case 'o':
out.name = optarg;
break;
case 'r':
rootfs.name = optarg;
break;
case 's':
sscanf(optarg, "%u", &rootfs_size);
break;
case 'v':
version_name = optarg;
break;
case 'l':
sscanf(optarg, "%u", &header_length);
break;
default:
usage(EXIT_FAILURE);
break;
}
}
ret = check_options();
if (ret)
usage(EXIT_FAILURE);
/* As ZyXEL Web-GUI only accept images with a rootfs equal or larger than the first firmware shipped
* for the device, we need to pad rootfs partition to this size. To perform further calculations, we
* decide the size of this part here. In case the rootfs we want to integrate in our image is larger,
* take it's size, otherwise the supplied size.
*
* Be careful! We rely on assertion of correct size to be performed beforehand. It is unknown if images
* with a to large rootfs are accepted or not.
*/
rootfs_out.size = rootfs_size < rootfs.size ? rootfs.size : rootfs_size;
return build_image();
}
|
the_stack_data/77365.c
|
#include <stdio.h>
#define FUNDLEN 50
#define N 2
struct funds {
char bank[FUNDLEN];
double bankfund;
char save[FUNDLEN];
double savefund;
};
double sum(const struct funds money[], int n);
int main(void) {
struct funds jones[N] = {
{
"A bank",
4032.27,
"Lucky's savings and loan",
8543.94
},
{
"Honest Jack's Bank",
3620.88,
"Party Time Savings",
3082.91
}
};
printf("total $%.2f", sum(jones, N));
return 0;
}
double sum(const struct funds money[], int n) {
double total = 0;
for (int i = 0; i < n; i++) {
total += money[i].bankfund + money[i].savefund;
}
return total;
}
|
the_stack_data/50423.c
|
/**
******************************************************************************
* @file stm32g4xx_ll_lptim.c
* @author MCD Application Team
* @brief LPTIM LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
* ******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_ll_lptim.h"
#include "stm32g4xx_ll_bus.h"
#include "stm32g4xx_ll_rcc.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
/** @addtogroup LPTIM_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup LPTIM_LL_Private_Macros
* @{
*/
#define IS_LL_LPTIM_CLOCK_SOURCE(__VALUE__) (((__VALUE__) == LL_LPTIM_CLK_SOURCE_INTERNAL) \
|| ((__VALUE__) == LL_LPTIM_CLK_SOURCE_EXTERNAL))
#define IS_LL_LPTIM_CLOCK_PRESCALER(__VALUE__) (((__VALUE__) == LL_LPTIM_PRESCALER_DIV1) \
|| ((__VALUE__) == LL_LPTIM_PRESCALER_DIV2) \
|| ((__VALUE__) == LL_LPTIM_PRESCALER_DIV4) \
|| ((__VALUE__) == LL_LPTIM_PRESCALER_DIV8) \
|| ((__VALUE__) == LL_LPTIM_PRESCALER_DIV16) \
|| ((__VALUE__) == LL_LPTIM_PRESCALER_DIV32) \
|| ((__VALUE__) == LL_LPTIM_PRESCALER_DIV64) \
|| ((__VALUE__) == LL_LPTIM_PRESCALER_DIV128))
#define IS_LL_LPTIM_WAVEFORM(__VALUE__) (((__VALUE__) == LL_LPTIM_OUTPUT_WAVEFORM_PWM) \
|| ((__VALUE__) == LL_LPTIM_OUTPUT_WAVEFORM_SETONCE))
#define IS_LL_LPTIM_OUTPUT_POLARITY(__VALUE__) (((__VALUE__) == LL_LPTIM_OUTPUT_POLARITY_REGULAR) \
|| ((__VALUE__) == LL_LPTIM_OUTPUT_POLARITY_INVERSE))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup LPTIM_Private_Functions LPTIM Private Functions
* @{
*/
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup LPTIM_LL_Exported_Functions
* @{
*/
/** @addtogroup LPTIM_LL_EF_Init
* @{
*/
/**
* @brief Set LPTIMx registers to their reset values.
* @param LPTIMx LP Timer instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: LPTIMx registers are de-initialized
* - ERROR: invalid LPTIMx instance
*/
ErrorStatus LL_LPTIM_DeInit(LPTIM_TypeDef *LPTIMx)
{
ErrorStatus result = SUCCESS;
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(LPTIMx));
if (LPTIMx == LPTIM1)
{
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_LPTIM1);
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_LPTIM1);
}
else
{
result = ERROR;
}
return result;
}
/**
* @brief Set each fields of the LPTIM_InitStruct structure to its default
* value.
* @param LPTIM_InitStruct pointer to a @ref LL_LPTIM_InitTypeDef structure
* @retval None
*/
void LL_LPTIM_StructInit(LL_LPTIM_InitTypeDef *LPTIM_InitStruct)
{
/* Set the default configuration */
LPTIM_InitStruct->ClockSource = LL_LPTIM_CLK_SOURCE_INTERNAL;
LPTIM_InitStruct->Prescaler = LL_LPTIM_PRESCALER_DIV1;
LPTIM_InitStruct->Waveform = LL_LPTIM_OUTPUT_WAVEFORM_PWM;
LPTIM_InitStruct->Polarity = LL_LPTIM_OUTPUT_POLARITY_REGULAR;
}
/**
* @brief Configure the LPTIMx peripheral according to the specified parameters.
* @note LL_LPTIM_Init can only be called when the LPTIM instance is disabled.
* @note LPTIMx can be disabled using unitary function @ref LL_LPTIM_Disable().
* @param LPTIMx LP Timer Instance
* @param LPTIM_InitStruct pointer to a @ref LL_LPTIM_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: LPTIMx instance has been initialized
* - ERROR: LPTIMx instance hasn't been initialized
*/
ErrorStatus LL_LPTIM_Init(LPTIM_TypeDef *LPTIMx, LL_LPTIM_InitTypeDef *LPTIM_InitStruct)
{
ErrorStatus result = SUCCESS;
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(LPTIMx));
assert_param(IS_LL_LPTIM_CLOCK_SOURCE(LPTIM_InitStruct->ClockSource));
assert_param(IS_LL_LPTIM_CLOCK_PRESCALER(LPTIM_InitStruct->Prescaler));
assert_param(IS_LL_LPTIM_WAVEFORM(LPTIM_InitStruct->Waveform));
assert_param(IS_LL_LPTIM_OUTPUT_POLARITY(LPTIM_InitStruct->Polarity));
/* The LPTIMx_CFGR register must only be modified when the LPTIM is disabled
(ENABLE bit is reset to 0).
*/
if (LL_LPTIM_IsEnabled(LPTIMx) == 1UL)
{
result = ERROR;
}
else
{
/* Set CKSEL bitfield according to ClockSource value */
/* Set PRESC bitfield according to Prescaler value */
/* Set WAVE bitfield according to Waveform value */
/* Set WAVEPOL bitfield according to Polarity value */
MODIFY_REG(LPTIMx->CFGR,
(LPTIM_CFGR_CKSEL | LPTIM_CFGR_PRESC | LPTIM_CFGR_WAVE | LPTIM_CFGR_WAVPOL),
LPTIM_InitStruct->ClockSource | \
LPTIM_InitStruct->Prescaler | \
LPTIM_InitStruct->Waveform | \
LPTIM_InitStruct->Polarity);
}
return result;
}
/**
* @}
*/
/**
* @}
*/
/**
* @brief Disable the LPTIM instance
* @rmtoll CR ENABLE LL_LPTIM_Disable
* @param LPTIMx Low-Power Timer instance
* @note The following sequence is required to solve LPTIM disable HW limitation.
* Please check Errata Sheet ES0335 for more details under "MCU may remain
* stuck in LPTIM interrupt when entering Stop mode" section.
* @retval None
*/
void LL_LPTIM_Disable(LPTIM_TypeDef *LPTIMx)
{
LL_RCC_ClocksTypeDef rcc_clock;
uint32_t tmpclksource = 0;
uint32_t tmpIER;
uint32_t tmpCFGR;
uint32_t tmpCMP;
uint32_t tmpARR;
uint32_t tmpOR;
/* Check the parameters */
assert_param(IS_LPTIM_INSTANCE(LPTIMx));
__disable_irq();
/********** Save LPTIM Config *********/
/* Save LPTIM source clock */
switch ((uint32_t)LPTIMx)
{
case LPTIM1_BASE:
tmpclksource = LL_RCC_GetLPTIMClockSource(LL_RCC_LPTIM1_CLKSOURCE);
break;
default:
break;
}
/* Save LPTIM configuration registers */
tmpIER = LPTIMx->IER;
tmpCFGR = LPTIMx->CFGR;
tmpCMP = LPTIMx->CMP;
tmpARR = LPTIMx->ARR;
tmpOR = LPTIMx->OR;
/************* Reset LPTIM ************/
(void)LL_LPTIM_DeInit(LPTIMx);
/********* Restore LPTIM Config *******/
LL_RCC_GetSystemClocksFreq(&rcc_clock);
if ((tmpCMP != 0UL) || (tmpARR != 0UL))
{
/* Force LPTIM source kernel clock from APB */
switch ((uint32_t)LPTIMx)
{
case LPTIM1_BASE:
LL_RCC_SetLPTIMClockSource(LL_RCC_LPTIM1_CLKSOURCE_PCLK1);
break;
default:
break;
}
if (tmpCMP != 0UL)
{
/* Restore CMP and ARR registers (LPTIM should be enabled first) */
LPTIMx->CR |= LPTIM_CR_ENABLE;
LPTIMx->CMP = tmpCMP;
/* Polling on CMP write ok status after above restore operation */
do
{
rcc_clock.SYSCLK_Frequency--; /* Used for timeout */
} while (((LL_LPTIM_IsActiveFlag_CMPOK(LPTIMx) != 1UL)) && ((rcc_clock.SYSCLK_Frequency) > 0UL));
LL_LPTIM_ClearFlag_CMPOK(LPTIMx);
}
if (tmpARR != 0UL)
{
LPTIMx->CR |= LPTIM_CR_ENABLE;
LPTIMx->ARR = tmpARR;
LL_RCC_GetSystemClocksFreq(&rcc_clock);
/* Polling on ARR write ok status after above restore operation */
do
{
rcc_clock.SYSCLK_Frequency--; /* Used for timeout */
} while (((LL_LPTIM_IsActiveFlag_ARROK(LPTIMx) != 1UL)) && ((rcc_clock.SYSCLK_Frequency) > 0UL));
LL_LPTIM_ClearFlag_ARROK(LPTIMx);
}
/* Restore LPTIM source kernel clock */
LL_RCC_SetLPTIMClockSource(tmpclksource);
}
/* Restore configuration registers (LPTIM should be disabled first) */
LPTIMx->CR &= ~(LPTIM_CR_ENABLE);
LPTIMx->IER = tmpIER;
LPTIMx->CFGR = tmpCFGR;
LPTIMx->OR = tmpOR;
__enable_irq();
}
/**
* @}
*/
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/131858.c
|
/*
* Copyright (c) 1996,1999 by Internet Software Consortium.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
* ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
* CONSORTIUM 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.
*/
#if !defined(_LIBC) && !defined(lint)
static const char rcsid[] = "$BINDId: ns_name.c,v 8.15 2000/03/30 22:53:46 vixie Exp $";
#endif
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <errno.h>
#include <resolv.h>
#include <string.h>
#include <ctype.h>
/* Data. */
static const char digits[] = "0123456789";
/* Forward. */
static int special(int);
static int printable(int);
static int dn_find(const u_char *, const u_char *,
const u_char * const *,
const u_char * const *);
/* Public. */
/*
* ns_name_ntop(src, dst, dstsiz)
* Convert an encoded domain name to printable ascii as per RFC1035.
* return:
* Number of bytes written to buffer, or -1 (with errno set)
* notes:
* The root is returned as "."
* All other domains are returned in non absolute form
*/
int
ns_name_ntop(const u_char *src, char *dst, size_t dstsiz) {
const u_char *cp;
char *dn, *eom;
u_char c;
u_int n;
cp = src;
dn = dst;
eom = dst + dstsiz;
while ((n = *cp++) != 0) {
if ((n & NS_CMPRSFLGS) != 0) {
/* Some kind of compression pointer. */
__set_errno (EMSGSIZE);
return (-1);
}
if (dn != dst) {
if (dn >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*dn++ = '.';
}
if (dn + n >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
for ((void)NULL; n > 0; n--) {
c = *cp++;
if (special(c)) {
if (dn + 1 >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*dn++ = '\\';
*dn++ = (char)c;
} else if (!printable(c)) {
if (dn + 3 >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*dn++ = '\\';
*dn++ = digits[c / 100];
*dn++ = digits[(c % 100) / 10];
*dn++ = digits[c % 10];
} else {
if (dn >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*dn++ = (char)c;
}
}
}
if (dn == dst) {
if (dn >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*dn++ = '.';
}
if (dn >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*dn++ = '\0';
return (dn - dst);
}
/*
* ns_name_pton(src, dst, dstsiz)
* Convert a ascii string into an encoded domain name as per RFC1035.
* return:
* -1 if it fails
* 1 if string was fully qualified
* 0 is string was not fully qualified
* notes:
* Enforces label and domain length limits.
*/
int
ns_name_pton(const char *src, u_char *dst, size_t dstsiz) {
u_char *label, *bp, *eom;
int c, n, escaped;
char *cp;
escaped = 0;
bp = dst;
eom = dst + dstsiz;
label = bp++;
while ((c = *src++) != 0) {
if (escaped) {
if ((cp = strchr(digits, c)) != NULL) {
n = (cp - digits) * 100;
if ((c = *src++) == 0 ||
(cp = strchr(digits, c)) == NULL) {
__set_errno (EMSGSIZE);
return (-1);
}
n += (cp - digits) * 10;
if ((c = *src++) == 0 ||
(cp = strchr(digits, c)) == NULL) {
__set_errno (EMSGSIZE);
return (-1);
}
n += (cp - digits);
if (n > 255) {
__set_errno (EMSGSIZE);
return (-1);
}
c = n;
}
escaped = 0;
} else if (c == '\\') {
escaped = 1;
continue;
} else if (c == '.') {
c = (bp - label - 1);
if ((c & NS_CMPRSFLGS) != 0) { /* Label too big. */
__set_errno (EMSGSIZE);
return (-1);
}
if (label >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*label = c;
/* Fully qualified ? */
if (*src == '\0') {
if (c != 0) {
if (bp >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*bp++ = '\0';
}
if ((bp - dst) > MAXCDNAME) {
__set_errno (EMSGSIZE);
return (-1);
}
return (1);
}
if (c == 0 || *src == '.') {
__set_errno (EMSGSIZE);
return (-1);
}
label = bp++;
continue;
}
if (bp >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*bp++ = (u_char)c;
}
c = (bp - label - 1);
if ((c & NS_CMPRSFLGS) != 0) { /* Label too big. */
__set_errno (EMSGSIZE);
return (-1);
}
if (label >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*label = c;
if (c != 0) {
if (bp >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*bp++ = 0;
}
if ((bp - dst) > MAXCDNAME) { /* src too big */
__set_errno (EMSGSIZE);
return (-1);
}
return (0);
}
/*
* ns_name_ntol(src, dst, dstsiz)
* Convert a network strings labels into all lowercase.
* return:
* Number of bytes written to buffer, or -1 (with errno set)
* notes:
* Enforces label and domain length limits.
*/
int
ns_name_ntol(const u_char *src, u_char *dst, size_t dstsiz) {
const u_char *cp;
u_char *dn, *eom;
u_char c;
u_int n;
cp = src;
dn = dst;
eom = dst + dstsiz;
while ((n = *cp++) != 0) {
if ((n & NS_CMPRSFLGS) != 0) {
/* Some kind of compression pointer. */
__set_errno (EMSGSIZE);
return (-1);
}
*dn++ = n;
if (dn + n >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
for ((void)NULL; n > 0; n--) {
c = *cp++;
if (isupper(c))
*dn++ = tolower(c);
else
*dn++ = c;
}
}
*dn++ = '\0';
return (dn - dst);
}
/*
* ns_name_unpack(msg, eom, src, dst, dstsiz)
* Unpack a domain name from a message, source may be compressed.
* return:
* -1 if it fails, or consumed octets if it succeeds.
*/
int
ns_name_unpack(const u_char *msg, const u_char *eom, const u_char *src,
u_char *dst, size_t dstsiz)
{
const u_char *srcp, *dstlim;
u_char *dstp;
int n, len, checked;
len = -1;
checked = 0;
dstp = dst;
srcp = src;
dstlim = dst + dstsiz;
if (srcp < msg || srcp >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
/* Fetch next label in domain name. */
while ((n = *srcp++) != 0) {
/* Check for indirection. */
switch (n & NS_CMPRSFLGS) {
case 0:
/* Limit checks. */
if (dstp + n + 1 >= dstlim || srcp + n >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
checked += n + 1;
*dstp++ = n;
memcpy(dstp, srcp, n);
dstp += n;
srcp += n;
break;
case NS_CMPRSFLGS:
if (srcp >= eom) {
__set_errno (EMSGSIZE);
return (-1);
}
if (len < 0)
len = srcp - src + 1;
srcp = msg + (((n & 0x3f) << 8) | (*srcp & 0xff));
if (srcp < msg || srcp >= eom) { /* Out of range. */
__set_errno (EMSGSIZE);
return (-1);
}
checked += 2;
/*
* Check for loops in the compressed name;
* if we've looked at the whole message,
* there must be a loop.
*/
if (checked >= eom - msg) {
__set_errno (EMSGSIZE);
return (-1);
}
break;
default:
__set_errno (EMSGSIZE);
return (-1); /* flag error */
}
}
*dstp = '\0';
if (len < 0)
len = srcp - src;
return (len);
}
/*
* ns_name_pack(src, dst, dstsiz, dnptrs, lastdnptr)
* Pack domain name 'domain' into 'comp_dn'.
* return:
* Size of the compressed name, or -1.
* notes:
* 'dnptrs' is an array of pointers to previous compressed names.
* dnptrs[0] is a pointer to the beginning of the message. The array
* ends with NULL.
* 'lastdnptr' is a pointer to the end of the array pointed to
* by 'dnptrs'.
* Side effects:
* The list of pointers in dnptrs is updated for labels inserted into
* the message as we compress the name. If 'dnptr' is NULL, we don't
* try to compress names. If 'lastdnptr' is NULL, we don't update the
* list.
*/
int
ns_name_pack(const u_char *src, u_char *dst, int dstsiz,
const u_char **dnptrs, const u_char **lastdnptr)
{
u_char *dstp;
const u_char **cpp, **lpp, *eob, *msg;
const u_char *srcp;
int n, l, first = 1;
srcp = src;
dstp = dst;
eob = dstp + dstsiz;
lpp = cpp = NULL;
if (dnptrs != NULL) {
if ((msg = *dnptrs++) != NULL) {
for (cpp = dnptrs; *cpp != NULL; cpp++)
(void)NULL;
lpp = cpp; /* end of list to search */
}
} else
msg = NULL;
/* make sure the domain we are about to add is legal */
l = 0;
do {
n = *srcp;
if ((n & NS_CMPRSFLGS) != 0) {
__set_errno (EMSGSIZE);
return (-1);
}
l += n + 1;
if (l > MAXCDNAME) {
__set_errno (EMSGSIZE);
return (-1);
}
srcp += n + 1;
} while (n != 0);
/* from here on we need to reset compression pointer array on error */
srcp = src;
do {
/* Look to see if we can use pointers. */
n = *srcp;
if (n != 0 && msg != NULL) {
l = dn_find(srcp, msg, (const u_char * const *)dnptrs,
(const u_char * const *)lpp);
if (l >= 0) {
if (dstp + 1 >= eob) {
goto cleanup;
}
*dstp++ = (l >> 8) | NS_CMPRSFLGS;
*dstp++ = l % 256;
return (dstp - dst);
}
/* Not found, save it. */
if (lastdnptr != NULL && cpp < lastdnptr - 1 &&
(dstp - msg) < 0x4000 && first) {
*cpp++ = dstp;
*cpp = NULL;
first = 0;
}
}
/* copy label to buffer */
if (n & NS_CMPRSFLGS) { /* Should not happen. */
goto cleanup;
}
if (dstp + 1 + n >= eob) {
goto cleanup;
}
memcpy(dstp, srcp, n + 1);
srcp += n + 1;
dstp += n + 1;
} while (n != 0);
if (dstp > eob) {
cleanup:
if (msg != NULL)
*lpp = NULL;
__set_errno (EMSGSIZE);
return (-1);
}
return (dstp - dst);
}
/*
* ns_name_uncompress(msg, eom, src, dst, dstsiz)
* Expand compressed domain name to presentation format.
* return:
* Number of bytes read out of `src', or -1 (with errno set).
* note:
* Root domain returns as "." not "".
*/
int
ns_name_uncompress(const u_char *msg, const u_char *eom, const u_char *src,
char *dst, size_t dstsiz)
{
u_char tmp[NS_MAXCDNAME];
int n;
if ((n = ns_name_unpack(msg, eom, src, tmp, sizeof tmp)) == -1)
return (-1);
if (ns_name_ntop(tmp, dst, dstsiz) == -1)
return (-1);
return (n);
}
/*
* ns_name_compress(src, dst, dstsiz, dnptrs, lastdnptr)
* Compress a domain name into wire format, using compression pointers.
* return:
* Number of bytes consumed in `dst' or -1 (with errno set).
* notes:
* 'dnptrs' is an array of pointers to previous compressed names.
* dnptrs[0] is a pointer to the beginning of the message.
* The list ends with NULL. 'lastdnptr' is a pointer to the end of the
* array pointed to by 'dnptrs'. Side effect is to update the list of
* pointers for labels inserted into the message as we compress the name.
* If 'dnptr' is NULL, we don't try to compress names. If 'lastdnptr'
* is NULL, we don't update the list.
*/
int
ns_name_compress(const char *src, u_char *dst, size_t dstsiz,
const u_char **dnptrs, const u_char **lastdnptr)
{
u_char tmp[NS_MAXCDNAME];
if (ns_name_pton(src, tmp, sizeof tmp) == -1)
return (-1);
return (ns_name_pack(tmp, dst, dstsiz, dnptrs, lastdnptr));
}
/*
* Reset dnptrs so that there are no active references to pointers at or
* after src.
*/
void
ns_name_rollback(const u_char *src, const u_char **dnptrs,
const u_char **lastdnptr)
{
while (dnptrs < lastdnptr && *dnptrs != NULL) {
if (*dnptrs >= src) {
*dnptrs = NULL;
break;
}
dnptrs++;
}
}
/*
* ns_name_skip(ptrptr, eom)
* Advance *ptrptr to skip over the compressed name it points at.
* return:
* 0 on success, -1 (with errno set) on failure.
*/
int
ns_name_skip(const u_char **ptrptr, const u_char *eom) {
const u_char *cp;
u_int n;
cp = *ptrptr;
while (cp < eom && (n = *cp++) != 0) {
/* Check for indirection. */
switch (n & NS_CMPRSFLGS) {
case 0: /* normal case, n == len */
cp += n;
continue;
case NS_CMPRSFLGS: /* indirection */
cp++;
break;
default: /* illegal type */
__set_errno (EMSGSIZE);
return (-1);
}
break;
}
if (cp > eom) {
__set_errno (EMSGSIZE);
return (-1);
}
*ptrptr = cp;
return (0);
}
/* Private. */
/*
* special(ch)
* Thinking in noninternationalized USASCII (per the DNS spec),
* is this characted special ("in need of quoting") ?
* return:
* boolean.
*/
static int
special(int ch) {
switch (ch) {
case 0x22: /* '"' */
case 0x2E: /* '.' */
case 0x3B: /* ';' */
case 0x5C: /* '\\' */
/* Special modifiers in zone files. */
case 0x40: /* '@' */
case 0x24: /* '$' */
return (1);
default:
return (0);
}
}
/*
* printable(ch)
* Thinking in noninternationalized USASCII (per the DNS spec),
* is this character visible and not a space when printed ?
* return:
* boolean.
*/
static int
printable(int ch) {
return (ch > 0x20 && ch < 0x7f);
}
/*
* Thinking in noninternationalized USASCII (per the DNS spec),
* convert this character to lower case if it's upper case.
*/
static int
mklower(int ch) {
if (ch >= 0x41 && ch <= 0x5A)
return (ch + 0x20);
return (ch);
}
/*
* dn_find(domain, msg, dnptrs, lastdnptr)
* Search for the counted-label name in an array of compressed names.
* return:
* offset from msg if found, or -1.
* notes:
* dnptrs is the pointer to the first name on the list,
* not the pointer to the start of the message.
*/
static int
dn_find(const u_char *domain, const u_char *msg,
const u_char * const *dnptrs,
const u_char * const *lastdnptr)
{
const u_char *dn, *cp, *sp;
const u_char * const *cpp;
u_int n;
for (cpp = dnptrs; cpp < lastdnptr; cpp++) {
sp = *cpp;
/*
* terminate search on:
* root label
* compression pointer
* unusable offset
*/
while (*sp != 0 && (*sp & NS_CMPRSFLGS) == 0 &&
(sp - msg) < 0x4000) {
dn = domain;
cp = sp;
while ((n = *cp++) != 0) {
/*
* check for indirection
*/
switch (n & NS_CMPRSFLGS) {
case 0: /* normal case, n == len */
if (n != *dn++)
goto next;
for ((void)NULL; n > 0; n--)
if (mklower(*dn++) !=
mklower(*cp++))
goto next;
/* Is next root for both ? */
if (*dn == '\0' && *cp == '\0')
return (sp - msg);
if (*dn)
continue;
goto next;
case NS_CMPRSFLGS: /* indirection */
cp = msg + (((n & 0x3f) << 8) | *cp);
break;
default: /* illegal type */
__set_errno (EMSGSIZE);
return (-1);
}
}
next:
sp += *sp + 1;
}
}
__set_errno (ENOENT);
return (-1);
}
|
the_stack_data/1188989.c
|
/* f2c.h -- Standard Fortran to C header file */
/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed."
- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
#ifndef F2C_INCLUDE
#define F2C_INCLUDE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimag(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static integer c__1 = 1;
/* > \brief \b CGTCON */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download CGTCON + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/cgtcon.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/cgtcon.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/cgtcon.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE CGTCON( NORM, N, DL, D, DU, DU2, IPIV, ANORM, RCOND, */
/* WORK, INFO ) */
/* CHARACTER NORM */
/* INTEGER INFO, N */
/* REAL ANORM, RCOND */
/* INTEGER IPIV( * ) */
/* COMPLEX D( * ), DL( * ), DU( * ), DU2( * ), WORK( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > CGTCON estimates the reciprocal of the condition number of a complex */
/* > tridiagonal matrix A using the LU factorization as computed by */
/* > CGTTRF. */
/* > */
/* > An estimate is obtained for norm(inv(A)), and the reciprocal of the */
/* > condition number is computed as RCOND = 1 / (ANORM * norm(inv(A))). */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] NORM */
/* > \verbatim */
/* > NORM is CHARACTER*1 */
/* > Specifies whether the 1-norm condition number or the */
/* > infinity-norm condition number is required: */
/* > = '1' or 'O': 1-norm; */
/* > = 'I': Infinity-norm. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The order of the matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] DL */
/* > \verbatim */
/* > DL is COMPLEX array, dimension (N-1) */
/* > The (n-1) multipliers that define the matrix L from the */
/* > LU factorization of A as computed by CGTTRF. */
/* > \endverbatim */
/* > */
/* > \param[in] D */
/* > \verbatim */
/* > D is COMPLEX array, dimension (N) */
/* > The n diagonal elements of the upper triangular matrix U from */
/* > the LU factorization of A. */
/* > \endverbatim */
/* > */
/* > \param[in] DU */
/* > \verbatim */
/* > DU is COMPLEX array, dimension (N-1) */
/* > The (n-1) elements of the first superdiagonal of U. */
/* > \endverbatim */
/* > */
/* > \param[in] DU2 */
/* > \verbatim */
/* > DU2 is COMPLEX array, dimension (N-2) */
/* > The (n-2) elements of the second superdiagonal of U. */
/* > \endverbatim */
/* > */
/* > \param[in] IPIV */
/* > \verbatim */
/* > IPIV is INTEGER array, dimension (N) */
/* > The pivot indices; for 1 <= i <= n, row i of the matrix was */
/* > interchanged with row IPIV(i). IPIV(i) will always be either */
/* > i or i+1; IPIV(i) = i indicates a row interchange was not */
/* > required. */
/* > \endverbatim */
/* > */
/* > \param[in] ANORM */
/* > \verbatim */
/* > ANORM is REAL */
/* > If NORM = '1' or 'O', the 1-norm of the original matrix A. */
/* > If NORM = 'I', the infinity-norm of the original matrix A. */
/* > \endverbatim */
/* > */
/* > \param[out] RCOND */
/* > \verbatim */
/* > RCOND is REAL */
/* > The reciprocal of the condition number of the matrix A, */
/* > computed as RCOND = 1/(ANORM * AINVNM), where AINVNM is an */
/* > estimate of the 1-norm of inv(A) computed in this routine. */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is COMPLEX array, dimension (2*N) */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument had an illegal value */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup complexGTcomputational */
/* ===================================================================== */
/* Subroutine */ int cgtcon_(char *norm, integer *n, complex *dl, complex *
d__, complex *du, complex *du2, integer *ipiv, real *anorm, real *
rcond, complex *work, integer *info)
{
/* System generated locals */
integer i__1, i__2;
/* Local variables */
integer kase, kase1, i__;
extern logical lsame_(char *, char *);
integer isave[3];
extern /* Subroutine */ int clacn2_(integer *, complex *, complex *, real
*, integer *, integer *), xerbla_(char *, integer *, ftnlen);
real ainvnm;
logical onenrm;
extern /* Subroutine */ int cgttrs_(char *, integer *, integer *, complex
*, complex *, complex *, complex *, integer *, complex *, integer
*, integer *);
/* -- LAPACK computational routine (version 3.7.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* December 2016 */
/* ===================================================================== */
/* Test the input arguments. */
/* Parameter adjustments */
--work;
--ipiv;
--du2;
--du;
--d__;
--dl;
/* Function Body */
*info = 0;
onenrm = *(unsigned char *)norm == '1' || lsame_(norm, "O");
if (! onenrm && ! lsame_(norm, "I")) {
*info = -1;
} else if (*n < 0) {
*info = -2;
} else if (*anorm < 0.f) {
*info = -8;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("CGTCON", &i__1, (ftnlen)6);
return 0;
}
/* Quick return if possible */
*rcond = 0.f;
if (*n == 0) {
*rcond = 1.f;
return 0;
} else if (*anorm == 0.f) {
return 0;
}
/* Check that D(1:N) is non-zero. */
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
i__2 = i__;
if (d__[i__2].r == 0.f && d__[i__2].i == 0.f) {
return 0;
}
/* L10: */
}
ainvnm = 0.f;
if (onenrm) {
kase1 = 1;
} else {
kase1 = 2;
}
kase = 0;
L20:
clacn2_(n, &work[*n + 1], &work[1], &ainvnm, &kase, isave);
if (kase != 0) {
if (kase == kase1) {
/* Multiply by inv(U)*inv(L). */
cgttrs_("No transpose", n, &c__1, &dl[1], &d__[1], &du[1], &du2[1]
, &ipiv[1], &work[1], n, info);
} else {
/* Multiply by inv(L**H)*inv(U**H). */
cgttrs_("Conjugate transpose", n, &c__1, &dl[1], &d__[1], &du[1],
&du2[1], &ipiv[1], &work[1], n, info);
}
goto L20;
}
/* Compute the estimate of the reciprocal condition number. */
if (ainvnm != 0.f) {
*rcond = 1.f / ainvnm / *anorm;
}
return 0;
/* End of CGTCON */
} /* cgtcon_ */
|
the_stack_data/8524.c
|
// RUN: %clang_cc1 -triple nvptx-unknown-unknown -target-cpu sm_20 -O3 -S -o %t %s -emit-llvm
// RUN: %clang_cc1 -triple nvptx-unknown-unknown -target-cpu sm_21 -O3 -S -o %t %s -emit-llvm
// RUN: %clang_cc1 -triple nvptx-unknown-unknown -target-cpu sm_30 -O3 -S -o %t %s -emit-llvm
// RUN: %clang_cc1 -triple nvptx-unknown-unknown -target-cpu sm_35 -O3 -S -o %t %s -emit-llvm
// RUN: %clang_cc1 -triple nvptx-unknown-unknown -target-cpu sm_37 -O3 -S -o %t %s -emit-llvm
// RUN: %clang_cc1 -triple nvptx-unknown-unknown -target-cpu sm_50 -O3 -S -o %t %s -emit-llvm
// RUN: %clang_cc1 -triple nvptx-unknown-unknown -target-cpu sm_52 -O3 -S -o %t %s -emit-llvm
// RUN: %clang_cc1 -triple nvptx-unknown-unknown -target-cpu sm_53 -O3 -S -o %t %s -emit-llvm
// Make sure clang accepts all supported architectures.
void foo(float* a,
float* b) {
a[0] = b[0];
}
|
the_stack_data/895202.c
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m,n,i,j,o,r,p,k;
printf("Enter the dimensions of matrix 1\n");
scanf("%d%d",&m,&n);
int a[m][n];
printf("Enter the elements\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
printf("Enter the dimensions of matrix 2\n");
scanf("%d%d",&o,&p);
int b[o][p];
printf("Enter the elements\n");
for(i=0;i<o;i++)
{
for(j=0;j<p;j++)
scanf("%d",&b[i][j]);
}
if(n!=o)
{
printf("Multiplication not possible");
exit(0);
}
int c[m][p];
for(i=0;i<m;i++)
{
int r=0;
for(j=0;j<p;j++)
{
c[i][r]=0;
for(k=0;k<n;k++)
c[i][r]=c[i][r]+a[i][k]*b[k][j];
r++;
}
}
printf("The multiplication of the two matrices is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<p;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
return 0;
}
|
the_stack_data/248580852.c
|
#if 0
#ifdef STM32F0xx
#include "stm32f0xx_hal_msp_template.c"
#endif
#ifdef STM32F1xx
#include "stm32f1xx_hal_msp_template.c"
#endif
#ifdef STM32F2xx
#include "stm32f2xx_hal_msp_template.c"
#endif
#ifdef STM32F3xx
#include "stm32f3xx_hal_msp_template.c"
#endif
#ifdef STM32F4xx
#include "stm32f4xx_hal_msp_template.c"
#endif
#ifdef STM32F7xx
#include "stm32f7xx_hal_msp_template.c"
#endif
#ifdef STM32G0xx
#include "stm32g0xx_hal_msp_template.c"
#endif
#ifdef STM32G4xx
#include "stm32g4xx_hal_msp_template.c"
#endif
#ifdef STM32H7xx
#include "stm32h7xx_hal_msp_template.c"
#endif
#ifdef STM32L0xx
#include "stm32l0xx_hal_msp_template.c"
#endif
#ifdef STM32L1xx
#include "stm32l1xx_hal_msp_template.c"
#endif
#ifdef STM32L4xx
#include "stm32l4xx_hal_msp_template.c"
#endif
#ifdef STM32WBxx
#include "stm32wbxx_hal_msp_template.c"
#endif
#endif /* 0 */
|
the_stack_data/20451353.c
|
// code: 0
int main() { return ~1 + 2; }
|
the_stack_data/61075729.c
|
#include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULL;
typedef long long LL;
void ULLdivULL(ULL a, ULL b, ULL *qp, ULL *rp)
{
ULL r = 0, q = 0;
int i;
for (i = 0; i < 64; i++) {
r = (r << 1) + (a >> 63);
a <<= 1;
q <<= 1;
if (r >= b) {
r -= b;
q += 1;
}
}
if (qp) *qp = q;
if (rp) *rp = r;
}
void LLdivLL(LL a, LL b, LL *qp, LL *rp)
{
int qf = 0, rf = 0;
if (a < 0) { qf = rf = 1; a = -a; }
if (b < 0) { qf ^= 1; b = -b; }
ULLdivULL(a, b, (ULL *) qp, (ULL *) rp);
if (qp && qf) *qp = -*qp;
if (rp && rf) *rp = -*rp;
}
/* test data */
LL data[] = {
0, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29
-1, -2, -3, -5, -7, -11, -13, -17, -19, -23, -29,
20, 30, 50,
-20, -30, -50,
0x7ffffffffffffffa, 0x7ffffffffffffffb,
0x7ffffffffffffffc, 0x7ffffffffffffffd,
0x7ffffffffffffffe, 0x7fffffffffffffff,
0x8000000000000000, 0x8000000000000001,
0x8000000000000002, 0x8000000000000003,
0x8000000000000004, 0x8000000000000005,
0x6631a3c5992d428b, 0x3a6ac5ed24cb0563,
0x2fa099392715ddf4, 0x434c1488ec806d82,
0xf8a9e478877a4107, 0x17f95918e3c2dad4,
0x9dc1dadd05fe03c5, 0x4660525725384aa2,
0x91a4716950c8f9b7, 0x7d85a9cbf5371f84,
0x0f49b3ddf4f1e168, 0xbae686f31cfb42e0,
0xe3665b91bc16d67e, 0xd808a3ba85fdacbd,
0x2865e0d75a01f456, 0x292d75ea6fb0e5e8,
0x36fd4f379934ed15, 0xff8f2d6ea26d7db4,
0xf9035c37627d8250, 0x87d18d6b2d3cf3ca,
};
int data_size = sizeof(data) / sizeof(data[0]);
/* test function */
#define MAKE_TEST_FUNC(TYPE, FMT) \
void test_ ## TYPE() \
{ \
TYPE a, b; \
TYPE q, r; \
TYPE qans, rans; \
int i, j; \
for (i = 0; i < data_size; i++) \
for (j = 0; j < data_size; j++) { \
a = data[i]; \
b = data[j]; \
if (b == 0) continue; \
qans = a / b; \
rans = a % b; \
TYPE ## div ## TYPE (a, b, &q, &r); \
if (q != qans || r != rans) { \
puts(#TYPE " ERROR"); \
printf(FMT " div " FMT "\n", a, b); \
printf(FMT " " FMT "\n", q, r); \
printf(FMT " " FMT "\n", qans, rans); \
exit(1); \
} \
} \
}
MAKE_TEST_FUNC(LL, "%lld")
MAKE_TEST_FUNC(ULL, "%llu")
int main()
{
test_LL();
test_ULL();
puts("TEST OK");
exit(0);
}
|
the_stack_data/111078620.c
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char palavra[50];
int c, tam, j, i, interador = 1;
char **aux = (char **)malloc(sizeof(char *));
aux[0] = (char *)malloc(sizeof(char));
if (aux[0] == NULL) {
printf("Erro\n");
free(aux[0]);
free(aux);
return 0;
}
c = 0;
j = 0;
while (scanf(" %s", palavra) != EOF) {
tam = strlen(palavra);
aux = (char **)realloc(aux, (c + 1) * sizeof(char *));
aux[j] = (char *)realloc(aux[j], tam * sizeof(char));
if (aux[j] == NULL) {
printf("Erro ao Realocar\n");
for (i = j; i <= 0; i--) {
free(aux[i]);
}
free(aux);
return 0;
}
strcpy(aux[j], palavra);
c++;
j++;
}
while (c != 0) {
printf("Plavra na posicao %d = %s\n", interador, aux[interador - 1]);
free(aux[interador - 1]);
c--;
interador++;
}
free(aux);
return 0;
}
|
the_stack_data/173577976.c
|
#include <stdio.h>
int main() {
int i, n;
float arr[100];
printf("Enter the number of elements (1 to 100): ");
scanf("%d", &n);
for (i = 0; i < n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%f", &arr[i]);
}
for (i = 1; i < n; ++i) {
if (arr[0] < arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);
return 0;
}
|
the_stack_data/146356.c
|
#include <math.h>
#include <stdint.h>
#include <stdio.h>
int16_t is_prime(int32_t n) {
int32_t i;
if (n == 2) {
return 1;
}
if (n % 2 == 0 || n < 2) {
return 0;
}
for (i = 3; i <= sqrt(n); i += 2) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int32_t n;
scanf("%ld", &n);
if (is_prime(n)) {
printf("sim");
} else {
printf("nao");
}
return 0;
}
|
the_stack_data/875744.c
|
#include <stdio.h>
#include <string.h>
int main(){
int len = 3;
char ch[len][len];
char (*p)[len] = ch;
int i,j;
printf("input: ");
scanf("%s",(*p));
for(i=0;i<len;i++){
for(j=0;j<len;j++){
printf("%c ", *(*(ch + i)+j) );
}
putchar('\n');
}
return 0;
}
|
the_stack_data/68229.c
|
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
int main() {
char host[256] = "--------------------------";
printf("gethostid: %d\n", gethostid());
printf("errno: %d\n\n", errno);
errno = 0;
printf("gethostname/2 ret: %d\n", gethostname(host, 2));
printf("gethostname/2: %s\n", host);
printf("errno: %d\n\n", errno);
errno = 0;
printf("gethostname/256 ret: %d\n", gethostname(host, 256));
printf("gethostname/256: %s\n", host);
printf("errno: %d\n\n", errno);
errno = 0;
char login[256] = "--------------------------";
printf("login: %s\n", getlogin());
printf("errno: %d\n\n", errno);
errno = 0;
printf("login_r/2 ret: %d\n", getlogin_r(login, 2));
printf("login_r/2: %s\n", login);
printf("errno: %d\n\n", errno);
errno = 0;
printf("login_r/256 ret: %d\n", getlogin_r(login, 256));
printf("login_r/256: %s\n", login);
printf("errno: %d\n", errno);
errno = 0;
return 0;
}
|
the_stack_data/181156.c
|
#include <stdio.h>
enum RoomType {Economy=1, Business, Executive, Deluxe};
double GetPayment(short stay, enum RoomType room)
{
double payment = 0;
float rate = 0;
switch(room)
{
case Economy:
rate = 850;
break;
case Business:
rate = 950;
break;
case Executive:
rate = 1200;
break;
default:
rate = 1500;
}
payment = stay * rate * 1.12;
return payment;
}
int main(void)
{
short days;
printf("Number of days: ");
scanf("%hd", &days);
printf("Payment for Economy = %.2lf\n", GetPayment(days, Economy));
printf("Payment for Business = %.2lf\n", GetPayment(days, Business));
printf("Payment for Executive = %.2lf\n", GetPayment(days, Executive));
printf("Payment for Deluxe = %.2lf\n", GetPayment(days, Deluxe));
}
|
the_stack_data/45450563.c
|
/*
* Copyright (c) 2016-present, Programming Research Laboratory (ROPAS)
* Seoul National University, Korea
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
void nested_loop() {
int i, j;
char a[10];
for (i = 0; i < 10; i++) {
a[i] = 'a'; /* SAFE */
for (j = 0; j <= 10; j++) {
a[j] = 'a'; /* BUG */
}
}
}
void nested_loop2_Ok() {
double arr[10];
int i, j;
for (i = 0; i < 10; i++) {
for (j = 5; j < 15; j++) {
arr[i] = 0.0;
arr[j - 5] = 0.0;
}
}
}
void nested_loop3_Bad() {
double arr[10];
int i, j;
for (i = 0; i <= 10; i++) {
for (j = 5; j < 15; j++) {
arr[i] = 0.0;
}
}
}
void nested_loop4_Bad() {
double arr[10];
int i, j;
for (i = 0; i < 10; i++) {
for (j = 5; j <= 15; j++) {
arr[j - 5] = 0.0;
}
}
}
|
the_stack_data/623207.c
|
//Alquimia é uma prática que combina elementos da Química, Física, Biologia, Medicina, Semiótica, Misticismo, Espiritualismo, Arte, Antropologia, Astrologia, Filosofia, Metalurgia e Matemática.
#include <stdio.h>
int main(){
float altura, peso;
int idade, ano, dia;
printf("diga sua peso: ");
scanf("%f", &peso);
printf("diga sua altura: ");
scanf("%f", &altura);
printf("diga sua idade: ");
scanf("%d", &idade);
printf("diga o ano de seu nascimento: ");
scanf("%d", &ano);
printf("diga o dia do seu nascimento: ");
scanf("%d", &dia);
float numero = (((peso + altura)/idade) + ano) * dia;
printf("%f", numero);
return 0;
}
|
the_stack_data/178265298.c
|
#include <stdio.h>
#include <math.h>
double f(double x)
{
return 1/x;
}
int main()
{
int N;
double a,b;
printf("Enter a lower bound: ");
scanf("%lf", &a);
printf("Enter an upper bound: ");
scanf("%lf", &b);
printf("Enter a number: ");
scanf("%d", &N);
double h[N], R[N][N];
for (int i = 0; i < N + 1; ++i)
{
h[i] = (b - a) / pow(2, i);
}
R[0][0] = (h[0] / 2) * (f(a) + f(b));
for (int i = 1; i < N + 1; ++i)
{
double sum = 0;
for (int k = 1; k <= pow(2, i - 1); ++k)
{
sum += f(a + (2 * k -1) * h[i]);
}
R[i][0] = 0.5 * R[i - 1][0] + h[i] * sum;
}
for (int i = 1; i < N + 1; ++i)
{
for (int j = 1; j <= i; ++j)
{
R[i][j] = R[i][j - 1] + (R[i][j-1] - R[i-1][j-1]) / (pow(4,j) - 1);
}
}
printf("Result: %lf", R[N][N]);
}
|
the_stack_data/181394439.c
|
#include <stdio.h>
#define N 10 //row 行
#define M 5 //column 列
float mark[N][M]; //全局数组
float aver_stu[N], aver_cour[M]; // aver_stu 来存放每个学生的平均成绩 aver_cour 来存放每门课的平均成绩
int r, c; // 最高分的行标 r, c 列标
int main(void)
{
int i, j;
void input(void); //输入数据
void stuAver(void); //学生平均成绩
void courAver(void); //课程平均成绩
float highest(); // 最高分
float var(void); // 方差 variance
input();
stuAver();
courAver();
printf("\n 编号 课程1 课程2 课程3 课程4 课程5 平均分\n");
for (i = 0; i < N; i++)
{
printf("\n NO %2d", i + 1);
for (j = 0; j < M; j++)
{
printf("%8.2f", mark[i][j]);
}
printf("%8.2f", aver_stu[i]);
}
printf("\n");
//输出课程平均分
printf("课程平均分:\n");
for (j = 0; j < M; j++)
{
printf("%8.2f", aver_cour[j]);
}
printf("\n");
// 求最高分
float h;
h = highest();
printf("最高分为 %8.2f, NO %2d 课程号 %2d\n", h, r, c);
printf("方差为 %8.2f\n", var());
return 0;
}
void input(void) //输入函数
{
int i, j;
for (i = 0; i < N; i++)
{
printf("\n请输入第 %d 位同学的成绩:\n", i + 1);
for (j = 0; j < M; j++)
{
scanf("%f", &mark[i][j]);
}
}
}
void stuAver(void) // 计算平均成绩
{
int i, j;
float sum;
for (i = 0; i < N; i++)
{
for (j = 0, sum = 0; j < M; j++) // sum = 0 关键 外层循环一遍 sum 重新赋值
{
sum = sum + mark[i][j];
}
aver_stu[i] = sum / 5.0; //计算完一行后求平均值
}
}
void courAver(void) // 课程平均成绩函数
{
int i, j;
float sum;
for (j = 0; j < M; j++)
{
sum = 0;
for (i = 0; i < N; i++)
{
sum = sum + mark[i][j];
}
aver_cour[j] = sum / 10.0;
}
}
float highest()
{
int i, j;
float high = mark[0][0];
for (i = 0; i < N; i++)
{
for (j = 0; j < M; j++)
{
if (mark[i][j] > high)
{
high = mark[i][j];
r = i + 1;
c = j + 1;
}
}
}
return high;
}
float var(void)
{
int i;
float var, sumx = 0.0, sumxn = 0.0;
for (i = 0; i < N; i++)
{
sumx = sumx + aver_stu[i] * aver_stu[i];
sumxn = sumxn + aver_stu[i];
}
var = sumx / N - (sumxn / N) * (sumxn / N);
return var;
}
|
the_stack_data/25335.c
|
/*
Autor: anaramos
Compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Compilado: gcc -o Problema1.out Problema1.c
Fecha: 05/07/22
Librerías: stdio
Resumen: programa que ordena un vector de forma ascendente o descendente, según lo indique el usuario
*/
//Librerías
#include <stdio.h>
//prototipo de funciones
void imprimira(int datos[]); // funcion para imprimir los datos de forma ascendente
void imprimird(int datos[]); // funcion para imprimir los datos de forma descendente
int main(){
//declaracion de variables
int nums[10];
char op;
//inicializacion de vector
for (int i = 0; i < 10; i++)
{
//se llena el vector solo con numeros pares del 2 al 20
nums[i]=2+2*i;
}
//se muestra al usuario el menú
puts("**Menú**");
printf("a Mostrar vector en orden ascendente\nd Mostrar vector en orden descendente\nx salir\n");
//se le solicita al usuario la opción
printf("ingrese una opcion: ");
//se guarda la opcion solicitada por el usuario en la variable op
scanf("%c", &op);
//ciclo para que el programa no termine hasta que el usuario ingrese la opcion de salir
while (op!='x')
{
//casos del menu
switch (op)
{
case 'a':
puts("vector ascendente");
//se imprime el vector con la funcion ascendente
imprimira(nums);
//se guarda la opcion solicitada por el usuario en la variable op
scanf("%c", &op);
break;
case 'd':
puts("vector descendente");
//se imprime el vector con la funcion descendente
imprimird(nums);
scanf("%c", &op);
break;
case 'x':
puts("Salida exitosa");
break;
default:
puts("Ingrese otra opcion");
scanf("%c", &op);
break;
}
}
}
void imprimira(int datos[]){
for (int i = 0; i < 10; i++)
{
//se imprimen los datos del vector
printf("%d ",datos[i]);
}
puts("\n");
}
void imprimird(int datos[]){
for (int i = 9; i >= 0; i--)
{
//se imprimen los datos del vector
printf("%d ",datos[i]);
}
puts("\n");
}
|
the_stack_data/132953379.c
|
#ifndef NULL
#define NULL ((void *) 0)
#endif
/* This is part of the shared library ld test. This file becomes part
of a shared library. */
/* This variable is supplied by the main program. */
#ifndef XCOFF_TEST
extern int mainvar;
#endif
/* This variable is defined in the shared library, and overridden by
the main program. */
#ifndef XCOFF_TEST
int overriddenvar = -1;
#endif
/* This variable is defined in the shared library. */
int shlibvar1 = 3;
/* This variable is defined by another object in the shared library. */
extern int shlibvar2;
/* These functions return the values of the above variables as seen in
the shared library. */
#ifndef XCOFF_TEST
int
shlib_mainvar ()
{
return mainvar;
}
#endif
#ifndef XCOFF_TEST
int
shlib_overriddenvar ()
{
return overriddenvar;
}
#endif
int
shlib_shlibvar1 ()
{
return shlibvar1;
}
int
shlib_shlibvar2 ()
{
return shlibvar2;
}
/* This function calls a function defined by another object in the
shared library. */
extern int shlib_shlibcalled ();
int
shlib_shlibcall ()
{
return shlib_shlibcalled ();
}
#ifndef XCOFF_TEST
/* This function calls a function defined in this object in the shared
library. The main program will override the called function. */
extern int shlib_overriddencall2 ();
int
shlib_shlibcall2 ()
{
return shlib_overriddencall2 ();
}
int
shlib_overriddencall2 ()
{
return 7;
}
#endif
/* This function calls a function defined by the main program. */
#ifndef XCOFF_TEST
extern int main_called ();
int
shlib_maincall ()
{
return main_called ();
}
#endif
/* This function is passed a function pointer to shlib_mainvar. It
confirms that the pointer compares equally. */
int
shlib_checkfunptr1 (p)
int (*p) ();
{
return p == shlib_shlibvar1;
}
/* This function is passed a function pointer to main_called. It
confirms that the pointer compares equally. */
#ifndef XCOFF_TEST
int
shlib_checkfunptr2 (p)
int (*p) ();
{
return p == main_called;
}
#endif
/* This function returns a pointer to shlib_mainvar. */
int
(*shlib_getfunptr1 ()) ()
{
return shlib_shlibvar1;
}
/* This function returns a pointer to main_called. */
#ifndef XCOFF_TEST
int
(*shlib_getfunptr2 ()) ()
{
return main_called;
}
#endif
/* This function makes sure that constant data and local functions
work. */
#ifndef __STDC__
#define const
#endif
static int i = 6;
static const char *str = "Hello, world\n";
int
shlib_check ()
{
const char *s1, *s2;
if (i != 6)
return 0;
/* To isolate the test, don't rely on any external functions, such
as strcmp. */
s1 = "Hello, world\n";
s2 = str;
while (*s1 != '\0')
if (*s1++ != *s2++)
return 0;
if (*s2 != '\0')
return 0;
if (shlib_shlibvar1 () != 3)
return 0;
return 1;
}
#ifdef HIDDEN_WEAK_TEST
#define HIDDEN_UNDEF_TEST
#define WEAK_TEST
#endif
#ifdef PROTECTED_WEAK_TEST
#define PROTECTED_UNDEF_TEST
#define WEAK_TEST
#endif
#if defined (HIDDEN_UNDEF_TEST) || defined (PROTECTED_UNDEF_TEST)
#ifdef WEAK_TEST
#pragma weak visibility
#endif
extern int visibility ();
#else
int
visibility ()
{
return 2;
}
#endif
#ifdef HIDDEN_NORMAL_TEST
asm (".hidden visibility_normal");
int
visibility_normal ()
{
return 2;
}
#endif
int
visibility_checkfunptr ()
{
#ifdef WEAK_TEST
return 1;
#else
#ifdef HIDDEN_NORMAL_TEST
int (*v) () = visibility_normal;
#else
int (*v) () = visibility;
#endif
return (*v) () == 2;
#endif
}
int
visibility_check ()
{
#ifdef WEAK_TEST
if (&visibility)
return visibility () == 1;
else
return 1;
#else
#ifdef HIDDEN_NORMAL_TEST
return visibility_normal () == 2;
#else
return visibility () == 2;
#endif
#endif
}
void *
visibility_funptr ()
{
#ifdef WEAK_TEST
if (&visibility == NULL)
return NULL;
else
#endif
return visibility;
}
#if defined (HIDDEN_UNDEF_TEST) || defined (PROTECTED_UNDEF_TEST)
#ifdef WEAK_TEST
#pragma weak visibility_var
#endif
extern int visibility_var;
#else
int visibility_var = 2;
#endif
#ifdef HIDDEN_NORMAL_TEST
asm (".hidden visibility_var_normal");
int visibility_var_normal = 2;
#endif
int
visibility_checkvarptr ()
{
#ifdef WEAK_TEST
if (&visibility_var)
return visibility_var == 1;
else
return 1;
#else
#ifdef HIDDEN_NORMAL_TEST
int *v = &visibility_var_normal;
#else
int *v = &visibility_var;
#endif
return *v == 2;
#endif
}
int
visibility_checkvar ()
{
#ifdef WEAK_TEST
return 1;
#else
#ifdef HIDDEN_NORMAL_TEST
return visibility_var_normal == 2;
#else
return visibility_var == 2;
#endif
#endif
}
void *
visibility_varptr ()
{
#ifdef WEAK_TEST
if (&visibility_var == NULL)
return NULL;
else
#endif
return &visibility_var;
}
int
visibility_varval ()
{
#ifdef WEAK_TEST
if (&visibility_var == NULL)
return 0;
else
#endif
return visibility_var;
}
#if defined (HIDDEN_TEST) || defined (HIDDEN_UNDEF_TEST)
asm (".hidden visibility");
asm (".hidden visibility_var");
#else
#if defined (PROTECTED_TEST) || defined (PROTECTED_UNDEF_TEST) || defined (PROTECTED_WEAK_TEST)
asm (".protected visibility");
asm (".protected visibility_var");
#endif
#endif
|
the_stack_data/59513390.c
|
/**
@Generated PIC10 / PIC12 / PIC16 / PIC18 MCUs Source File
@Company:
Microchip Technology Inc.
@File Name:
mcc.c
@Summary:
This is the device_config.c file generated using PIC10 / PIC12 / PIC16 / PIC18 MCUs
@Description:
This header file provides implementations for driver APIs for all modules selected in the GUI.
Generation Information :
Product Revision : PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.81.6
Device : PIC18F47K42
Driver Version : 2.00
The generated drivers are tested against the following:
Compiler : XC8 2.30 and above or later
MPLAB : MPLAB X 5.40
*/
/*
(c) 2018 Microchip Technology Inc. and its subsidiaries.
Subject to your compliance with these terms, you may use Microchip software and any
derivatives exclusively with Microchip products. It is your responsibility to comply with third party
license terms applicable to your use of third party software (including open source software) that
may accompany Microchip software.
THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY
IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS
FOR A PARTICULAR PURPOSE.
IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP
HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO
THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL
CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT
OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS
SOFTWARE.
*/
// Configuration bits: selected in the GUI
// CONFIG1L
#pragma config FEXTOSC = OFF // External Oscillator Selection->Oscillator not enabled
#pragma config RSTOSC = HFINTOSC_64MHZ // Reset Oscillator Selection->HFINTOSC with HFFRQ = 64 MHz and CDIV = 1:1
// CONFIG1H
#pragma config CLKOUTEN = OFF // Clock out Enable bit->CLKOUT function is disabled
#pragma config PR1WAY = ON // PRLOCKED One-Way Set Enable bit->PRLOCK bit can be cleared and set only once
#pragma config CSWEN = ON // Clock Switch Enable bit->Writing to NOSC and NDIV is allowed
#pragma config FCMEN = ON // Fail-Safe Clock Monitor Enable bit->Fail-Safe Clock Monitor enabled
// CONFIG2L
#pragma config MCLRE = EXTMCLR // MCLR Enable bit->If LVP = 0, MCLR pin is MCLR; If LVP = 1, RE3 pin function is MCLR
#pragma config PWRTS = PWRT_OFF // Power-up timer selection bits->PWRT is disabled
#pragma config MVECEN = OFF // Multi-vector enable bit->Interrupt contoller does not use vector table to prioritze interrupts
#pragma config IVT1WAY = ON // IVTLOCK bit One-way set enable bit->IVTLOCK bit can be cleared and set only once
#pragma config LPBOREN = OFF // Low Power BOR Enable bit->ULPBOR disabled
#pragma config BOREN = SBORDIS // Brown-out Reset Enable bits->Brown-out Reset enabled , SBOREN bit is ignored
// CONFIG2H
#pragma config BORV = VBOR_2P45 // Brown-out Reset Voltage Selection bits->Brown-out Reset Voltage (VBOR) set to 2.45V
#pragma config ZCD = OFF // ZCD Disable bit->ZCD disabled. ZCD can be enabled by setting the ZCDSEN bit of ZCDCON
#pragma config PPS1WAY = ON // PPSLOCK bit One-Way Set Enable bit->PPSLOCK bit can be cleared and set only once; PPS registers remain locked after one clear/set cycle
#pragma config STVREN = ON // Stack Full/Underflow Reset Enable bit->Stack full/underflow will cause Reset
#pragma config DEBUG = OFF // Debugger Enable bit->Background debugger disabled
#pragma config XINST = OFF // Extended Instruction Set Enable bit->Extended Instruction Set and Indexed Addressing Mode disabled
// CONFIG3L
#pragma config WDTCPS = WDTCPS_31 // WDT Period selection bits->Divider ratio 1:65536; software control of WDTPS
#pragma config WDTE = OFF // WDT operating mode->WDT Disabled; SWDTEN is ignored
// CONFIG3H
#pragma config WDTCWS = WDTCWS_7 // WDT Window Select bits->window always open (100%); software control; keyed access not required
#pragma config WDTCCS = SC // WDT input clock selector->Software Control
// CONFIG4L
#pragma config BBSIZE = BBSIZE_512 // Boot Block Size selection bits->Boot Block size is 512 words
#pragma config BBEN = OFF // Boot Block enable bit->Boot block disabled
#pragma config SAFEN = OFF // Storage Area Flash enable bit->SAF disabled
#pragma config WRTAPP = OFF // Application Block write protection bit->Application Block not write protected
// CONFIG4H
#pragma config WRTB = OFF // Configuration Register Write Protection bit->Configuration registers (300000-30000Bh) not write-protected
#pragma config WRTC = OFF // Boot Block Write Protection bit->Boot Block (000000-0007FFh) not write-protected
#pragma config WRTD = OFF // Data EEPROM Write Protection bit->Data EEPROM not write-protected
#pragma config WRTSAF = OFF // SAF Write protection bit->SAF not Write Protected
#pragma config LVP = ON // Low Voltage Programming Enable bit->Low voltage programming enabled. MCLR/VPP pin function is MCLR. MCLRE configuration bit is ignored
// CONFIG5L
#pragma config CP = OFF // PFM and Data EEPROM Code Protection bit->PFM and Data EEPROM code protection disabled
|
the_stack_data/150141753.c
|
int islower(int c)
{
return (unsigned)c-'a' < 26;
}
|
the_stack_data/114306.c
|
extern void abort (void);
extern int inside_main;
__attribute__ ((__noinline__))
void *
memset (void *dst, int c, __SIZE_TYPE__ n)
{
while (n-- != 0)
n[(char *) dst] = c;
/* Single-byte memsets should be done inline when optimisation
is enabled. Do this after the copy in case we're being called to
initialize bss. */
#ifdef __OPTIMIZE__
if (inside_main && n < 2)
abort ();
#endif
return dst;
}
|
the_stack_data/133440.c
|
int mx_count_words(const char *str, char c) {
int a = 0;
if (str == 0)
return - 1;
for (int i = 0; str[i] != '\0'; i++) {
while (str[i] == c && str[i + 1] != '\0')
i++;
if (str[i] != c && str[i] != '\0') {
while (str[i] != c && str[i + 1] != '\0')
i++;
a++;
}
}
return a;
}
|
the_stack_data/354154.c
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main() {
int tamanho, maior1, index1, maior2, index2, valor, extra;
maior1 = maior2 = index1 = index2= 0;
scanf("%i", &tamanho);
int vetor[tamanho];
for(int i=1; i < tamanho; i++) {
scanf(" %i", &vetor[i]);
}
for(int i=0; i < tamanho; i++) {
if (vetor[i] > maior1) {
maior1 = vetor[i];
index1 = i;
}
}
vetor[index1] = 0;
for(int i=0; i < tamanho; i++) {
if (vetor[i] > maior2) {
maior2 = vetor[i];
index2 = i;
}
}
maior1++;
maior2++;
printf("index1 %i\n", index1);
printf("index2 %i\n", index2);
if (index2 >= index1 + 2 || index1 >= index2 + 2) {
valor = maior1 + maior2 + abs(index2 - index1);
} else {
valor = maior1 + maior2;
// printf("maior1: %i\n ", maior1);
// printf("maior2: %i\n ", maior2);
// printf("difrenca: %i\n ", abs(index2 - index1));
// valor = maior1 + maior2 + abs(index2 - index1);
}
printf("%i\n", valor);
return 0;
}
|
the_stack_data/198579378.c
|
/* $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $ */
/*
* Copyright (c) 1998, 2015 Todd C. Miller <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <string.h>
/*
* Copy string src to buffer dst of size dsize. At most dsize-1
* chars will be copied. Always NUL terminates (unless dsize == 0).
* Returns strlen(src); if retval >= dsize, truncation occurred.
*/
size_t
strlcpy(char *dst, const char *src, size_t dsize)
{
const char *osrc = src;
size_t nleft = dsize;
/* Copy as many bytes as will fit. */
if (nleft != 0) {
while (--nleft != 0) {
if ((*dst++ = *src++) == '\0')
break;
}
}
/* Not enough room in dst, add NUL and traverse rest of src. */
if (nleft == 0) {
if (dsize != 0)
*dst = '\0'; /* NUL-terminate dst */
while (*src++)
;
}
return(src - osrc - 1); /* count does not include NUL */
}
|
the_stack_data/23576673.c
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
const char *f = "foo";
int main(int argc, char* argv[]) {
printf("hello world %s\n", f);
printf("argc=%d\n", argc);
printf("argv=%p\n", (void*)argv);
for (int i = 0; i < argc; ++i)
printf("argv[%d](%p)=%s\n", i, (void*)argv[i], argv[i]);
printf("sin(%d)=%f\n", argc, sinf(argc));
exit(42);
}
|
the_stack_data/59512018.c
|
/* In Linear search, we search an element or value in a given array by traversing the array from the starting,
till the desired element or value is found.
If the desired element is found, the index position is displayed, else -1 is displayed.*/
#include<stdio.h>
int linear_search(int* arr, int ele, int n);
// function returns the index position if the element is found, else return -1
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
int arr[n];
printf("Enter the elements of the array: \n");
for(int i = 0; i<n; i++)
scanf("%d",&arr[i]);
int ele;
printf("Enter the element to be searched: ");
scanf("%d",&ele);
int pos = linear_search(arr,ele,n);
if(pos==-1) printf("%d not found.",ele);
else printf("%d found at index position %d",ele,pos);
return 0;
}
int linear_search(int* arr, int ele, int n)
{
for(int i = 0; i<n; i++)
if(arr[i]==ele) return i;
return -1;
}
|
the_stack_data/64201192.c
|
#include <stdio.h>
void shellsort(int arr[], int num)
{
int i, j, k, tmp;
for (i = num / 2; i > 0; i = i / 2)
{
for (j = i; j < num; j++)
{
for(k = j - i; k >= 0; k = k - i)
{
if (arr[k+i] >= arr[k])
break;
else
{
tmp = arr[k];
arr[k] = arr[k+i];
arr[k+i] = tmp;
}
}
}
}
}
int main()
{
int arr[30];
int k, num;
printf("Enter total no. of elements : ");
scanf("%d", &num);
printf("\nEnter %d numbers: ", num);
for (k = 0 ; k < num; k++)
{
scanf("%d", &arr[k]);
}
shellsort(arr, num);
printf("\n Sorted array is: ");
for (k = 0; k < num; k++)
printf("%d ", arr[k]);
return 0;
}
|
the_stack_data/156392831.c
|
/*
* Copyright 2018 Daniel G. Robinson
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* @file format.c
* @brief routines to do printf type formating
* @author Daniel G. Robinson
* @date 3 Jul 2018
*/
#include <stdint.h>
/**
* do hexformating on an unsigned 32 bit quantity
*/
const static char *hexchar = "0123456789abcdef";
/*
* args are value, number of bytes to format and a character buffer that is
* at least 9 bytes long
*
* See CONSOLE_BUILD for usage
*/
char* format_x(uint32_t val, int len, char *output_buf)
{
char *ss = output_buf;
int ii;
ss[8] = 0;
if(len <= 0 || len > 8) return &ss[8];
for(ii = 0; ii < len; ii++) {
ss[7 - ii] = hexchar[val & 0xf];
val >>= 4;
}
return &ss[8 - ii];
}
/*
* decimal format an integer for output
*
* responsibility of caller to make sure output_buf is large enough
* to hold output
*/
char* format_d(int32_t val, char *output_buf)
{
char *ss;
int32_t power;
ss = output_buf;
if(val == 0) {
*ss++ = '0';
*ss = 0;
return output_buf;
}
if(val < 0) {
val = -val;
*ss++ = '-';
}
power = 1;
while((power * 10) < val) power *= 10;
do {
int32_t digit;
int32_t remain;
digit = val / power;
remain = val % power;
*ss++ = '0' + digit;
power /= 10;
val = remain;
} while(power > 0);
*ss = 0;
return output_buf;
}
#ifdef CONSOLE_BUILD
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
uint32_t val;
char buf[9];
val = 0xdeadbeef;
printf("last five of 0x%08x, %s\n", val, format_x(val, 5, buf));
val = 0xcafedead;
printf("last five of 0x%08x, %s\n", val, format_x(val, 5, buf));
val = 0xcafe;
printf("eight of 0x%08x, %s\n", val, format_x(val, 8, buf));
val = 3003;
printf("%d: %s\n", val, format_d(val, buf));
val = -9123;
printf("%d: %s\n", val, format_d(val, buf));
}
#endif
|
the_stack_data/87636594.c
|
//EXERCICIO 2
#include <stdio.h>
#include <string.h>
int main()
{
char nome[50];
printf("Digite seu nome:");
gets(nome);
for (int cont = strlen(nome); cont >= 0; cont--)
{
printf("%c\n", nome[cont]);
}
return 0;
}
|
the_stack_data/50568.c
|
//Verifique o que ocorre com a variavel v
#include <stdio.h>
void main(void){
int v[99];
for (int i = 0; i < 99; ++i){
v[i] = 98 - i;
// printf("%d\n", v[i]);
}
for (int i = 0; i < 99; ++i){
v[i] = v[v[i]];
printf("%d\n", v[v[i]]);
}
/*
Veja que:
i = 0;
v[i] = 0;
i = 1;
v[i] = 1;
...
i = 99;
v[i] = 98;
Desta forma:
i = 99;
v[i] = 98;
v[v[i]] == v[98];
*/
}
|
the_stack_data/62637213.c
|
#include <assert.h>
int main() {
__int128 X;
__ESBMC_assume(X>0);
__int128 Z = 2;
Z = Z << 70;
assert((X+Z) > 0);
}
|
the_stack_data/417580.c
|
#include<stdio.h>
void two_pointer(int *mp)
{
*mp = 30;
}
void two_pointer2(int **mmp)
{
*mmp = (int*)0x100;
}
int main()
{
int a = 10;
printf("a = %d, &a = %p\n", a, &a);
int* p = &a;
*p = 20;
printf("a = %d, p = %p\n", a, &p);
two_pointer(p);
printf("a = %d, p = %p\n", a, p);
two_pointer2(&p);
printf("p = %p\n", p);
return 0;
}
|
the_stack_data/131913.c
|
/* Code generated from eC source file: pass1.ec */
#if defined(_WIN32)
#define __runtimePlatform 1
#elif defined(__APPLE__)
#define __runtimePlatform 3
#else
#define __runtimePlatform 2
#endif
#if defined(__GNUC__) || defined(__clang__)
#if defined(__clang__) && defined(__WIN32__)
#define int64 long long
#define uint64 unsigned long long
#if defined(_WIN64)
#define ssize_t long long
#else
#define ssize_t long
#endif
#else
typedef long long int64;
typedef unsigned long long uint64;
#endif
#ifndef _WIN32
#define __declspec(x)
#endif
#elif defined(__TINYC__)
#include <stdarg.h>
#define __builtin_va_list va_list
#define __builtin_va_start va_start
#define __builtin_va_end va_end
#ifdef _WIN32
#define strcasecmp stricmp
#define strncasecmp strnicmp
#define __declspec(x) __attribute__((x))
#else
#define __declspec(x)
#endif
typedef long long int64;
typedef unsigned long long uint64;
#else
typedef __int64 int64;
typedef unsigned __int64 uint64;
#endif
#ifdef __BIG_ENDIAN__
#define __ENDIAN_PAD(x) (8 - (x))
#else
#define __ENDIAN_PAD(x) 0
#endif
#if defined(_WIN32)
# if defined(__clang__) && defined(__WIN32__)
# define ecere_stdcall __stdcall
# define ecere_gcc_struct
# elif defined(__GNUC__) || defined(__TINYC__)
# define ecere_stdcall __attribute__((__stdcall__))
# define ecere_gcc_struct __attribute__((gcc_struct))
# else
# define ecere_stdcall __stdcall
# define ecere_gcc_struct
# endif
#else
# define ecere_stdcall
# define ecere_gcc_struct
#endif
#include <stdint.h>
#include <sys/types.h>
extern int yydebug;
enum yytokentype
{
IDENTIFIER = 258, CONSTANT = 259, STRING_LITERAL = 260, SIZEOF = 261, PTR_OP = 262, INC_OP = 263, DEC_OP = 264, LEFT_OP = 265, RIGHT_OP = 266, LE_OP = 267, GE_OP = 268, EQ_OP = 269, NE_OP = 270, AND_OP = 271, OR_OP = 272, MUL_ASSIGN = 273, DIV_ASSIGN = 274, MOD_ASSIGN = 275, ADD_ASSIGN = 276, SUB_ASSIGN = 277, LEFT_ASSIGN = 278, RIGHT_ASSIGN = 279, AND_ASSIGN = 280, XOR_ASSIGN = 281, OR_ASSIGN = 282, TYPE_NAME = 283, TYPEDEF = 284, EXTERN = 285, STATIC = 286, AUTO = 287, REGISTER = 288, CHAR = 289, SHORT = 290, INT = 291, UINT = 292, INT64 = 293, INT128 = 294, FLOAT128 = 295, LONG = 296, SIGNED = 297, UNSIGNED = 298, FLOAT = 299, DOUBLE = 300, CONST = 301, VOLATILE = 302, VOID = 303, VALIST = 304, STRUCT = 305, UNION = 306, ENUM = 307, ELLIPSIS = 308, CASE = 309, DEFAULT = 310, IF = 311, SWITCH = 312, WHILE = 313, DO = 314, FOR = 315, GOTO = 316, CONTINUE = 317, BREAK = 318, RETURN = 319, IFX = 320, ELSE = 321, CLASS = 322, THISCLASS = 323, PROPERTY = 324, SETPROP = 325, GETPROP = 326, NEWOP = 327, RENEW = 328, DELETE = 329, EXT_DECL = 330, EXT_STORAGE = 331, IMPORT = 332, DEFINE = 333, VIRTUAL = 334, ATTRIB = 335, PUBLIC = 336, PRIVATE = 337, TYPED_OBJECT = 338, ANY_OBJECT = 339, _INCREF = 340, EXTENSION = 341, ASM = 342, TYPEOF = 343, WATCH = 344, STOPWATCHING = 345, FIREWATCHERS = 346, WATCHABLE = 347, CLASS_DESIGNER = 348, CLASS_NO_EXPANSION = 349, CLASS_FIXED = 350, ISPROPSET = 351, CLASS_DEFAULT_PROPERTY = 352, PROPERTY_CATEGORY = 353, CLASS_DATA = 354, CLASS_PROPERTY = 355, SUBCLASS = 356, NAMESPACE = 357, NEW0OP = 358, RENEW0 = 359, VAARG = 360, DBTABLE = 361, DBFIELD = 362, DBINDEX = 363, DATABASE_OPEN = 364, ALIGNOF = 365, ATTRIB_DEP = 366, __ATTRIB = 367, BOOL = 368, _BOOL = 369, _COMPLEX = 370, _IMAGINARY = 371, RESTRICT = 372, THREAD = 373, WIDE_STRING_LITERAL = 374, BUILTIN_OFFSETOF = 375, PRAGMA = 376, STATIC_ASSERT = 377
};
int yyparse(void);
extern int propWatcherID;
unsigned int buildingECERECOM = 0;
unsigned int buildingECERECOMModule = 0;
extern unsigned int inCompiler;
extern const char * outputFile;
extern struct __ecereNameSpace__ecere__com__Property * __ecereProp_Type_isPointerTypeSize;
extern struct __ecereNameSpace__ecere__com__Property * __ecereProp___ecereNameSpace__ecere__sys__BinaryTree_first;
extern struct __ecereNameSpace__ecere__com__Property * __ecereProp___ecereNameSpace__ecere__sys__BTNode_next;
extern unsigned int parsingType;
extern const char * sourceFile;
static struct __ecereNameSpace__ecere__com__Instance * classPropValues;
extern struct __ecereNameSpace__ecere__com__Property * __ecereProp___ecereNameSpace__ecere__com__Iterator_data;
extern struct __ecereNameSpace__ecere__com__Property * __ecereProp_Type_isPointerType;
struct __ecereNameSpace__ecere__sys__OldList
{
void * first;
void * last;
int count;
unsigned int offset;
unsigned int circ;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__DataValue
{
union
{
char c;
unsigned char uc;
short s;
unsigned short us;
int i;
unsigned int ui;
void * p;
float f;
double d;
long long i64;
uint64 ui64;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__SerialBuffer
{
unsigned char * _buffer;
size_t count;
size_t _size;
size_t pos;
} ecere_gcc_struct;
extern void * __ecereNameSpace__ecere__com__eSystem_New(unsigned int size);
extern void * __ecereNameSpace__ecere__com__eSystem_New0(unsigned int size);
extern void * __ecereNameSpace__ecere__com__eSystem_Renew(void * memory, unsigned int size);
extern void * __ecereNameSpace__ecere__com__eSystem_Renew0(void * memory, unsigned int size);
extern void __ecereNameSpace__ecere__com__eSystem_Delete(void * memory);
struct Pointer;
struct InitDeclarator;
struct AsmField;
struct Attrib;
struct ExtDecl;
struct Attribute;
struct Instantiation;
struct MembersInit;
struct MemberInit;
struct PropertyDef;
struct DBTableEntry;
struct DBIndexItem;
struct DBTableDef;
struct CodePosition
{
int line;
int charPos;
int pos;
int included;
} ecere_gcc_struct;
struct ModuleImport;
struct ClassImport;
struct __ecereNameSpace__ecere__com__LinkList
{
void * first;
void * last;
int count;
} ecere_gcc_struct;
extern void Compiler_Error(const char * format, ...);
extern const char * __ecereNameSpace__ecere__GetTranslatedString(const char * name, const char * string, const char * stringAndContext);
extern char * __ecereNameSpace__ecere__sys__CopyString(const char * string);
extern char * __ecereNameSpace__ecere__sys__GetLastDirectory(const char * string, char * output);
extern unsigned int __ecereNameSpace__ecere__sys__StripExtension(char * string);
extern void FixModuleName(char * moduleName);
extern int sprintf(char * , const char * , ...);
extern char * QMkString(const char * source);
extern char * strcpy(char * , const char * );
extern void FullClassNameCat(char * output, const char * className, unsigned int includeTemplateParams);
extern char * strcat(char * , const char * );
extern int strcmp(const char * , const char * );
extern char * PrintInt64(long long result);
extern void __ecereNameSpace__ecere__sys__ChangeCh(char * string, char ch1, char ch2);
extern unsigned int DummyMethod(void);
extern char * PrintUInt64(uint64 result);
extern size_t strlen(const char * );
struct __ecereNameSpace__ecere__com__IteratorPointer;
struct __ecereNameSpace__ecere__com__GlobalFunction;
extern int __ecereVMethodID_class_OnGetString;
void SetBuildingEcereCom(unsigned int b)
{
buildingECERECOM = b;
}
unsigned int GetBuildingEcereCom()
{
return buildingECERECOM;
}
void SetBuildingEcereComModule(unsigned int b)
{
buildingECERECOMModule = b;
}
unsigned int GetBuildingEcereComModule()
{
return buildingECERECOMModule;
}
extern struct __ecereNameSpace__ecere__sys__OldList * MkList(void);
extern struct __ecereNameSpace__ecere__sys__OldList * excludedSymbols;
extern struct __ecereNameSpace__ecere__sys__OldList * CopyList(struct __ecereNameSpace__ecere__sys__OldList * source, void * (* CopyFunction)(void * ));
extern void ListAdd(struct __ecereNameSpace__ecere__sys__OldList * list, void * item);
extern struct __ecereNameSpace__ecere__sys__OldList * MkListOne(void * item);
extern struct __ecereNameSpace__ecere__sys__OldList * ast;
struct __ecereNameSpace__ecere__com__EnumClassData
{
struct __ecereNameSpace__ecere__sys__OldList values;
long long largest;
} ecere_gcc_struct;
unsigned int __ecereMethod___ecereNameSpace__ecere__sys__OldList_Insert(struct __ecereNameSpace__ecere__sys__OldList * this, void * prevItem, void * item);
void __ecereMethod___ecereNameSpace__ecere__sys__OldList_Add(struct __ecereNameSpace__ecere__sys__OldList * this, void * item);
void __ecereMethod___ecereNameSpace__ecere__sys__OldList_Remove(struct __ecereNameSpace__ecere__sys__OldList * this, void * item);
extern struct Pointer * MkPointer(struct __ecereNameSpace__ecere__sys__OldList * qualifiers, struct Pointer * pointer);
extern struct Attrib * MkAttrib(int type, struct __ecereNameSpace__ecere__sys__OldList * attribs);
extern struct ExtDecl * MkExtDeclAttrib(struct Attrib * attr);
extern struct MembersInit * MkMembersInitList(struct __ecereNameSpace__ecere__sys__OldList * dataMembers);
struct Location
{
struct CodePosition start;
struct CodePosition end;
} ecere_gcc_struct;
extern struct Location yylloc;
struct Statement;
static struct Statement * registerModuleBody;
static struct Statement * unregisterModuleBody;
extern struct Statement * MkCompoundStmt(struct __ecereNameSpace__ecere__sys__OldList * declarations, struct __ecereNameSpace__ecere__sys__OldList * statements);
extern struct Statement * MkExpressionStmt(struct __ecereNameSpace__ecere__sys__OldList * expressions);
extern struct Statement * MkIfStmt(struct __ecereNameSpace__ecere__sys__OldList * exp, struct Statement * statement, struct Statement * elseStmt);
struct External;
static struct External * registerModuleExternal;
static struct External * unregisterModuleExternal;
extern void FreeExternal(struct External * external);
extern struct External * DeclareStruct(struct External * neededBy, const char * name, unsigned int skipNoHead, unsigned int needDereference);
extern struct External * curExternal;
struct Context;
extern struct Context * globalContext;
extern struct Context * curContext;
extern struct Context * PushContext(void);
extern void PopContext(struct Context * ctx);
struct Expression;
extern struct Attribute * MkAttribute(char * attr, struct Expression * exp);
extern struct Expression * MkExpConstant(const char * string);
extern struct Expression * MkExpString(const char * string);
extern struct Expression * MkExpOp(struct Expression * exp1, int op, struct Expression * exp2);
extern struct Expression * MkExpCall(struct Expression * expression, struct __ecereNameSpace__ecere__sys__OldList * arguments);
extern struct Expression * CopyExpression(struct Expression * exp);
extern struct Expression * ParseExpressionString(char * expression);
extern struct Expression * MkExpCondition(struct Expression * cond, struct __ecereNameSpace__ecere__sys__OldList * expressions, struct Expression * elseExp);
extern void ProcessExpressionType(struct Expression * exp);
extern void FreeExpContents(struct Expression * exp);
extern void ComputeExpression(struct Expression * exp);
extern struct Expression * MkExpInstance(struct Instantiation * inst);
extern void PrintExpression(struct Expression * exp, char * string);
struct __ecereNameSpace__ecere__sys__BTNode;
struct __ecereNameSpace__ecere__sys__BTNode
{
uintptr_t key;
struct __ecereNameSpace__ecere__sys__BTNode * parent;
struct __ecereNameSpace__ecere__sys__BTNode * left;
struct __ecereNameSpace__ecere__sys__BTNode * right;
int depth;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__sys__BTNode * __ecereProp___ecereNameSpace__ecere__sys__BTNode_Get_next(struct __ecereNameSpace__ecere__sys__BTNode * this);
struct __ecereNameSpace__ecere__com__Class;
struct __ecereNameSpace__ecere__com__Instance
{
void * * _vTbl;
struct __ecereNameSpace__ecere__com__Class * _class;
int _refCount;
} ecere_gcc_struct;
extern long long __ecereNameSpace__ecere__com__eClass_GetProperty(struct __ecereNameSpace__ecere__com__Class * _class, const char * name);
extern void __ecereNameSpace__ecere__com__eClass_SetProperty(struct __ecereNameSpace__ecere__com__Class * _class, const char * name, long long value);
extern void ReplaceThisClassSpecifiers(struct __ecereNameSpace__ecere__sys__OldList * specs, struct __ecereNameSpace__ecere__com__Class * _class);
extern void __ecereNameSpace__ecere__com__eEnum_AddFixedValue(struct __ecereNameSpace__ecere__com__Class * _class, const char * string, long long value);
extern long long __ecereNameSpace__ecere__com__eEnum_AddValue(struct __ecereNameSpace__ecere__com__Class * _class, const char * string);
extern void * __ecereNameSpace__ecere__com__eInstance_New(struct __ecereNameSpace__ecere__com__Class * _class);
extern void __ecereNameSpace__ecere__com__eInstance_SetMethod(struct __ecereNameSpace__ecere__com__Instance * instance, const char * name, void * function);
extern void __ecereNameSpace__ecere__com__eInstance_IncRef(struct __ecereNameSpace__ecere__com__Instance * instance);
struct __ecereNameSpace__ecere__com__Iterator
{
struct __ecereNameSpace__ecere__com__Instance * container;
struct __ecereNameSpace__ecere__com__IteratorPointer * pointer;
} ecere_gcc_struct;
extern int __ecereVMethodID___ecereNameSpace__ecere__com__Container_Add;
extern int __ecereVMethodID___ecereNameSpace__ecere__com__Container_Free;
extern void __ecereNameSpace__ecere__com__eInstance_DecRef(struct __ecereNameSpace__ecere__com__Instance * instance);
unsigned int __ecereMethod___ecereNameSpace__ecere__com__Iterator_Next(struct __ecereNameSpace__ecere__com__Iterator * this);
uint64 __ecereProp___ecereNameSpace__ecere__com__Iterator_Get_data(struct __ecereNameSpace__ecere__com__Iterator * this);
void __ecereProp___ecereNameSpace__ecere__com__Iterator_Set_data(struct __ecereNameSpace__ecere__com__Iterator * this, uint64 value);
void __ecereDestroyModuleInstances_pass1()
{
(__ecereNameSpace__ecere__com__eInstance_DecRef(classPropValues), classPropValues = 0);
}
struct Specifier;
extern struct Specifier * MkSpecifier(int specifier);
extern struct Specifier * CopySpecifier(struct Specifier * spec);
extern struct Specifier * MkSpecifierName(const char * name);
extern struct Specifier * MkSpecifierExtended(struct ExtDecl * extDecl);
extern struct Instantiation * MkInstantiation(struct Specifier * _class, struct Expression * exp, struct __ecereNameSpace__ecere__sys__OldList * members);
struct __ecereNameSpace__ecere__com__Method;
extern void ProcessMethodType(struct __ecereNameSpace__ecere__com__Method * method);
extern void DeclareMethod(struct External * neededFor, struct __ecereNameSpace__ecere__com__Method * method, const char * name);
struct Type;
struct __ecereNameSpace__ecere__com__Method
{
const char * name;
struct __ecereNameSpace__ecere__com__Method * parent;
struct __ecereNameSpace__ecere__com__Method * left;
struct __ecereNameSpace__ecere__com__Method * right;
int depth;
int (* function)();
int vid;
int type;
struct __ecereNameSpace__ecere__com__Class * _class;
void * symbol;
const char * dataTypeString;
struct Type * dataType;
int memberAccess;
} ecere_gcc_struct;
extern struct Type * ProcessTypeString(const char * string, unsigned int staticMethod);
extern unsigned int MatchTypes(struct Type * source, struct Type * dest, struct __ecereNameSpace__ecere__sys__OldList * conversions, struct __ecereNameSpace__ecere__com__Class * owningClassSource, struct __ecereNameSpace__ecere__com__Class * owningClassDest, unsigned int doConversion, unsigned int enumBaseType, unsigned int acceptReversedParams, unsigned int isConversionExploration, unsigned int warnConst);
extern void FreeType(struct Type * type);
extern int ComputeTypeSize(struct Type * type);
extern void PrintType(struct Type * type, char * string, unsigned int printName, unsigned int fullName);
struct Symbol;
extern struct Symbol * FindClass(const char * name);
struct Declarator;
extern struct Declarator * GetFuncDecl(struct Declarator * decl);
extern struct Declarator * CopyDeclarator(struct Declarator * declarator);
extern struct Declarator * MkDeclaratorFunction(struct Declarator * declarator, struct __ecereNameSpace__ecere__sys__OldList * parameters);
extern struct Declarator * MkDeclaratorPointer(struct Pointer * pointer, struct Declarator * declarator);
extern struct Type * ProcessType(struct __ecereNameSpace__ecere__sys__OldList * specs, struct Declarator * decl);
extern char * StringFromSpecDecl(struct __ecereNameSpace__ecere__sys__OldList * specs, struct Declarator * decl);
struct TemplateDatatype
{
struct __ecereNameSpace__ecere__sys__OldList * specifiers;
struct Declarator * decl;
} ecere_gcc_struct;
struct Identifier;
struct Declarator
{
struct Declarator * prev;
struct Declarator * next;
struct Location loc;
int type;
struct Symbol * symbol;
struct Declarator * declarator;
union
{
struct Identifier * identifier;
struct
{
struct Expression * exp;
struct Expression * posExp;
struct Attrib * attrib;
} ecere_gcc_struct structDecl;
struct
{
struct Expression * exp;
struct Specifier * enumClass;
} ecere_gcc_struct array;
struct
{
struct __ecereNameSpace__ecere__sys__OldList * parameters;
} ecere_gcc_struct function;
struct
{
struct Pointer * pointer;
} ecere_gcc_struct pointer;
struct
{
struct ExtDecl * extended;
} ecere_gcc_struct extended;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct;
extern struct Declarator * MkDeclaratorIdentifier(struct Identifier * id);
extern struct Identifier * MkIdentifier(const char * string);
extern struct Expression * MkExpIdentifier(struct Identifier * id);
extern struct Expression * MkExpMember(struct Expression * expression, struct Identifier * member);
extern struct Specifier * MkStructOrUnion(int type, struct Identifier * id, struct __ecereNameSpace__ecere__sys__OldList * definitions);
struct Identifier
{
struct Identifier * prev;
struct Identifier * next;
struct Location loc;
struct Symbol * classSym;
struct Specifier * _class;
char * string;
struct Identifier * badID;
} ecere_gcc_struct;
extern struct Identifier * GetDeclId(struct Declarator * decl);
struct ClassPropertyValue
{
struct __ecereNameSpace__ecere__com__Class * regClass;
unsigned int staticClass;
struct Identifier * id;
struct Expression * exp;
} ecere_gcc_struct;
extern void FreeIdentifier(struct Identifier * id);
struct __ecereNameSpace__ecere__sys__NamedLink64;
struct __ecereNameSpace__ecere__sys__NamedLink64
{
struct __ecereNameSpace__ecere__sys__NamedLink64 * prev;
struct __ecereNameSpace__ecere__sys__NamedLink64 * next;
char * name;
long long data;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__sys__OldLink;
struct __ecereNameSpace__ecere__sys__OldLink
{
struct __ecereNameSpace__ecere__sys__OldLink * prev;
struct __ecereNameSpace__ecere__sys__OldLink * next;
void * data;
} ecere_gcc_struct;
struct ClassFunction;
struct ClassFunction
{
struct ClassFunction * prev;
struct ClassFunction * next;
struct Location loc;
struct __ecereNameSpace__ecere__sys__OldList * specifiers;
struct Declarator * declarator;
struct __ecereNameSpace__ecere__sys__OldList * declarations;
struct Statement * body;
struct __ecereNameSpace__ecere__com__Class * _class;
struct __ecereNameSpace__ecere__sys__OldList attached;
int declMode;
struct Type * type;
struct Symbol * propSet;
unsigned int isVirtual;
unsigned int isConstructor;
unsigned int isDestructor;
unsigned int dontMangle;
int id;
int idCode;
} ecere_gcc_struct;
extern struct ClassFunction * MkClassFunction(struct __ecereNameSpace__ecere__sys__OldList * specifiers, struct Specifier * _class, struct Declarator * decl, struct __ecereNameSpace__ecere__sys__OldList * declList);
extern void ProcessClassFunctionBody(struct ClassFunction * func, struct Statement * body);
struct PropertyWatch;
struct PropertyWatch
{
struct PropertyWatch * prev;
struct PropertyWatch * next;
struct Location loc;
struct Statement * compound;
struct __ecereNameSpace__ecere__sys__OldList * properties;
unsigned int deleteWatch;
} ecere_gcc_struct;
extern void FreePropertyWatch(struct PropertyWatch * watcher);
struct Declaration;
struct Statement
{
struct Statement * prev;
struct Statement * next;
struct Location loc;
int type;
union
{
struct __ecereNameSpace__ecere__sys__OldList * expressions;
struct
{
struct Identifier * id;
struct Statement * stmt;
} ecere_gcc_struct labeled;
struct
{
struct Expression * exp;
struct Statement * stmt;
} ecere_gcc_struct caseStmt;
struct
{
struct __ecereNameSpace__ecere__sys__OldList * declarations;
struct __ecereNameSpace__ecere__sys__OldList * statements;
struct Context * context;
unsigned int isSwitch;
} ecere_gcc_struct compound;
struct
{
struct __ecereNameSpace__ecere__sys__OldList * exp;
struct Statement * stmt;
struct Statement * elseStmt;
} ecere_gcc_struct ifStmt;
struct
{
struct __ecereNameSpace__ecere__sys__OldList * exp;
struct Statement * stmt;
} ecere_gcc_struct switchStmt;
struct
{
struct __ecereNameSpace__ecere__sys__OldList * exp;
struct Statement * stmt;
} ecere_gcc_struct whileStmt;
struct
{
struct __ecereNameSpace__ecere__sys__OldList * exp;
struct Statement * stmt;
} ecere_gcc_struct doWhile;
struct
{
struct Statement * init;
struct Statement * check;
struct __ecereNameSpace__ecere__sys__OldList * increment;
struct Statement * stmt;
} ecere_gcc_struct forStmt;
struct
{
struct Identifier * id;
} ecere_gcc_struct gotoStmt;
struct
{
struct Specifier * spec;
char * statements;
struct __ecereNameSpace__ecere__sys__OldList * inputFields;
struct __ecereNameSpace__ecere__sys__OldList * outputFields;
struct __ecereNameSpace__ecere__sys__OldList * clobberedFields;
} ecere_gcc_struct asmStmt;
struct
{
struct Expression * watcher;
struct Expression * object;
struct __ecereNameSpace__ecere__sys__OldList * watches;
} ecere_gcc_struct _watch;
struct
{
struct Identifier * id;
struct __ecereNameSpace__ecere__sys__OldList * exp;
struct __ecereNameSpace__ecere__sys__OldList * filter;
struct Statement * stmt;
} ecere_gcc_struct forEachStmt;
struct Declaration * decl;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct;
extern struct Declaration * MkDeclaration(struct __ecereNameSpace__ecere__sys__OldList * specifiers, struct __ecereNameSpace__ecere__sys__OldList * initDeclarators);
struct Declaration
{
struct Declaration * prev;
struct Declaration * next;
struct Location loc;
int type;
union
{
struct
{
struct __ecereNameSpace__ecere__sys__OldList * specifiers;
struct __ecereNameSpace__ecere__sys__OldList * declarators;
} ecere_gcc_struct __anon1;
struct Instantiation * inst;
struct
{
struct Identifier * id;
struct Expression * exp;
} ecere_gcc_struct __anon2;
} ecere_gcc_struct __anon1;
struct Specifier * extStorage;
struct Symbol * symbol;
int declMode;
} ecere_gcc_struct;
struct Initializer;
extern struct InitDeclarator * MkInitDeclarator(struct Declarator * declarator, struct Initializer * initializer);
extern struct Initializer * MkInitializerAssignment(struct Expression * exp);
extern struct MemberInit * MkMemberInit(struct __ecereNameSpace__ecere__sys__OldList * ids, struct Initializer * initializer);
struct Initializer
{
struct Initializer * prev;
struct Initializer * next;
struct Location loc;
int type;
union
{
struct Expression * exp;
struct __ecereNameSpace__ecere__sys__OldList * list;
} ecere_gcc_struct __anon1;
unsigned int isConstant;
struct Identifier * id;
} ecere_gcc_struct;
struct FunctionDefinition;
extern struct FunctionDefinition * _MkFunction(struct __ecereNameSpace__ecere__sys__OldList * specifiers, struct Declarator * declarator, struct __ecereNameSpace__ecere__sys__OldList * declarationList, unsigned int errorOnOmit);
struct FunctionDefinition
{
struct FunctionDefinition * prev;
struct FunctionDefinition * next;
struct Location loc;
struct __ecereNameSpace__ecere__sys__OldList * specifiers;
struct Declarator * declarator;
struct __ecereNameSpace__ecere__sys__OldList * declarations;
struct Statement * body;
struct __ecereNameSpace__ecere__com__Class * _class;
struct __ecereNameSpace__ecere__sys__OldList attached;
int declMode;
struct Type * type;
struct Symbol * propSet;
int tempCount;
unsigned int propertyNoThis;
} ecere_gcc_struct;
extern void ProcessFunctionBody(struct FunctionDefinition * func, struct Statement * body);
extern struct External * MkExternalFunction(struct FunctionDefinition * function);
struct TypeName;
struct TypeName
{
struct TypeName * prev;
struct TypeName * next;
struct Location loc;
struct __ecereNameSpace__ecere__sys__OldList * qualifiers;
struct Declarator * declarator;
int classObjectType;
struct Expression * bitCount;
} ecere_gcc_struct;
extern struct TypeName * MkTypeName(struct __ecereNameSpace__ecere__sys__OldList * qualifiers, struct Declarator * declarator);
extern struct Expression * MkExpCast(struct TypeName * typeName, struct Expression * expression);
extern struct Expression * MkExpTypeSize(struct TypeName * typeName);
struct Expression
{
struct Expression * prev;
struct Expression * next;
struct Location loc;
int type;
union
{
struct
{
char * constant;
struct Identifier * identifier;
} ecere_gcc_struct __anon1;
struct Statement * compound;
struct Instantiation * instance;
struct
{
char * string;
unsigned int intlString;
unsigned int wideString;
} ecere_gcc_struct __anon2;
struct __ecereNameSpace__ecere__sys__OldList * list;
struct
{
struct __ecereNameSpace__ecere__sys__OldList * specifiers;
struct Declarator * decl;
} ecere_gcc_struct _classExp;
struct
{
struct Identifier * id;
} ecere_gcc_struct classData;
struct
{
struct Expression * exp;
struct __ecereNameSpace__ecere__sys__OldList * arguments;
struct Location argLoc;
} ecere_gcc_struct call;
struct
{
struct Expression * exp;
struct __ecereNameSpace__ecere__sys__OldList * index;
} ecere_gcc_struct index;
struct
{
struct Expression * exp;
struct Identifier * member;
int memberType;
unsigned int thisPtr;
} ecere_gcc_struct member;
struct
{
int op;
struct Expression * exp1;
struct Expression * exp2;
} ecere_gcc_struct op;
struct TypeName * typeName;
struct Specifier * _class;
struct
{
struct TypeName * typeName;
struct Expression * exp;
} ecere_gcc_struct cast;
struct
{
struct Expression * cond;
struct __ecereNameSpace__ecere__sys__OldList * exp;
struct Expression * elseExp;
} ecere_gcc_struct cond;
struct
{
struct TypeName * typeName;
struct Expression * size;
} ecere_gcc_struct _new;
struct
{
struct TypeName * typeName;
struct Expression * size;
struct Expression * exp;
} ecere_gcc_struct _renew;
struct
{
char * table;
struct Identifier * id;
} ecere_gcc_struct db;
struct
{
struct Expression * ds;
struct Expression * name;
} ecere_gcc_struct dbopen;
struct
{
struct TypeName * typeName;
struct Initializer * initializer;
} ecere_gcc_struct initializer;
struct
{
struct Expression * exp;
struct TypeName * typeName;
} ecere_gcc_struct vaArg;
struct
{
struct TypeName * typeName;
struct Identifier * id;
} ecere_gcc_struct offset;
} ecere_gcc_struct __anon1;
unsigned int debugValue;
struct __ecereNameSpace__ecere__com__DataValue val;
uint64 address;
unsigned int hasAddress;
struct Type * expType;
struct Type * destType;
unsigned int usage;
int tempCount;
unsigned int byReference;
unsigned int isConstant;
unsigned int addedThis;
unsigned int needCast;
unsigned int thisPtr;
unsigned int opDestType;
unsigned int usedInComparison;
unsigned int ambiguousUnits;
unsigned int parentOpDestType;
unsigned int needTemplateCast;
} ecere_gcc_struct;
struct Operand;
struct OpTable
{
unsigned int (* Add)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* Sub)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* Mul)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* Div)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* Mod)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* Neg)(struct Expression *, struct Operand *);
unsigned int (* Inc)(struct Expression *, struct Operand *);
unsigned int (* Dec)(struct Expression *, struct Operand *);
unsigned int (* Asign)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* AddAsign)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* SubAsign)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* MulAsign)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* DivAsign)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* ModAsign)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* BitAnd)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* BitOr)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* BitXor)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* LShift)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* RShift)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* BitNot)(struct Expression *, struct Operand *);
unsigned int (* AndAsign)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* OrAsign)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* XorAsign)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* LShiftAsign)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* RShiftAsign)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* Not)(struct Expression *, struct Operand *);
unsigned int (* Equ)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* Nqu)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* And)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* Or)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* Grt)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* Sma)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* GrtEqu)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* SmaEqu)(struct Expression *, struct Operand *, struct Operand *);
unsigned int (* Cond)(struct Expression *, struct Operand *, struct Operand *, struct Operand *);
} ecere_gcc_struct;
struct Operand
{
int kind;
struct Type * type;
unsigned int ptrSize;
union
{
char c;
unsigned char uc;
short s;
unsigned short us;
int i;
unsigned int ui;
float f;
double d;
long long i64;
uint64 ui64;
} ecere_gcc_struct __anon1;
struct OpTable ops;
} ecere_gcc_struct;
extern struct Operand GetOperand(struct Expression * exp);
struct __ecereNameSpace__ecere__sys__BinaryTree;
struct __ecereNameSpace__ecere__sys__BinaryTree
{
struct __ecereNameSpace__ecere__sys__BTNode * root;
int count;
int (* CompareKey)(struct __ecereNameSpace__ecere__sys__BinaryTree * tree, uintptr_t a, uintptr_t b);
void (* FreeKey)(void * key);
} ecere_gcc_struct;
void __ecereMethod___ecereNameSpace__ecere__sys__BinaryTree_Remove(struct __ecereNameSpace__ecere__sys__BinaryTree * this, struct __ecereNameSpace__ecere__sys__BTNode * node);
struct __ecereNameSpace__ecere__sys__BTNode * __ecereProp___ecereNameSpace__ecere__sys__BinaryTree_Get_first(struct __ecereNameSpace__ecere__sys__BinaryTree * this);
struct TemplateParameter;
struct Specifier
{
struct Specifier * prev;
struct Specifier * next;
struct Location loc;
int type;
union
{
int specifier;
struct
{
struct ExtDecl * extDecl;
char * name;
struct Symbol * symbol;
struct __ecereNameSpace__ecere__sys__OldList * templateArgs;
struct Specifier * nsSpec;
} ecere_gcc_struct __anon1;
struct
{
struct Identifier * id;
struct __ecereNameSpace__ecere__sys__OldList * list;
struct __ecereNameSpace__ecere__sys__OldList * baseSpecs;
struct __ecereNameSpace__ecere__sys__OldList * definitions;
unsigned int addNameSpace;
struct Context * ctx;
struct ExtDecl * extDeclStruct;
} ecere_gcc_struct __anon2;
struct Expression * expression;
struct Specifier * _class;
struct TemplateParameter * templateParameter;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct;
struct Type
{
struct Type * prev;
struct Type * next;
int refCount;
union
{
struct Symbol * _class;
struct
{
struct __ecereNameSpace__ecere__sys__OldList members;
char * enumName;
} ecere_gcc_struct __anon1;
struct
{
struct Type * returnType;
struct __ecereNameSpace__ecere__sys__OldList params;
struct Symbol * thisClass;
unsigned int staticMethod;
struct TemplateParameter * thisClassTemplate;
} ecere_gcc_struct __anon2;
struct
{
struct __ecereNameSpace__ecere__com__Method * method;
struct __ecereNameSpace__ecere__com__Class * methodClass;
struct __ecereNameSpace__ecere__com__Class * usedClass;
} ecere_gcc_struct __anon3;
struct
{
struct Type * arrayType;
int arraySize;
struct Expression * arraySizeExp;
unsigned int freeExp;
struct Symbol * enumClass;
} ecere_gcc_struct __anon4;
struct Type * type;
struct TemplateParameter * templateParameter;
} ecere_gcc_struct __anon1;
int kind;
unsigned int size;
char * name;
char * typeName;
struct __ecereNameSpace__ecere__com__Class * thisClassFrom;
int promotedFrom;
int classObjectType;
int alignment;
unsigned int offset;
int bitFieldCount;
int count;
int bitMemberSize;
unsigned int isSigned : 1;
unsigned int constant : 1;
unsigned int truth : 1;
unsigned int byReference : 1;
unsigned int extraParam : 1;
unsigned int directClassAccess : 1;
unsigned int computing : 1;
unsigned int keepCast : 1;
unsigned int passAsTemplate : 1;
unsigned int dllExport : 1;
unsigned int attrStdcall : 1;
unsigned int declaredWithStruct : 1;
unsigned int typedByReference : 1;
unsigned int casted : 1;
unsigned int pointerAlignment : 1;
unsigned int isLong : 1;
unsigned int signedBeforePromotion : 1;
unsigned int isVector : 1;
} ecere_gcc_struct;
unsigned int __ecereProp_Type_Get_isPointerTypeSize(struct Type * this);
unsigned int __ecereProp_Type_Get_isPointerType(struct Type * this);
struct __ecereNameSpace__ecere__com__DataMember;
struct __ecereNameSpace__ecere__com__DataMember
{
struct __ecereNameSpace__ecere__com__DataMember * prev;
struct __ecereNameSpace__ecere__com__DataMember * next;
const char * name;
unsigned int isProperty;
int memberAccess;
int id;
struct __ecereNameSpace__ecere__com__Class * _class;
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Class * dataTypeClass;
struct Type * dataType;
int type;
int offset;
int memberID;
struct __ecereNameSpace__ecere__sys__OldList members;
struct __ecereNameSpace__ecere__sys__BinaryTree membersAlpha;
int memberOffset;
short structAlignment;
short pointerAlignment;
} ecere_gcc_struct;
extern struct __ecereNameSpace__ecere__com__DataMember * __ecereNameSpace__ecere__com__eClass_AddDataMember(struct __ecereNameSpace__ecere__com__Class * _class, const char * name, const char * type, unsigned int size, unsigned int alignment, int declMode);
struct __ecereNameSpace__ecere__com__Property;
struct __ecereNameSpace__ecere__com__ClassTemplateArgument
{
union
{
struct
{
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Class * dataTypeClass;
} ecere_gcc_struct __anon1;
struct __ecereNameSpace__ecere__com__DataValue expression;
struct
{
const char * memberString;
union
{
struct __ecereNameSpace__ecere__com__DataMember * member;
struct __ecereNameSpace__ecere__com__Property * prop;
struct __ecereNameSpace__ecere__com__Method * method;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct __anon2;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Property
{
struct __ecereNameSpace__ecere__com__Property * prev;
struct __ecereNameSpace__ecere__com__Property * next;
const char * name;
unsigned int isProperty;
int memberAccess;
int id;
struct __ecereNameSpace__ecere__com__Class * _class;
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Class * dataTypeClass;
struct Type * dataType;
void (* Set)(void * , int);
int (* Get)(void * );
unsigned int (* IsSet)(void * );
void * data;
void * symbol;
int vid;
unsigned int conversion;
unsigned int watcherOffset;
const char * category;
unsigned int compiled;
unsigned int selfWatchable;
unsigned int isWatchable;
} ecere_gcc_struct;
extern void __ecereNameSpace__ecere__com__eInstance_FireSelfWatchers(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property);
extern void __ecereNameSpace__ecere__com__eInstance_StopWatching(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property, struct __ecereNameSpace__ecere__com__Instance * object);
extern void __ecereNameSpace__ecere__com__eInstance_Watch(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property, void * object, void (* callback)(void * , void * ));
extern void __ecereNameSpace__ecere__com__eInstance_FireWatchers(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property);
struct Symbol
{
char * string;
struct Symbol * parent;
struct Symbol * left;
struct Symbol * right;
int depth;
struct Type * type;
union
{
struct __ecereNameSpace__ecere__com__Method * method;
struct __ecereNameSpace__ecere__com__Property * _property;
struct __ecereNameSpace__ecere__com__Class * registered;
} ecere_gcc_struct __anon1;
unsigned int notYetDeclared;
union
{
struct
{
struct External * pointerExternal;
struct External * structExternal;
} ecere_gcc_struct __anon1;
struct
{
struct External * externalGet;
struct External * externalSet;
struct External * externalPtr;
struct External * externalIsSet;
} ecere_gcc_struct __anon2;
struct
{
struct External * methodExternal;
struct External * methodCodeExternal;
} ecere_gcc_struct __anon3;
} ecere_gcc_struct __anon2;
unsigned int imported;
unsigned int declaredStructSym;
struct __ecereNameSpace__ecere__com__Class * _class;
unsigned int declaredStruct;
unsigned int needConstructor;
unsigned int needDestructor;
char * constructorName;
char * structName;
char * className;
char * destructorName;
struct ModuleImport * module;
struct ClassImport * _import;
struct Location nameLoc;
unsigned int isParam;
unsigned int isRemote;
unsigned int isStruct;
unsigned int fireWatchersDone;
int declaring;
unsigned int classData;
unsigned int isStatic;
char * shortName;
struct __ecereNameSpace__ecere__sys__OldList * templateParams;
struct __ecereNameSpace__ecere__sys__OldList templatedClasses;
struct Context * ctx;
int isIterator;
struct Expression * propCategory;
unsigned int mustRegister;
} ecere_gcc_struct;
extern struct __ecereNameSpace__ecere__com__ClassTemplateArgument * FindTemplateArg(struct __ecereNameSpace__ecere__com__Class * _class, struct TemplateParameter * param);
struct __ecereNameSpace__ecere__com__Module;
extern struct __ecereNameSpace__ecere__com__Property * __ecereNameSpace__ecere__com__eClass_FindProperty(struct __ecereNameSpace__ecere__com__Class * _class, const char * name, struct __ecereNameSpace__ecere__com__Instance * module);
extern struct __ecereNameSpace__ecere__com__Instance * privateModule;
extern struct __ecereNameSpace__ecere__com__Class * __ecereNameSpace__ecere__com__eSystem_FindClass(struct __ecereNameSpace__ecere__com__Instance * module, const char * name);
extern struct __ecereNameSpace__ecere__com__GlobalFunction * __ecereNameSpace__ecere__com__eSystem_RegisterFunction(const char * name, const char * type, void * func, struct __ecereNameSpace__ecere__com__Instance * module, int declMode);
extern struct __ecereNameSpace__ecere__com__Class * __ecereNameSpace__ecere__com__eSystem_RegisterClass(int type, const char * name, const char * baseName, int size, int sizeClass, unsigned int (* Constructor)(void * ), void (* Destructor)(void * ), struct __ecereNameSpace__ecere__com__Instance * module, int declMode, int inheritanceAccess);
extern struct __ecereNameSpace__ecere__com__Instance * __thisModule;
struct __ecereNameSpace__ecere__com__BitMember;
struct __ecereNameSpace__ecere__com__BitMember
{
struct __ecereNameSpace__ecere__com__BitMember * prev;
struct __ecereNameSpace__ecere__com__BitMember * next;
const char * name;
unsigned int isProperty;
int memberAccess;
int id;
struct __ecereNameSpace__ecere__com__Class * _class;
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Class * dataTypeClass;
struct Type * dataType;
int type;
int size;
int pos;
uint64 mask;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__ClassProperty;
struct __ecereNameSpace__ecere__com__ClassProperty
{
const char * name;
struct __ecereNameSpace__ecere__com__ClassProperty * parent;
struct __ecereNameSpace__ecere__com__ClassProperty * left;
struct __ecereNameSpace__ecere__com__ClassProperty * right;
int depth;
void (* Set)(struct __ecereNameSpace__ecere__com__Class *, long long);
long long (* Get)(struct __ecereNameSpace__ecere__com__Class *);
const char * dataTypeString;
struct Type * dataType;
unsigned int constant;
} ecere_gcc_struct;
struct ClassDefinition;
struct External
{
struct External * prev;
struct External * next;
struct Location loc;
int type;
struct Symbol * symbol;
union
{
struct FunctionDefinition * function;
struct ClassDefinition * _class;
struct Declaration * declaration;
char * importString;
struct Identifier * id;
struct DBTableDef * table;
char * pragma;
} ecere_gcc_struct __anon1;
int importType;
struct External * fwdDecl;
struct __ecereNameSpace__ecere__com__Instance * outgoing;
struct __ecereNameSpace__ecere__com__Instance * incoming;
int nonBreakableIncoming;
} ecere_gcc_struct;
struct Context
{
struct Context * parent;
struct __ecereNameSpace__ecere__sys__BinaryTree types;
struct __ecereNameSpace__ecere__sys__BinaryTree classes;
struct __ecereNameSpace__ecere__sys__BinaryTree symbols;
struct __ecereNameSpace__ecere__sys__BinaryTree structSymbols;
int nextID;
int simpleID;
struct __ecereNameSpace__ecere__sys__BinaryTree templateTypes;
struct ClassDefinition * classDef;
unsigned int templateTypesOnly;
unsigned int hasNameSpace;
} ecere_gcc_struct;
struct ClassDefinition
{
struct ClassDefinition * prev;
struct ClassDefinition * next;
struct Location loc;
struct Specifier * _class;
struct __ecereNameSpace__ecere__sys__OldList * baseSpecs;
struct __ecereNameSpace__ecere__sys__OldList * definitions;
struct Symbol * symbol;
struct Location blockStart;
struct Location nameLoc;
int declMode;
unsigned int deleteWatchable;
} ecere_gcc_struct;
void __ecereMethod_External_CreateUniqueEdge(struct External * this, struct External * from, unsigned int soft);
struct Enumerator;
struct Enumerator
{
struct Enumerator * prev;
struct Enumerator * next;
struct Location loc;
struct Identifier * id;
struct Expression * exp;
struct __ecereNameSpace__ecere__sys__OldList * attribs;
} ecere_gcc_struct;
struct TemplateArgument;
struct TemplateParameter
{
struct TemplateParameter * prev;
struct TemplateParameter * next;
struct Location loc;
int type;
struct Identifier * identifier;
union
{
struct TemplateDatatype * dataType;
int memberType;
} ecere_gcc_struct __anon1;
struct TemplateArgument * defaultArgument;
const char * dataTypeString;
struct Type * baseType;
} ecere_gcc_struct;
struct TemplateArgument
{
struct TemplateArgument * prev;
struct TemplateArgument * next;
struct Location loc;
struct Identifier * name;
int type;
union
{
struct Expression * expression;
struct Identifier * identifier;
struct TemplateDatatype * templateDatatype;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct;
struct ClassDef;
typedef union YYSTYPE
{
int specifierType;
int i;
int declMode;
struct Identifier * id;
struct Expression * exp;
struct Specifier * specifier;
struct __ecereNameSpace__ecere__sys__OldList * list;
struct Enumerator * enumerator;
struct Declarator * declarator;
struct Pointer * pointer;
struct Initializer * initializer;
struct InitDeclarator * initDeclarator;
struct TypeName * typeName;
struct Declaration * declaration;
struct Statement * stmt;
struct FunctionDefinition * function;
struct External * external;
struct Context * context;
struct AsmField * asmField;
struct Attrib * attrib;
struct ExtDecl * extDecl;
struct Attribute * attribute;
struct Instantiation * instance;
struct MembersInit * membersInit;
struct MemberInit * memberInit;
struct ClassFunction * classFunction;
struct ClassDefinition * _class;
struct ClassDef * classDef;
struct PropertyDef * prop;
char * string;
struct Symbol * symbol;
struct PropertyWatch * propertyWatch;
struct TemplateParameter * templateParameter;
struct TemplateArgument * templateArgument;
struct TemplateDatatype * templateDatatype;
struct DBTableEntry * dbtableEntry;
struct DBIndexItem * dbindexItem;
struct DBTableDef * dbtableDef;
} ecere_gcc_struct YYSTYPE;
extern YYSTYPE yylval;
struct ClassDef
{
struct ClassDef * prev;
struct ClassDef * next;
struct Location loc;
int type;
union
{
struct Declaration * decl;
struct ClassFunction * function;
struct __ecereNameSpace__ecere__sys__OldList * defProperties;
struct PropertyDef * propertyDef;
struct PropertyWatch * propertyWatch;
char * designer;
struct Identifier * defaultProperty;
struct
{
struct Identifier * id;
struct Initializer * initializer;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct __anon1;
int memberAccess;
void * object;
} ecere_gcc_struct;
extern struct ClassDef * MkClassDefFunction(struct ClassFunction * function);
struct __ecereNameSpace__ecere__com__NameSpace;
struct __ecereNameSpace__ecere__com__NameSpace
{
const char * name;
struct __ecereNameSpace__ecere__com__NameSpace * btParent;
struct __ecereNameSpace__ecere__com__NameSpace * left;
struct __ecereNameSpace__ecere__com__NameSpace * right;
int depth;
struct __ecereNameSpace__ecere__com__NameSpace * parent;
struct __ecereNameSpace__ecere__sys__BinaryTree nameSpaces;
struct __ecereNameSpace__ecere__sys__BinaryTree classes;
struct __ecereNameSpace__ecere__sys__BinaryTree defines;
struct __ecereNameSpace__ecere__sys__BinaryTree functions;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Class
{
struct __ecereNameSpace__ecere__com__Class * prev;
struct __ecereNameSpace__ecere__com__Class * next;
const char * name;
int offset;
int structSize;
void * * _vTbl;
int vTblSize;
unsigned int (* Constructor)(void * );
void (* Destructor)(void * );
int offsetClass;
int sizeClass;
struct __ecereNameSpace__ecere__com__Class * base;
struct __ecereNameSpace__ecere__sys__BinaryTree methods;
struct __ecereNameSpace__ecere__sys__BinaryTree members;
struct __ecereNameSpace__ecere__sys__BinaryTree prop;
struct __ecereNameSpace__ecere__sys__OldList membersAndProperties;
struct __ecereNameSpace__ecere__sys__BinaryTree classProperties;
struct __ecereNameSpace__ecere__sys__OldList derivatives;
int memberID;
int startMemberID;
int type;
struct __ecereNameSpace__ecere__com__Instance * module;
struct __ecereNameSpace__ecere__com__NameSpace * nameSpace;
const char * dataTypeString;
struct Type * dataType;
int typeSize;
int defaultAlignment;
void (* Initialize)();
int memberOffset;
struct __ecereNameSpace__ecere__sys__OldList selfWatchers;
const char * designerClass;
unsigned int noExpansion;
const char * defaultProperty;
unsigned int comRedefinition;
int count;
int isRemote;
unsigned int internalDecl;
void * data;
unsigned int computeSize;
short structAlignment;
short pointerAlignment;
int destructionWatchOffset;
unsigned int fixed;
struct __ecereNameSpace__ecere__sys__OldList delayedCPValues;
int inheritanceAccess;
const char * fullName;
void * symbol;
struct __ecereNameSpace__ecere__sys__OldList conversions;
struct __ecereNameSpace__ecere__sys__OldList templateParams;
struct __ecereNameSpace__ecere__com__ClassTemplateArgument * templateArgs;
struct __ecereNameSpace__ecere__com__Class * templateClass;
struct __ecereNameSpace__ecere__sys__OldList templatized;
int numParams;
unsigned int isInstanceClass;
unsigned int byValueSystemClass;
void * bindingsClass;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Application
{
int argc;
const char * * argv;
int exitCode;
unsigned int isGUIApp;
struct __ecereNameSpace__ecere__sys__OldList allModules;
char * parsedCommand;
struct __ecereNameSpace__ecere__com__NameSpace systemNameSpace;
} ecere_gcc_struct;
void GetNameSpaceString(struct __ecereNameSpace__ecere__com__NameSpace * ns, char * string)
{
if(ns->parent)
GetNameSpaceString(ns->parent, string);
if(ns->name)
{
strcat(string, ns->name);
strcat(string, "::");
}
}
static struct __ecereNameSpace__ecere__com__Class * __ecereClass_ClassPropertyValue;
struct External * ProcessClassFunction(struct __ecereNameSpace__ecere__com__Class * owningClass, struct ClassFunction * func, struct __ecereNameSpace__ecere__sys__OldList * defs, struct External * after, unsigned int makeStatic)
{
struct Type * type = (((void *)0));
struct Symbol * symbol;
struct External * external = (((void *)0));
if(defs && func->declarator)
{
struct FunctionDefinition * function = (((void *)0));
struct Symbol * propSymbol;
if(inCompiler)
{
if(!func->specifiers)
func->specifiers = MkList();
if(makeStatic)
{
struct Specifier * s;
for(s = (*func->specifiers).first; s; s = s->next)
if(s->type == 0 && s->__anon1.specifier == STATIC)
break;
if(!s)
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Insert((&*func->specifiers), (((void *)0)), MkSpecifier(STATIC));
}
}
propSymbol = func->declarator->symbol;
ReplaceThisClassSpecifiers(func->specifiers, owningClass);
if(propSymbol->__anon2.__anon2.externalGet == (struct External *)func)
func->declarator->symbol = (((void *)0));
else if(propSymbol->__anon2.__anon2.externalSet == (struct External *)func)
func->declarator->symbol = (((void *)0));
else if(propSymbol->__anon2.__anon2.externalIsSet == (struct External *)func)
func->declarator->symbol = (((void *)0));
{
function = _MkFunction(func->specifiers, func->declarator, (((void *)0)), 0);
function->propSet = func->propSet;
function->type = func->type;
if(func->type)
func->type->refCount++;
ProcessFunctionBody(function, func->body);
external = MkExternalFunction(function);
external->symbol = func->declarator->symbol;
external->__anon1.function->_class = func->_class;
}
symbol = func->declarator->symbol;
if(!func->dontMangle)
{
struct __ecereNameSpace__ecere__com__Method * method = func->declarator->symbol->__anon1.method;
func->declarator->symbol->__anon2.__anon3.methodExternal = external;
if(method && method->symbol)
((struct Symbol *)method->symbol)->__anon2.__anon3.methodCodeExternal = external;
if(method && method->type == 1)
{
struct Type * methodDataType;
ProcessMethodType(method);
methodDataType = method->dataType;
type = symbol->type;
if(!type->__anon1.__anon2.staticMethod && !type->__anon1.__anon2.thisClass && !type->__anon1.__anon2.thisClassTemplate)
{
if(method->dataType->__anon1.__anon2.thisClassTemplate)
{
if(owningClass->templateArgs)
{
struct __ecereNameSpace__ecere__com__ClassTemplateArgument * arg = FindTemplateArg(owningClass, method->dataType->__anon1.__anon2.thisClassTemplate);
type->byReference = method->dataType->byReference;
methodDataType = ProcessTypeString(method->dataTypeString, 0);
type->__anon1.__anon2.thisClass = methodDataType->__anon1.__anon2.thisClass = (arg && (*arg).__anon1.__anon1.dataTypeString) ? FindClass((*arg).__anon1.__anon1.dataTypeString) : (((void *)0));
}
}
else if(method->dataType->__anon1.__anon2.staticMethod)
type->__anon1.__anon2.staticMethod = 1;
else if(method->dataType->__anon1.__anon2.thisClass)
{
type->__anon1.__anon2.thisClass = method->dataType->__anon1.__anon2.thisClass;
type->byReference = method->dataType->byReference;
}
else
{
if(!owningClass->symbol)
owningClass->symbol = FindClass(owningClass->fullName);
type->__anon1.__anon2.thisClass = owningClass->symbol;
type->extraParam = 1;
}
}
yylloc = func->loc;
if(!MatchTypes(type, methodDataType, (((void *)0)), owningClass, method->_class, 1, 1, 1, 0, 1))
{
Compiler_Error(__ecereNameSpace__ecere__GetTranslatedString("ec", "Incompatible virtual function %s\n", (((void *)0))), method->name);
}
else
{
struct Type * typeParam;
struct Declarator * funcDecl = GetFuncDecl(func->declarator);
if(funcDecl->__anon1.function.parameters && (*funcDecl->__anon1.function.parameters).first)
{
struct TypeName * param = (*funcDecl->__anon1.function.parameters).first;
for(typeParam = methodDataType->__anon1.__anon2.params.first; typeParam && param; typeParam = typeParam->next)
{
if(typeParam->classObjectType)
{
param->classObjectType = typeParam->classObjectType;
if(param->declarator && param->declarator->symbol)
param->declarator->symbol->type->classObjectType = typeParam->classObjectType;
}
param = param ? param->next : (((void *)0));
}
}
}
if(methodDataType != method->dataType)
FreeType(methodDataType);
}
else
{
type = symbol->type;
if(!type->__anon1.__anon2.staticMethod && !type->__anon1.__anon2.thisClass)
{
if(owningClass && !owningClass->symbol)
owningClass->symbol = FindClass(owningClass->fullName);
type->__anon1.__anon2.thisClass = owningClass ? FindClass(owningClass->fullName) : (((void *)0));
}
}
}
else
{
if(symbol->type && !symbol->type->__anon1.__anon2.staticMethod && !symbol->type->__anon1.__anon2.thisClass)
{
if(!owningClass->symbol)
owningClass->symbol = FindClass(owningClass->fullName);
symbol->type->__anon1.__anon2.thisClass = owningClass->symbol;
}
if(propSymbol->__anon2.__anon2.externalSet == (struct External *)func && propSymbol->__anon1._property && propSymbol->__anon1._property->conversion)
{
if(symbol->type->__anon1.__anon2.thisClass && symbol->type->classObjectType != 1)
{
if(owningClass->type != 1)
symbol->type->__anon1.__anon2.thisClass = (((void *)0));
}
}
if(propSymbol->__anon2.__anon2.externalGet == (struct External *)func)
{
propSymbol->__anon2.__anon2.externalGet = external;
}
else if(propSymbol->__anon2.__anon2.externalSet == (struct External *)func)
{
propSymbol->__anon2.__anon2.externalSet = external;
}
else if(propSymbol->__anon2.__anon2.externalIsSet == (struct External *)func)
{
propSymbol->__anon2.__anon2.externalIsSet = external;
}
else
{
}
}
if(inCompiler)
{
if(func->body)
{
func->declarator = (((void *)0));
func->specifiers = (((void *)0));
func->body = (((void *)0));
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Insert(defs, after, external);
}
else
{
struct __ecereNameSpace__ecere__com__Method * method = func->declarator->symbol->__anon1.method;
if(method && method->symbol)
((struct Symbol *)method->symbol)->__anon2.__anon3.methodCodeExternal = (((void *)0));
if(func->declarator->symbol && func->declarator->symbol->__anon2.__anon3.methodExternal == external)
func->declarator->symbol->__anon2.__anon3.methodExternal = (((void *)0));
func->declarator = (((void *)0));
func->specifiers = (((void *)0));
FreeExternal(external);
}
}
else
{
__ecereMethod___ecereNameSpace__ecere__sys__BinaryTree_Remove(&globalContext->symbols, (struct __ecereNameSpace__ecere__sys__BTNode *)symbol);
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Add((&*excludedSymbols), symbol);
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Insert(defs, after, external);
external->__anon1.function->declarator = CopyDeclarator(external->__anon1.function->declarator);
external->__anon1.function->specifiers = CopyList(external->__anon1.function->specifiers, (void *)(CopySpecifier));
external->__anon1.function->body = (((void *)0));
}
}
return external;
}
extern char * __ecereNameSpace__ecere__com__PrintString(struct __ecereNameSpace__ecere__com__Class * class, const void * object, ...);
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass_Context;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass_Type;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass_Symbol;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass___ecereNameSpace__ecere__com__List_TPL_ClassPropertyValue_;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass_char__PTR_;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass_uint;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass___ecereNameSpace__ecere__com__TemplateMemberType;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass___ecereNameSpace__ecere__com__List;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass___ecereNameSpace__ecere__com__Module;
struct __ecereNameSpace__ecere__com__Module
{
struct __ecereNameSpace__ecere__com__Instance * application;
struct __ecereNameSpace__ecere__sys__OldList classes;
struct __ecereNameSpace__ecere__sys__OldList defines;
struct __ecereNameSpace__ecere__sys__OldList functions;
struct __ecereNameSpace__ecere__sys__OldList modules;
struct __ecereNameSpace__ecere__com__Instance * prev;
struct __ecereNameSpace__ecere__com__Instance * next;
const char * name;
void * library;
void * Unload;
int importType;
int origImportType;
struct __ecereNameSpace__ecere__com__NameSpace privateNameSpace;
struct __ecereNameSpace__ecere__com__NameSpace publicNameSpace;
} ecere_gcc_struct;
void __ecereDestructor_ClassPropertyValue(struct __ecereNameSpace__ecere__com__Instance * this)
{
__attribute__((unused)) struct ClassPropertyValue * __ecerePointer_ClassPropertyValue = (struct ClassPropertyValue *)(this ? (((char *)this) + __ecereClass_ClassPropertyValue->offset) : 0);
{
FreeIdentifier(__ecerePointer_ClassPropertyValue->id);
}
}
void CreateRegisterModuleBody()
{
if(!registerModuleBody && inCompiler)
{
char registerName[1024], moduleName[274];
struct __ecereNameSpace__ecere__sys__OldList * specifiers;
struct Declarator * declarator;
struct TypeName * moduleParam;
registerModuleBody = MkCompoundStmt(MkList(), MkList());
registerModuleBody->__anon1.compound.context = __extension__ ({
struct Context * __ecereInstance1 = __ecereNameSpace__ecere__com__eInstance_New(__ecereClass_Context);
__ecereInstance1->parent = globalContext, __ecereInstance1;
});
ListAdd(registerModuleBody->__anon1.compound.declarations, MkDeclaration((specifiers = MkListOne(MkSpecifierName("ecere::com::Class"))), MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("class")), (((void *)0))))));
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Add((&*specifiers), MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(__ecereNameSpace__ecere__sys__CopyString("unused"), (((void *)0))))))));
specifiers = MkList();
ListAdd(specifiers, MkSpecifier(VOID));
moduleParam = MkTypeName(MkListOne(MkSpecifierName("Module")), MkDeclaratorIdentifier(MkIdentifier("module")));
__ecereNameSpace__ecere__sys__GetLastDirectory(outputFile, moduleName);
__ecereNameSpace__ecere__sys__StripExtension(moduleName);
FixModuleName(moduleName);
sprintf(registerName, "__ecereRegisterModule_%s", moduleName);
declarator = MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(registerName)), MkListOne(moduleParam));
{
struct FunctionDefinition * function = _MkFunction(specifiers, declarator, (((void *)0)), 0);
ProcessFunctionBody(function, registerModuleBody);
function->declMode = 0;
if(!ast)
ast = MkList();
ListAdd(ast, (registerModuleExternal = MkExternalFunction(function)));
DeclareStruct(registerModuleExternal, "ecere::com::Instance", 0, 1);
DeclareStruct(registerModuleExternal, "ecere::com::Module", 0, 1);
}
}
if(!unregisterModuleBody && inCompiler)
{
char registerName[1024], moduleName[274];
struct __ecereNameSpace__ecere__sys__OldList * specifiers;
struct Declarator * declarator;
struct TypeName * moduleParam;
unregisterModuleBody = MkCompoundStmt(MkList(), MkList());
unregisterModuleBody->__anon1.compound.context = __extension__ ({
struct Context * __ecereInstance1 = __ecereNameSpace__ecere__com__eInstance_New(__ecereClass_Context);
__ecereInstance1->parent = globalContext, __ecereInstance1;
});
specifiers = MkList();
ListAdd(specifiers, MkSpecifier(VOID));
moduleParam = MkTypeName(MkListOne(MkSpecifierName("Module")), MkDeclaratorIdentifier(MkIdentifier("module")));
__ecereNameSpace__ecere__sys__GetLastDirectory(outputFile, moduleName);
__ecereNameSpace__ecere__sys__StripExtension(moduleName);
FixModuleName(moduleName);
sprintf(registerName, "__ecereUnregisterModule_%s", moduleName);
declarator = MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(registerName)), MkListOne(moduleParam));
{
struct FunctionDefinition * function = _MkFunction(specifiers, declarator, (((void *)0)), 0);
ProcessFunctionBody(function, unregisterModuleBody);
function->declMode = 0;
if(!ast)
ast = MkList();
ListAdd(ast, (unregisterModuleExternal = MkExternalFunction(function)));
DeclareStruct(unregisterModuleExternal, "ecere::com::Instance", 0, 1);
DeclareStruct(unregisterModuleExternal, "ecere::com::Module", 0, 1);
}
}
}
void __ecereCreateModuleInstances_pass1()
{
classPropValues = __ecereNameSpace__ecere__com__eInstance_New(__ecereClass___ecereNameSpace__ecere__com__List_TPL_ClassPropertyValue_);
__ecereNameSpace__ecere__com__eInstance_IncRef(classPropValues);
}
void RegisterMembersAndProperties(struct __ecereNameSpace__ecere__com__Class * regClass, unsigned int isMember, const char * className, struct Statement * statement)
{
struct __ecereNameSpace__ecere__com__DataMember * dataMember = isMember ? (struct __ecereNameSpace__ecere__com__DataMember *)regClass : (((void *)0));
struct __ecereNameSpace__ecere__com__DataMember * member;
struct __ecereNameSpace__ecere__com__Property * prop;
struct Expression * exp;
struct Statement * stmt;
char dataMemberSize[16];
unsigned int lastOffset = 0;
int privateID = 0;
unsigned int privateMembers = 0;
unsigned int privateAlignment = 0;
unsigned int privateAlignmentPtr = 0;
sprintf(dataMemberSize, "%d", (int)sizeof(struct __ecereNameSpace__ecere__com__DataMember *));
if(!isMember)
{
for(prop = regClass->conversions.first; prop; prop = prop->next)
{
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
char name[1024];
ListAdd(args, MkExpIdentifier(MkIdentifier(className)));
ListAdd(args, MkExpConstant("0"));
{
char * string = QMkString(prop->dataTypeString);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
if(prop->Set)
{
strcpy(name, "__ecereProp_");
FullClassNameCat(name, regClass->fullName, 0);
strcat(name, "_Set_");
FullClassNameCat(name, prop->name, 1);
ListAdd(args, MkExpIdentifier(MkIdentifier(name)));
}
else
ListAdd(args, MkExpConstant("0"));
if(prop->Get)
{
strcpy(name, "__ecereProp_");
FullClassNameCat(name, regClass->fullName, 0);
strcat(name, "_Get_");
FullClassNameCat(name, prop->name, 1);
ListAdd(args, MkExpIdentifier(MkIdentifier(name)));
}
else
ListAdd(args, MkExpConstant("0"));
switch(prop->memberAccess)
{
case 3:
ListAdd(args, MkExpIdentifier(MkIdentifier("staticAccess")));
break;
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
break;
case 1:
default:
ListAdd(args, MkExpIdentifier(MkIdentifier("publicAccess")));
break;
}
strcpy(name, "__ecereProp_");
FullClassNameCat(name, regClass->fullName, 0);
strcat(name, "_");
FullClassNameCat(name, prop->name, 1);
stmt = MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', MkExpCall(MkExpIdentifier(MkIdentifier("eClass_AddProperty")), args))));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
}
for(member = isMember ? dataMember->members.first : regClass->membersAndProperties.first; member; member = member->next)
{
if(member->isProperty)
{
prop = (struct __ecereNameSpace__ecere__com__Property *)member;
{
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
char name[1024], nameM[1024];
char * string = QMkString(prop->name);
ListAdd(args, MkExpIdentifier(MkIdentifier(className)));
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
{
char * string = QMkString(prop->dataTypeString);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
if(prop->Set)
{
strcpy(name, "__ecereProp_");
FullClassNameCat(name, regClass->fullName, 0);
strcat(name, "_Set_");
FullClassNameCat(name, prop->name, 1);
ListAdd(args, MkExpIdentifier(MkIdentifier(name)));
}
else
ListAdd(args, MkExpConstant("0"));
if(prop->Get)
{
strcpy(name, "__ecereProp_");
FullClassNameCat(name, regClass->fullName, 0);
strcat(name, "_Get_");
FullClassNameCat(name, prop->name, 1);
ListAdd(args, MkExpIdentifier(MkIdentifier(name)));
}
else
ListAdd(args, MkExpConstant("0"));
switch(prop->memberAccess)
{
case 3:
ListAdd(args, MkExpIdentifier(MkIdentifier("staticAccess")));
break;
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
break;
case 1:
default:
ListAdd(args, MkExpIdentifier(MkIdentifier("publicAccess")));
break;
}
strcpy(name, "__ecereProp_");
FullClassNameCat(name, regClass->fullName, 0);
strcat(name, "_");
FullClassNameCat(name, prop->name, 1);
strcpy(nameM, "__ecerePropM_");
FullClassNameCat(nameM, regClass->fullName, 0);
strcat(nameM, "_");
FullClassNameCat(nameM, prop->name, 1);
if(prop->dataTypeString)
{
stmt = MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(nameM)), '=', MkExpCall(MkExpIdentifier(MkIdentifier("eClass_AddProperty")), args))));
}
else
{
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eClass_AddProperty")), args)));
}
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
if(prop->IsSet)
{
char name[1024];
strcpy(name, "__ecereProp_");
FullClassNameCat(name, regClass->fullName, 1);
strcat(name, "_IsSet_");
FullClassNameCat(name, prop->name, 0);
stmt = MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier(nameM)), MkIdentifier("IsSet")), '=', MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer((((void *)0)), (((void *)0))), (((void *)0)))), MkExpIdentifier(MkIdentifier(name))))));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
if(prop->symbol && ((struct Symbol *)prop->symbol)->propCategory)
{
stmt = MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier(nameM)), MkIdentifier("category")), '=', CopyExpression(((struct Symbol *)prop->symbol)->propCategory))));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
if(prop->dataTypeString)
{
struct __ecereNameSpace__ecere__sys__OldList * list = MkList();
ListAdd(list, MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', MkExpIdentifier(MkIdentifier(nameM))));
ListAdd(list, MkExpOp(MkExpIdentifier(MkIdentifier(nameM)), '=', MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer((((void *)0)), (((void *)0))), (((void *)0)))), MkExpConstant("0"))));
stmt = MkIfStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("module")), MkIdentifier("application")), EQ_OP, MkExpMember(MkExpIdentifier(MkIdentifier("__thisModule")), MkIdentifier("application")))), MkExpressionStmt(list), (((void *)0)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
stmt = MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(nameM)), '=', MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer((((void *)0)), (((void *)0))), (((void *)0)))), MkExpConstant("0")))));
ListAdd(unregisterModuleBody->__anon1.compound.statements, stmt);
}
}
}
else if(member->type == 0 && !isMember && regClass->type == 2)
{
struct __ecereNameSpace__ecere__com__BitMember * bitMember = (struct __ecereNameSpace__ecere__com__BitMember *)member;
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
ListAdd(args, MkExpIdentifier(MkIdentifier(className)));
{
char * string = QMkString(bitMember->name);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
{
char * string = QMkString(bitMember->dataTypeString);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
{
char string[256];
sprintf(string, "%d", bitMember->size);
ListAdd(args, (exp = MkExpConstant(string)));
}
{
char string[256];
sprintf(string, "%d", bitMember->pos);
ListAdd(args, (exp = MkExpConstant(string)));
}
switch(member->memberAccess)
{
case 3:
ListAdd(args, MkExpIdentifier(MkIdentifier("staticAccess")));
break;
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
break;
case 1:
default:
ListAdd(args, MkExpIdentifier(MkIdentifier("publicAccess")));
break;
}
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eClass_AddBitMember")), args)));
ListAdd(statement->__anon1.compound.statements, stmt);
}
else if(member->memberAccess == 1 || (member->type == 0 && !member->dataTypeString))
{
struct __ecereNameSpace__ecere__sys__OldList * args;
if(privateMembers)
{
unsigned int offset = member->offset - lastOffset;
args = MkList();
ListAdd(args, MkExpIdentifier(MkIdentifier(className)));
{
char string[200];
sprintf(string, "\"__ecerePrivateData%d\"", privateID++);
ListAdd(args, MkExpString(string));
}
{
char string[200];
sprintf(string, "\"byte[%d]\"", offset);
ListAdd(args, MkExpString(string));
}
{
char string[256];
sprintf(string, "%d", offset);
ListAdd(args, (exp = MkExpConstant(string)));
}
ListAdd(args, (exp = MkExpConstant("1")));
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier(isMember ? "eMember_AddDataMember" : "eClass_AddDataMember")), args)));
ListAdd(statement->__anon1.compound.statements, stmt);
privateMembers = 0;
}
if(member->type == 0)
{
if(!member->dataType)
member->dataType = ProcessTypeString(member->dataTypeString, 0);
ComputeTypeSize(member->dataType);
args = MkList();
ListAdd(args, MkExpIdentifier(MkIdentifier(className)));
{
char * string = QMkString(member->name);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
{
char * string = QMkString(member->dataTypeString);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
{
if(__ecereProp_Type_Get_isPointerTypeSize(member->dataType))
{
ListAdd(args, (exp = MkExpTypeSize(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer((((void *)0)), (((void *)0))), (((void *)0)))))));
ListAdd(args, (exp = MkExpConstant("0xF000F000")));
}
else
{
char string[256];
if(member->dataType->kind == 8 && member->dataType->__anon1._class && member->dataType->__anon1._class->__anon1.registered && member->dataType->__anon1._class->__anon1.registered->offset == 0 && (member->dataType->__anon1._class->__anon1.registered->type == 1 || member->dataType->__anon1._class->__anon1.registered->type == 5 || member->dataType->__anon1._class->__anon1.registered->type == 0))
{
string[0] = '\0';
DeclareStruct(registerModuleExternal, member->dataType->__anon1._class->string, 0, 1);
FullClassNameCat(string, member->dataType->__anon1._class->string, 0);
exp = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(3, MkIdentifier(string), (((void *)0)))), (((void *)0))));
}
else
{
sprintf(string, "%d", member->dataType->size);
exp = MkExpConstant(string);
}
ListAdd(args, exp);
if(member->dataType->pointerAlignment)
exp = MkExpConstant("0xF000F000");
else
{
sprintf(string, "%d", member->dataType->alignment);
exp = MkExpConstant(string);
}
ListAdd(args, exp);
}
}
switch(member->memberAccess)
{
case 3:
ListAdd(args, MkExpIdentifier(MkIdentifier("staticAccess")));
break;
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
break;
case 1:
default:
ListAdd(args, MkExpIdentifier(MkIdentifier("publicAccess")));
break;
}
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier(isMember ? "eMember_AddDataMember" : "eClass_AddDataMember")), args)));
ListAdd(statement->__anon1.compound.statements, stmt);
lastOffset = member->offset + member->dataType->size;
}
else
{
static int memberCount = 0;
struct Context * context;
struct Statement * compound;
char memberName[256];
sprintf(memberName, "dataMember%d", memberCount);
memberCount++;
curContext = statement->__anon1.compound.context;
context = PushContext();
args = MkListOne(MkExpIdentifier(MkIdentifier((member->type == 1) ? "unionMember" : "structMember")));
switch(member->memberAccess)
{
case 3:
ListAdd(args, MkExpIdentifier(MkIdentifier("staticAccess")));
break;
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
break;
case 1:
default:
ListAdd(args, MkExpIdentifier(MkIdentifier("publicAccess")));
break;
}
compound = MkCompoundStmt(MkListOne(MkDeclaration(MkListOne(MkSpecifierName("DataMember")), MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(memberName)), MkInitializerAssignment(MkExpCall(MkExpIdentifier(MkIdentifier("eMember_New")), args)))))), MkList());
compound->__anon1.compound.context = context;
args = MkList();
ListAdd(args, MkExpIdentifier(MkIdentifier(className)));
ListAdd(args, MkExpIdentifier(MkIdentifier(memberName)));
RegisterMembersAndProperties((struct __ecereNameSpace__ecere__com__Class *)member, 1, memberName, compound);
if(isMember)
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eMember_AddMember")), args)));
else
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eClass_AddMember")), args)));
ListAdd(compound->__anon1.compound.statements, stmt);
PopContext(context);
ListAdd(statement->__anon1.compound.statements, compound);
memberCount--;
lastOffset = member->offset + member->memberOffset;
}
}
else
{
privateMembers = 1;
if(member->type == 0)
{
unsigned int __simpleStruct0;
if(!member->dataType)
member->dataType = ProcessTypeString(member->dataTypeString, 0);
ComputeTypeSize(member->dataType);
if(__ecereProp_Type_Get_isPointerTypeSize(member->dataType) || member->dataType->pointerAlignment)
privateAlignmentPtr = 1;
else
privateAlignment = (__simpleStruct0 = member->dataType->alignment, (privateAlignment > __simpleStruct0) ? privateAlignment : __simpleStruct0);
}
else
{
unsigned int __simpleStruct0;
if(member->pointerAlignment)
privateAlignmentPtr = 1;
privateAlignment = (__simpleStruct0 = member->structAlignment, (privateAlignment > __simpleStruct0) ? privateAlignment : __simpleStruct0);
}
}
}
if(privateAlignment)
{
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
ListAdd(args, MkExpIdentifier(MkIdentifier(className)));
ListAdd(args, MkExpIdentifier(MkIdentifier("null")));
ListAdd(args, MkExpIdentifier(MkIdentifier("null")));
ListAdd(args, MkExpConstant("0"));
if(privateAlignmentPtr)
{
char * s = __ecereNameSpace__ecere__com__PrintString(__ecereClass_char__PTR_, "sizeof(void *) > ", __ecereClass_uint, (void *)&privateAlignment, __ecereClass_char__PTR_, " ? sizeof(void *) : ", __ecereClass_uint, (void *)&privateAlignment, (void *)0);
ListAdd(args, ParseExpressionString(s));
(__ecereNameSpace__ecere__com__eSystem_Delete(s), s = 0);
}
else
{
char string[256];
sprintf(string, "%d", privateAlignment);
ListAdd(args, MkExpConstant(string));
}
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier(isMember ? "eMember_AddDataMember" : "eClass_AddDataMember")), args)));
ListAdd(statement->__anon1.compound.statements, stmt);
}
if(!isMember)
{
struct __ecereNameSpace__ecere__com__ClassProperty * classProperty;
for(prop = regClass->membersAndProperties.first; prop; prop = prop->next)
{
if(prop->isProperty && prop->isWatchable)
{
struct __ecereNameSpace__ecere__sys__OldList * args;
char name[1024], nameM[1024];
strcpy(name, "__ecereProp_");
FullClassNameCat(name, regClass->fullName, 1);
strcat(name, "_");
FullClassNameCat(name, prop->name, 0);
strcpy(nameM, "__ecerePropM_");
FullClassNameCat(nameM, regClass->fullName, 1);
strcat(nameM, "_");
FullClassNameCat(nameM, prop->name, 0);
args = MkListOne(MkExpCondition(MkExpIdentifier(MkIdentifier(nameM)), MkListOne(MkExpIdentifier(MkIdentifier(nameM))), MkExpIdentifier(MkIdentifier(name))));
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eProperty_Watchable")), args)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
}
for(classProperty = (struct __ecereNameSpace__ecere__com__ClassProperty *)__ecereProp___ecereNameSpace__ecere__sys__BinaryTree_Get_first(®Class->classProperties); classProperty; classProperty = (struct __ecereNameSpace__ecere__com__ClassProperty *)__ecereProp___ecereNameSpace__ecere__sys__BTNode_Get_next(((struct __ecereNameSpace__ecere__sys__BTNode *)classProperty)))
{
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
char name[1024];
char * string = QMkString(classProperty->name);
ListAdd(args, MkExpIdentifier(MkIdentifier(className)));
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
{
char * string = QMkString(classProperty->dataTypeString);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
if(classProperty->Set)
{
strcpy(name, "__ecereClassProp_");
FullClassNameCat(name, regClass->fullName, 1);
strcat(name, "_Set_");
strcat(name, classProperty->name);
ListAdd(args, MkExpIdentifier(MkIdentifier(name)));
}
else
ListAdd(args, MkExpConstant("0"));
if(classProperty->Get)
{
strcpy(name, "__ecereClassProp_");
FullClassNameCat(name, regClass->fullName, 1);
strcat(name, "_Get_");
strcat(name, classProperty->name);
ListAdd(args, MkExpIdentifier(MkIdentifier(name)));
}
else
ListAdd(args, MkExpConstant("0"));
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eClass_AddClassProperty")), args)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
}
}
void __ecereUnregisterModule_pass1(struct __ecereNameSpace__ecere__com__Instance * module)
{
}
static void ProcessClass(int classType, struct __ecereNameSpace__ecere__sys__OldList * definitions, struct Symbol * symbol, struct __ecereNameSpace__ecere__sys__OldList * baseSpecs, struct __ecereNameSpace__ecere__sys__OldList * enumValues, struct __ecereNameSpace__ecere__sys__OldList * defs, struct External * external, int declMode)
{
struct ClassDef * def;
struct __ecereNameSpace__ecere__com__Class * regClass = symbol->__anon1.registered;
if(regClass)
{
classType = regClass->type;
if(classType == 4 && enumValues && (inCompiler || !buildingECERECOMModule))
{
struct Enumerator * e;
long long lastValue = -1;
unsigned int lastValueSet = 0;
for(e = enumValues->first; e; e = e->next)
{
if(e->exp)
{
struct Type * destType = (destType = __ecereNameSpace__ecere__com__eInstance_New(__ecereClass_Type), destType->kind = 4, destType->refCount = 1, destType);
e->exp->destType = destType;
parsingType = 1;
ProcessExpressionType(e->exp);
parsingType = 0;
if(!e->exp->expType)
{
destType->kind = 8;
destType->__anon1._class = symbol;
ProcessExpressionType(e->exp);
}
if(e->exp->type == 0 && e->exp->expType && e->exp->__anon1.__anon1.identifier && e->exp->__anon1.__anon1.identifier->string && e->exp->expType->kind == 15)
{
struct __ecereNameSpace__ecere__sys__NamedLink64 * l;
char * string = e->exp->__anon1.__anon1.identifier->string;
for(l = e->exp->expType->__anon1.__anon1.members.first; l; l = l->next)
{
if(!strcmp(l->name, string))
{
if(l->data)
{
FreeExpContents(e->exp);
e->exp->type = 2;
e->exp->__anon1.__anon1.constant = PrintInt64(l->data);
FreeType(e->exp->expType);
e->exp->expType = ProcessTypeString("int64", 0);
}
break;
}
}
}
else
ComputeExpression(e->exp);
if(e->exp->isConstant && e->exp->type == 2)
{
struct Operand op = GetOperand(e->exp);
long long value;
switch(op.kind)
{
case 1:
value = op.type->isSigned ? (long long)op.__anon1.c : (long long)op.__anon1.uc;
break;
case 2:
value = op.type->isSigned ? (long long)op.__anon1.s : (long long)op.__anon1.us;
break;
case 4:
value = op.type->isSigned ? op.__anon1.i64 : (long long)op.__anon1.ui64;
break;
case 3:
default:
value = op.type->isSigned ? (long long)op.__anon1.i : (int)op.__anon1.ui;
}
lastValue = value;
lastValueSet = 1;
__ecereNameSpace__ecere__com__eEnum_AddFixedValue(regClass, e->id->string, value);
}
else
{
if(lastValueSet)
__ecereNameSpace__ecere__com__eEnum_AddFixedValue(regClass, e->id->string, ++lastValue);
else
__ecereNameSpace__ecere__com__eEnum_AddValue(regClass, e->id->string);
}
}
else
{
if(lastValueSet)
__ecereNameSpace__ecere__com__eEnum_AddFixedValue(regClass, e->id->string, ++lastValue);
else
__ecereNameSpace__ecere__com__eEnum_AddValue(regClass, e->id->string);
}
}
{
struct __ecereNameSpace__ecere__com__EnumClassData * baseData = regClass->data;
struct __ecereNameSpace__ecere__sys__OldLink * deriv;
for(deriv = regClass->derivatives.first; deriv; deriv = deriv->next)
{
struct __ecereNameSpace__ecere__com__Class * c = deriv->data;
if(c && c->type == 4)
{
struct __ecereNameSpace__ecere__com__EnumClassData * data = c->data;
data->largest = baseData->largest;
}
}
}
}
if(definitions != (((void *)0)))
{
if(inCompiler)
{
for(def = definitions->first; def; def = def->next)
{
if(def->type == 4 && def->__anon1.propertyWatch)
{
struct PropertyWatch * propWatch = def->__anon1.propertyWatch;
struct ClassFunction * func;
char watcherName[1024];
struct Identifier * propID;
struct Statement * stmt = MkExpressionStmt(MkList());
struct Declarator * decl;
struct __ecereNameSpace__ecere__sys__OldList * specs;
sprintf(watcherName, "__ecerePropertySelfWatcher_%d", propWatcherID++);
for(propID = (*propWatch->properties).first; propID; propID = propID->next)
{
strcat(watcherName, "_");
strcat(watcherName, propID->string);
}
decl = MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)), MkListOne(MkTypeName(MkListOne(MkSpecifier(VOID)), (((void *)0)))));
specs = MkList();
ListAdd(specs, MkSpecifier(STATIC));
ListAdd(specs, MkSpecifier(VOID));
func = MkClassFunction(specs, (((void *)0)), decl, (((void *)0)));
ProcessClassFunctionBody(func, propWatch->compound);
decl->symbol = __ecereNameSpace__ecere__com__eInstance_New(__ecereClass_Symbol);
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Add((&*excludedSymbols), decl->symbol);
func->dontMangle = 1;
propWatch->compound = (((void *)0));
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Insert(definitions, (((void *)0)), MkClassDefFunction(func));
for(propID = (*propWatch->properties).first; propID; propID = propID->next)
{
struct __ecereNameSpace__ecere__com__Property * prop = __ecereNameSpace__ecere__com__eClass_FindProperty(regClass, propID->string, privateModule);
if(prop)
{
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
ListAdd(args, MkExpIdentifier(MkIdentifier("class")));
{
char * s = QMkString(propID->string);
ListAdd(args, MkExpString(s));
(__ecereNameSpace__ecere__com__eSystem_Delete(s), s = 0);
}
ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
ListAdd(stmt->__anon1.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("eProperty_SelfWatch")), args));
}
else
Compiler_Error(__ecereNameSpace__ecere__GetTranslatedString("ec", "Property %s not found in class %s\n", (((void *)0))), propID->string, regClass->fullName);
}
FreePropertyWatch(def->__anon1.propertyWatch);
def->__anon1.propertyWatch = (struct PropertyWatch *)stmt;
}
}
}
for(def = definitions->first; def; def = def->next)
{
if(def->type == 0)
{
ProcessClassFunction(regClass, def->__anon1.function, defs, external->prev, declMode == 3);
}
}
}
if(inCompiler && symbol->mustRegister && regClass)
{
struct Statement * stmt;
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
struct __ecereNameSpace__ecere__com__Method * method;
struct Expression * exp;
const char * registerFunction = (((void *)0));
int inheritanceAccess = 1;
CreateRegisterModuleBody();
curExternal = registerModuleExternal;
switch(regClass->type)
{
case 1:
ListAdd(args, MkExpIdentifier(MkIdentifier("structClass")));
break;
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("bitClass")));
break;
case 4:
ListAdd(args, MkExpIdentifier(MkIdentifier("enumClass")));
break;
case 5:
ListAdd(args, MkExpIdentifier(MkIdentifier("noHeadClass")));
break;
case 3:
ListAdd(args, MkExpIdentifier(MkIdentifier("unitClass")));
break;
case 0:
ListAdd(args, MkExpIdentifier(MkIdentifier("normalClass")));
break;
}
{
char nameSpace[1024] = "";
char className[1024] = "";
char * string;
GetNameSpaceString(regClass->nameSpace, nameSpace);
if(declMode == 3)
{
__ecereNameSpace__ecere__sys__GetLastDirectory(sourceFile, className);
__ecereNameSpace__ecere__sys__ChangeCh(className, '.', '_');
strcat(className, "}");
}
strcat(className, nameSpace);
strcat(className, regClass->name);
string = QMkString(className);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
if(baseSpecs != (((void *)0)))
{
struct Type * baseType = ProcessType(baseSpecs, (((void *)0)));
if(baseType->kind != 9 && baseType->kind != 10)
{
char baseName[1024] = "";
char * string;
if(baseType->kind == 8 && baseType->__anon1._class && baseType->__anon1._class->isStatic)
{
__ecereNameSpace__ecere__sys__GetLastDirectory(sourceFile, baseName);
__ecereNameSpace__ecere__sys__ChangeCh(baseName, '.', '_');
strcat(baseName, "}");
strcat(baseName, baseType->__anon1._class->string);
}
else
PrintType(baseType, baseName, 0, 1);
string = QMkString(baseName);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
else
ListAdd(args, MkExpConstant("0"));
FreeType(baseType);
if(((struct Specifier *)baseSpecs->first)->type == 0 && ((struct Specifier *)baseSpecs->first)->__anon1.specifier == PRIVATE)
inheritanceAccess = 2;
}
else
ListAdd(args, MkExpConstant("0"));
if(regClass->type == 1 || regClass->type == 0 || regClass->type == 5)
{
struct __ecereNameSpace__ecere__com__DataMember * member = (((void *)0));
{
struct __ecereNameSpace__ecere__com__Class * base;
for(base = regClass->base; base && base->type != 1000; base = base->next)
{
for(member = base->membersAndProperties.first; member; member = member->next)
if(!member->isProperty)
break;
if(member)
break;
}
}
if(regClass->type == 1 && symbol->declaredStruct && member)
{
char baseStructName[1024];
baseStructName[0] = 0;
strcpy(baseStructName, (regClass->base->templateClass ? regClass->base->templateClass : regClass->base)->fullName);
ListAdd(args, MkExpOp(MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(3, MkIdentifier(symbol->structName), (((void *)0)))), (((void *)0)))), '-', MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(3, MkIdentifier(baseStructName), (((void *)0)))), (((void *)0))))));
}
else
ListAdd(args, symbol->declaredStruct ? MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(3, MkIdentifier(symbol->structName), (((void *)0)))), (((void *)0)))) : MkExpConstant("0"));
}
else
{
ListAdd(args, MkExpConstant("0"));
}
{
char classDataStructName[1024];
strcpy(classDataStructName, "__ecereClassData_");
FullClassNameCat(classDataStructName, symbol->string, 0);
ListAdd(args, symbol->classData ? MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(3, MkIdentifier(classDataStructName), (((void *)0)))), (((void *)0)))) : MkExpConstant("0"));
}
if(regClass->type == 0 || regClass->type == 5)
{
ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer((((void *)0)), (((void *)0))), (((void *)0)))), symbol->needConstructor ? MkExpIdentifier(MkIdentifier(symbol->constructorName)) : MkExpConstant("0")));
ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer((((void *)0)), (((void *)0))), (((void *)0)))), symbol->needDestructor ? MkExpIdentifier(MkIdentifier(symbol->destructorName)) : MkExpConstant("0")));
}
else
{
ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer((((void *)0)), (((void *)0))), (((void *)0)))), MkExpConstant("0")));
ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer((((void *)0)), (((void *)0))), (((void *)0)))), MkExpConstant("0")));
}
ListAdd(args, MkExpIdentifier(MkIdentifier("module")));
switch(declMode)
{
case 3:
ListAdd(args, MkExpIdentifier(MkIdentifier("staticAccess")));
break;
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
break;
case 1:
default:
ListAdd(args, MkExpIdentifier(MkIdentifier(buildingECERECOMModule ? "baseSystemAccess" : "publicAccess")));
break;
}
switch(inheritanceAccess)
{
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
break;
case 1:
default:
ListAdd(args, MkExpIdentifier(MkIdentifier("publicAccess")));
break;
}
registerFunction = "eSystem_RegisterClass";
stmt = MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier("class")), '=', MkExpCall((exp = MkExpIdentifier(MkIdentifier(registerFunction))), args))));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
stmt = MkIfStmt(MkListOne(MkExpOp(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("module")), MkIdentifier("application")), EQ_OP, MkExpMember(MkExpIdentifier(MkIdentifier("__thisModule")), MkIdentifier("application"))), AND_OP, MkExpIdentifier(MkIdentifier("class")))), MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(symbol->className)), '=', MkExpIdentifier(MkIdentifier("class"))))), (((void *)0)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
if(external && external->type == 2 && external->__anon1._class->deleteWatchable)
{
args = MkListOne(MkExpIdentifier(MkIdentifier("class")));
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eClass_DestructionWatchable")), args)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
if(regClass->base)
{
struct __ecereNameSpace__ecere__com__Class * base = regClass->base;
int c;
for(c = 0; c < base->vTblSize; c++)
{
struct Symbol * method = (struct Symbol *)regClass->_vTbl[c];
if((void *)method != DummyMethod && base->_vTbl[c] != (void *)method && method->__anon2.__anon3.methodExternal)
{
struct External * external = method->__anon2.__anon3.methodExternal;
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
struct Identifier * id = external->__anon1.function ? GetDeclId(external->__anon1.function->declarator) : (((void *)0));
{
struct External * e = method->__anon2.__anon3.methodExternal ? method->__anon2.__anon3.methodExternal : method->__anon2.__anon3.methodCodeExternal;
__ecereMethod_External_CreateUniqueEdge(registerModuleExternal, e, e->type == 0);
}
ListAdd(args, MkExpIdentifier(MkIdentifier("class")));
{
char * string = QMkString(method->__anon1.method->name);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
ListAdd(args, MkExpConstant("0"));
ListAdd(args, (exp = MkExpIdentifier(MkIdentifier(id->string))));
ListAdd(args, MkExpIdentifier(MkIdentifier("publicAccess")));
exp->expType = __extension__ ({
struct Type * __ecereInstance1 = __ecereNameSpace__ecere__com__eInstance_New(__ecereClass_Type);
__ecereInstance1->refCount = 1, __ecereInstance1;
});
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eClass_AddMethod")), args)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
}
}
{
int c;
for(c = regClass->base ? regClass->base->vTblSize : 0; c < regClass->vTblSize; c++)
{
for(method = (struct __ecereNameSpace__ecere__com__Method *)__ecereProp___ecereNameSpace__ecere__sys__BinaryTree_Get_first(®Class->methods); method; method = (struct __ecereNameSpace__ecere__com__Method *)__ecereProp___ecereNameSpace__ecere__sys__BTNode_Get_next(((struct __ecereNameSpace__ecere__sys__BTNode *)method)))
{
if(method->type == 1 && method->_class == regClass && method->vid == c)
{
char name[1024];
struct Expression * exp;
struct External * external = method->symbol ? ((struct Symbol *)method->symbol)->__anon2.__anon3.methodCodeExternal : (((void *)0));
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
struct Identifier * id = (external && external->__anon1.function) ? GetDeclId(external->__anon1.function->declarator) : (((void *)0));
ListAdd(args, MkExpIdentifier(MkIdentifier("class")));
{
char * string = QMkString(method->name);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
{
char * string = QMkString(method->dataTypeString);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
if(id && external->__anon1.function->body)
{
ListAdd(args, (exp = MkExpIdentifier(MkIdentifier(id->string))));
exp->expType = __extension__ ({
struct Type * __ecereInstance1 = __ecereNameSpace__ecere__com__eInstance_New(__ecereClass_Type);
__ecereInstance1->refCount = 1, __ecereInstance1;
});
}
else
{
ListAdd(args, (exp = MkExpConstant("0")));
}
switch(method->memberAccess)
{
case 3:
ListAdd(args, MkExpIdentifier(MkIdentifier("staticAccess")));
break;
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
break;
case 1:
default:
ListAdd(args, MkExpIdentifier(MkIdentifier("publicAccess")));
break;
}
strcpy(name, "__ecereVMethodID_");
FullClassNameCat(name, method->_class->fullName, 0);
strcat(name, "_");
strcat(name, method->name);
exp = MkExpCall(MkExpIdentifier(MkIdentifier("eClass_AddVirtualMethod")), args);
stmt = MkExpressionStmt(MkListOne(exp));
if(external)
__ecereMethod_External_CreateUniqueEdge(registerModuleExternal, external, external->type == 0);
DeclareMethod(curExternal, method, name);
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
}
}
}
for(method = (struct __ecereNameSpace__ecere__com__Method *)__ecereProp___ecereNameSpace__ecere__sys__BinaryTree_Get_first(®Class->methods); method; method = (struct __ecereNameSpace__ecere__com__Method *)__ecereProp___ecereNameSpace__ecere__sys__BTNode_Get_next(((struct __ecereNameSpace__ecere__sys__BTNode *)method)))
{
if(method->type == 1 && method->_class == regClass)
;
else if(method->memberAccess == 1 || !method->dataTypeString)
{
struct External * external = method->symbol ? ((struct Symbol *)method->symbol)->__anon2.__anon3.methodCodeExternal : (((void *)0));
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
struct Identifier * id = (external && external->__anon1.function) ? GetDeclId(external->__anon1.function->declarator) : (((void *)0));
ListAdd(args, MkExpIdentifier(MkIdentifier("class")));
{
char * string = QMkString(method->name);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
{
char * string = QMkString(method->dataTypeString);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
if(id && external->__anon1.function->body)
{
ListAdd(args, (exp = MkExpIdentifier(MkIdentifier(id->string))));
exp->expType = __extension__ ({
struct Type * __ecereInstance1 = __ecereNameSpace__ecere__com__eInstance_New(__ecereClass_Type);
__ecereInstance1->refCount = 1, __ecereInstance1;
});
}
else
{
ListAdd(args, (exp = MkExpConstant("0")));
}
switch(method->memberAccess)
{
case 3:
ListAdd(args, MkExpIdentifier(MkIdentifier("staticAccess")));
break;
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
break;
case 1:
default:
ListAdd(args, MkExpIdentifier(MkIdentifier("publicAccess")));
break;
}
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eClass_AddMethod")), args)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
if(external)
__ecereMethod_External_CreateUniqueEdge(registerModuleExternal, external, external->type == 0);
}
}
RegisterMembersAndProperties(regClass, 0, "class", registerModuleBody);
if(classType == 4)
{
struct __ecereNameSpace__ecere__sys__NamedLink64 * value;
struct __ecereNameSpace__ecere__com__Class * enumClass = __ecereNameSpace__ecere__com__eSystem_FindClass(privateModule, "enum");
struct __ecereNameSpace__ecere__com__EnumClassData * e = (regClass ? ((void *)(((char *)regClass->data) + enumClass->offsetClass)) : (((void *)0)));
for(value = e->values.first; value; value = value->next)
{
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
ListAdd(args, MkExpIdentifier(MkIdentifier("class")));
{
char * string = QMkString(value->name);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
{
char * temp;
if(regClass->dataTypeString && !strcmp(regClass->dataTypeString, "uint64"))
temp = PrintUInt64(value->data);
else
temp = PrintInt64(value->data);
ListAdd(args, MkExpConstant(temp));
(__ecereNameSpace__ecere__com__eSystem_Delete(temp), temp = 0);
}
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eEnum_AddFixedValue")), args)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
}
if(symbol->templateParams)
{
struct TemplateParameter * param;
for(param = (*symbol->templateParams).first; param; param = param->next)
{
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
ListAdd(args, MkExpIdentifier(MkIdentifier("class")));
{
char * string = QMkString(param->identifier->string);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
ListAdd(args, MkExpIdentifier(MkIdentifier((param->type == 0) ? "type" : ((param->type == 1) ? "identifier" : "expression"))));
switch(param->type)
{
case 0:
case 2:
{
char * typeString = param->__anon1.dataType ? StringFromSpecDecl(param->__anon1.dataType->specifiers, param->__anon1.dataType->decl) : (((void *)0));
char * string = QMkString(typeString);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(typeString), typeString = 0);
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
break;
}
case 1:
{
char memberTypeString[132] = "TemplateMemberType::";
unsigned int onType = 1;
(__extension__ ({
const char * (* __internal_VirtualMethod)(struct __ecereNameSpace__ecere__com__Class * , const void * , char * tempString, void * reserved, unsigned int * onType);
__internal_VirtualMethod = ((const char * (*)(struct __ecereNameSpace__ecere__com__Class *, const void *, char * tempString, void * reserved, unsigned int * onType))__ecereClass___ecereNameSpace__ecere__com__TemplateMemberType->_vTbl[__ecereVMethodID_class_OnGetString]);
__internal_VirtualMethod ? __internal_VirtualMethod(__ecereClass___ecereNameSpace__ecere__com__TemplateMemberType, (void *)¶m->__anon1.memberType, memberTypeString + strlen(memberTypeString), (((void *)0)), &onType) : (const char * )1;
}));
ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer((((void *)0)), (((void *)0))), (((void *)0)))), MkExpIdentifier(MkIdentifier(memberTypeString))));
break;
}
}
if(param->defaultArgument)
{
struct __ecereNameSpace__ecere__sys__OldList * members = MkList();
switch(param->type)
{
case 0:
{
char * typeString = param->defaultArgument->__anon1.templateDatatype ? StringFromSpecDecl(param->defaultArgument->__anon1.templateDatatype->specifiers, param->defaultArgument->__anon1.templateDatatype->decl) : (((void *)0));
char * string = QMkString(typeString);
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Add((&*members), MkMemberInit(MkListOne(MkIdentifier("dataTypeString")), MkInitializerAssignment(MkExpString(string))));
(__ecereNameSpace__ecere__com__eSystem_Delete(typeString), typeString = 0);
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
break;
}
case 1:
{
char memberString[1024];
char * string;
memberString[0] = '\0';
if(param->defaultArgument->__anon1.identifier->_class)
{
if(param->defaultArgument->__anon1.identifier->_class->type == 8)
strcpy(memberString, param->defaultArgument->__anon1.identifier->_class->__anon1.templateParameter->identifier->string);
else if(param->defaultArgument->__anon1.identifier->_class->__anon1.__anon1.name)
strcpy(memberString, param->defaultArgument->__anon1.identifier->_class->__anon1.__anon1.name);
}
if(memberString[0])
strcat(memberString, "::");
strcat(memberString, param->defaultArgument->__anon1.identifier->string);
string = QMkString(memberString);
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Add((&*members), MkMemberInit(MkListOne(MkIdentifier("dataTypeString")), MkInitializerAssignment(MkExpString(string))));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
break;
}
case 2:
{
struct Operand op =
{
0, 0, 0,
.__anon1 = {
.c = 0
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
};
struct __ecereNameSpace__ecere__sys__OldList * ids = MkList();
char * ui64String;
char * string = (((void *)0));
op = GetOperand(param->defaultArgument->__anon1.expression);
ui64String = PrintUInt64(op.__anon1.ui64);
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Add((&*ids), MkIdentifier("expression"));
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Add((&*ids), MkIdentifier("ui64"));
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Add((&*members), MkMemberInit(ids, MkInitializerAssignment(MkExpConstant(ui64String))));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
(__ecereNameSpace__ecere__com__eSystem_Delete(ui64String), ui64String = 0);
break;
}
}
ListAdd(args, MkExpInstance(MkInstantiation(MkSpecifierName("ClassTemplateArgument"), (((void *)0)), MkListOne(MkMembersInitList(members)))));
}
else
ListAdd(args, MkExpIdentifier(MkIdentifier("null")));
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eClass_AddTemplateParameter")), args)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
stmt = MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("eClass_DoneAddingTemplateParameters")), MkListOne(MkExpIdentifier(MkIdentifier("class"))))));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
if(definitions != (((void *)0)))
{
for(def = definitions->first; def; def = def->next)
{
if(def->type == 4 && def->__anon1.propertyWatch)
{
ListAdd(registerModuleBody->__anon1.compound.statements, (struct Statement *)def->__anon1.propertyWatch);
def->__anon1.propertyWatch = (((void *)0));
}
else if(def->type == 5)
{
{
char * s = QMkString(def->__anon1.designer);
stmt = MkIfStmt(MkListOne(MkExpIdentifier(MkIdentifier("class"))), MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("class")), MkIdentifier("designerClass")), '=', MkExpString(s)))), (((void *)0)));
(__ecereNameSpace__ecere__com__eSystem_Delete(s), s = 0);
}
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
else if(def->type == 6)
{
stmt = MkIfStmt(MkListOne(MkExpIdentifier(MkIdentifier("class"))), MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("class")), MkIdentifier("noExpansion")), '=', MkExpConstant("1")))), (((void *)0)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
else if(def->type == 7)
{
stmt = MkIfStmt(MkListOne(MkExpIdentifier(MkIdentifier("class"))), MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("class")), MkIdentifier("fixed")), '=', MkExpConstant("1")))), (((void *)0)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
if(regClass)
regClass->fixed = 1;
}
else if(def->type == 8)
{
char * s = QMkString(def->__anon1.defaultProperty->string);
stmt = MkIfStmt(MkListOne(MkExpIdentifier(MkIdentifier("class"))), MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("class")), MkIdentifier("defaultProperty")), '=', MkExpString(s)))), (((void *)0)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
(__ecereNameSpace__ecere__com__eSystem_Delete(s), s = 0);
}
else if(def->type == 11)
{
(__extension__ ({
struct __ecereNameSpace__ecere__com__IteratorPointer * (* __internal_VirtualMethod)(struct __ecereNameSpace__ecere__com__Instance *, uint64 value);
__internal_VirtualMethod = ((struct __ecereNameSpace__ecere__com__IteratorPointer * (*)(struct __ecereNameSpace__ecere__com__Instance *, uint64 value))__extension__ ({
struct __ecereNameSpace__ecere__com__Instance * __internal_ClassInst = classPropValues;
__internal_ClassInst ? __internal_ClassInst->_vTbl : __ecereClass___ecereNameSpace__ecere__com__List->_vTbl;
})[__ecereVMethodID___ecereNameSpace__ecere__com__Container_Add]);
__internal_VirtualMethod ? __internal_VirtualMethod(classPropValues, (uint64)(uintptr_t)(__extension__ ({
struct __ecereNameSpace__ecere__com__Instance * __ecereInstance1 = __ecereNameSpace__ecere__com__eInstance_New(__ecereClass_ClassPropertyValue);
((struct ClassPropertyValue *)(((char *)__ecereInstance1 + __ecereClass_ClassPropertyValue->offset)))->regClass = regClass, ((struct ClassPropertyValue *)(((char *)__ecereInstance1 + __ecereClass_ClassPropertyValue->offset)))->staticClass = (declMode == 3), ((struct ClassPropertyValue *)(((char *)__ecereInstance1 + __ecereClass_ClassPropertyValue->offset)))->id = def->__anon1.__anon1.id, ((struct ClassPropertyValue *)(((char *)__ecereInstance1 + __ecereClass_ClassPropertyValue->offset)))->exp = def->__anon1.__anon1.initializer->__anon1.exp, __ecereInstance1;
}))) : (struct __ecereNameSpace__ecere__com__IteratorPointer *)1;
}));
def->__anon1.__anon1.id = (((void *)0));
def->__anon1.__anon1.initializer->__anon1.exp = (((void *)0));
}
}
}
}
}
}
void ProcessClassDefinitions()
{
struct External * external, * next;
CreateRegisterModuleBody();
if(ast)
{
for(external = (*ast).first; external; external = next)
{
next = external->next;
curExternal = external;
if(external->type == 2)
{
struct ClassDefinition * _class = external->__anon1._class;
if(_class->definitions)
{
ProcessClass(0, _class->definitions, _class->symbol, _class->baseSpecs, (((void *)0)), ast, external, _class->declMode);
}
if(inCompiler)
{
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Remove((&*ast), external);
FreeExternal(external);
}
}
else if(external->type == 0)
{
unsigned int setStaticMethod = 0;
if(external->symbol && !external->symbol->type->__anon1.__anon2.thisClass && !external->symbol->type->__anon1.__anon2.staticMethod)
{
external->symbol->type->__anon1.__anon2.staticMethod = 1;
setStaticMethod = 1;
}
if(inCompiler)
{
struct FunctionDefinition * function = external->__anon1.function;
struct Statement * stmt;
struct __ecereNameSpace__ecere__sys__OldList * args;
if(!strcmp(function->declarator->symbol->string, "__on_register_module"))
{
ListAdd(registerModuleBody->__anon1.compound.statements, function->body);
function->body->__anon1.compound.context->parent = registerModuleBody->__anon1.compound.context;
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Remove((&*ast), external);
function->body = (((void *)0));
FreeExternal(external);
continue;
}
if(function->declMode != 2 && function->declMode != 1)
continue;
args = MkList();
CreateRegisterModuleBody();
{
char * string = QMkString(function->declarator->symbol->string);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
{
char * string;
char type[1024] = "";
if(setStaticMethod)
function->declarator->symbol->type->__anon1.__anon2.staticMethod = 0;
PrintType(function->declarator->symbol->type, type, 1, 1);
if(setStaticMethod)
function->declarator->symbol->type->__anon1.__anon2.staticMethod = 1;
string = QMkString(type);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
{
ListAdd(args, MkExpIdentifier(MkIdentifier(function->declarator->symbol->string)));
}
ListAdd(args, MkExpIdentifier(MkIdentifier("module")));
switch(function->declMode)
{
case 3:
ListAdd(args, MkExpIdentifier(MkIdentifier("staticAccess")));
break;
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
break;
case 1:
default:
ListAdd(args, MkExpIdentifier(MkIdentifier(buildingECERECOMModule ? "baseSystemAccess" : "publicAccess")));
break;
}
stmt = MkExpressionStmt(MkListOne(MkExpCall((MkExpIdentifier(MkIdentifier("eSystem_RegisterFunction"))), args)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
}
else if(external->type == 1)
{
struct Declaration * declaration = external->__anon1.declaration;
if(external->symbol)
{
if(external->symbol->type && external->symbol->type->kind == 11 && !external->symbol->type->__anon1.__anon2.thisClass)
external->symbol->type->__anon1.__anon2.staticMethod = 1;
}
if(external->symbol && declaration && declaration->type == 1)
{
if(declaration->__anon1.__anon1.specifiers)
{
struct Specifier * specifier;
unsigned int removeExternal = 0;
for(specifier = (*declaration->__anon1.__anon1.specifiers).first; specifier; specifier = specifier->next)
{
if((specifier->type == 2 || specifier->type == 3 || specifier->type == 4) && specifier->__anon1.__anon2.id && specifier->__anon1.__anon2.id->string && (declaration->declMode || specifier->__anon1.__anon2.baseSpecs || (specifier->type == 2 && specifier->__anon1.__anon2.definitions)))
{
struct Symbol * symbol = FindClass(specifier->__anon1.__anon2.id->string);
if(symbol)
{
int classType;
if(specifier->type == 2)
classType = 4;
else
classType = 1;
removeExternal = 1;
symbol->ctx = specifier->__anon1.__anon2.ctx;
specifier->__anon1.__anon2.ctx = (((void *)0));
ProcessClass(classType, specifier->__anon1.__anon2.definitions, symbol, specifier->__anon1.__anon2.baseSpecs, specifier->__anon1.__anon2.list, ast, external, declaration->declMode);
}
}
}
if(inCompiler && removeExternal)
{
__ecereMethod___ecereNameSpace__ecere__sys__OldList_Remove((&*ast), external);
FreeExternal(external);
}
}
}
else if(declaration && declaration->type == 3)
{
if(inCompiler && declaration->declMode != 3)
{
struct Statement * stmt;
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
CreateRegisterModuleBody();
{
char * string = QMkString(declaration->__anon1.__anon2.id->string);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
{
char * string;
char type[1024] = "";
PrintExpression(declaration->__anon1.__anon2.exp, type);
string = QMkString(type);
ListAdd(args, MkExpString(string));
(__ecereNameSpace__ecere__com__eSystem_Delete(string), string = 0);
}
ListAdd(args, MkExpIdentifier(MkIdentifier("module")));
switch(declaration->declMode)
{
case 3:
ListAdd(args, MkExpIdentifier(MkIdentifier("staticAccess")));
break;
case 2:
ListAdd(args, MkExpIdentifier(MkIdentifier("privateAccess")));
break;
case 1:
default:
ListAdd(args, MkExpIdentifier(MkIdentifier(buildingECERECOMModule ? "baseSystemAccess" : "publicAccess")));
break;
}
stmt = MkExpressionStmt(MkListOne(MkExpCall((MkExpIdentifier(MkIdentifier("eSystem_RegisterDefine"))), args)));
ListAdd(registerModuleBody->__anon1.compound.statements, stmt);
}
}
}
}
{
struct __ecereNameSpace__ecere__com__Iterator v =
{
(classPropValues), 0
};
while(__ecereMethod___ecereNameSpace__ecere__com__Iterator_Next(&v))
{
struct __ecereNameSpace__ecere__sys__OldList * findClassArgs = MkList();
struct __ecereNameSpace__ecere__sys__OldList * args = MkList();
struct Statement * compoundStmt;
char * s;
struct Expression * e;
if(__extension__ ({
char * __ecTemp1 = (char *)(((struct __ecereNameSpace__ecere__com__Instance *)(uintptr_t)__ecereProp___ecereNameSpace__ecere__com__Iterator_Get_data(&v)));
((struct ClassPropertyValue *)(__ecTemp1 + __ecereClass_ClassPropertyValue->offset));
})->exp)
yylloc = __extension__ ({
char * __ecTemp1 = (char *)(((struct __ecereNameSpace__ecere__com__Instance *)(uintptr_t)__ecereProp___ecereNameSpace__ecere__com__Iterator_Get_data(&v)));
((struct ClassPropertyValue *)(__ecTemp1 + __ecereClass_ClassPropertyValue->offset));
})->exp->loc;
ListAdd(findClassArgs, MkExpIdentifier(MkIdentifier("module")));
{
char nameSpace[1024] = "";
char className[1024] = "";
struct __ecereNameSpace__ecere__com__Class * regClass = __extension__ ({
char * __ecTemp1 = (char *)(((struct __ecereNameSpace__ecere__com__Instance *)(uintptr_t)__ecereProp___ecereNameSpace__ecere__com__Iterator_Get_data(&v)));
((struct ClassPropertyValue *)(__ecTemp1 + __ecereClass_ClassPropertyValue->offset));
})->regClass;
GetNameSpaceString(regClass->nameSpace, nameSpace);
if(__extension__ ({
char * __ecTemp1 = (char *)(((struct __ecereNameSpace__ecere__com__Instance *)(uintptr_t)__ecereProp___ecereNameSpace__ecere__com__Iterator_Get_data(&v)));
((struct ClassPropertyValue *)(__ecTemp1 + __ecereClass_ClassPropertyValue->offset));
})->staticClass)
{
__ecereNameSpace__ecere__sys__GetLastDirectory(sourceFile, className);
__ecereNameSpace__ecere__sys__ChangeCh(className, '.', '_');
strcat(className, "}");
}
strcat(className, nameSpace);
strcat(className, regClass->name);
s = QMkString(className);
}
ListAdd(findClassArgs, MkExpString(s));
(__ecereNameSpace__ecere__com__eSystem_Delete(s), s = 0);
ListAdd(args, MkExpIdentifier(MkIdentifier("_class")));
s = QMkString(__extension__ ({
char * __ecTemp1 = (char *)(((struct __ecereNameSpace__ecere__com__Instance *)(uintptr_t)__ecereProp___ecereNameSpace__ecere__com__Iterator_Get_data(&v)));
((struct ClassPropertyValue *)(__ecTemp1 + __ecereClass_ClassPropertyValue->offset));
})->id->string);
ListAdd(args, MkExpString(s));
(__ecereNameSpace__ecere__com__eSystem_Delete(s), s = 0);
e = __extension__ ({
char * __ecTemp1 = (char *)(((struct __ecereNameSpace__ecere__com__Instance *)(uintptr_t)__ecereProp___ecereNameSpace__ecere__com__Iterator_Get_data(&v)));
((struct ClassPropertyValue *)(__ecTemp1 + __ecereClass_ClassPropertyValue->offset));
})->exp;
ProcessExpressionType(e);
if(__ecereProp_Type_Get_isPointerType(e->expType))
e = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("intptr")), (((void *)0))), e);
ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(INT64)), (((void *)0))), e));
compoundStmt = MkCompoundStmt(MkListOne(MkDeclaration(MkListOne(MkSpecifierName("ecere::com::Class")), MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("_class")), MkInitializerAssignment(MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eSystem_FindClass")), findClassArgs)))))), MkListOne(MkExpressionStmt(MkListOne(MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eClass_SetProperty")), args)))));
compoundStmt->__anon1.compound.context = __extension__ ({
struct Context * __ecereInstance1 = __ecereNameSpace__ecere__com__eInstance_New(__ecereClass_Context);
__ecereInstance1->parent = registerModuleBody->__anon1.compound.context, __ecereInstance1;
});
ListAdd(registerModuleBody->__anon1.compound.statements, compoundStmt);
}
}
(__extension__ ({
void (* __internal_VirtualMethod)(struct __ecereNameSpace__ecere__com__Instance *);
__internal_VirtualMethod = ((void (*)(struct __ecereNameSpace__ecere__com__Instance *))__extension__ ({
struct __ecereNameSpace__ecere__com__Instance * __internal_ClassInst = classPropValues;
__internal_ClassInst ? __internal_ClassInst->_vTbl : __ecereClass___ecereNameSpace__ecere__com__List->_vTbl;
})[__ecereVMethodID___ecereNameSpace__ecere__com__Container_Free]);
__internal_VirtualMethod ? __internal_VirtualMethod(classPropValues) : (void)1;
}));
}
}
void __ecereRegisterModule_pass1(struct __ecereNameSpace__ecere__com__Instance * module)
{
struct __ecereNameSpace__ecere__com__Class __attribute__((unused)) * class;
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("SetBuildingEcereCom", "void SetBuildingEcereCom(bool b)", SetBuildingEcereCom, module, 1);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("GetBuildingEcereCom", "bool GetBuildingEcereCom(void)", GetBuildingEcereCom, module, 1);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("SetBuildingEcereComModule", "void SetBuildingEcereComModule(bool b)", SetBuildingEcereComModule, module, 1);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("GetBuildingEcereComModule", "bool GetBuildingEcereComModule(void)", GetBuildingEcereComModule, module, 1);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("ProcessClassFunction", "External ProcessClassFunction(ecere::com::Class owningClass, ClassFunction func, ecere::sys::OldList defs, External after, bool makeStatic)", ProcessClassFunction, module, 2);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("CreateRegisterModuleBody", "void CreateRegisterModuleBody(void)", CreateRegisterModuleBody, module, 2);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("RegisterMembersAndProperties", "void RegisterMembersAndProperties(ecere::com::Class regClass, bool isMember, const char * className, Statement statement)", RegisterMembersAndProperties, module, 2);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("GetNameSpaceString", "void GetNameSpaceString(ecere::com::NameSpace ns, char * string)", GetNameSpaceString, module, 2);
class = __ecereNameSpace__ecere__com__eSystem_RegisterClass(0, "ClassPropertyValue", 0, sizeof(struct ClassPropertyValue), 0, (void *)0, (void *)__ecereDestructor_ClassPropertyValue, module, 2, 1);
if(((struct __ecereNameSpace__ecere__com__Module *)(((char *)module + sizeof(struct __ecereNameSpace__ecere__com__Instance))))->application == ((struct __ecereNameSpace__ecere__com__Module *)(((char *)__thisModule + sizeof(struct __ecereNameSpace__ecere__com__Instance))))->application && class)
__ecereClass_ClassPropertyValue = class;
__ecereNameSpace__ecere__com__eClass_AddDataMember(class, (((void *)0)), (((void *)0)), 0, sizeof(void *) > 4 ? sizeof(void *) : 4, 2);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("ProcessClassDefinitions", "void ProcessClassDefinitions(void)", ProcessClassDefinitions, module, 1);
}
|
the_stack_data/154827172.c
|
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
short socket_create(void)
{
short h_socket = 0;
printf("Create the socket\n");
h_socket = socket(AF_INET, SOCK_STREAM, 0);
return h_socket;
}
int bind_created_socket(int h_socket)
{
int i_retval = -1;
int client_port = 12345;
struct sockaddr_in remote = { 0 };
/* Internet address family */
remote.sin_family = AF_INET;
/* Any incoming interface */
remote.sin_addr.s_addr = htonl(INADDR_ANY);
remote.sin_port = htons(client_port); /* local port */
i_retval = bind(h_socket, (struct sockaddr *)&remote,
sizeof(remote));
return i_retval;
}
int main(int argc, char const *argv[])
{
int socket_desc = 0;
int sock = 0;
int client_len = 0;
struct sockaddr_in client;
char client_message[200] = { 0 };
char message[100] = { 0 };
const char *p_message = "hello from Chen's server";
/* Create socket */
socket_desc = socket_create();
if (socket_desc == -1)
{
printf("Could not create socket");
return 1;
}
printf("Socket created\n");
/* Bind */
if (bind_created_socket(socket_desc) < 0)
{
/* print the error message */
perror("bind failed.");
return 1;
}
printf("bind done\n");
/* Listen */
listen(socket_desc, 3);
/* Accept and incoming connection */
while(1)
{
printf("Waiting for incoming connections...\n");
client_len = sizeof(struct sockaddr_in);
/* accept connection from an incoming client */
sock = accept(socket_desc, (struct sockaddr *)&client,
(socklen_t*)&client_len);
if (sock < 0)
{
perror("accept failed");
return 1;
}
printf("Connection accepted\n");
memset(client_message, '\0', sizeof client_message);
memset(message, '\0', sizeof message);
/* Receive a reply from the client */
if (recv(sock, client_message, 200, 0) < 0)
{
printf("recv failed");
break;
}
printf("Client reply: %s\n", client_message);
if (strcmp(p_message, client_message) == 0)
{
strcpy(message, "Hi there!");
}
else
{
strcpy(message, "Invalid Message!");
}
/* Send some data */
if (send(sock, message, strlen(message), 0) < 0)
{
printf("Send failed");
return 1;
}
close(sock);
sleep(1);
}
return 0;
}
|
the_stack_data/97768.c
|
#include <unistd.h>
void ft_putchar(char *str);
void rush04_first(int x)
{
int i;
i = 1;
ft_putchar("A");
while (x >= 1 && i < (x - 1))
{
ft_putchar("B");
i++;
}
if (x > 1)
{
ft_putchar("C");
}
ft_putchar("\n");
}
void rush04_last(int x)
{
int i;
i = 1;
ft_putchar("C");
while (x >= 1 && i < (x - 1))
{
ft_putchar("B");
i++;
}
if (x > 1)
{
ft_putchar("A");
}
ft_putchar("\n");
}
void rush04_govde(int x, int y)
{
int i;
int j;
j = 1;
while (j <= (y - 2))
{
i = 1;
ft_putchar("B");
while (i < (x - 1))
{
ft_putchar(" ");
i++;
}
if (x > 1)
{
ft_putchar("B");
}
ft_putchar("\n");
j++;
}
}
void rush(int x, int y)
{
if (x > 0)
{
if (y > 0)
{
rush04_first(x);
}
if (y > 2)
{
rush04_govde(x, y);
}
if (y >= 2)
{
rush04_last(x);
}
}
}
|
the_stack_data/170452105.c
|
/* ヘッダファイルのインクルード */
#include <stdio.h> /* 標準入出力 */
#include <string.h> /* 文字列操作 */
#include <ctype.h> /* 文字操作 */
/* main関数の定義 */
int main(void){
/* 変数, 配列の初期化 */
int len = 0; /* textの長さlenを0に初期化. */
int i = 0; /* iを0に初期化. */
char text[256] = {'\0'}; /* textを'\0'で埋める. */
/* 文字列の取得 */
fgets(text, 256, stdin); /* 標準入力stdinからfgetsで1行読み込み, textに格納. */
/* 最後の文字をチェック. */
len = strlen(text); /* textの長さを取得. */
if (text[len - 1] == '\n'){ /* 最後の文字が'\n'. */
text[len - 1] = '\0'; /* '\0'を代入. */
}
len = strlen(text); /* もう一度長さを取得.(改行がなくなった分減っている.) */
/* 入力された文字列に大文字が含まれていたら小文字に変換する. */
for (i = 0; i < len; i++){ /* lenの分だけ繰り返す. */
text[i] = tolower(text[i]); /* textのi番目をtolowerで小文字に変換してtextのi番目に入れ直す. */
}
/* 変換後のtextの出力. */
printf("%s\n", text); /* printfでtextを出力. */
/* プログラムの終了 */
return 0; /* 0を返して正常終了. */
}
|
the_stack_data/1248669.c
|
/*******************************************************************************
* The BYTE UNIX Benchmarks - Release 3
* Module: big.c SID: 3.3 5/15/91 19:30:18
*
*******************************************************************************
* Bug reports, patches, comments, suggestions should be sent to:
*
* Ben Smith, Rick Grehan or Tom Yager
* [email protected] [email protected] [email protected]
*
*******************************************************************************
* Modification Log:
* 10/22/97 - code cleanup to remove ANSI C compiler warnings
* Andy Kahn <[email protected]>
*
******************************************************************************/
/*
* dummy code for execl test [ old version of makework.c ]
*
* makework [ -r rate ] [ -c copyfile ] nusers
*
* job streams are specified on standard input with lines of the form
* full_path_name_for_command [ options ] [ <standard_input_file ]
*
* "standard input" is send to all nuser instances of the commands in the
* job streams at a rate not in excess of "rate" characters per second
* per command
*
*/
/* this code is included in other files and therefore has no SCCSid */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <sys/wait.h>
#define DEF_RATE 5.0
#define GRANULE 5
#define CHUNK 60
#define MAXCHILD 12
#define MAXWORK 10
void wrapup(char *);
void onalarm(int);
void pipeerr();
void grunt();
void getwork(void);
#if debug
void dumpwork(void);
#endif
void fatal(char *s);
float thres;
float est_rate = DEF_RATE;
int nusers; /* number of concurrent users to be simulated by
* this process */
int firstuser; /* ordinal identification of first user for this
* process */
int nwork = 0; /* number of job streams */
int exit_status = 0; /* returned to parent */
int sigpipe; /* pipe write error flag */
struct st_work {
char *cmd; /* name of command to run */
char **av; /* arguments to command */
char *input; /* standard input buffer */
int inpsize; /* size of standard input buffer */
char *outf; /* standard output (filename) */
} work[MAXWORK];
struct {
int xmit; /* # characters sent */
char *bp; /* std input buffer pointer */
int blen; /* std input buffer length */
int fd; /* stdin to command */
int pid; /* child PID */
char *line; /* start of input line */
int firstjob; /* inital piece of work */
int thisjob; /* current piece of work */
} child[MAXCHILD], *cp;
int main(argc, argv)
int argc;
char *argv[];
{
int i;
int l;
int fcopy = 0; /* fd for copy output */
int master = 1; /* the REAL master, == 0 for clones */
int nchild; /* no. of children for a clone to run */
int done; /* count of children finished */
int output; /* aggregate output char count for all
children */
int c;
int thiswork = 0; /* next job stream to allocate */
int nch; /* # characters to write */
int written; /* # characters actully written */
char logname[15]; /* name of the log file(s) */
int pvec[2]; /* for pipes */
char *p;
char *prog; /* my name */
#if ! debug
freopen("masterlog.00", "a", stderr);
#endif
fprintf(stderr, "*** New Run *** ");
prog = argv[0];
while (argc > 1 && argv[1][0] == '-') {
p = &argv[1][1];
argc--;
argv++;
while (*p) {
switch (*p) {
case 'r':
est_rate = atoi(argv[1]);
sscanf(argv[1], "%f", &est_rate);
if (est_rate <= 0) {
fprintf(stderr, "%s: bad rate, reset to %.2f chars/sec\n", prog, DEF_RATE);
est_rate = DEF_RATE;
}
argc--;
argv++;
break;
case 'c':
fcopy = open(argv[1], 1);
if (fcopy < 0)
fcopy = creat(argv[1], 0600);
if (fcopy < 0) {
fprintf(stderr, "%s: cannot open copy file '%s'\n",
prog, argv[1]);
exit(2);
}
lseek(fcopy, 0L, 2); /* append at end of file */
argc--;
argv++;
break;
default:
fprintf(stderr, "%s: bad flag '%c'\n", prog, *p);
exit(4);
}
p++;
}
}
if (argc < 2) {
fprintf(stderr, "%s: missing nusers\n", prog);
exit(4);
}
nusers = atoi(argv[1]);
if (nusers < 1) {
fprintf(stderr, "%s: impossible nusers (%d<-%s)\n", prog, nusers, argv[1]);
exit(4);
}
fprintf(stderr, "%d Users\n", nusers);
argc--;
argv++;
/* build job streams */
getwork();
#if debug
dumpwork();
#endif
/* clone copies of myself to run up to MAXCHILD jobs each */
firstuser = MAXCHILD;
fprintf(stderr, "master pid %d\n", getpid());
fflush(stderr);
while (nusers > MAXCHILD) {
fflush(stderr);
if (nusers >= 2*MAXCHILD)
/* the next clone must run MAXCHILD jobs */
nchild = MAXCHILD;
else
/* the next clone must run the leftover jobs */
nchild = nusers - MAXCHILD;
if ((l = fork()) == -1) {
/* fork failed */
fatal("** clone fork failed **\n");
goto bepatient;
} else if (l > 0) {
fprintf(stderr, "master clone pid %d\n", l);
/* I am the master with nchild fewer jobs to run */
nusers -= nchild;
firstuser += MAXCHILD;
continue;
} else {
/* I am a clone, run MAXCHILD jobs */
#if ! debug
sprintf(logname, "masterlog.%02d", firstuser/MAXCHILD);
freopen(logname, "w", stderr);
#endif
master = 0;
nusers = nchild;
break;
}
}
if (master)
firstuser = 0;
close(0);
for (i = 0; i < nusers; i++ ) {
fprintf(stderr, "user %d job %d ", firstuser+i, thiswork);
if (pipe(pvec) == -1) {
/* this is fatal */
fatal("** pipe failed **\n");
goto bepatient;
}
fflush(stderr);
if ((child[i].pid = fork()) == 0) {
int fd;
/* the command */
if (pvec[0] != 0) {
close(0);
dup(pvec[0]);
}
#if ! debug
sprintf(logname, "userlog.%02d", firstuser+i);
freopen(logname, "w", stderr);
#endif
for (fd = 3; fd < 24; fd++)
close(fd);
if (work[thiswork].outf[0] != '\0') {
/* redirect std output */
char *q;
for (q = work[thiswork].outf; *q != '\n'; q++) ;
*q = '\0';
if (freopen(work[thiswork].outf, "w", stdout) == NULL) {
fprintf(stderr, "makework: cannot open %s for std output\n",
work[thiswork].outf);
fflush(stderr);
}
*q = '\n';
}
execv(work[thiswork].cmd, work[thiswork].av);
/* don't expect to get here! */
fatal("** exec failed **\n");
goto bepatient;
}
else if (child[i].pid == -1) {
fatal("** fork failed **\n");
goto bepatient;
}
else {
close(pvec[0]);
child[i].fd = pvec[1];
child[i].line = child[i].bp = work[thiswork].input;
child[i].blen = work[thiswork].inpsize;
child[i].thisjob = thiswork;
child[i].firstjob = thiswork;
fprintf(stderr, "pid %d pipe fd %d", child[i].pid, child[i].fd);
if (work[thiswork].outf[0] != '\0') {
char *q;
fprintf(stderr, " > ");
for (q=work[thiswork].outf; *q != '\n'; q++)
fputc(*q, stderr);
}
fputc('\n', stderr);
thiswork++;
if (thiswork >= nwork)
thiswork = 0;
}
}
fflush(stderr);
srand(time(0));
thres = 0;
done = output = 0;
for (i = 0; i < nusers; i++) {
if (child[i].blen == 0)
done++;
else
thres += est_rate * GRANULE;
}
est_rate = thres;
signal(SIGALRM, onalarm);
signal(SIGPIPE, pipeerr);
alarm(GRANULE);
while (done < nusers) {
for (i = 0; i < nusers; i++) {
cp = &child[i];
if (cp->xmit >= cp->blen) continue;
l = rand() % CHUNK + 1; /* 1-CHUNK chars */
if (l == 0) continue;
if (cp->xmit + l > cp->blen)
l = cp->blen - cp->xmit;
p = cp->bp;
cp->bp += l;
cp->xmit += l;
#if debug
fprintf(stderr, "child %d, %d processed, %d to go\n", i, cp->xmit, cp->blen - cp->xmit);
#endif
while (p < cp->bp) {
if (*p == '\n' || (p == &cp->bp[-1] && cp->xmit >= cp->blen)) {
/* write it out */
nch = p - cp->line + 1;
if ((written = write(cp->fd, cp->line, nch)) != nch) {
/* argh! */
cp->line[nch] = '\0';
fprintf(stderr, "user %d job %d cmd %s ",
firstuser+i, cp->thisjob, cp->line);
fprintf(stderr, "write(,,%d) returns %d\n", nch, written);
if (sigpipe)
fatal("** SIGPIPE error **\n");
else
fatal("** write error **\n");
goto bepatient;
}
if (fcopy)
write(fcopy, cp->line, p - cp->line + 1);
#if debug
fprintf(stderr, "child %d gets \"", i);
{
char *q = cp->line;
while (q <= p) {
if (*q >= ' ' && *q <= '~')
fputc(*q, stderr);
else
fprintf(stderr, "\\%03o", *q);
q++;
}
}
fputc('"', stderr);
#endif
cp->line = &p[1];
}
p++;
}
if (cp->xmit >= cp->blen) {
done++;
close(cp->fd);
#if debug
fprintf(stderr, "child %d, close std input\n", i);
#endif
}
output += l;
}
while (output > thres) {
pause();
#if debug
fprintf(stderr, "after pause: output, thres, done %d %.2f %d\n", output, thres, done);
#endif
}
}
bepatient:
alarm(0);
/****
* If everything is going OK, we should simply be able to keep
* looping unitil 'wait' fails, however some descendent process may
* be in a state from which it can never exit, and so a timeout
* is used.
* 5 minutes should be ample, since the time to run all jobs is of
* the order of 5-10 minutes, however some machines are painfully slow,
* so the timeout has been set at 20 minutes (1200 seconds).
****/
signal(SIGALRM, grunt);
alarm(1200);
while ((c = wait(&l)) != -1) {
for (i = 0; i < nusers; i++) {
if (c == child[i].pid) {
fprintf(stderr, "user %d job %d pid %d done", firstuser+i, child[i].thisjob, c);
if (l != 0) {
if (l & 0x7f)
fprintf(stderr, " status %d", l & 0x7f);
if (l & 0xff00)
fprintf(stderr, " exit code %d", (l>>8) & 0xff);
exit_status = 4;
}
fputc('\n', stderr);
c = child[i].pid = -1;
break;
}
}
if (c != -1) {
fprintf(stderr, "master clone done, pid %d ", c);
if (l != 0) {
if (l & 0x7f)
fprintf(stderr, " status %d", l & 0x7f);
if (l & 0xff00)
fprintf(stderr, " exit code %d", (l>>8) & 0xff);
exit_status = 4;
}
fputc('\n', stderr);
}
}
alarm(0);
wrapup("Finished waiting ...");
exit(0);
}
void onalarm(int foo)
{
thres += est_rate;
signal(SIGALRM, onalarm);
alarm(GRANULE);
}
void grunt()
{
/* timeout after label "bepatient" in main */
exit_status = 4;
wrapup("Timed out waiting for jobs to finish ...");
}
void pipeerr()
{
sigpipe++;
}
void wrapup(char *reason)
{
int i;
int killed = 0;
fflush(stderr);
for (i = 0; i < nusers; i++) {
if (child[i].pid > 0 && kill(child[i].pid, SIGKILL) != -1) {
if (!killed) {
killed++;
fprintf(stderr, "%s\n", reason);
fflush(stderr);
}
fprintf(stderr, "user %d job %d pid %d killed off\n", firstuser+i, child[i].thisjob, child[i].pid);
fflush(stderr);
}
}
exit(exit_status);
}
#define MAXLINE 512
void getwork(void)
{
int i;
int f;
int ac=0;
char *lp = (void *)0;
char *q = (void *)0;
struct st_work *w = (void *)0;
char line[MAXLINE];
while (fgets(line, MAXLINE, stdin) != NULL) {
if (nwork >= MAXWORK) {
fprintf(stderr, "Too many jobs specified, .. increase MAXWORK\n");
exit(4);
}
w = &work[nwork];
lp = line;
i = 1;
while (*lp && *lp != ' ') {
i++;
lp++;
}
w->cmd = (char *)malloc(i);
strncpy(w->cmd, line, i-1);
w->cmd[i-1] = '\0';
w->inpsize = 0;
w->input = "";
/* start to build arg list */
ac = 2;
w->av = (char **)malloc(2*sizeof(char *));
q = w->cmd;
while (*q) q++;
q--;
while (q >= w->cmd) {
if (*q == '/') {
q++;
break;
}
q--;
}
w->av[0] = q;
while (*lp) {
if (*lp == ' ') {
/* space */
lp++;
continue;
}
else if (*lp == '<') {
/* standard input for this job */
q = ++lp;
while (*lp && *lp != ' ') lp++;
*lp = '\0';
if ((f = open(q, 0)) == -1) {
fprintf(stderr, "cannot open input file (%s) for job %d\n",
q, nwork);
exit(4);
}
/* gobble input */
w->input = (char *)malloc(512);
while ((i = read(f, &w->input[w->inpsize], 512)) > 0) {
w->inpsize += i;
w->input = (char *)realloc(w->input, w->inpsize+512);
}
w->input = (char *)realloc(w->input, w->inpsize);
close(f);
/* extract stdout file name from line beginning "C=" */
w->outf = "";
for (q = w->input; q < &w->input[w->inpsize-10]; q++) {
if (*q == '\n' && strncmp(&q[1], "C=", 2) == 0) {
w->outf = &q[3];
break;
}
}
#if debug
if (*w->outf) {
fprintf(stderr, "stdout->");
for (q=w->outf; *q != '\n'; q++)
fputc(*q, stderr);
fputc('\n', stderr);
}
#endif
}
else {
/* a command option */
ac++;
w->av = (char **)realloc(w->av, ac*sizeof(char *));
q = lp;
i = 1;
while (*lp && *lp != ' ') {
lp++;
i++;
}
w->av[ac-2] = (char *)malloc(i);
strncpy(w->av[ac-2], q, i-1);
w->av[ac-2][i-1] = '\0';
}
}
w->av[ac-1] = (char *)0;
nwork++;
}
}
#if debug
void dumpwork(void)
{
int i;
int j;
for (i = 0; i < nwork; i++) {
fprintf(stderr, "job %d: cmd: %s\n", i, work[i].cmd);
j = 0;
while (work[i].av[j]) {
fprintf(stderr, "argv[%d]: %s\n", j, work[i].av[j]);
j++;
}
fprintf(stderr, "input: %d chars text: ", work[i].inpsize);
if (work[i].input == (char *)0)
fprintf(stderr, "<NULL>\n");
else {
register char *pend;
char *p;
char c;
p = work[i].input;
while (*p) {
pend = p;
while (*pend && *pend != '\n')
pend++;
c = *pend;
*pend = '\0';
fprintf(stderr, "%s\n", p);
*pend = c;
p = &pend[1];
}
}
}
}
#endif
void fatal(char *s)
{
int i;
fprintf(stderr, s);
fflush(stderr);
perror("Reason?");
fflush(stderr);
for (i = 0; i < nusers; i++) {
if (child[i].pid > 0 && kill(child[i].pid, SIGKILL) != -1) {
fprintf(stderr, "pid %d killed off\n", child[i].pid);
fflush(stderr);
}
}
exit_status = 4;
}
|
the_stack_data/150142988.c
|
#if (defined(__unix__) || defined(__unix) || defined(unix)) && !defined(MEMORY_ACCESSOR)
#define MEMORY_ACCESSOR
#if defined(__linux__)
/* Linux Depenent Code */
#endif
#endif
|
the_stack_data/147195.c
|
// RUN: %clang -fsanitize=vla-bound %s -O3 -o %t
// RUN: %t 2>&1 | FileCheck %s --check-prefix=CHECK-MINUS-ONE
// RUN: %t a 2>&1 | FileCheck %s --check-prefix=CHECK-ZERO
// RUN: %t a b
int main(int argc, char **argv) {
// CHECK-MINUS-ONE: vla.c:9:11: runtime error: variable length array bound evaluates to non-positive value -1
// CHECK-ZERO: vla.c:9:11: runtime error: variable length array bound evaluates to non-positive value 0
int arr[argc - 2];
return 0;
}
|
the_stack_data/1151806.c
|
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } }
#define N 100000
int main ( ) {
int a[N];
int i = 0;
while ( i < N ) {
a[i] = 42;
i = i + 1;
}
i = 0;
while ( i < N ) {
a[i] = 43;
i = i + 1;
}
i = 0;
while ( i < N ) {
a[i] = 44;
i = i + 1;
}
i = 0;
while ( i < N ) {
a[i] = 45;
i = i + 1;
}
i = 0;
while ( i < N ) {
a[i] = 46;
i = i + 1;
}
i = 0;
while ( i < N ) {
a[i] = 47;
i = i + 1;
}
i = 0;
while ( i < N ) {
a[i] = 48;
i = i + 1;
}
i = 0;
while ( i < N ) {
a[i] = 49;
i = i + 1;
}
int x;
for ( x = 0 ; x < N ; x++ ) {
__VERIFIER_assert( a[x] == 49 );
}
return 0;
}
|
the_stack_data/68362.c
|
#include <stdio.h>
#include <stdlib.h>
void hamster()
{
void *p;
puts("Hi from hamster!");
p = malloc(111);
}
|
the_stack_data/20450190.c
|
#include <stdio.h>
#include <stdlib.h>
// pythonic list structure
typedef struct {
int *t;
size_t capacity; // number of disks the peg can hold (= length of t)
size_t nb; // number of disks on the peg
char label; // label of the peg
} peg;
void init(peg *p, size_t capacity, size_t nb, char label) {
p->t = (int *) malloc(capacity * sizeof(int));
p->capacity = capacity;
p->nb = nb;
p->label = label;
// populate peg in reverse order (largest at bottom)
for (int i = 0; i < nb; i++) {
p->t[i] = nb-i;
}
}
void destroy(peg *p) {
free(p->t);
}
// adds the disk of size n onto to the p peg
int append(peg *p, int n) {
if (p->nb+1 <= p->capacity) {
p->t[p->nb] = n;
p->nb++;
return 1;
} else {
// peg is full
return 0;
}
}
// removes the disk on top of the p peg and returns it
int pop(peg *p) {
if (p->nb > 0) {
p->nb--;
return p->t[p->nb];
} else {
// peg is already empty
return -1;
}
}
// finds and returns the peg that has the correct label amongst p1, p2 and p3
// if none have the correct label, returns a null
peg *findWithLabel(peg *p1, peg *p2, peg *p3, char label) {
if (p1->label == label) {
return p1;
} else if (p2->label == label) {
return p2;
} else if (p3->label == label) {
return p3;
} else {
return NULL;
}
}
//displays the pegs in order
void display(peg *p1, peg *p2, peg *p3) {
peg *A = findWithLabel(p1, p2, p3, 'A');
peg *B = findWithLabel(p1, p2, p3, 'B');
peg *C = findWithLabel(p1, p2, p3, 'C');
// print A's contents
printf("A: ");
for (size_t i = 0; i < A->nb; i++) {
printf("%2d ", A->t[i]);
}
// represent the empty end with underscores
for (size_t i = A->nb; i < A->capacity; i++) {
printf("__ ");
}
printf("\n");
// print B's contents
printf("B: ");
for (size_t i = 0; i < B->nb; i++) {
printf("%2d ", B->t[i]);
}
for (size_t i = B->nb; i < B->capacity; i++) {
printf("__ ");
}
printf("\n");
// print C's contents
printf("C: ");
for (size_t i = 0; i < C->nb; i++) {
printf("%2d ", C->t[i]);
}
for (size_t i = C->nb; i < C->capacity; i++) {
printf("__ ");
}
printf("\n");
}
void hanoi(peg *source, peg *target, peg *spare, int n) {
// if n == 0, do nothing
if (n != 0) {
// move n-1 disks from source to spare
hanoi(source, spare, target, n-1);
// move nth disk to target
append(target, pop(source));
printf("__________\n");
display(source, spare, target);
// move n-1 disks from spare to target
hanoi(spare, target, source, n-1);
}
}
int main(int argc, char **argv) {
peg peg1;
peg peg2;
peg peg3;
size_t n;
if (argc == 1) {
// default: 3
printf("Initializing Towers of Hanoï with default size of 3:\n");
n = 3;
} else if (argc == 2 && sscanf(argv[1], "%ld", &n) == 1) {
printf("Initializing Towers of Hanoï with size of %ld:\n", n);
} else {
printf("Usage: %s [peg size]\n", argv[0]);
return 1;
}
// initialize pegs
init(&peg1, n, n, 'A');
init(&peg2, n, 0, 'B');
init(&peg3, n, 0, 'C');
printf("Initial state:\n");
display(&peg1, &peg2, &peg3);
// move n disks from peg1 to peg3
hanoi(&peg1, &peg3, &peg2, n);
printf("\nFinal state:\n");
display(&peg1, &peg2, &peg3);
destroy(&peg1);
destroy(&peg2);
destroy(&peg3);
return 0;
}
|
the_stack_data/61075662.c
|
#define MSPACES 1
#define ONLY_MSPACES 1
#define USE_LOCKS 2 // > 1 => custom locks
#ifdef __STANDALONE__
#define HAVE_MORECORE 0
#else
#define HAVE_MORECORE 0
#endif
#define HAVE_MMAP 0
#define MALLOC_ALIGNMENT 32
// begin: kernel space related
#if !defined(__STANDALONE__) && defined(__KERNEL__)
#ifdef ARM
#undef ARM
#endif // ifdef ARM
#include <linux/kernel.h> // We're doing kernel work
#include <linux/module.h> // Specifically, a module
// #include <linux/moduleparam.h> // for parameter use
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/cdev.h> // Char device structure
#include <asm/uaccess.h> // for get_user and put_user
#else // #if !defined(__STANDALONE__) && defined(__KERNEL__)
//#include <string.h>
//#include "sysc_kernel_api.h"
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#endif // #if !defined(__STANDALONE__) && defined(__KERNEL__)
// end: kernel space related
// begin: kernel space related
#if !defined(__STANDALONE__) && defined(__KERNEL__)
#define ABORT printk(KERN_INFO "SRAM Doug Leas allocator error.\n");
// memset on ioremapped memory doesn't work => custom memset required
#define memset my_memset
static void *my_memset(void *apAddr, int8_t aVal, size_t aSize)
{
size_t i = 0;
int8_t *lpDst = (int8_t*) apAddr;
for(i = 0; i < aSize; i++)
{
lpDst[i] = aVal;
} // for the whole size
return apAddr;
} // my_memset
#else // #if !defined(__STANDALONE__) && defined(__KERNEL__)
#define ABORT printf("SRAM Doug Leas allocator error.\n");
#endif // #if !defined(__STANDALONE__) && defined(__KERNEL__)
// end: kernel space related
//#define LACKS_UNISTD_H
//#define LACKS_FCNTL_H
//#define LACKS_SYS_PARAM_H
//#define LACKS_SYS_MMAN_H
//#define LACKS_STRINGS_H
//#define LACKS_STRING_H
//#define LACKS_SYS_TYPES_H
//#define LACKS_ERRNO_H
//#define LACKS_STDLIB_H
#ifdef NO_HEAPMON
#define NO_MALLINFO 1
#else
#define NO_MALLINFO 0
#endif
/*
$Id: malloc.c,v 1.4 2006/03/30 16:47:29 wg Exp $
This version of malloc.c was adapted for ptmalloc3 by Wolfram Gloger
<[email protected]>. Therefore, some of the comments below do not apply
for this modified version. However, it is the intention to keep
differences to Doug Lea's original version minimal, hence the
comments were mostly left unchanged.
-----------------------------------------------------------------------
This is a version (aka dlmalloc) of malloc/free/realloc written by
Doug Lea and released to the public domain, as explained at
http://creativecommons.org/licenses/publicdomain. Send questions,
comments, complaints, performance data, etc to [email protected]
* Version pre-2.8.4 Wed Mar 29 19:46:29 2006 (dl at gee)
Note: There may be an updated version of this malloc obtainable at
ftp://gee.cs.oswego.edu/pub/misc/malloc.c
Check before installing!
* Quickstart
This library is all in one file to simplify the most common usage:
ftp it, compile it (-O3), and link it into another program. All of
the compile-time options default to reasonable values for use on
most platforms. You might later want to step through various
compile-time and dynamic tuning options.
For convenience, an include file for code using this malloc is at:
ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.3.h
You don't really need this .h file unless you call functions not
defined in your system include files. The .h file contains only the
excerpts from this file needed for using this malloc on ANSI C/C++
systems, so long as you haven't changed compile-time options about
naming and tuning parameters. If you do, then you can create your
own malloc.h that does include all settings by cutting at the point
indicated below. Note that you may already by default be using a C
library containing a malloc that is based on some version of this
malloc (for example in linux). You might still want to use the one
in this file to customize settings or to avoid overheads associated
with library versions.
* Vital statistics:
Supported pointer/size_t representation: 4 or 8 bytes
size_t MUST be an unsigned type of the same width as
pointers. (If you are using an ancient system that declares
size_t as a signed type, or need it to be a different width
than pointers, you can use a previous release of this malloc
(e.g. 2.7.2) supporting these.)
Alignment: 8 bytes (default)
This suffices for nearly all current machines and C compilers.
However, you can define MALLOC_ALIGNMENT to be wider than this
if necessary (up to 128bytes), at the expense of using more space.
Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes)
8 or 16 bytes (if 8byte sizes)
Each malloced chunk has a hidden word of overhead holding size
and status information, and additional cross-check word
if FOOTERS is defined.
Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead)
8-byte ptrs: 32 bytes (including overhead)
Even a request for zero bytes (i.e., malloc(0)) returns a
pointer to something of the minimum allocatable size.
The maximum overhead wastage (i.e., number of extra bytes
allocated than were requested in malloc) is less than or equal
to the minimum size, except for requests >= mmap_threshold that
are serviced via mmap(), where the worst case wastage is about
32 bytes plus the remainder from a system page (the minimal
mmap unit); typically 4096 or 8192 bytes.
Security: static-safe; optionally more or less
The "security" of malloc refers to the ability of malicious
code to accentuate the effects of errors (for example, freeing
space that is not currently malloc'ed or overwriting past the
ends of chunks) in code that calls malloc. This malloc
guarantees not to modify any memory locations below the base of
heap, i.e., static variables, even in the presence of usage
errors. The routines additionally detect most improper frees
and reallocs. All this holds as long as the static bookkeeping
for malloc itself is not corrupted by some other means. This
is only one aspect of security -- these checks do not, and
cannot, detect all possible programming errors.
If FOOTERS is defined nonzero, then each allocated chunk
carries an additional check word to verify that it was malloced
from its space. These check words are the same within each
execution of a program using malloc, but differ across
executions, so externally crafted fake chunks cannot be
freed. This improves security by rejecting frees/reallocs that
could corrupt heap memory, in addition to the checks preventing
writes to statics that are always on. This may further improve
security at the expense of time and space overhead. (Note that
FOOTERS may also be worth using with MSPACES.)
By default detected errors cause the program to abort (calling
"abort()"). You can override this to instead proceed past
errors by defining PROCEED_ON_ERROR. In this case, a bad free
has no effect, and a malloc that encounters a bad address
caused by user overwrites will ignore the bad address by
dropping pointers and indices to all known memory. This may
be appropriate for programs that should continue if at all
possible in the face of programming errors, although they may
run out of memory because dropped memory is never reclaimed.
If you don't like either of these options, you can define
CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
else. And if if you are sure that your program using malloc has
no errors or vulnerabilities, you can define INSECURE to 1,
which might (or might not) provide a small performance improvement.
Thread-safety: NOT thread-safe unless USE_LOCKS defined
When USE_LOCKS is defined, each public call to malloc, free,
etc is surrounded with either a pthread mutex or a win32
spinlock (depending on WIN32). This is not especially fast, and
can be a major bottleneck. It is designed only to provide
minimal protection in concurrent environments, and to provide a
basis for extensions. If you are using malloc in a concurrent
program, consider instead using nedmalloc
(http://www.nedprod.com/programs/portable/nedmalloc/) or
ptmalloc (See http://www.malloc.de), which are derived
from versions of this malloc.
System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
This malloc can use unix sbrk or any emulation (invoked using
the CALL_MORECORE macro) and/or mmap/munmap or any emulation
(invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
memory. On most unix systems, it tends to work best if both
MORECORE and MMAP are enabled. On Win32, it uses emulations
based on VirtualAlloc. It also uses common C library functions
like memset.
Compliance: I believe it is compliant with the Single Unix Specification
(See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
others as well.
* Overview of algorithms
This is not the fastest, most space-conserving, most portable, or
most tunable malloc ever written. However it is among the fastest
while also being among the most space-conserving, portable and
tunable. Consistent balance across these factors results in a good
general-purpose allocator for malloc-intensive programs.
In most ways, this malloc is a best-fit allocator. Generally, it
chooses the best-fitting existing chunk for a request, with ties
broken in approximately least-recently-used order. (This strategy
normally maintains low fragmentation.) However, for requests less
than 256bytes, it deviates from best-fit when there is not an
exactly fitting available chunk by preferring to use space adjacent
to that used for the previous small request, as well as by breaking
ties in approximately most-recently-used order. (These enhance
locality of series of small allocations.) And for very large requests
(>= 256Kb by default), it relies on system memory mapping
facilities, if supported. (This helps avoid carrying around and
possibly fragmenting memory used only for large chunks.)
All operations (except malloc_stats and mallinfo) have execution
times that are bounded by a constant factor of the number of bits in
a size_t, not counting any clearing in calloc or copying in realloc,
or actions surrounding MORECORE and MMAP that have times
proportional to the number of non-contiguous regions returned by
system allocation routines, which is often just 1. In real-time
applications, you can optionally suppress segment traversals using
NO_SEGMENT_TRAVERSAL, which assures bounded execution even when
system allocators return non-contiguous spaces, at the typical
expense of carrying around more memory and increased fragmentation.
The implementation is not very modular and seriously overuses
macros. Perhaps someday all C compilers will do as good a job
inlining modular code as can now be done by brute-force expansion,
but now, enough of them seem not to.
Some compilers issue a lot of warnings about code that is
dead/unreachable only on some platforms, and also about intentional
uses of negation on unsigned types. All known cases of each can be
ignored.
For a longer but out of date high-level description, see
http://gee.cs.oswego.edu/dl/html/malloc.html
* MSPACES
If MSPACES is defined, then in addition to malloc, free, etc.,
this file also defines mspace_malloc, mspace_free, etc. These
are versions of malloc routines that take an "mspace" argument
obtained using create_mspace, to control all internal bookkeeping.
If ONLY_MSPACES is defined, only these versions are compiled.
So if you would like to use this allocator for only some allocations,
and your system malloc for others, you can compile with
ONLY_MSPACES and then do something like...
static mspace mymspace = create_mspace(0,0); // for example
#define mymalloc(bytes) mspace_malloc(mymspace, bytes)
(Note: If you only need one instance of an mspace, you can instead
use "USE_DL_PREFIX" to relabel the global malloc.)
You can similarly create thread-local allocators by storing
mspaces as thread-locals. For example:
static __thread mspace tlms = 0;
void* tlmalloc(size_t bytes) {
if (tlms == 0) tlms = create_mspace(0, 0);
return mspace_malloc(tlms, bytes);
}
void tlfree(void* mem) { mspace_free(tlms, mem); }
Unless FOOTERS is defined, each mspace is completely independent.
You cannot allocate from one and free to another (although
conformance is only weakly checked, so usage errors are not always
caught). If FOOTERS is defined, then each chunk carries around a tag
indicating its originating mspace, and frees are directed to their
originating spaces.
------------------------- Compile-time options ---------------------------
Be careful in setting #define values for numerical constants of type
size_t. On some systems, literal values are not automatically extended
to size_t precision unless they are explicitly casted. You can also
use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below.
WIN32 default: defined if _WIN32 defined
Defining WIN32 sets up defaults for MS environment and compilers.
Otherwise defaults are for unix.
MALLOC_ALIGNMENT default: (size_t)8
Controls the minimum alignment for malloc'ed chunks. It must be a
power of two and at least 8, even on machines for which smaller
alignments would suffice. It may be defined as larger than this
though. Note however that code and data structures are optimized for
the case of 8-byte alignment.
MSPACES default: 0 (false)
If true, compile in support for independent allocation spaces.
This is only supported if HAVE_MMAP is true.
ONLY_MSPACES default: 0 (false)
If true, only compile in mspace versions, not regular versions.
USE_LOCKS default: 0 (false)
Causes each call to each public routine to be surrounded with
pthread or WIN32 mutex lock/unlock. (If set true, this can be
overridden on a per-mspace basis for mspace versions.) If set to a
non-zero value other than 1, locks are used, but their
implementation is left out, so lock functions must be supplied manually.
USE_SPIN_LOCKS default: 1 iff USE_LOCKS and on x86 using gcc or MSC
If true, uses custom spin locks for locking. This is currently
supported only for x86 platforms using gcc or recent MS compilers.
Otherwise, posix locks or win32 critical sections are used.
FOOTERS default: 0
If true, provide extra checking and dispatching by placing
information in the footers of allocated chunks. This adds
space and time overhead.
INSECURE default: 0
If true, omit checks for usage errors and heap space overwrites.
USE_DL_PREFIX default: NOT defined
Causes compiler to prefix all public routines with the string 'dl'.
This can be useful when you only want to use this malloc in one part
of a program, using your regular system malloc elsewhere.
ABORT default: defined as abort()
Defines how to abort on failed checks. On most systems, a failed
check cannot die with an "assert" or even print an informative
message, because the underlying print routines in turn call malloc,
which will fail again. Generally, the best policy is to simply call
abort(). It's not very useful to do more than this because many
errors due to overwriting will show up as address faults (null, odd
addresses etc) rather than malloc-triggered checks, so will also
abort. Also, most compilers know that abort() does not return, so
can better optimize code conditionally calling it.
PROCEED_ON_ERROR default: defined as 0 (false)
Controls whether detected bad addresses cause them to bypassed
rather than aborting. If set, detected bad arguments to free and
realloc are ignored. And all bookkeeping information is zeroed out
upon a detected overwrite of freed heap space, thus losing the
ability to ever return it from malloc again, but enabling the
application to proceed. If PROCEED_ON_ERROR is defined, the
static variable malloc_corruption_error_count is compiled in
and can be examined to see if errors have occurred. This option
generates slower code than the default abort policy.
DEBUG default: NOT defined
The DEBUG setting is mainly intended for people trying to modify
this code or diagnose problems when porting to new platforms.
However, it may also be able to better isolate user errors than just
using runtime checks. The assertions in the check routines spell
out in more detail the assumptions and invariants underlying the
algorithms. The checking is fairly extensive, and will slow down
execution noticeably. Calling malloc_stats or mallinfo with DEBUG
set will attempt to check every non-mmapped allocated and free chunk
in the course of computing the summaries.
ABORT_ON_ASSERT_FAILURE default: defined as 1 (true)
Debugging assertion failures can be nearly impossible if your
version of the assert macro causes malloc to be called, which will
lead to a cascade of further failures, blowing the runtime stack.
ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
which will usually make debugging easier.
MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32
The action to take before "return 0" when malloc fails to be able to
return memory because there is none available.
HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES
True if this system supports sbrk or an emulation of it.
MORECORE default: sbrk
The name of the sbrk-style system routine to call to obtain more
memory. See below for guidance on writing custom MORECORE
functions. The type of the argument to sbrk/MORECORE varies across
systems. It cannot be size_t, because it supports negative
arguments, so it is normally the signed type of the same width as
size_t (sometimes declared as "intptr_t"). It doesn't much matter
though. Internally, we only call it with arguments less than half
the max value of a size_t, which should work across all reasonable
possibilities, although sometimes generating compiler warnings. See
near the end of this file for guidelines for creating a custom
version of MORECORE.
MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE
If true, take advantage of fact that consecutive calls to MORECORE
with positive arguments always return contiguous increasing
addresses. This is true of unix sbrk. It does not hurt too much to
set it true anyway, since malloc copes with non-contiguities.
Setting it false when definitely non-contiguous saves time
and possibly wasted space it would take to discover this though.
MORECORE_CANNOT_TRIM default: NOT defined
True if MORECORE cannot release space back to the system when given
negative arguments. This is generally necessary only if you are
using a hand-crafted MORECORE function that cannot handle negative
arguments.
NO_SEGMENT_TRAVERSAL default: 0
If non-zero, suppresses traversals of memory segments
returned by either MORECORE or CALL_MMAP. This disables
merging of segments that are contiguous, and selectively
releasing them to the OS if unused, but bounds execution times.
HAVE_MMAP default: 1 (true)
True if this system supports mmap or an emulation of it. If so, and
HAVE_MORECORE is not true, MMAP is used for all system
allocation. If set and HAVE_MORECORE is true as well, MMAP is
primarily used to directly allocate very large blocks. It is also
used as a backup strategy in cases where MORECORE fails to provide
space from system. Note: A single call to MUNMAP is assumed to be
able to unmap memory that may have be allocated using multiple calls
to MMAP, so long as they are adjacent.
HAVE_MREMAP default: 1 on linux, else 0
If true realloc() uses mremap() to re-allocate large blocks and
extend or shrink allocation spaces.
MMAP_CLEARS default: 1 except on WINCE.
True if mmap clears memory so calloc doesn't need to. This is true
for standard unix mmap using /dev/zero and on WIN32 except for WINCE.
USE_BUILTIN_FFS default: 0 (i.e., not used)
Causes malloc to use the builtin ffs() function to compute indices.
Some compilers may recognize and intrinsify ffs to be faster than the
supplied C version. Also, the case of x86 using gcc is special-cased
to an asm instruction, so is already as fast as it can be, and so
this setting has no effect. Similarly for Win32 under recent MS compilers.
(On most x86s, the asm version is only slightly faster than the C version.)
malloc_getpagesize default: derive from system includes, or 4096.
The system page size. To the extent possible, this malloc manages
memory from the system in page-size units. This may be (and
usually is) a function rather than a constant. This is ignored
if WIN32, where page size is determined using getSystemInfo during
initialization.
USE_DEV_RANDOM default: 0 (i.e., not used)
Causes malloc to use /dev/random to initialize secure magic seed for
stamping footers. Otherwise, the current time is used.
NO_MALLINFO default: 0
If defined, don't compile "mallinfo". This can be a simple way
of dealing with mismatches between system declarations and
those in this file.
MALLINFO_FIELD_TYPE default: size_t
The type of the fields in the mallinfo struct. This was originally
defined as "int" in SVID etc, but is more usefully defined as
size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set
REALLOC_ZERO_BYTES_FREES default: not defined
This should be set if a call to realloc with zero bytes should
be the same as a call to free. Some people think it should. Otherwise,
since this malloc returns a unique pointer for malloc(0), so does
realloc(p, 0).
LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H
LACKS_STDLIB_H default: NOT defined unless on WIN32
Define these if your system does not have these header files.
You might need to manually insert some of the declarations they provide.
DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS,
system_info.dwAllocationGranularity in WIN32,
otherwise 64K.
Also settable using mallopt(M_GRANULARITY, x)
The unit for allocating and deallocating memory from the system. On
most systems with contiguous MORECORE, there is no reason to
make this more than a page. However, systems with MMAP tend to
either require or encourage larger granularities. You can increase
this value to prevent system allocation functions to be called so
often, especially if they are slow. The value must be at least one
page and must be a power of two. Setting to 0 causes initialization
to either page size or win32 region size. (Note: In previous
versions of malloc, the equivalent of this option was called
"TOP_PAD")
DEFAULT_TRIM_THRESHOLD default: 2MB
Also settable using mallopt(M_TRIM_THRESHOLD, x)
The maximum amount of unused top-most memory to keep before
releasing via malloc_trim in free(). Automatic trimming is mainly
useful in long-lived programs using contiguous MORECORE. Because
trimming via sbrk can be slow on some systems, and can sometimes be
wasteful (in cases where programs immediately afterward allocate
more large chunks) the value should be high enough so that your
overall system performance would improve by releasing this much
memory. As a rough guide, you might set to a value close to the
average size of a process (program) running on your system.
Releasing this much memory would allow such a process to run in
memory. Generally, it is worth tuning trim thresholds when a
program undergoes phases where several large chunks are allocated
and released in ways that can reuse each other's storage, perhaps
mixed with phases where there are no such chunks at all. The trim
value must be greater than page size to have any useful effect. To
disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
some people use of mallocing a huge space and then freeing it at
program startup, in an attempt to reserve system memory, doesn't
have the intended effect under automatic trimming, since that memory
will immediately be returned to the system.
DEFAULT_MMAP_THRESHOLD default: 256K
Also settable using mallopt(M_MMAP_THRESHOLD, x)
The request size threshold for using MMAP to directly service a
request. Requests of at least this size that cannot be allocated
using already-existing space will be serviced via mmap. (If enough
normal freed space already exists it is used instead.) Using mmap
segregates relatively large chunks of memory so that they can be
individually obtained and released from the host system. A request
serviced through mmap is never reused by any other request (at least
not directly; the system may just so happen to remap successive
requests to the same locations). Segregating space in this way has
the benefits that: Mmapped space can always be individually released
back to the system, which helps keep the system level memory demands
of a long-lived program low. Also, mapped memory doesn't become
`locked' between other chunks, as can happen with normally allocated
chunks, which means that even trimming via malloc_trim would not
release them. However, it has the disadvantage that the space
cannot be reclaimed, consolidated, and then used to service later
requests, as happens with normal chunks. The advantages of mmap
nearly always outweigh disadvantages for "large" chunks, but the
value of "large" may vary across systems. The default is an
empirically derived value that works well in most systems. You can
disable mmap by setting to MAX_SIZE_T.
MAX_RELEASE_CHECK_RATE default: 255 unless not HAVE_MMAP
The number of consolidated frees between checks to release
unused segments when freeing. When using non-contiguous segments,
especially with multiple mspaces, checking only for topmost space
doesn't always suffice to trigger trimming. To compensate for this,
free() will, with a period of MAX_RELEASE_CHECK_RATE (or the
current number of segments, if greater) try to release unused
segments to the OS when freeing chunks that result in
consolidation. The best value for this parameter is a compromise
between slowing down frees with relatively costly checks that
rarely trigger versus holding on to unused memory. To effectively
disable, set to MAX_SIZE_T. This may lead to a very slight speed
improvement at the expense of carrying around more memory.
*/
#ifndef WIN32
#ifdef _WIN32
#define WIN32 1
#endif /* _WIN32 */
#endif /* WIN32 */
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define HAVE_MMAP 1
#define HAVE_MORECORE 0
#define LACKS_UNISTD_H
#define LACKS_SYS_PARAM_H
#define LACKS_SYS_MMAN_H
#define LACKS_STRING_H
#define LACKS_STRINGS_H
#define LACKS_SYS_TYPES_H
#define LACKS_ERRNO_H
#define MALLOC_FAILURE_ACTION
#ifdef _WIN32_WCE /* WINCE reportedly does not clear */
#define MMAP_CLEARS 0
#else
#define MMAP_CLEARS 1
#endif /* _WIN32_WCE */
#endif /* WIN32 */
#if defined(DARWIN) || defined(_DARWIN)
/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
#ifndef HAVE_MORECORE
#define HAVE_MORECORE 0
#define HAVE_MMAP 1
#endif /* HAVE_MORECORE */
#endif /* DARWIN */
//#include <string.h> //TB edit
//#include <stdlib.h> //TB edit
//void abort(void);
//#define ENOMEM 42 //TB edit
#ifndef LACKS_SYS_TYPES_H
#include <stddef.h> /* For size_t */
#endif /* LACKS_SYS_TYPES_H */
/* The maximum possible size_t value has all bits set */
#define MAX_SIZE_T (~(size_t)0)
#ifndef ONLY_MSPACES
#define ONLY_MSPACES 0
#endif /* ONLY_MSPACES */
#ifndef MSPACES
#if ONLY_MSPACES
#define MSPACES 1
#else /* ONLY_MSPACES */
#define MSPACES 0
#endif /* ONLY_MSPACES */
#endif /* MSPACES */
#ifndef MALLOC_ALIGNMENT
#define MALLOC_ALIGNMENT ((size_t)8U)
#endif /* MALLOC_ALIGNMENT */
#ifndef FOOTERS
#define FOOTERS 0
#endif /* FOOTERS */
#ifndef ABORT
#define ABORT abort()
#endif /* ABORT */
#ifndef ABORT_ON_ASSERT_FAILURE
#define ABORT_ON_ASSERT_FAILURE 1
#endif /* ABORT_ON_ASSERT_FAILURE */
#ifndef PROCEED_ON_ERROR
#define PROCEED_ON_ERROR 0
#endif /* PROCEED_ON_ERROR */
#ifndef USE_LOCKS
#define USE_LOCKS 0
#endif /* USE_LOCKS */
#ifndef USE_SPIN_LOCKS
#if USE_LOCKS && (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))) || (defined(_MSC_VER) && _MSC_VER>=1310)
#define USE_SPIN_LOCKS 1
#else
#define USE_SPIN_LOCKS 0
#endif /* USE_LOCKS && ... */
#endif /* USE_SPIN_LOCKS */
#ifndef INSECURE
#define INSECURE 0
#endif /* INSECURE */
#ifndef HAVE_MMAP
#define HAVE_MMAP 1
#endif /* HAVE_MMAP */
#ifndef MMAP_CLEARS
#define MMAP_CLEARS 1
#endif /* MMAP_CLEARS */
#ifndef HAVE_MREMAP
#ifdef linux
#define HAVE_MREMAP 1
#else /* linux */
#define HAVE_MREMAP 0
#endif /* linux */
#endif /* HAVE_MREMAP */
#ifndef MALLOC_FAILURE_ACTION
#define MALLOC_FAILURE_ACTION //errno = ENOMEM;
#endif /* MALLOC_FAILURE_ACTION */
#ifndef HAVE_MORECORE
#if ONLY_MSPACES
#define HAVE_MORECORE 0
#else /* ONLY_MSPACES */
#define HAVE_MORECORE 1
#endif /* ONLY_MSPACES */
#endif /* HAVE_MORECORE */
#if !HAVE_MORECORE
#define MORECORE_CONTIGUOUS 0
#else /* !HAVE_MORECORE */
#ifndef MORECORE
#define MORECORE sbrk
#endif /* MORECORE */
#ifndef MORECORE_CONTIGUOUS
#define MORECORE_CONTIGUOUS 1
#endif /* MORECORE_CONTIGUOUS */
#endif /* HAVE_MORECORE */
#ifndef DEFAULT_GRANULARITY
#if MORECORE_CONTIGUOUS
#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */
#else /* MORECORE_CONTIGUOUS */
#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
#endif /* MORECORE_CONTIGUOUS */
#endif /* DEFAULT_GRANULARITY */
#ifndef DEFAULT_TRIM_THRESHOLD
#ifndef MORECORE_CANNOT_TRIM
#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
#else /* MORECORE_CANNOT_TRIM */
#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
#endif /* MORECORE_CANNOT_TRIM */
#endif /* DEFAULT_TRIM_THRESHOLD */
#ifndef DEFAULT_MMAP_THRESHOLD
#if HAVE_MMAP
#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
#else /* HAVE_MMAP */
#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
#endif /* HAVE_MMAP */
#endif /* DEFAULT_MMAP_THRESHOLD */
#ifndef MAX_RELEASE_CHECK_RATE
#if HAVE_MMAP
#define MAX_RELEASE_CHECK_RATE 255
#else
#define MAX_RELEASE_CHECK_RATE MAX_SIZE_T
#endif /* HAVE_MMAP */
#endif /* MAX_RELEASE_CHECK_RATE */
#ifndef USE_BUILTIN_FFS
#define USE_BUILTIN_FFS 0
#endif /* USE_BUILTIN_FFS */
#ifndef USE_DEV_RANDOM
#define USE_DEV_RANDOM 0
#endif /* USE_DEV_RANDOM */
#ifndef NO_MALLINFO
#define NO_MALLINFO 0
#endif /* NO_MALLINFO */
#ifndef MALLINFO_FIELD_TYPE
#define MALLINFO_FIELD_TYPE size_t
#endif /* MALLINFO_FIELD_TYPE */
#ifndef NO_SEGMENT_TRAVERSAL
#define NO_SEGMENT_TRAVERSAL 0
#endif /* NO_SEGMENT_TRAVERSAL */
/*
mallopt tuning options. SVID/XPG defines four standard parameter
numbers for mallopt, normally defined in malloc.h. None of these
are used in this malloc, so setting them has no effect. But this
malloc does support the following options.
*/
#define M_TRIM_THRESHOLD (-1)
#define M_GRANULARITY (-2)
#define M_MMAP_THRESHOLD (-3)
/* ------------------------ Mallinfo declarations ------------------------ */
#if !NO_MALLINFO
/*
This version of malloc supports the standard SVID/XPG mallinfo
routine that returns a struct containing usage properties and
statistics. It should work on any system that has a
/usr/include/malloc.h defining struct mallinfo. The main
declaration needed is the mallinfo struct that is returned (by-copy)
by mallinfo(). The malloinfo struct contains a bunch of fields that
are not even meaningful in this version of malloc. These fields are
are instead filled by mallinfo() with other numbers that might be of
interest.
HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
/usr/include/malloc.h file that includes a declaration of struct
mallinfo. If so, it is included; else a compliant version is
declared below. These must be precisely the same for mallinfo() to
work. The original SVID version of this struct, defined on most
systems with mallinfo, declares all fields as ints. But some others
define as unsigned long. If your system defines the fields using a
type of different width than listed here, you MUST #include your
system version and #define HAVE_USR_INCLUDE_MALLOC_H.
*/
/* #define HAVE_USR_INCLUDE_MALLOC_H */
#ifdef HAVE_USR_INCLUDE_MALLOC_H
#include "/usr/include/malloc.h"
#else /* HAVE_USR_INCLUDE_MALLOC_H */
struct mallinfo {
MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */
MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */
MALLINFO_FIELD_TYPE smblks; /* always 0 */
MALLINFO_FIELD_TYPE hblks; /* always 0 */
MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */
MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */
MALLINFO_FIELD_TYPE fsmblks; /* always 0 */
MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
MALLINFO_FIELD_TYPE fordblks; /* total free space */
MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
};
#endif /* HAVE_USR_INCLUDE_MALLOC_H */
#endif /* NO_MALLINFO */
/*
Try to persuade compilers to inline. The most critical functions for
inlining are defined as macros, so these aren't used for them.
*/
#ifndef FORCEINLINE
#if defined(__GNUC__)
#define FORCEINLINE __inline __attribute__ ((always_inline))
#elif defined(_MSC_VER)
#define FORCEINLINE __forceinline
#endif
#endif
#ifndef NOINLINE
#if defined(__GNUC__)
#define NOINLINE __attribute__ ((noinline))
#elif defined(_MSC_VER)
#define NOINLINE __declspec(noinline)
#else
#define NOINLINE
#endif
#endif
#ifdef __cplusplus
extern "C" {
#ifndef FORCEINLINE
#define FORCEINLINE inline
#endif
#endif /* __cplusplus */
#ifndef FORCEINLINE
#define FORCEINLINE
#endif
#if !ONLY_MSPACES
/* ------------------- Declarations of public routines ------------------- */
#ifndef USE_DL_PREFIX
#define dlcalloc calloc
#define dlfree free
#define dlmalloc malloc
#define dlmemalign memalign
#define dlrealloc realloc
#define dlvalloc valloc
#define dlpvalloc pvalloc
#define dlmallinfo mallinfo
#define dlmallopt mallopt
#define dlmalloc_trim malloc_trim
#define dlmalloc_stats malloc_stats
#define dlmalloc_usable_size malloc_usable_size
#define dlmalloc_footprint malloc_footprint
#define dlmalloc_max_footprint malloc_max_footprint
#define dlindependent_calloc independent_calloc
#define dlindependent_comalloc independent_comalloc
#endif /* USE_DL_PREFIX */
/*
malloc(size_t n)
Returns a pointer to a newly allocated chunk of at least n bytes, or
null if no space is available, in which case errno is set to ENOMEM
on ANSI C systems.
If n is zero, malloc returns a minimum-sized chunk. (The minimum
size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
systems.) Note that size_t is an unsigned type, so calls with
arguments that would be negative if signed are interpreted as
requests for huge amounts of space, which will often fail. The
maximum supported value of n differs across systems, but is in all
cases less than the maximum representable value of a size_t.
*/
void* dlmalloc(size_t);
/*
free(void* p)
Releases the chunk of memory pointed to by p, that had been previously
allocated using malloc or a related routine such as realloc.
It has no effect if p is null. If p was not malloced or already
freed, free(p) will by default cause the current program create_mspace_with_baseto abort.
*/
void dlfree(void*);
/*
calloc(size_t n_elements, size_t element_size);
Returns a pointer to n_elements * element_size bytes, with all locations
set to zero.
*/
void* dlcalloc(size_t, size_t);
/*
realloc(void* p, size_t n)
Returns a pointer to a chunk of size n that contains the same data
as does chunk p up to the minimum of (n, p's size) bytes, or null
if no space is available.
The returned pointer may or may not be the same as p. The algorithm
prefers extending p in most cases when possible, otherwise it
employs the equivalent of a malloc-copy-free sequence.
If p is null, realloc is equivalent to malloc.
If space is not available, realloc returns null, errno is set (if on
ANSI) and p is NOT freed.
if n is for fewer bytes than already held by p, the newly unused
space is lopped off and freed if possible. realloc with a size
argument of zero (re)allocates a minimum-sized chunk.
The old unix realloc convention of allowing the last-free'd chunk
to be used as an argument to realloc is not supported.
*/
void* dlrealloc(void*, size_t);
/*
memalign(size_t alignment, size_t n);
Returns a pointer to a newly allocated chunk of n bytes, aligned
in accord with the alignment argument.
The alignment argument should be a power of two. If the argument is
not a power of two, the nearest greater power is used.
8-byte alignment is guaranteed by normal malloc calls, so don't
bother calling memalign with an argument of 8 or less.
Overreliance on memalign is a sure way to fragment space.
*/
void* dlmemalign(size_t, size_t);
/*
valloc(size_t n);
Equivalent to memalign(pagesize, n), where pagesize is the page
size of the system. If the pagesize is unknown, 4096 is used.
*/
void* dlvalloc(size_t);
/*
mallopt(int parameter_number, int parameter_value)
Sets tunable parameters The format is to provide a
(parameter-number, parameter-value) pair. mallopt then sets the
corresponding parameter to the argument value if it can (i.e., so
long as the value is meaningful), and returns 1 if successful else
0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
normally defined in malloc.h. None of these are use in this malloc,
so setting them has no effect. But this malloc also supports other
options in mallopt. See below for details. Briefly, supported
parameters are as follows (listed defaults are for "typical"
configurations).
Symbol param # default allowed param values
M_TRIM_THRESHOLD -1 2*1024*1024 any (MAX_SIZE_T disables)
M_GRANULARITY -2 page size any power of 2 >= page size
M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)
*/
int dlmallopt(int, int);
/*
malloc_footprint();
Returns the number of bytes obtained from the system. The total
number of bytes allocated by malloc, realloc etc., is less than this
value. Unlike mallinfo, this function returns only a precomputed
result, so can be called frequently to monitor memory consumption.
Even if locks are otherwise defined, this function does not use them,
so results might not be up to date.
*/
size_t dlmalloc_footprint(void);
/*
malloc_max_footprint();
Returns the maximum number of bytes obtained from the system. This
value will be greater than current footprint if deallocated space
has been reclaimed by the system. The peak number of bytes allocated
by malloc, realloc etc., is less than this value. Unlike mallinfo,
this function returns only a precomputed result, so can be called
frequently to monitor memory consumption. Even if locks are
otherwise defined, this function does not use them, so results might
not be up to date.
*/
size_t dlmalloc_max_footprint(void);
#if !NO_MALLINFO
/*
mallinfo()
Returns (by copy) a struct containing various summary statistics:
arena: current total non-mmapped bytes allocated from system
ordblks: the number of free chunks
smblks: always zero.
hblks: current number of mmapped regions
hblkhd: total bytes held in mmapped regions
usmblks: the maximum total allocated space. This will be greater
than current total if trimming has occurred.
fsmblks: always zero
uordblks: current total allocated space (normal or mmapped)
fordblks: total free space
keepcost: the maximum number of bytes that could ideally be released
back to system via malloc_trim. ("ideally" means that
it ignores page restrictions etc.)
Because these fields are ints, but internal bookkeeping may
be kept as longs, the reported values may wrap around zero and
thus be inaccurate.
*/
struct mallinfo dlmallinfo(void);
#endif /* NO_MALLINFO */
/*
independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
independent_calloc is similar to calloc, but instead of returning a
single cleared space, it returns an array of pointers to n_elements
independent elements that can hold contents of size elem_size, each
of which starts out cleared, and can be independently freed,
realloc'ed etc. The elements are guaranteed to be adjacently
allocated (this is not guaranteed to occur with multiple callocs or
mallocs), which may also improve cache locality in some
applications.
The "chunks" argument is optional (i.e., may be null, which is
probably the most typical usage). If it is null, the returned array
is itself dynamically allocated and should also be freed when it is
no longer needed. Otherwise, the chunks array must be of at least
n_elements in length. It is filled in with the pointerscreate_mspace_with_base to the
chunks.
In either case, independent_calloc returns this pointer array, or
null if the allocation failed. If n_elements is zero and "chunks"
is null, it returns a chunk representing an array with zero elements
(which should be freed if not wanted).
Each element must be individually freed when it is no longer
needed. If you'd like to instead be able to free all at once, you
should instead use regular calloc and assign pointers into this
space to represent elements. (In this case though, you cannot
independently free elements.)
independent_calloc simplifies and speeds up implementations of many
kinds of pools. It may also be useful when constructing large data
structures that initially have a fixed number of fixed-sized nodes,
but the number is not known at compile time, and some of the nodes
may later need to be freed. For example:
struct Node { int item; struct Node* next; };
struct Node* build_list() {
struct Node** pool;
int n = read_number_of_nodes_needed();
if (n <= 0) return 0;
pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
if (pool == 0) die();
// organize into a linked list...
struct Node* first = pool[0];
for (i = 0; i < n-1; ++i)
pool[i]->next = pool[i+1];
free(pool); // Can now free the array (or not, if it is needed later)
return first;
}
*/
void** dlindependent_calloc(size_t, size_t, void**);
/*
independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
independent_comalloc allocates, all at once, a set of n_elements
chunks with sizes indicated in the "sizes" array. It returns
an array of pointers to these elements, each of which can be
independently freed, realloc'ed etc. The elements are guaranteed to
be adjacently allocated (this is not guaranteed to occur with
multiple callocs or mallocs), which may also improve cache locality
in some applications.
The "chunks" argument is optional (i.e., may be null). If it is null
the returned array is itself dynamically allocated and should also
be freed when it is no longer needed. Otherwise, the chunks array
must be of at least n_elements in length. It is filled in with the
pointers to the chunks.
In either case, independent_comalloc returns this pointer array, or
null if the allocation failed. If n_elements is zero and chunks is
null, it returns a chunk representing an array with zero elements
(which should be freed if not wanted).
Each element must be individually freed when it is no longer
needed. If you'd like to instead be able to free all at once, you
should instead use a single regular malloc, and assign pointers at
particular offsets in the aggregate space. (In this case though, you
cannot independently free elements.)
independent_comallac differs from independent_calloc in that each
element may have a different size, and also that it does not
automatically clear elements.
independent_comalloc can be used to speed up allocation in cases
where several structs or objects must always be allocated at the
same time. For example:
struct Head { ... }
struct Foot { ... }
void send_message(char* msg) {
int msglen = strlen(msg);
size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
void* chunks[3];
if (independent_comalloc(3, sizes, chunks) == 0)
die();
struct Head* head = (struct Head*)(chunks[0]);
char* body = (char*)(chunks[1]);
struct Foot* foot = (struct Foot*)(chunks[2]);
// ...
}
In general though, independent_comalloc is worth using only for
larger values of n_elements. For small values, you probably won't
detect enough difference from series of malloc calls to bother.
Overuse of independent_comalloc can increase overall memory usage,
since it cannot reuse existing noncontiguous small chunks that
might be available for some of the elements.
*/
void** dlindependent_comalloc(size_t, size_t*, void**);
/*
pvalloc(size_t n);
Equivalent to valloc(minimum-page-that-holds(n)), that is,
round up n to nearest pagesize.
*/
void* dlpvalloc(size_t);
/*
malloc_trim(size_t pad);
If possible, gives memory back to the system (via negative arguments
to sbrk) if there is unused memory at the `high' end of the malloc
pool or in unused MMAP segments. You can call this after freeing
large blocks of memory to potentially reduce the system-level memory
requirements of a program. However, it cannot guarantee to reduce
memory. Under some allocation patterns, some large free blocks of
memory will be locked between two used chunks, so they cannot be
given back to the system.
The `pad' argument to malloc_trim represents the amount of free
trailing space to leave untrimmed. If this argument is zero, only
the minimum amount of memory to maintain internal data structures
will be left. Non-zero arguments can be supplied to maintain enough
trailing space to service future expected allocations without having
to re-obtain memory from the system.
Malloc_trim returns 1 if it actually released any memory, else 0.
*/
int dlmalloc_trim(size_t);
/*
malloc_usable_size(void* p);
Returns the number of bytes you can actually use in
an allocated chunk, which may be more than you requested (although
often not) due to alignment and minimum size constraints.
You can use this many bytes without worrying about
overwriting other allocated objects. This is not a particularly great
programming practice. malloc_usable_size can be more useful in
debugging and assertions, for example:
p = malloc(n);
assert(malloc_usable_size(p) >= 256);
*/
size_t dlmalloc_usable_size(void*);
/*
malloc_stats();
Prints on stderr the amount of space obtained from the system (both
via sbrk and mmap), the maximum amount (which may be more than
current if malloc_trim and/or munmap got called), and the current
number of bytes allocated via malloc (or realloc, etc) but not yet
freed. Note that this is the number of bytes allocated, not the
number requested. It will be larger than the number requested
because of alignment and bookkeeping overhead. Because it includes
alignment wastage as being in use, this figure may be greater than
zero even when no user-level chunks are allocated.
The reported current and maximum system memory can be inaccurate if
a program makes other calls to system memory allocation functions
(normally sbrk) outside of malloc.
malloc_stats prints only the most commonly interesting statistics.
More information can be obtained by calling mallinfo.
*/
void dlmalloc_stats(void);
#endif /* ONLY_MSPACES */
#if MSPACES
/*
mspace is an opaque type representing an independent
region of space that supports mspace_malloc, etc.
*/
typedef void* mspace;
/*
create_mspace creates and returns a new independent space with the
given initial capacity, or, if 0, the default granularity size. It
returns null if there is no system memory available to create the
space. If argument locked is non-zero, the space uses a separate
lock to control access. The capacity of the space will grow
dynamically as needed to service mspace_malloc requests. You can
control the sizes of incremental increases of this space by
compiling with a different DEFAULT_GRANULARITY or dynamically
setting with mallopt(M_GRANULARITY, value).
*/
mspace create_mspace(size_t capacity, int locked);
/*
destroy_mspace destroys the given space, and attempts to return all
of its memory back to the system, returning the total number of
bytes freed. After destruction, the results of access to all memory
used by the space become undefined.
*/
size_t destroy_mspace(mspace msp);
/*
create_mspace_with_base uses the memory supplied as the initial base
of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
space is used for bookkeeping, so the capacity must be at least this
large. (Otherwise 0 is returned.) When this initial space is
exhausted, additional memory will be obtained from the system.
Destroying this space will deallocate all additionally allocated
space (if possible) but not the initial base.
*/
mspace create_mspace_with_base(void* base, size_t capacity, int locked);
/*
mspace_malloc behaves as malloc, but operates within
the given space.
*/
void* mspace_malloc(mspace msp, size_t bytes);
/*
mspace_free behaves as free, but operates within
the given space.
If compiled with FOOTERS==1, mspace_free is not actually needed.
free may be called instead of mspace_free because freed chunks from
any space are handled by their originating spaces.
*/
void mspace_free(mspace msp, void* mem);
/*
mspace_realloc behaves as realloc, but operates within
the given space.
If compiled with FOOTERS==1, mspace_realloc is not actually
needed. realloc may be called instead of mspace_realloc because
realloced chunks from any space are handled by their originating
spaces.
*/
void* mspace_realloc(mspace msp, void* mem, size_t newsize);
/*
mspace_calloc behaves as calloc, but operates within
the given space.
*/
void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
/*
mspace_memalign behaves as memalign, but operates within
the given space.
*/
void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
/*
mspace_independent_calloc behaves as independent_calloc, but
operates within the given space.
*/
void** mspace_independent_calloc(mspace msp, size_t n_elements,
size_t elem_size, void* chunks[]);
/*
mspace_independent_comalloc behaves as independent_comalloc, but
operates within the given space.
*/
void** mspace_independent_comalloc(mspace msp, size_t n_elements,
size_t sizes[], void* chunks[]);
/*
mspace_footprint() returns the number of bytes obtained from the
system for this space.
*/
size_t mspace_footprint(mspace msp);
/*
mspace_max_footprint() returns the peak number of bytes obtained from the
system for this space.
*/
size_t mspace_max_footprint(mspace msp);
#if !NO_MALLINFO
/*
mspace_mallinfo behaves as mallinfo, but reports properties of
the given space.
*/
struct mallinfo mspace_mallinfo(mspace msp);
#endif /* NO_MALLINFO */
/*
mspace_malloc_stats behaves as malloc_stats, but reports
properties of the given space.
*/
void mspace_malloc_stats(mspace msp);
/*
mspace_trim behaves as malloc_trim, but
operates within the given space.
*/
int mspace_trim(mspace msp, size_t pad);
/*
An alias for mallopt.
*/
int mspace_mallopt(int, int);
#endif /* MSPACES */
#ifdef __cplusplus
}; /* end of extern "C" */
#endif /* __cplusplus */
/*
========================================================================
To make a fully customizable malloc.h header file, cut everything
above this line, put into file malloc.h, edit to suit, and #include it
on the next line, as well as in programs that use this malloc.
========================================================================
*/
/* #include "malloc.h" */
/*------------------------------ internal #includes ---------------------- */
#ifdef WIN32
#pragma warning( disable : 4146 ) /* no "unsigned" warnings */
#endif /* WIN32 */
//#include <stdio.h> /* for printing in malloc_stats */
#ifndef LACKS_ERRNO_H
//#include <errno.h> /* for MALLOC_FAILURE_ACTION */
#endif /* LACKS_ERRNO_H */
#if FOOTERS
#include <time.h> /* for magic initialization */
#endif /* FOOTERS */
#ifndef LACKS_STDLIB_H
//#include <stdlib.h> /* for abort() */
#endif /* LACKS_STDLIB_H */
#ifdef DEBUG
#if ABORT_ON_ASSERT_FAILURE
#define assert(x) if(!(x)) ABORT
#else /* ABORT_ON_ASSERT_FAILURE */
#include <assert.h>
#endif /* ABORT_ON_ASSERT_FAILURE */
#else /* DEBUG */
#ifdef assert
#undef assert
#endif
#define assert(x)
#endif /* DEBUG */
#ifndef LACKS_STRING_H
//#include <string.h> /* for memset etc */
#endif /* LACKS_STRING_H */
#if USE_BUILTIN_FFS
#ifndef LACKS_STRINGS_H
//#include <strings.h> /* for ffs */
#endif /* LACKS_STRINGS_H */
#endif /* USE_BUILTIN_FFS */
#if HAVE_MMAP
#ifndef LACKS_SYS_MMAN_H
#include <sys/mman.h> /* for mmap */
#endif /* LACKS_SYS_MMAN_H */
#ifndef LACKS_FCNTL_H
#include <fcntl.h>
#endif /* LACKS_FCNTL_H */
#endif /* HAVE_MMAP */
#if HAVE_MORECORE
#ifndef LACKS_UNISTD_H
//#include <unistd.h> /* for sbrk */
#else /* LACKS_UNISTD_H */
#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
extern void* sbrk(ptrdiff_t);
#endif /* FreeBSD etc */
#endif /* LACKS_UNISTD_H */
#endif /* HAVE_MMAP */
/* Declarations for locking */
#if USE_LOCKS
#ifndef __KERNEL__
#ifndef WIN32
#include <pthread.h>
#if defined (__SVR4) && defined (__sun) /* solaris */
#include <thread.h>
#endif /* solaris */
#else
#ifndef _M_AMD64
/* These are already defined on AMD64 builds */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
LONG __cdecl _InterlockedCompareExchange(LPLONG volatile Dest, LONG Exchange, LONG Comp);
LONG __cdecl _InterlockedExchange(LPLONG volatile Target, LONG Value);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* _M_AMD64 */
#pragma intrinsic (_InterlockedCompareExchange)
#pragma intrinsic (_InterlockedExchange)
#define interlockedcompareexchange _InterlockedCompareExchange
#define interlockedexchange _InterlockedExchange
#endif /* Win32 */
#else // KERNEL
#if !defined(__STANDALONE__) && defined(__KERNEL__)
#include <linux/mutex.h>
#endif // #if !defined(__STANDALONE__) && defined(__KERNEL__)
#endif // KERNEL
#endif /* USE_LOCKS */
/* Declarations for bit scanning on win32 */
#if defined(_MSC_VER) && _MSC_VER>=1300
#ifndef BitScanForward /* Try to avoid pulling in WinNT.h */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
unsigned char _BitScanForward(unsigned long *index, unsigned long mask);
unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#define BitScanForward _BitScanForward
#define BitScanReverse _BitScanReverse
#pragma intrinsic(_BitScanForward)
#pragma intrinsic(_BitScanReverse)
#endif /* BitScanForward */
#endif /* defined(_MSC_VER) && _MSC_VER>=1300 */
#ifndef WIN32
#ifndef malloc_getpagesize
# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
# ifndef _SC_PAGE_SIZE
# define _SC_PAGE_SIZE _SC_PAGESIZE
# endif
# endif
# ifdef _SC_PAGE_SIZE
# define malloc_getpagesize 4096
# else
# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
extern size_t getpagesize();
# define malloc_getpagesize getpagesize()
# else
# ifdef WIN32 /* use supplied emulation of getpagesize */
# define malloc_getpagesize getpagesize()
# else
# ifndef LACKS_SYS_PARAM_H
//# include <sys/param.h>
# endif
# ifdef EXEC_PAGESIZE
# define malloc_getpagesize EXEC_PAGESIZE
# else
# ifdef NBPG
# ifndef CLSIZE
# define malloc_getpagesize NBPG
# else
# define malloc_getpagesize (NBPG * CLSIZE)
# endif
# else
# ifdef NBPC
# define malloc_getpagesize NBPC
# else
# ifdef PAGESIZE
# define malloc_getpagesize PAGESIZE
# else /* just guess */
# define malloc_getpagesize ((size_t)4096U)
# endif
# endif
# endif
# endif
# endif
# endif
# endif
#endif
#endif
/* ------------------- size_t and alignment properties -------------------- */
/* The byte and bit size of a size_t */
#define SIZE_T_SIZE (sizeof(size_t))
#define SIZE_T_BITSIZE (sizeof(size_t) << 3)
/* Some constants coerced to size_t */
/* Annoying but necessary to avoid errors on some platforms */
#define SIZE_T_ZERO ((size_t)0)
#define SIZE_T_ONE ((size_t)1)
#define SIZE_T_TWO ((size_t)2)
#define SIZE_T_FOUR ((size_t)4)
#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1)
#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2)
#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U)
/* The bit mask value corresponding to MALLOC_ALIGNMENT */
#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE)
/* True if address a has acceptable alignment */
#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
/* the number of bytes to offset an address to align it */
#define align_offset(A)\
((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
/* -------------------------- MMAP preliminaries ------------------------- */
/*
If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
checks to fail so compiler optimizer can delete code rather than
using so many "#if"s.
*/
/* MORECORE and MMAP must return MFAIL on failure */
#define MFAIL ((void*)(MAX_SIZE_T))
#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */
#if !HAVE_MMAP
#define IS_MMAPPED_BIT (SIZE_T_ZERO)
#define USE_MMAP_BIT (SIZE_T_ZERO)
#define CALL_MMAP(s) MFAIL
#define CALL_MUNMAP(a, s) (-1)
#define DIRECT_MMAP(s) MFAIL
#else /* HAVE_MMAP */
#define IS_MMAPPED_BIT (SIZE_T_ONE)
#define USE_MMAP_BIT (SIZE_T_ONE)
#ifndef WIN32
#define CALL_MUNMAP(a, s) munmap((a), (s))
#define MMAP_PROT (PROT_READ|PROT_WRITE)
#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
#define MAP_ANONYMOUS MAP_ANON
#endif /* MAP_ANON */
#ifdef MAP_ANONYMOUS
#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)
#define CALL_MMAP(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
#else /* MAP_ANONYMOUS */
/*
Nearly all versions of mmap support MAP_ANONYMOUS, so the following
is unlikely to be needed, but is supplied just in case.
*/
#define MMAP_FLAGS (MAP_PRIVATE)
static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
#define CALL_MMAP(s) ((dev_zero_fd < 0) ? \
(dev_zero_fd = open("/dev/zero", O_RDWR), \
mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
#endif /* MAP_ANONYMOUS */
#define DIRECT_MMAP(s) CALL_MMAP(s)
#else /* WIN32 */
/* Win32 MMAP via VirtualAlloc */
static FORCEINLINE void* win32mmap(size_t size) {
void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
return (ptr != 0)? ptr: MFAIL;
}
/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
static FORCEINLINE void* win32direct_mmap(size_t size) {
void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,
PAGE_READWRITE);
return (ptr != 0)? ptr: MFAIL;
}
/* This function supports releasing coalesed segments */
static FORCEINLINE int win32munmap(void* ptr, size_t size) {
MEMORY_BASIC_INFORMATION minfo;
char* cptr = (char*)ptr;
while (size) {
if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
return -1;
if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
minfo.State != MEM_COMMIT || minfo.RegionSize > size)
return -1;
if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
return -1;
cptr += minfo.RegionSize;
size -= minfo.RegionSize;
}
return 0;
}
#define CALL_MMAP(s) win32mmap(s)
#define CALL_MUNMAP(a, s) win32munmap((a), (s))
#define DIRECT_MMAP(s) win32direct_mmap(s)
#endif /* WIN32 */
#endif /* HAVE_MMAP */
#if HAVE_MMAP && HAVE_MREMAP
#define CALL_MREMAP(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
#else /* HAVE_MMAP && HAVE_MREMAP */
#define CALL_MREMAP(addr, osz, nsz, mv) ((void)(addr),(void)(osz), \
(void)(nsz), (void)(mv),MFAIL)
#endif /* HAVE_MMAP && HAVE_MREMAP */
#if HAVE_MORECORE
#define CALL_MORECORE(S) MORECORE(S)
#else /* HAVE_MORECORE */
#define CALL_MORECORE(S) MFAIL
#endif /* HAVE_MORECORE */
/* mstate bit set if continguous morecore disabled or failed */
#define USE_NONCONTIGUOUS_BIT (4U)
/* segment bit set in create_mspace_with_base */
#define EXTERN_BIT (8U)
/* --------------------------- Lock preliminaries ------------------------ */
/*
When locks are defined, there are up to two global locks:
* If HAVE_MORECORE, morecore_mutex protects sequences of calls to
MORECORE. In many cases sys_alloc requires two calls, that should
not be interleaved with calls by other threads. This does not
protect against direct calls to MORECORE by other threads not
using this lock, so there is still code to cope the best we can on
interference.
* magic_init_mutex ensures that mparams.magic and other
unique mparams values are initialized only once.
To enable use in layered extensions, locks are reentrant.
Because lock-protected regions generally have bounded times, we use
the supplied simple spinlocks in the custom versions for x86.
If USE_LOCKS is > 1, the definitions of lock routines here are
bypassed, in which case you will need to define at least
INITIAL_LOCK, ACQUIRE_LOCK, RELEASE_LOCK, and
NULL_LOCK_INITIALIZER, and possibly TRY_LOCK and IS_LOCKED
(The latter two are not used in this malloc, but are
commonly needed in extensions.)
*/
#if USE_LOCKS == 1
#if USE_SPIN_LOCKS
#ifndef WIN32
/* Custom pthread-style spin locks on x86 and x64 for gcc */
struct pthread_mlock_t
{
volatile pthread_t threadid;
volatile unsigned int c;
volatile unsigned int l;
};
#define MLOCK_T struct pthread_mlock_t
#define CURRENT_THREAD pthread_self()
#define SPINS_PER_YIELD 63
static FORCEINLINE int pthread_acquire_lock (MLOCK_T *sl) {
if(CURRENT_THREAD==sl->threadid)
++sl->c;
else {
int spins = 0;
for (;;) {
int ret;
__asm__ __volatile__ ("lock cmpxchgl %2,(%1)" : "=a" (ret) : "r" (&sl->l), "r" (1), "a" (0));
if(!ret) {
assert(!sl->threadid);
sl->threadid=CURRENT_THREAD;
sl->c=1;
break;
}
if ((++spins & SPINS_PER_YIELD) == 0) {
#if defined (__SVR4) && defined (__sun) /* solaris */
thr_yield();
#else
#ifdef linux
sched_yield();
#else /* no-op yield on unknown systems */
;
#endif /* linux */
#endif /* solaris */
}
}
}
return 0;
}
static FORCEINLINE void pthread_release_lock (MLOCK_T *sl) {
int ret;
assert(CURRENT_THREAD==sl->threadid);
if (!--sl->c) {
sl->threadid=0;
__asm__ __volatile__ ("xchgl %2,(%1)" : "=r" (ret) : "r" (&sl->l), "0" (0));
}
}
static FORCEINLINE int pthread_try_lock (MLOCK_T *sl) {
int ret;
__asm__ __volatile__ ("lock cmpxchgl %2,(%1)" : "=a" (ret) : "r" (&sl->l), "r" (1), "a" (0));
if(!ret){
assert(!sl->threadid);
sl->threadid=CURRENT_THREAD;
sl->c=1;
return 1;
}
return 0;
}
#define INITIAL_LOCK(sl) (memset((sl), 0, sizeof(MLOCK_T)), 0)
#define ACQUIRE_LOCK(sl) pthread_acquire_lock(sl)
#define RELEASE_LOCK(sl) pthread_release_lock(sl)
#define TRY_LOCK(sl) pthread_try_lock(sl)
#define IS_LOCKED(sl) ((sl)->l)
static MLOCK_T magic_init_mutex = {0, 0, 0 };
#if HAVE_MORECORE
static MLOCK_T morecore_mutex = {0, 0, 0 };
#endif /* HAVE_MORECORE */
#else /* WIN32 */
/* Custom win32-style spin locks on x86 and x64 for MSC */
struct win32_mlock_t
{
volatile long threadid;
volatile unsigned int c;
long l;
};
#define MLOCK_T struct win32_mlock_t
#define CURRENT_THREAD GetCurrentThreadId()
#define SPINS_PER_YIELD 63
static FORCEINLINE int win32_acquire_lock (MLOCK_T *sl) {
long mythreadid=CURRENT_THREAD;
if(mythreadid==sl->threadid)
++sl->c;
else {
int spins = 0;
for (;;) {
if (!interlockedexchange(&sl->l, 1)) {
assert(!sl->threadid);
sl->threadid=mythreadid;
sl->c=1;
break;
}
if ((++spins & SPINS_PER_YIELD) == 0)
SleepEx(0, FALSE);
}
}
return 0;
}
static FORCEINLINE void win32_release_lock (MLOCK_T *sl) {
assert(CURRENT_THREAD==sl->threadid);
if (!--sl->c) {
sl->threadid=0;
interlockedexchange (&sl->l, 0);
}
}
static FORCEINLINE int win32_try_lock (MLOCK_T *sl) {
if (!interlockedexchange(&sl->l, 1)){
assert(!sl->threadid);
sl->threadid=CURRENT_THREAD;
sl->c=1;
return 1;
}
return 0;
}
#define INITIAL_LOCK(sl) (memset(sl, 0, sizeof(MLOCK_T)), 0)
#define ACQUIRE_LOCK(sl) win32_acquire_lock(sl)
#define RELEASE_LOCK(sl) win32_release_lock(sl)
#define TRY_LOCK(sl) win32_try_lock(sl)
#define IS_LOCKED(sl) ((sl)->l)
static MLOCK_T magic_init_mutex = {0, 0 };
#if HAVE_MORECORE
static MLOCK_T morecore_mutex = {0, 0 };
#endif /* HAVE_MORECORE */
#endif /* WIN32 */
#else /* USE_SPIN_LOCKS */
#ifndef WIN32
/* pthreads-based locks */
struct pthread_mlock_t
{
volatile unsigned int c;
pthread_mutex_t l;
};
#define MLOCK_T struct pthread_mlock_t
#define CURRENT_THREAD pthread_self()
static FORCEINLINE int pthread_acquire_lock (MLOCK_T *sl) {
if(!pthread_mutex_lock(&(sl)->l)){
sl->c++;
return 0;
}
return 1;
}
static FORCEINLINE void pthread_release_lock (MLOCK_T *sl) {
--sl->c;
pthread_mutex_unlock(&(sl)->l);
}
static FORCEINLINE int pthread_try_lock (MLOCK_T *sl) {
if(!pthread_mutex_trylock(&(sl)->l)){
sl->c++;
return 1;
}
return 0;
}
static FORCEINLINE int pthread_init_lock (MLOCK_T *sl) {
pthread_mutexattr_t attr;
sl->c=0;
if(pthread_mutexattr_init(&attr)) return 1;
if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1;
if(pthread_mutex_init(&sl->l, &attr)) return 1;
pthread_mutexattr_destroy(&attr);
return 0;
}
static FORCEINLINE int pthread_islocked (MLOCK_T *sl) {
if(!pthread_try_lock(sl)){
int ret = (sl->c != 0);
pthread_mutex_unlock(sl);
return ret;
}
return 0;
}
#define INITIAL_LOCK(sl) pthread_init_lock(sl)
#define ACQUIRE_LOCK(sl) pthread_acquire_lock(sl)
#define RELEASE_LOCK(sl) pthread_release_lock(sl)
#define TRY_LOCK(sl) pthread_try_lock(sl)
#define IS_LOCKED(sl) pthread_islocked(sl)
static MLOCK_T magic_init_mutex = {0, PTHREAD_MUTEX_INITIALIZER };
#if HAVE_MORECORE
static MLOCK_T morecore_mutex = {0, PTHREAD_MUTEX_INITIALIZER };
#endif /* HAVE_MORECORE */
#else /* WIN32 */
/* Win32 critical sections */
#define MLOCK_T CRITICAL_SECTION
#define CURRENT_THREAD GetCurrentThreadId()
#define INITIAL_LOCK(s) (!InitializeCriticalSectionAndSpinCount((s), 4000)
#define ACQUIRE_LOCK(s) ( (!((s))->DebugInfo ? INITIAL_LOCK((s)) : 0), !EnterCriticalSection((s)), 0)
#define RELEASE_LOCK(s) ( LeaveCriticalSection((s)), 0 )
#define TRY_LOCK(s) ( TryEnterCriticalSection((s)) )
#define IS_LOCKED(s) ( (s)->LockCount >= 0 )
#define NULL_LOCK_INITIALIZER
static MLOCK_T magic_init_mutex;
#if HAVE_MORECORE
static MLOCK_T morecore_mutex;
#endif /* HAVE_MORECORE */
#endif /* WIN32 */
#endif /* USE_SPIN_LOCKS */
#endif /* USE_LOCKS == 1 */
/* ----------------------- User-defined locks ------------------------ */
#if USE_LOCKS > 1
#if !defined(__STANDALONE__) && defined(__KERNEL__)
#include <linux/mutex.h>
//typedef struct mutex k_mutex_t;
//#define MLOCK_T k_mutex_t;
#define MLOCK_T struct mutex
#else // #if !defined(__STANDALONE__) && defined(__KERNEL__)
#ifdef __STANDALONE__
#define MLOCK_T uint32_t // placeholder
#else
#include <pthread.h>
#define MLOCK_T pthread_mutex_t
#endif // ifdef __STANDALONE__
#endif // #if !defined(__STANDALONE__) && defined(__KERNEL__)
#ifndef __STANDALONE__
// Define your own lock implementation here
#define INITIAL_LOCK(sl) mutex_init(sl)
#define ACQUIRE_LOCK(sl) (mutex_lock_interruptible(sl))
#define RELEASE_LOCK(sl) (mutex_unlock(sl))
#define TRY_LOCK(sl) printk("try lock \n");
#define IS_LOCKED(sl) printk("is locked \n");
#define NULL_LOCK_INITIALIZER 0;
#else // #ifndef __STANDALONE__
#define INITIAL_LOCK(sl) //(printf("Not implemented. Unlock1\n"))
#define ACQUIRE_LOCK(sl) (0)//(printf("Not implemented. Unlock1\n"))
#define RELEASE_LOCK(sl) //(printf("Not implemented. Unlock1\n"))
#define TRY_LOCK(sl) //(printf("Not implemented. Try lock \n"));
#define IS_LOCKED(sl) //(printk("Not implemented. Is locked \n"));
#define NULL_LOCK_INITIALIZER 0;
#endif // #ifndef __STANDALONE__
extern MLOCK_T magic_init_mutex;
extern MLOCK_T mspace_mutex;
#if HAVE_MORECORE
extern MLOCK_T morecore_mutex;
//MLOCK_T gMoreCoreMutex;
#endif /* HAVE_MORECORE */
#endif /* USE_LOCKS > 1 */
/* ----------------------- Lock-based state ------------------------ */
#if USE_LOCKS
#define USE_LOCK_BIT (2U)
#else /* USE_LOCKS */
#define USE_LOCK_BIT (0U)
#define INITIAL_LOCK(l)
#endif /* USE_LOCKS */
#if USE_LOCKS && HAVE_MORECORE
#define ACQUIRE_MORECORE_LOCK() ACQUIRE_LOCK(&morecore_mutex);
#define RELEASE_MORECORE_LOCK() RELEASE_LOCK(&morecore_mutex);
#else /* USE_LOCKS && HAVE_MORECORE */
#define ACQUIRE_MORECORE_LOCK()
#define RELEASE_MORECORE_LOCK()
#endif /* USE_LOCKS && HAVE_MORECORE */
#if USE_LOCKS
#define ACQUIRE_MAGIC_INIT_LOCK() ACQUIRE_LOCK(&magic_init_mutex);
#define RELEASE_MAGIC_INIT_LOCK() RELEASE_LOCK(&magic_init_mutex);
#else /* USE_LOCKS */
#define ACQUIRE_MAGIC_INIT_LOCK()
#define RELEASE_MAGIC_INIT_LOCK()
#endif /* USE_LOCKS */
/* ----------------------- Chunk representations ------------------------ */
/*
(The following includes lightly edited explanations by Colin Plumb.)
The malloc_chunk declaration below is misleading (but accurate and
necessary). It declares a "view" into memory allowing access to
necessary fields at known offsets from a given base.
Chunks of memory are maintained using a `boundary tag' method as
originally described by Knuth. (See the paper by Paul Wilson
ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
techniques.) Sizes of free chunks are stored both in the front of
each chunk and at the end. This makes consolidating fragmented
chunks into bigger chunks fast. The head fields also hold bits
representing whether chunks are free or in use.
Here are some pictures to make it clearer. They are "exploded" to
show that the state of a chunk can be thought of as extending from
the high 31 bits of the head field of its header through the
prev_foot and PINUSE_BIT bit of the following chunk header.
A chunk that's in use looks like:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk (if P = 1) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
| Size of this chunk 1| +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+- -+
| |
+- -+
| :
+- size - sizeof(size_t) available payload bytes -+
: |
chunk-> +- -+
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
| Size of next chunk (may or may not be in use) | +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
And if it's free, it looks like this:
chunk-> +- -+
| User payload (must be in use, or we would have merged!) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
| Size of this chunk 0| +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Prev pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| :
+- size - sizeof(struct chunk) unused bytes -+
: |
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of this chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
| Size of next chunk (must be in use, or we would have merged)| +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| :
+- User payload -+
: |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0|
+-+
Note that since we always merge adjacent free chunks, the chunks
adjacent to a free chunk must be in use.
Given a pointer to a chunk (which can be derived trivially from the
payload pointer) we can, in O(1) time, find out whether the adjacent
chunks are free, and if so, unlink them from the lists that they
are on and merge them with the current chunk.
Chunks always begin on even word boundaries, so the mem portion
(which is returned to the user) is also on an even word boundary, and
thus at least double-word aligned.
The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
chunk size (which is always a multiple of two words), is an in-use
bit for the *previous* chunk. If that bit is *clear*, then the
word before the current chunk size contains the previous chunk
size, and can be used to find the front of the previous chunk.
The very first chunk allocated always has this bit set, preventing
access to non-existent (or non-owned) memory. If pinuse is set for
any given chunk, then you CANNOT determine the size of the
previous chunk, and might even get a memory addressing fault when
trying to do so.
The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
the chunk size redundantly records whether the current chunk is
inuse. This redundancy enables usage checks within free and realloc,
and reduces indirection when freeing and consolidating chunks.
Each freshly allocated chunk must have both cinuse and pinuse set.
That is, each allocated chunk borders either a previously allocated
and still in-use chunk, or the base of its memory arena. This is
ensured by making all allocations from the the `lowest' part of any
found chunk. Further, no free chunk physically borders another one,
so each free chunk is known to be preceded and followed by either
inuse chunks or the ends of memory.
Note that the `foot' of the current chunk is actually represented
as the prev_foot of the NEXT chunk. This makes it easier to
deal with alignments etc but can be very confusing when trying
to extend or adapt this code.
The exceptions to all this are
1. The special chunk `top' is the top-most available chunk (i.e.,
the one bordering the end of available memory). It is treated
specially. Top is never included in any bin, is used only if
no other chunk is available, and is released back to the
system if it is very large (see M_TRIM_THRESHOLD). In effect,
the top chunk is treated as larger (and thus less well
fitting) than any other available chunk. The top chunk
doesn't update its trailing size field since there is no next
contiguous chunk that would have to index off it. However,
space is still allocated for it (TOP_FOOT_SIZE) to enable
separation or merging when space is extended.
3. Chunks allocated via mmap, which have the lowest-order bit
(IS_MMAPPED_BIT) set in their prev_foot fields, and do not set
PINUSE_BIT in their head fields. Because they are allocated
one-by-one, each must carry its own prev_foot field, which is
also used to hold the offset this chunk has within its mmapped
region, which is needed to preserve alignment. Each mmapped
chunk is trailed by the first two fields of a fake next-chunk
for sake of usage checks.
*/
struct malloc_chunk {
size_t prev_foot; /* Size of previous chunk (if free). */
size_t head; /* Size and inuse bits. */
struct malloc_chunk* fd; /* double links -- used only if free. */
struct malloc_chunk* bk;
};
typedef struct malloc_chunk mchunk;
typedef struct malloc_chunk* mchunkptr;
typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */
typedef unsigned int bindex_t; /* Described below */
typedef unsigned int binmap_t; /* Described below */
typedef unsigned int flag_t; /* The type of various bit flag sets */
/* ------------------- Chunks sizes and alignments ----------------------- */
#define MCHUNK_SIZE (sizeof(mchunk))
#if FOOTERS
#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
#else /* FOOTERS */
#define CHUNK_OVERHEAD (SIZE_T_SIZE)
#endif /* FOOTERS */
/* MMapped chunks need a second word of overhead ... */
#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
/* ... and additional padding for fake next-chunk at foot */
#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES)
/* The smallest size we can malloc is an aligned minimal chunk */
#define MIN_CHUNK_SIZE\
((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
/* conversion from malloc headers to user pointers, and back */
#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES))
#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
/* chunk associated with aligned address A */
#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A)))
/* Bounds on request (not chunk) sizes. */
#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2)
#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
/* pad request bytes into a usable size */
#define pad_request(req) \
(((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
/* pad request, checking for minimum (but not maximum) */
#define request2size(req) \
(((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
/* ------------------ Operations on head and foot fields ----------------- */
/*
The head field of a chunk is or'ed with PINUSE_BIT when previous
adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
use. If the chunk was obtained with mmap, the prev_foot field has
IS_MMAPPED_BIT set, otherwise holding the offset of the base of the
mmapped region to the base of the chunk.
FLAG4_BIT is not used by this malloc, but might be useful in extensions.
*/
#define PINUSE_BIT (SIZE_T_ONE)
#define CINUSE_BIT (SIZE_T_TWO)
#define FLAG4_BIT (SIZE_T_FOUR)
#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT)
#define FLAG_BITS (PINUSE_BIT|CINUSE_BIT|FLAG4_BIT)
/* Head value for fenceposts */
#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE)
/* extraction of fields from head words */
#define cinuse(p) ((p)->head & CINUSE_BIT)
#define pinuse(p) ((p)->head & PINUSE_BIT)
#define chunksize(p) ((p)->head & ~(FLAG_BITS))
#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT)
#define clear_cinuse(p) ((p)->head &= ~CINUSE_BIT)
/* Treat space at ptr +/- offset as a chunk */
#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
/* Ptr to next or previous physical malloc_chunk. */
#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~FLAG_BITS)))
#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
/* extract next chunk's pinuse bit */
#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT)
/* Get/set size at footer */
#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot)
#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
/* Set size, pinuse bit, and foot */
#define set_size_and_pinuse_of_free_chunk(p, s)\
((p)->head = (s|PINUSE_BIT), set_foot(p, s))
/* Set size, pinuse bit, foot, and clear next pinuse */
#define set_free_with_pinuse(p, s, n)\
(clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
#define is_mmapped(p)\
(!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_MMAPPED_BIT))
/* Get the internal overhead associated with chunk p */
#define overhead_for(p)\
(is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
/* Return true if malloced space is not necessarily cleared */
#if MMAP_CLEARS
#define calloc_must_clear(p) (!is_mmapped(p))
#else /* MMAP_CLEARS */
#define calloc_must_clear(p) (1)
#endif /* MMAP_CLEARS */
/* ---------------------- Overlaid data structures ----------------------- */
/*
When chunks are not in use, they are treated as nodes of either
lists or trees.
"Small" chunks are stored in circular doubly-linked lists, and look
like this:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`head:' | Size of chunk, in bytes |P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Forward pointer to next chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Back pointer to previous chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Unused space (may be 0 bytes long) .
. .
. |
nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`foot:' | Size of chunk, in bytes |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Larger chunks are kept in a form of bitwise digital trees (aka
tries) keyed on chunksizes. Because malloc_tree_chunks are only for
free chunks greater than 256 bytes, their size doesn't impose any
constraints on user chunk sizes. Each node looks like:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`head:' | Size of chunk, in bytes |P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Forward pointer to next chunk of same size |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Back pointer to previous chunk of same size |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Pointer to left child (child[0]) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Pointer to right child (child[1]) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Pointer to parent |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| bin index of this chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Unused space .
. |
nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`foot:' | Size of chunk, in bytes |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Each tree holding treenodes is a tree of unique chunk sizes. Chunks
of the same size are arranged in a circularly-linked list, with only
the oldest chunk (the next to be used, in our FIFO ordering)
actually in the tree. (Tree members are distinguished by a non-null
parent pointer.) If a chunk with the same size an an existing node
is inserted, it is linked off the existing node using pointers that
work in the same way as fd/bk pointers of small chunks.
Each tree contains a power of 2 sized range of chunk sizes (the
smallest is 0x100 <= x < 0x180), which is is divided in half at each
tree level, with the chunks in the smaller half of the range (0x100
<= x < 0x140 for the top nose) in the left subtree and the larger
half (0x140 <= x < 0x180) in the right subtree. This is, of course,
done by inspecting individual bits.
Using these rules, each node's left subtree contains all smaller
sizes than its right subtree. However, the node at the root of each
subtree has no particular ordering relationship to either. (The
dividing line between the subtree sizes is based on trie relation.)
If we remove the last chunk of a given size from the interior of the
tree, we need to replace it with a leaf node. The tree ordering
rules permit a node to be replaced by any leaf below it.
The smallest chunk in a tree (a common operation in a best-fit
allocator) can be found by walking a path to the leftmost leaf in
the tree. Unlike a usual binary tree, where we follow left child
pointers until we reach a null, here we follow the right child
pointer any time the left one is null, until we reach a leaf with
both child pointers null. The smallest chunk in the tree will be
somewhere along that path.
The worst case number of steps to add, find, or remove a node is
bounded by the number of bits differentiating chunks within
bins. Under current bin calculations, this ranges from 6 up to 21
(for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
is of course much better.
*/
struct malloc_tree_chunk {
/* The first four fields must be compatible with malloc_chunk */
size_t prev_foot;
size_t head;
struct malloc_tree_chunk* fd;
struct malloc_tree_chunk* bk;
struct malloc_tree_chunk* child[2];
struct malloc_tree_chunk* parent;
bindex_t index;
};
typedef struct malloc_tree_chunk tchunk;
typedef struct malloc_tree_chunk* tchunkptr;
typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */
/* A little helper macro for trees */
#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
/* ----------------------------- Segments -------------------------------- */
/*
Each malloc space may include non-contiguous segments, held in a
list headed by an embedded malloc_segment record representing the
top-most space. Segments also include flags holding properties of
the space. Large chunks that are directly allocated by mmap are not
included in this list. They are instead independently created and
destroyed without otherwise keeping track of them.
Segment management mainly comes into play for spaces allocated by
MMAP. Any call to MMAP might or might not return memory that is
adjacent to an existing segment. MORECORE normally contiguously
extends the current space, so this space is almost always adjacent,
which is simpler and faster to deal with. (This is why MORECORE is
used preferentially to MMAP when both are available -- see
sys_alloc.) When allocating using MMAP, we don't use any of the
hinting mechanisms (inconsistently) supported in various
implementations of unix mmap, or distinguish reserving from
committing memory. Instead, we just ask for space, and exploit
contiguity when we get it. It is probably possible to do
better than this on some systems, but no general scheme seems
to be significantly better.
Management entails a simpler variant of the consolidation scheme
used for chunks to reduce fragmentation -- new adjacent memory is
normally prepended or appended to an existing segment. However,
there are limitations compared to chunk consolidation that mostly
reflect the fact that segment processing is relatively infrequent
(occurring only when getting memory from system) and that we
don't expect to have huge numbers of segments:
* Segments are not indexed, so traversal requires linear scans. (It
would be possible to index these, but is not worth the extra
overhead and complexity for most programs on most platforms.)
* New segments are only appended to old ones when holding top-most
memory; if they cannot be prepended to others, they are held in
different segments.
Except for the top-most segment of an mstate, each segment record
is kept at the tail of its segment. Segments are added by pushing
segment records onto the list headed by &mstate.seg for the
containing mstate.
Segment flags control allocation/merge/deallocation policies:
* If EXTERN_BIT set, then we did not allocate this segment,
and so should not try to deallocate or merge with others.
(This currently holds only for the initial segment passed
into create_mspace_with_base.)
* If IS_MMAPPED_BIT set, the segment may be merged with
other surrounding mmapped segments and trimmed/de-allocated
using munmap.
* If neither bit is set, then the segment was obtained using
MORECORE so can be merged with surrounding MORECORE'd segments
and deallocated/trimmed using MORECORE with negative arguments.
*/
struct malloc_segment {
char* base; /* base address */
size_t size; /* allocated size */
struct malloc_segment* next; /* ptr to next segment */
flag_t sflags; /* mmap and extern flag */
};
#define is_mmapped_segment(S) ((S)->sflags & IS_MMAPPED_BIT)
#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT)
typedef struct malloc_segment msegment;
typedef struct malloc_segment* msegmentptr;
/* ---------------------------- malloc_state ----------------------------- */
/*
A malloc_state holds all of the bookkeeping for a space.
The main fields are:
Top
The topmost chunk of the currently active segment. Its size is
cached in topsize. The actual size of topmost space is
topsize+TOP_FOOT_SIZE, which includes space reserved for adding
fenceposts and segment records if necessary when getting more
space from the system. The size at which to autotrim top is
cached from mparams in trim_check, except that it is disabled if
an autotrim fails.
Designated victim (dv)
This is the preferred chunk for servicing small requests that
don't have exact fits. It is normally the chunk split off most
recently to service another small request. Its size is cached in
dvsize. The link fields of this chunk are not maintained since it
is not kept in a bin.
SmallBins
An array of bin headers for free chunks. These bins hold chunks
with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
chunks of all the same size, spaced 8 bytes apart. To simplify
use in double-linked lists, each bin header acts as a malloc_chunk
pointing to the real first node, if it exists (else pointing to
itself). This avoids special-casing for headers. But to avoid
waste, we allocate only the fd/bk pointers of bins, and then use
repositioning tricks to treat these as the fields of a chunk.
TreeBins
Treebins are pointers to the roots of trees holding a range of
sizes. There are 2 equally spaced treebins for each power of two
from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
larger.
Bin maps
There is one bit map for small bins ("smallmap") and one for
treebins ("treemap). Each bin sets its bit when non-empty, and
clears the bit when empty. Bit operations are then used to avoid
bin-by-bin searching -- nearly all "search" is done without ever
looking at bins that won't be selected. The bit maps
conservatively use 32 bits per map word, even if on 64bit system.
For a good description of some of the bit-based techniques used
here, see Henry S. Warren Jr's book "Hacker's Delight" (and
supplement at http://hackersdelight.org/). Many of these are
intended to reduce the branchiness of paths through malloc etc, as
well as to reduce the number of memory locations read or written.
Segments
A list of segments headed by an embedded malloc_segment record
representing the initial space.
Address check support
The least_addr field is the least address ever obtained from
MORECORE or MMAP. Attempted frees and reallocs of any address less
than this are trapped (unless INSECURE is defined).
Magic tag
A cross-check field that should always hold same value as mparams.magic.
Flags
Bits recording whether to use MMAP, locks, or contiguous MORECORE
Statistics
Each space keeps track of current and maximum system memory
obtained via MORECORE or MMAP.
Trim support
Fields holding the amount of unused topmost memory that should trigger
timming, and a counter to force periodic scanning to release unused
non-topmost segments.
Locking
If USE_LOCKS is defined, the "mutex" lock is acquired and released
around every public call using this mspace.
Extension support
A void* pointer and a size_t field that can be used to help implement
extensions to this malloc.
*/
/* Bin types, widths and sizes */
#define NSMALLBINS (32U)
#define NTREEBINS (32U)
#define SMALLBIN_SHIFT (3U)
#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT)
#define TREEBIN_SHIFT (8U)
#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT)
#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE)
#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
struct malloc_state {
binmap_t smallmap;
binmap_t treemap;
size_t dvsize;
size_t topsize;
char* least_addr;
mchunkptr dv;
mchunkptr top;
size_t trim_check;
size_t release_checks;
size_t magic;
mchunkptr smallbins[(NSMALLBINS+1)*2];
tbinptr treebins[NTREEBINS];
size_t footprint;
size_t max_footprint;
flag_t mflags;
#if USE_LOCKS
MLOCK_T mutex; /* locate lock among fields that rarely change */
#endif /* USE_LOCKS */
msegment seg;
void* extp; /* Unused but available for extensions */
size_t exts;
};
typedef struct malloc_state* mstate;
/* ------------- Global malloc_state and malloc_params ------------------- */
/*
malloc_params holds global properties, including those that can be
dynamically set using mallopt. There is a single instance, mparams,
initialized in init_mparams.
*/
struct malloc_params {
size_t magic;
size_t page_size;
size_t granularity;
size_t mmap_threshold;
size_t trim_threshold;
flag_t default_mflags;
};
static struct malloc_params mparams;
#if !ONLY_MSPACES
/* The global malloc_state used for all non-"mspace" calls */
static struct malloc_state _gm_;
#define gm (&_gm_)
#define is_global(M) ((M) == &_gm_)
#endif /* !ONLY_MSPACES */
#define is_initialized(M) ((M)->top != 0)
/* -------------------------- system alloc setup ------------------------- */
/* Operations on mflags */
#define use_lock(M) ((M)->mflags & USE_LOCK_BIT)
#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT)
#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT)
#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT)
#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT)
#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT)
#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT)
#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT)
#define set_lock(M,L)\
((M)->mflags = (L)?\
((M)->mflags | USE_LOCK_BIT) :\
((M)->mflags & ~USE_LOCK_BIT))
/* page-align a size */
#define page_align(S)\
(((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE))
/* granularity-align a size */
#define granularity_align(S)\
(((S) + (mparams.granularity - SIZE_T_ONE))\
& ~(mparams.granularity - SIZE_T_ONE))
/* For mmap, use granularity alignment on windows, else page-align */
#ifdef WIN32
#define mmap_align(S) granularity_align(S)
#else
#define mmap_align(S) page_align(S)
#endif
#define is_page_aligned(S)\
(((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
#define is_granularity_aligned(S)\
(((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
/* True if segment S holds address A */
#define segment_holds(S, A)\
((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
/* Return segment holding given address */
static msegmentptr segment_holding(mstate m, char* addr) {
msegmentptr sp = &m->seg;
for (;;) {
if (addr >= sp->base && addr < sp->base + sp->size)
return sp;
if ((sp = sp->next) == 0)
return 0;
}
}
/* Return true if segment contains a segment link */
static int has_segment_link(mstate m, msegmentptr ss) {
msegmentptr sp = &m->seg;
for (;;) {
if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
return 1;
if ((sp = sp->next) == 0)
return 0;
}
}
#ifndef MORECORE_CANNOT_TRIM
#define should_trim(M,s) ((s) > (M)->trim_check)
#else /* MORECORE_CANNOT_TRIM */
#define should_trim(M,s) (0)
#endif /* MORECORE_CANNOT_TRIM */
/*
TOP_FOOT_SIZE is padding at the end of a segment, including space
that may be needed to place segment records and fenceposts when new
noncontiguous segments are added.
*/
#define TOP_FOOT_SIZE\
(align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
/* ------------------------------- Hooks -------------------------------- */
/*
PREACTION should be defined to return 0 on success, and nonzero on
failure. If you are not using locking, you can redefine these to do
anything you like.
*/
#if USE_LOCKS
/* Ensure locks are initialized */
#define GLOBALLY_INITIALIZE() (mparams.page_size == 0 && init_mparams())
//#define PREACTION(M) ((GLOBALLY_INITIALIZE() || use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
//#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
#define PREACTION(M) ((GLOBALLY_INITIALIZE() || use_lock(M))? ACQUIRE_LOCK(&mspace_mutex) : 0)
#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&mspace_mutex); }
#else /* USE_LOCKS */
#ifndef PREACTION
#define PREACTION(M) (0)
#endif /* PREACTION */
#ifndef POSTACTION
#define POSTACTION(M)
#endif /* POSTACTION */
#endif /* USE_LOCKS */
/*
CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
USAGE_ERROR_ACTION is triggered on detected bad frees and
reallocs. The argument p is an address that might have triggered the
fault. It is ignored by the two predefined actions, but might be
useful in custom actions that try to help diagnose errors.
*/
#if PROCEED_ON_ERROR
/* A count of the number of corruption errors causing resets */
int malloc_corruption_error_count;
/* default corruption action */
static void reset_on_error(mstate m);
#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m)
#define USAGE_ERROR_ACTION(m, p)
#else /* PROCEED_ON_ERROR */
#ifndef CORRUPTION_ERROR_ACTION
#define CORRUPTION_ERROR_ACTION(m) ABORT
#endif /* CORRUPTION_ERROR_ACTION */
#ifndef USAGE_ERROR_ACTION
#define USAGE_ERROR_ACTION(m,p) ABORT
#endif /* USAGE_ERROR_ACTION */
#endif /* PROCEED_ON_ERROR */
/* -------------------------- Debugging setup ---------------------------- */
#if ! DEBUG
#define check_free_chunk(M,P)
#define check_inuse_chunk(M,P)
#define check_malloced_chunk(M,P,N)
#define check_mmapped_chunk(M,P)
#define check_malloc_state(M)
#define check_top_chunk(M,P)
#else /* DEBUG */
#define check_free_chunk(M,P) do_check_free_chunk(M,P)
#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P)
#define check_top_chunk(M,P) do_check_top_chunk(M,P)
#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P)
#define check_malloc_state(M) do_check_malloc_state(M)
static void do_check_any_chunk(mstate m, mchunkptr p);
static void do_check_top_chunk(mstate m, mchunkptr p);
static void do_check_mmapped_chunk(mstate m, mchunkptr p);
static void do_check_inuse_chunk(mstate m, mchunkptr p);
static void do_check_free_chunk(mstate m, mchunkptr p);
static void do_check_malloced_chunk(mstate m, void* mem, size_t s);
static void do_check_tree(mstate m, tchunkptr t);
static void do_check_treebin(mstate m, bindex_t i);
static void do_check_smallbin(mstate m, bindex_t i);
static void do_check_malloc_state(mstate m);
static int bin_find(mstate m, mchunkptr x);
static size_t traverse_and_check(mstate m);
#endif /* DEBUG */
/* ---------------------------- Indexing Bins ---------------------------- */
#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
#define small_index(s) ((s) >> SMALLBIN_SHIFT)
#define small_index2size(i) ((i) << SMALLBIN_SHIFT)
#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE))
/* addressing by index. See above about smallbin repositioning */
#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
#define treebin_at(M,i) (&((M)->treebins[i]))
/* assign tree index for size S to variable I */
#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
#define compute_tree_index(S, I)\
{\
unsigned int X = S >> TREEBIN_SHIFT;\
if (X == 0)\
I = 0;\
else if (X > 0xFFFF)\
I = NTREEBINS-1;\
else {\
unsigned int K;\
__asm__("bsrl\t%1, %0\n\t" : "=r" (K) : "g" (X));\
I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
}\
}
#elif defined(_MSC_VER) && _MSC_VER>=1300
#define compute_tree_index(S, I)\
{\
size_t X = S >> TREEBIN_SHIFT;\
if (X == 0)\
I = 0;\
else if (X > 0xFFFF)\
I = NTREEBINS-1;\
else {\
unsigned int K;\
_BitScanReverse((DWORD *) &K, X);\
I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
}\
}
#else /* GNUC */
#define compute_tree_index(S, I)\
{\
size_t X = S >> TREEBIN_SHIFT;\
if (X == 0)\
I = 0;\
else if (X > 0xFFFF)\
I = NTREEBINS-1;\
else {\
unsigned int Y = (unsigned int)X;\
unsigned int N = ((Y - 0x100) >> 16) & 8;\
unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
N += K;\
N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
K = 14 - N + ((Y <<= K) >> 15);\
I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
}\
}
#endif /* GNUC */
/* Bit representing maximum resolved size in a treebin at i */
#define bit_for_tree_index(i) \
(i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
/* Shift placing maximum resolved bit in a treebin at i as sign bit */
#define leftshift_for_tree_index(i) \
((i == NTREEBINS-1)? 0 : \
((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
/* The size of the smallest chunk held in bin with index i */
#define minsize_for_tree_index(i) \
((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \
(((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
/* ------------------------ Operations on bin maps ----------------------- */
/* bit corresponding to given index */
#define idx2bit(i) ((binmap_t)(1) << (i))
/* Mark/Clear bits with given index */
#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i))
#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i))
#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i))
#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i))
#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i))
#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i))
/* index corresponding to given bit */
#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
#define compute_bit2idx(X, I)\
{\
unsigned int J;\
__asm__("bsfl\t%1, %0\n\t" : "=r" (J) : "g" (X));\
I = (bindex_t)J;\
}
#elif defined(_MSC_VER) && _MSC_VER>=1300
#define compute_bit2idx(X, I)\
{\
unsigned int J;\
_BitScanForward((DWORD *) &J, X);\
I = (bindex_t)J;\
}
#else /* GNUC */
#if USE_BUILTIN_FFS
#define compute_bit2idx(X, I) I = ffs(X)-1
#else /* USE_BUILTIN_FFS */
#define compute_bit2idx(X, I)\
{\
unsigned int Y = X - 1;\
unsigned int K = Y >> (16-4) & 16;\
unsigned int N = K; Y >>= K;\
N += K = Y >> (8-3) & 8; Y >>= K;\
N += K = Y >> (4-2) & 4; Y >>= K;\
N += K = Y >> (2-1) & 2; Y >>= K;\
N += K = Y >> (1-0) & 1; Y >>= K;\
I = (bindex_t)(N + Y);\
}
#endif /* USE_BUILTIN_FFS */
#endif /* GNUC */
/* isolate the least set bit of a bitmap */
#define least_bit(x) ((x) & -(x))
/* mask with all bits to left of least bit of x on */
#define left_bits(x) ((x<<1) | -(x<<1))
/* mask with all bits to left of or equal to least bit of x on */
#define same_or_left_bits(x) ((x) | -(x))
/* ----------------------- Runtime Check Support ------------------------- */
/*
For security, the main invariant is that malloc/free/etc never
writes to a static address other than malloc_state, unless static
malloc_state itself has been corrupted, which cannot occur via
malloc (because of these checks). In essence this means that we
believe all pointers, sizes, maps etc held in malloc_state, but
check all of those linked or offsetted from other embedded data
structures. These checks are interspersed with main code in a way
that tends to minimize their run-time cost.
When FOOTERS is defined, in addition to range checking, we also
verify footer fields of inuse chunks, which can be used guarantee
that the mstate controlling malloc/free is intact. This is a
streamlined version of the approach described by William Robertson
et al in "Run-time Detection of Heap-based Overflows" LISA'03
http://www.usenix.org/events/lisa03/tech/robertson.html The footer
of an inuse chunk holds the xor of its mstate and a random seed,
that is checked upon calls to free() and realloc(). This is
(probablistically) unguessable from outside the program, but can be
computed by any code successfully malloc'ing any chunk, so does not
itself provide protection against code that has already broken
security through some other means. Unlike Robertson et al, we
always dynamically check addresses of all offset chunks (previous,
next, etc). This turns out to be cheaper than relying on hashes.
*/
#if !INSECURE
/* Check if address a is at least as high as any from MORECORE or MMAP */
#define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
/* Check if address of next chunk n is higher than base chunk p */
#define ok_next(p, n) ((char*)(p) < (char*)(n))
/* Check if p has its cinuse bit on */
#define ok_cinuse(p) cinuse(p)
/* Check if p has its pinuse bit on */
#define ok_pinuse(p) pinuse(p)
#else /* !INSECURE */
#define ok_address(M, a) (1)
#define ok_next(b, n) (1)
#define ok_cinuse(p) (1)
#define ok_pinuse(p) (1)
#endif /* !INSECURE */
#if (FOOTERS && !INSECURE)
/* Check if (alleged) mstate m has expected magic field */
#define ok_magic(M) ((M)->magic == mparams.magic)
#else /* (FOOTERS && !INSECURE) */
#define ok_magic(M) (1)
#endif /* (FOOTERS && !INSECURE) */
/* In gcc, use __builtin_expect to minimize impact of checks */
#if !INSECURE
#if defined(__GNUC__) && __GNUC__ >= 3
#define RTCHECK(e) __builtin_expect(e, 1)
#else /* GNUC */
#define RTCHECK(e) (e)
#endif /* GNUC */
#else /* !INSECURE */
#define RTCHECK(e) (1)
#endif /* !INSECURE */
/* macros to set up inuse chunks with or without footers */
#if !FOOTERS
#define mark_inuse_foot(M,p,s)
/* Set cinuse bit and pinuse bit of next chunk */
#define set_inuse(M,p,s)\
((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
/* Set cinuse and pinuse of this chunk and pinuse of next chunk */
#define set_inuse_and_pinuse(M,p,s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
/* Set size, cinuse and pinuse bit of this chunk */
#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
#else /* FOOTERS */
/* Set foot of inuse chunk to be xor of mstate and seed */
#define mark_inuse_foot(M,p,s)\
(((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
#define get_mstate_for(p)\
((mstate)(((mchunkptr)((char*)(p) +\
(chunksize(p))))->prev_foot ^ mparams.magic))
#define set_inuse(M,p,s)\
((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
(((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
mark_inuse_foot(M,p,s))
#define set_inuse_and_pinuse(M,p,s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
(((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
mark_inuse_foot(M,p,s))
#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
mark_inuse_foot(M, p, s))
#endif /* !FOOTERS */
/* ---------------------------- setting mparams -------------------------- */
/* Initialize mparams */
static int init_mparams(void) {
int lRet = 0;
if (mparams.page_size == 0) {
size_t s;
mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
#if MORECORE_CONTIGUOUS
mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;
#else /* MORECORE_CONTIGUOUS */
mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;
#endif /* MORECORE_CONTIGUOUS */
#if (FOOTERS && !INSECURE)
{
#if USE_DEV_RANDOM
int fd;
unsigned char buf[sizeof(size_t)];
/* Try to use /dev/urandom, else fall back on using time */
if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
read(fd, buf, sizeof(buf)) == sizeof(buf)) {
s = *((size_t *) buf);
close(fd);
}
else
#endif /* USE_DEV_RANDOM */
s = (size_t)(time(0) ^ (size_t)0x55555555U);
s |= (size_t)8U; /* ensure nonzero */
s &= ~(size_t)7U; /* improve chances of fault for bad values */
}
#else /* (FOOTERS && !INSECURE) */
s = (size_t)0x58585858U;
#endif /* (FOOTERS && !INSECURE) */
lRet = ACQUIRE_MAGIC_INIT_LOCK();
if (mparams.magic == 0) {
mparams.magic = s;
#if !ONLY_MSPACES
/* Set up lock for main malloc area */
//INITIAL_LOCK(&gm->mutex);
INITIAL_LOCK(&mspace_mutex);
gm->mflags = mparams.default_mflags;
#endif
}
RELEASE_MAGIC_INIT_LOCK();
#ifndef WIN32
mparams.page_size = malloc_getpagesize;
mparams.granularity = ((DEFAULT_GRANULARITY != 0)?
DEFAULT_GRANULARITY : mparams.page_size);
#else /* WIN32 */
{
SYSTEM_INFO system_info;
GetSystemInfo(&system_info);
mparams.page_size = system_info.dwPageSize;
mparams.granularity = system_info.dwAllocationGranularity;
}
#endif /* WIN32 */
/* Sanity-check configuration:
size_t must be unsigned and as wide as pointer type.
ints must be at least 4 bytes.
alignment must be at least 8.
Alignment, min chunk size, and page size must all be powers of 2.
*/
if ((sizeof(size_t) != sizeof(char*)) ||
(MAX_SIZE_T < MIN_CHUNK_SIZE) ||
(sizeof(int) < 4) ||
(MALLOC_ALIGNMENT < (size_t)8U) ||
((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) ||
((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) ||
((mparams.granularity & (mparams.granularity-SIZE_T_ONE)) != 0) ||
((mparams.page_size & (mparams.page_size-SIZE_T_ONE)) != 0))
ABORT;
}
return 0;
}
/* support for mallopt */
static int change_mparam(int param_number, int value) {
size_t val = (size_t)value;
init_mparams();
switch(param_number) {
case M_TRIM_THRESHOLD:
mparams.trim_threshold = val;
return 1;
case M_GRANULARITY:
if (val >= mparams.page_size && ((val & (val-1)) == 0)) {
mparams.granularity = val;
return 1;
}
else
return 0;
case M_MMAP_THRESHOLD:
mparams.mmap_threshold = val;
return 1;
default:
return 0;
}
}
#if DEBUG
/* ------------------------- Debugging Support --------------------------- */
/* Check properties of any chunk, whether free, inuse, mmapped etc */
static void do_check_any_chunk(mstate m, mchunkptr p) {
assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
assert(ok_address(m, p));
}
/* Check properties of top chunk */
static void do_check_top_chunk(mstate m, mchunkptr p) {
msegmentptr sp = segment_holding(m, (char*)p);
size_t sz = p->head & ~INUSE_BITS; /* third-lowest bit can be set! */
assert(sp != 0);
assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
assert(ok_address(m, p));
assert(sz == m->topsize);
assert(sz > 0);
assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);
assert(pinuse(p));
assert(!pinuse(chunk_plus_offset(p, sz)));
}
/* Check properties of (inuse) mmapped chunks */
static void do_check_mmapped_chunk(mstate m, mchunkptr p) {
size_t sz = chunksize(p);
size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD);
assert(is_mmapped(p));
assert(use_mmap(m));
assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
assert(ok_address(m, p));
assert(!is_small(sz));
assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);
assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);
}
/* Check properties of inuse chunks */
static void do_check_inuse_chunk(mstate m, mchunkptr p) {
do_check_any_chunk(m, p);
assert(cinuse(p));
assert(next_pinuse(p));
/* If not pinuse and not mmapped, previous chunk has OK offset */
assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
if (is_mmapped(p))
do_check_mmapped_chunk(m, p);
}
/* Check properties of free chunks */
static void do_check_free_chunk(mstate m, mchunkptr p) {
size_t sz = chunksize(p);
mchunkptr next = chunk_plus_offset(p, sz);
do_check_any_chunk(m, p);
assert(!cinuse(p));
assert(!next_pinuse(p));
assert (!is_mmapped(p));
if (p != m->dv && p != m->top) {
if (sz >= MIN_CHUNK_SIZE) {
assert((sz & CHUNK_ALIGN_MASK) == 0);
assert(is_aligned(chunk2mem(p)));
assert(next->prev_foot == sz);
assert(pinuse(p));
assert (next == m->top || cinuse(next));
assert(p->fd->bk == p);
assert(p->bk->fd == p);
}
else /* markers are always of size SIZE_T_SIZE */
assert(sz == SIZE_T_SIZE);
}
}
/* Check properties of malloced chunks at the point they are malloced */
static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT);
do_check_inuse_chunk(m, p);
assert((sz & CHUNK_ALIGN_MASK) == 0);
assert(sz >= MIN_CHUNK_SIZE);
assert(sz >= s);
/* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
}
}
/* Check a tree and its subtrees. */
static void do_check_tree(mstate m, tchunkptr t) {
tchunkptr head = 0;
tchunkptr u = t;
bindex_t tindex = t->index;
size_t tsize = chunksize(t);
bindex_t idx;
compute_tree_index(tsize, idx);
assert(tindex == idx);
assert(tsize >= MIN_LARGE_SIZE);
assert(tsize >= minsize_for_tree_index(idx));
assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));
do { /* traverse through chain of same-sized nodes */
do_check_any_chunk(m, ((mchunkptr)u));
assert(u->index == tindex);
assert(chunksize(u) == tsize);
assert(!cinuse(u));
assert(!next_pinuse(u));
assert(u->fd->bk == u);
assert(u->bk->fd == u);
if (u->parent == 0) {
assert(u->child[0] == 0);
assert(u->child[1] == 0);
}
else {
assert(head == 0); /* only one node on chain has parent */
head = u;
assert(u->parent != u);
assert (u->parent->child[0] == u ||
u->parent->child[1] == u ||
*((tbinptr*)(u->parent)) == u);
if (u->child[0] != 0) {
assert(u->child[0]->parent == u);
assert(u->child[0] != u);
do_check_tree(m, u->child[0]);
}
if (u->child[1] != 0) {
assert(u->child[1]->parent == u);
assert(u->child[1] != u);
do_check_tree(m, u->child[1]);
}
if (u->child[0] != 0 && u->child[1] != 0) {
assert(chunksize(u->child[0]) < chunksize(u->child[1]));
}
}
u = u->fd;
} while (u != t);
assert(head != 0);
}
/* Check all the chunks in a treebin. */
static void do_check_treebin(mstate m, bindex_t i) {
tbinptr* tb = treebin_at(m, i);
tchunkptr t = *tb;
int empty = (m->treemap & (1U << i)) == 0;
if (t == 0)
assert(empty);
if (!empty)
do_check_tree(m, t);
}
/* Check all the chunks in a smallbin. */
static void do_check_smallbin(mstate m, bindex_t i) {
sbinptr b = smallbin_at(m, i);
mchunkptr p = b->bk;
unsigned int empty = (m->smallmap & (1U << i)) == 0;
if (p == b)
assert(empty);
if (!empty) {
for (; p != b; p = p->bk) {
size_t size = chunksize(p);
mchunkptr q;
/* each chunk claims to be free */
do_check_free_chunk(m, p);
/* chunk belongs in bin */
assert(small_index(size) == i);
assert(p->bk == b || chunksize(p->bk) == chunksize(p));
/* chunk is followed by an inuse chunk */
q = next_chunk(p);
if (q->head != FENCEPOST_HEAD)
do_check_inuse_chunk(m, q);
}
}
}
/* Find x in a bin. Used in other check functions. */
static int bin_find(mstate m, mchunkptr x) {
size_t size = chunksize(x);
if (is_small(size)) {
bindex_t sidx = small_index(size);
sbinptr b = smallbin_at(m, sidx);
if (smallmap_is_marked(m, sidx)) {
mchunkptr p = b;
do {
if (p == x)
return 1;
} while ((p = p->fd) != b);
}
}
else {
bindex_t tidx;
compute_tree_index(size, tidx);
if (treemap_is_marked(m, tidx)) {
tchunkptr t = *treebin_at(m, tidx);
size_t sizebits = size << leftshift_for_tree_index(tidx);
while (t != 0 && chunksize(t) != size) {
t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
sizebits <<= 1;
}
if (t != 0) {
tchunkptr u = t;
do {
if (u == (tchunkptr)x)
return 1;
} while ((u = u->fd) != t);
}
}
}
return 0;
}
/* Traverse each chunk and check it; return total */
static size_t traverse_and_check(mstate m) {
size_t sum = 0;
if (is_initialized(m)) {
msegmentptr s = &m->seg;
sum += m->topsize + TOP_FOOT_SIZE;
while (s != 0) {
mchunkptr q = align_as_chunk(s->base);
mchunkptr lastq = 0;
assert(pinuse(q));
while (segment_holds(s, q) &&
q != m->top && q->head != FENCEPOST_HEAD) {
sum += chunksize(q);
if (cinuse(q)) {
assert(!bin_find(m, q));
do_check_inuse_chunk(m, q);
}
else {
assert(q == m->dv || bin_find(m, q));
assert(lastq == 0 || cinuse(lastq)); /* Not 2 consecutive free */
do_check_free_chunk(m, q);
}
lastq = q;
q = next_chunk(q);
}
s = s->next;
}
}
return sum;
}
/* Check all properties of malloc_state. */
static void do_check_malloc_state(mstate m) {
bindex_t i;
size_t total;
/* check bins */
for (i = 0; i < NSMALLBINS; ++i)
do_check_smallbin(m, i);
for (i = 0; i < NTREEBINS; ++i)
do_check_treebin(m, i);
if (m->dvsize != 0) { /* check dv chunk */
do_check_any_chunk(m, m->dv);
assert(m->dvsize == chunksize(m->dv));
assert(m->dvsize >= MIN_CHUNK_SIZE);
assert(bin_find(m, m->dv) == 0);
}
if (m->top != 0) { /* check top chunk */
do_check_top_chunk(m, m->top);
/*assert(m->topsize == chunksize(m->top)); redundant */
assert(m->topsize > 0);
assert(bin_find(m, m->top) == 0);
}
total = traverse_and_check(m);
assert(total <= m->footprint);
assert(m->footprint <= m->max_footprint);
}
#endif /* DEBUG */
/* ----------------------------- statistics ------------------------------ */
#if !NO_MALLINFO
static struct mallinfo internal_mallinfo(mstate m) {
struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
if (!PREACTION(m)) {
check_malloc_state(m);
if (is_initialized(m)) {
size_t nfree = SIZE_T_ONE; /* top always free */
size_t mfree = m->topsize + TOP_FOOT_SIZE;
size_t sum = mfree;
msegmentptr s = &m->seg;
while (s != 0) {
mchunkptr q = align_as_chunk(s->base);
while (segment_holds(s, q) &&
q != m->top && q->head != FENCEPOST_HEAD) {
size_t sz = chunksize(q);
sum += sz;
if (!cinuse(q)) {
mfree += sz;
++nfree;
}
q = next_chunk(q);
}
s = s->next;
}
nm.arena = sum;
nm.ordblks = nfree;
nm.hblkhd = m->footprint - sum;
nm.usmblks = m->max_footprint;
nm.uordblks = m->footprint - mfree;
nm.fordblks = mfree;
nm.keepcost = m->topsize;
}
POSTACTION(m);
}
return nm;
}
#endif /* !NO_MALLINFO */
static void internal_malloc_stats(mstate m) {
if (!PREACTION(m)) {
size_t fp = 0;
size_t used = 0;
check_malloc_state(m);
if (is_initialized(m)) {
msegmentptr s = &m->seg;
fp = m->footprint;
used = fp - (m->topsize + TOP_FOOT_SIZE);
while (s != 0) {
mchunkptr q = align_as_chunk(s->base);
while (segment_holds(s, q) &&
q != m->top && q->head != FENCEPOST_HEAD) {
if (!cinuse(q))
used -= chunksize(q);
q = next_chunk(q);
}
s = s->next;
}
}
//fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp));
//fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp));
//fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used));
POSTACTION(m);
}
}
/* ----------------------- Operations on smallbins ----------------------- */
/*
Various forms of linking and unlinking are defined as macros. Even
the ones for trees, which are very long but have very short typical
paths. This is ugly but reduces reliance on inlining support of
compilers.
*/
/* Link a free chunk into a smallbin */
#define insert_small_chunk(M, P, S) {\
bindex_t I = small_index(S);\
mchunkptr B = smallbin_at(M, I);\
mchunkptr F = B;\
assert(S >= MIN_CHUNK_SIZE);\
if (!smallmap_is_marked(M, I))\
mark_smallmap(M, I);\
else if (RTCHECK(ok_address(M, B->fd)))\
F = B->fd;\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
B->fd = P;\
F->bk = P;\
P->fd = F;\
P->bk = B;\
}
/* Unlink a chunk from a smallbin */
#define unlink_small_chunk(M, P, S) {\
mchunkptr F = P->fd;\
mchunkptr B = P->bk;\
bindex_t I = small_index(S);\
assert(P != B);\
assert(P != F);\
assert(chunksize(P) == small_index2size(I));\
if (F == B)\
clear_smallmap(M, I);\
else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\
(B == smallbin_at(M,I) || ok_address(M, B)))) {\
F->bk = B;\
B->fd = F;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}
/* Unlink the first chunk from a smallbin */
#define unlink_first_small_chunk(M, B, P, I) {\
mchunkptr F = P->fd;\
assert(P != B);\
assert(P != F);\
assert(chunksize(P) == small_index2size(I));\
if (B == F)\
clear_smallmap(M, I);\
else if (RTCHECK(ok_address(M, F))) {\
B->fd = F;\
F->bk = B;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}
/* Replace dv node, binning the old one */
/* Used only when dvsize known to be small */
#define replace_dv(M, P, S) {\
size_t DVS = M->dvsize;\
if (DVS != 0) {\
mchunkptr DV = M->dv;\
assert(is_small(DVS));\
insert_small_chunk(M, DV, DVS);\
}\
M->dvsize = S;\
M->dv = P;\
}
/* ------------------------- Operations on trees ------------------------- */
/* Insert chunk into tree */
#define insert_large_chunk(M, X, S) {\
tbinptr* H;\
bindex_t I;\
compute_tree_index(S, I);\
H = treebin_at(M, I);\
X->index = I;\
X->child[0] = X->child[1] = 0;\
if (!treemap_is_marked(M, I)) {\
mark_treemap(M, I);\
*H = X;\
X->parent = (tchunkptr)H;\
X->fd = X->bk = X;\
}\
else {\
tchunkptr T = *H;\
size_t K = S << leftshift_for_tree_index(I);\
for (;;) {\
if (chunksize(T) != S) {\
tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
K <<= 1;\
if (*C != 0)\
T = *C;\
else if (RTCHECK(ok_address(M, C))) {\
*C = X;\
X->parent = T;\
X->fd = X->bk = X;\
break;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
break;\
}\
}\
else {\
tchunkptr F = T->fd;\
if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
T->fd = F->bk = X;\
X->fd = F;\
X->bk = T;\
X->parent = 0;\
break;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
break;\
}\
}\
}\
}\
}
/*
Unlink steps:
1. If x is a chained node, unlink it from its same-sized fd/bk links
and choose its bk node as its replacement.
2. If x was the last node of its size, but not a leaf node, it must
be replaced with a leaf node (not merely one with an open left or
right), to make sure that lefts and rights of descendents
correspond properly to bit masks. We use the rightmost descendent
of x. We could use any other leaf, but this is easy to locate and
tends to counteract removal of leftmosts elsewhere, and so keeps
paths shorter than minimally guaranteed. This doesn't loop much
because on average a node in a tree is near the bottom.
3. If x is the base of a chain (i.e., has parent links) relink
x's parent and children to x's replacement (or null if none).
*/
#define unlink_large_chunk(M, X) {\
tchunkptr XP = X->parent;\
tchunkptr R;\
if (X->bk != X) {\
tchunkptr F = X->fd;\
R = X->bk;\
if (RTCHECK(ok_address(M, F))) {\
F->bk = R;\
R->fd = F;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
else {\
tchunkptr* RP;\
if (((R = *(RP = &(X->child[1]))) != 0) ||\
((R = *(RP = &(X->child[0]))) != 0)) {\
tchunkptr* CP;\
while ((*(CP = &(R->child[1])) != 0) ||\
(*(CP = &(R->child[0])) != 0)) {\
R = *(RP = CP);\
}\
if (RTCHECK(ok_address(M, RP)))\
*RP = 0;\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
}\
if (XP != 0) {\
tbinptr* H = treebin_at(M, X->index);\
if (X == *H) {\
if ((*H = R) == 0) \
clear_treemap(M, X->index);\
}\
else if (RTCHECK(ok_address(M, XP))) {\
if (XP->child[0] == X) \
XP->child[0] = R;\
else \
XP->child[1] = R;\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
if (R != 0) {\
if (RTCHECK(ok_address(M, R))) {\
tchunkptr C0, C1;\
R->parent = XP;\
if ((C0 = X->child[0]) != 0) {\
if (RTCHECK(ok_address(M, C0))) {\
R->child[0] = C0;\
C0->parent = R;\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
}\
if ((C1 = X->child[1]) != 0) {\
if (RTCHECK(ok_address(M, C1))) {\
R->child[1] = C1;\
C1->parent = R;\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
}
/* Relays to large vs small bin operations */
#define insert_chunk(M, P, S)\
if (is_small(S)) insert_small_chunk(M, P, S)\
else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
#define unlink_chunk(M, P, S)\
if (is_small(S)) unlink_small_chunk(M, P, S)\
else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
/* Relays to internal calls to malloc/free from realloc, memalign etc */
#if ONLY_MSPACES
#define internal_malloc(m, b) mspace_malloc(m, b)
#define internal_free(m, mem) mspace_free(m,mem);
#else /* ONLY_MSPACES */
#if MSPACES
#define internal_malloc(m, b)\
(m == gm)? dlmalloc(b) : mspace_malloc(m, b)
#define internal_free(m, mem)\
if (m == gm) dlfree(mem); else mspace_free(m,mem);
#else /* MSPACES */
#define internal_malloc(m, b) dlmalloc(b)
#define internal_free(m, mem) dlfree(mem)
#endif /* MSPACES */
#endif /* ONLY_MSPACES */
/* ----------------------- Direct-mmapping chunks ----------------------- */
/*
Directly mmapped chunks are set up with an offset to the start of
the mmapped region stored in the prev_foot field of the chunk. This
allows reconstruction of the required argument to MUNMAP when freed,
and also allows adjustment of the returned chunk to meet alignment
requirements (especially in memalign). There is also enough space
allocated to hold a fake next chunk of size SIZE_T_SIZE to maintain
the PINUSE bit so frees can be checked.
*/
/* Malloc using mmap */
static void* mmap_alloc(mstate m, size_t nb) {
size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
if (mmsize > nb) { /* Check for wrap around 0 */
char* mm = (char*)(DIRECT_MMAP(mmsize));
if (mm != CMFAIL) {
size_t offset = align_offset(chunk2mem(mm));
size_t psize = mmsize - offset - MMAP_FOOT_PAD;
mchunkptr p = (mchunkptr)(mm + offset);
p->prev_foot = offset | IS_MMAPPED_BIT;
(p)->head = (psize|CINUSE_BIT);
mark_inuse_foot(m, p, psize);
chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;
if (mm < m->least_addr)
m->least_addr = mm;
if ((m->footprint += mmsize) > m->max_footprint)
m->max_footprint = m->footprint;
assert(is_aligned(chunk2mem(p)));
check_mmapped_chunk(m, p);
return chunk2mem(p);
}
}
return 0;
}
/* Realloc using mmap */
static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) {
size_t oldsize = chunksize(oldp);
if (is_small(nb)) /* Can't shrink mmap regions below small size */
return 0;
/* Keep old chunk if big enough but not too big */
if (oldsize >= nb + SIZE_T_SIZE &&
(oldsize - nb) <= (mparams.granularity << 1))
return oldp;
else {
size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT;
size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;
size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
char* cp = (char*)CALL_MREMAP((char*)oldp - offset,
oldmmsize, newmmsize, 1);
if (cp != CMFAIL) {
mchunkptr newp = (mchunkptr)(cp + offset);
size_t psize = newmmsize - offset - MMAP_FOOT_PAD;
newp->head = (psize|CINUSE_BIT);
mark_inuse_foot(m, newp, psize);
chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;
chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0;
if (cp < m->least_addr)
m->least_addr = cp;
if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)
m->max_footprint = m->footprint;
check_mmapped_chunk(m, newp);
return newp;
}
}
return 0;
}
/* -------------------------- mspace management -------------------------- */
/* Initialize top chunk and its size */
static void init_top(mstate m, mchunkptr p, size_t psize) {
/* Ensure alignment */
size_t offset = align_offset(chunk2mem(p));
p = (mchunkptr)((char*)p + offset);
psize -= offset;
m->top = p;
m->topsize = psize;
p->head = psize | PINUSE_BIT;
/* set size of fake trailing chunk holding overhead space only once */
chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
m->trim_check = mparams.trim_threshold; /* reset on each update */
}
/* Initialize bins for a new mstate that is otherwise zeroed out */
static void init_bins(mstate m) {
/* Establish circular links for smallbins */
bindex_t i;
for (i = 0; i < NSMALLBINS; ++i) {
sbinptr bin = smallbin_at(m,i);
bin->fd = bin->bk = bin;
}
}
#if PROCEED_ON_ERROR
/* default corruption action */
static void reset_on_error(mstate m) {
int i;
++malloc_corruption_error_count;
/* Reinitialize fields to forget about all memory */
m->smallbins = m->treebins = 0;
m->dvsize = m->topsize = 0;
m->seg.base = 0;
m->seg.size = 0;
m->seg.next = 0;
m->top = m->dv = 0;
for (i = 0; i < NTREEBINS; ++i)
*treebin_at(m, i) = 0;
init_bins(m);
}
#endif /* PROCEED_ON_ERROR */
/* Allocate chunk and prepend remainder with chunk in successor base. */
static void* prepend_alloc(mstate m, char* newbase, char* oldbase,
size_t nb) {
mchunkptr p = align_as_chunk(newbase);
mchunkptr oldfirst = align_as_chunk(oldbase);
size_t psize = (char*)oldfirst - (char*)p;
mchunkptr q = chunk_plus_offset(p, nb);
size_t qsize = psize - nb;
set_size_and_pinuse_of_inuse_chunk(m, p, nb);
assert((char*)oldfirst > (char*)q);
assert(pinuse(oldfirst));
assert(qsize >= MIN_CHUNK_SIZE);
/* consolidate remainder with first chunk of old base */
if (oldfirst == m->top) {
size_t tsize = m->topsize += qsize;
m->top = q;
q->head = tsize | PINUSE_BIT;
check_top_chunk(m, q);
}
else if (oldfirst == m->dv) {
size_t dsize = m->dvsize += qsize;
m->dv = q;
set_size_and_pinuse_of_free_chunk(q, dsize);
}
else {
if (!cinuse(oldfirst)) {
size_t nsize = chunksize(oldfirst);
unlink_chunk(m, oldfirst, nsize);
oldfirst = chunk_plus_offset(oldfirst, nsize);
qsize += nsize;
}
set_free_with_pinuse(q, qsize, oldfirst);
insert_chunk(m, q, qsize);
check_free_chunk(m, q);
}
check_malloced_chunk(m, chunk2mem(p), nb);
return chunk2mem(p);
}
/* Add a segment to hold a new noncontiguous region */
static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {
/* Determine locations and sizes of segment, fenceposts, old top */
char* old_top = (char*)m->top;
msegmentptr oldsp = segment_holding(m, old_top);
char* old_end = oldsp->base + oldsp->size;
size_t ssize = pad_request(sizeof(struct malloc_segment));
char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
size_t offset = align_offset(chunk2mem(rawsp));
char* asp = rawsp + offset;
char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;
mchunkptr sp = (mchunkptr)csp;
msegmentptr ss = (msegmentptr)(chunk2mem(sp));
mchunkptr tnext = chunk_plus_offset(sp, ssize);
mchunkptr p = tnext;
int nfences = 0;
/* reset top to new space */
init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
/* Set up segment record */
assert(is_aligned(ss));
set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
*ss = m->seg; /* Push current record */
m->seg.base = tbase;
m->seg.size = tsize;
m->seg.sflags = mmapped;
m->seg.next = ss;
/* Insert trailing fenceposts */
for (;;) {
mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
p->head = FENCEPOST_HEAD;
++nfences;
if ((char*)(&(nextp->head)) < old_end)
p = nextp;
else
break;
}
assert(nfences >= 2);
/* Insert the rest of old top into a bin as an ordinary free chunk */
if (csp != old_top) {
mchunkptr q = (mchunkptr)old_top;
size_t psize = csp - old_top;
mchunkptr tn = chunk_plus_offset(q, psize);
set_free_with_pinuse(q, psize, tn);
insert_chunk(m, q, psize);
}
check_top_chunk(m, m->top);
}
/* -------------------------- System allocation -------------------------- */
/* Get memory from system using MORECORE or MMAP */
static void* sys_alloc(mstate m, size_t nb) {
char* tbase = CMFAIL;
size_t tsize = 0;
flag_t mmap_flag = 0;
init_mparams();
/* Directly map large chunks */
if (use_mmap(m) && nb >= mparams.mmap_threshold) {
void* mem = mmap_alloc(m, nb);
if (mem != 0)
return mem;
}
/*
Try getting memory in any of three ways (in most-preferred to
least-preferred order):
1. A call to MORECORE that can normally contiguously extend memory.
(disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or
or main space is mmapped or a previous contiguous call failed)
2. A call to MMAP new space (disabled if not HAVE_MMAP).
Note that under the default settings, if MORECORE is unable to
fulfill a request, and HAVE_MMAP is true, then mmap is
used as a noncontiguous system allocator. This is a useful backup
strategy for systems with holes in address spaces -- in this case
sbrk cannot contiguously expand the heap, but mmap may be able to
find space.
3. A call to MORECORE that cannot usually contiguously extend memory.
(disabled if not HAVE_MORECORE)
*/
if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {
char* br = CMFAIL;
msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top);
size_t asize = 0;
ACQUIRE_MORECORE_LOCK();
if (ss == 0) { /* First time through or recovery */
char* base = (char*)CALL_MORECORE(0);
if (base != CMFAIL) {
asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE);
/* Adjust to end on a page boundary */
if (!is_page_aligned(base))
asize += (page_align((size_t)base) - (size_t)base);
/* Can't call MORECORE if size is negative when treated as signed */
if (asize < HALF_MAX_SIZE_T &&
(br = (char*)(CALL_MORECORE(asize))) == base) {
tbase = base;
tsize = asize;
}
}
}
else {
/* Subtract out existing available top space from MORECORE request. */
asize = granularity_align(nb - m->topsize + TOP_FOOT_SIZE + SIZE_T_ONE);
/* Use mem here only if it did continuously extend old space */
if (asize < HALF_MAX_SIZE_T &&
(br = (char*)(CALL_MORECORE(asize))) == ss->base+ss->size) {
tbase = br;
tsize = asize;
}
}
if (tbase == CMFAIL) { /* Cope with partial failure */
if (br != CMFAIL) { /* Try to use/extend the space we did get */
if (asize < HALF_MAX_SIZE_T &&
asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) {
size_t esize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE - asize);
if (esize < HALF_MAX_SIZE_T) {
char* end = (char*)CALL_MORECORE(esize);
if (end != CMFAIL)
asize += esize;
else { /* Can't use; try to release */
(void) CALL_MORECORE(-asize);
br = CMFAIL;
}
}
}
}
if (br != CMFAIL) { /* Use the space we did get */
tbase = br;
tsize = asize;
}
else
disable_contiguous(m); /* Don't try contiguous path in the future */
}
RELEASE_MORECORE_LOCK();
}
if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */
size_t req = nb + TOP_FOOT_SIZE + SIZE_T_ONE;
size_t rsize = granularity_align(req);
if (rsize > nb) { /* Fail if wraps around zero */
char* mp = (char*)(CALL_MMAP(rsize));
if (mp != CMFAIL) {
tbase = mp;
tsize = rsize;
mmap_flag = IS_MMAPPED_BIT;
}
}
}
if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */
size_t asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE);
if (asize < HALF_MAX_SIZE_T) {
char* br = CMFAIL;
char* end = CMFAIL;
ACQUIRE_MORECORE_LOCK();
br = (char*)(CALL_MORECORE(asize));
end = (char*)(CALL_MORECORE(0));
RELEASE_MORECORE_LOCK();
if (br != CMFAIL && end != CMFAIL && br < end) {
size_t ssize = end - br;
if (ssize > nb + TOP_FOOT_SIZE) {
tbase = br;
tsize = ssize;
}
}
}
}
if (tbase != CMFAIL) {
if ((m->footprint += tsize) > m->max_footprint)
m->max_footprint = m->footprint;
if (!is_initialized(m)) { /* first-time initialization */
m->seg.base = m->least_addr = tbase;
m->seg.size = tsize;
m->seg.sflags = mmap_flag;
m->magic = mparams.magic;
m->release_checks = MAX_RELEASE_CHECK_RATE;
init_bins(m);
#if !ONLY_MSPACES
if (is_global(m))
init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
else
#endif
{
/* Offset top by embedded malloc_state */
mchunkptr mn = next_chunk(mem2chunk(m));
init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);
}
}
else {
/* Try to merge with an existing segment */
msegmentptr sp = &m->seg;
/* Only consider most recent segment if traversal suppressed */
while (sp != 0 && tbase != sp->base + sp->size)
sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
if (sp != 0 &&
!is_extern_segment(sp) &&
(sp->sflags & IS_MMAPPED_BIT) == mmap_flag &&
segment_holds(sp, m->top)) { /* append */
sp->size += tsize;
init_top(m, m->top, m->topsize + tsize);
}
else {
if (tbase < m->least_addr)
m->least_addr = tbase;
sp = &m->seg;
while (sp != 0 && sp->base != tbase + tsize)
sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
if (sp != 0 &&
!is_extern_segment(sp) &&
(sp->sflags & IS_MMAPPED_BIT) == mmap_flag) {
char* oldbase = sp->base;
sp->base = tbase;
sp->size += tsize;
return prepend_alloc(m, tbase, oldbase, nb);
}
else
add_segment(m, tbase, tsize, mmap_flag);
}
}
if (nb < m->topsize) { /* Allocate from new or extended top space */
size_t rsize = m->topsize -= nb;
mchunkptr p = m->top;
mchunkptr r = m->top = chunk_plus_offset(p, nb);
r->head = rsize | PINUSE_BIT;
set_size_and_pinuse_of_inuse_chunk(m, p, nb);
check_top_chunk(m, m->top);
check_malloced_chunk(m, chunk2mem(p), nb);
return chunk2mem(p);
}
}
MALLOC_FAILURE_ACTION;
return 0;
}
/* ----------------------- system deallocation -------------------------- */
/* Unmap and unlink any mmapped segments that don't contain used chunks */
static size_t release_unused_segments(mstate m) {
size_t released = 0;
int nsegs = 0;
msegmentptr pred = &m->seg;
msegmentptr sp = pred->next;
while (sp != 0) {
char* base = sp->base;
size_t size = sp->size;
msegmentptr next = sp->next;
++nsegs;
if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
mchunkptr p = align_as_chunk(base);
size_t psize = chunksize(p);
/* Can unmap if first chunk holds entire segment and not pinned */
if (!cinuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {
tchunkptr tp = (tchunkptr)p;
assert(segment_holds(sp, (char*)sp));
if (p == m->dv) {
m->dv = 0;
m->dvsize = 0;
}
else {
unlink_large_chunk(m, tp);
}
if (CALL_MUNMAP(base, size) == 0) {
released += size;
m->footprint -= size;
/* unlink obsoleted record */
sp = pred;
sp->next = next;
}
else { /* back out if cannot unmap */
insert_large_chunk(m, tp, psize);
}
}
}
if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */
break;
pred = sp;
sp = next;
}
/* Reset check counter */
m->release_checks = ((nsegs > MAX_RELEASE_CHECK_RATE)?
nsegs : MAX_RELEASE_CHECK_RATE);
return released;
}
static int sys_trim(mstate m, size_t pad) {
size_t released = 0;
if (pad < MAX_REQUEST && is_initialized(m)) {
pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */
if (m->topsize > pad) {
/* Shrink top space in granularity-size units, keeping at least one */
size_t unit = mparams.granularity;
size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
SIZE_T_ONE) * unit;
msegmentptr sp = segment_holding(m, (char*)m->top);
if (!is_extern_segment(sp)) {
if (is_mmapped_segment(sp)) {
if (HAVE_MMAP &&
sp->size >= extra &&
!has_segment_link(m, sp)) { /* can't shrink if pinned */
size_t newsize = sp->size - extra;
/* Prefer mremap, fall back to munmap */
if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||
(CALL_MUNMAP(sp->base + newsize, extra) == 0)) {
released = extra;
}
}
}
else if (HAVE_MORECORE) {
if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */
extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;
ACQUIRE_MORECORE_LOCK();
{
/* Make sure end of memory is where we last set it. */
char* old_br = (char*)(CALL_MORECORE(0));
if (old_br == sp->base + sp->size) {
char* rel_br = (char*)(CALL_MORECORE(-extra));
char* new_br = (char*)(CALL_MORECORE(0));
if (rel_br != CMFAIL && new_br < old_br)
released = old_br - new_br;
}
}
RELEASE_MORECORE_LOCK();
}
}
if (released != 0) {
sp->size -= released;
m->footprint -= released;
init_top(m, m->top, m->topsize - released);
check_top_chunk(m, m->top);
}
}
/* Unmap any unused mmapped segments */
if (HAVE_MMAP)
released += release_unused_segments(m);
/* On failure, disable autotrim to avoid repeated failed future calls */
if (released == 0 && m->topsize > m->trim_check)
m->trim_check = MAX_SIZE_T;
}
return (released != 0)? 1 : 0;
}
/* ---------------------------- malloc support --------------------------- */
/* allocate a large request from the best fitting chunk in a treebin */
static void* tmalloc_large(mstate m, size_t nb) {
tchunkptr v = 0;
size_t rsize = -nb; /* Unsigned negation */
tchunkptr t;
bindex_t idx;
compute_tree_index(nb, idx);
if ((t = *treebin_at(m, idx)) != 0) {
/* Traverse tree for this bin looking for node with size == nb */
size_t sizebits = nb << leftshift_for_tree_index(idx);
tchunkptr rst = 0; /* The deepest untaken right subtree */
for (;;) {
tchunkptr rt;
size_t trem = chunksize(t) - nb;
if (trem < rsize) {
v = t;
if ((rsize = trem) == 0)
break;
}
rt = t->child[1];
t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
if (rt != 0 && rt != t)
rst = rt;
if (t == 0) {
t = rst; /* set t to least subtree holding sizes > nb */
break;
}
sizebits <<= 1;
}
}
if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */
binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
if (leftbits != 0) {
bindex_t i;
binmap_t leastbit = least_bit(leftbits);
compute_bit2idx(leastbit, i);
t = *treebin_at(m, i);
}
}
while (t != 0) { /* find smallest of tree or subtree */
size_t trem = chunksize(t) - nb;
if (trem < rsize) {
rsize = trem;
v = t;
}
t = leftmost_child(t);
}
/* If dv is a better fit, return 0 so malloc will use it */
if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {
if (RTCHECK(ok_address(m, v))) { /* split */
mchunkptr r = chunk_plus_offset(v, nb);
assert(chunksize(v) == rsize + nb);
if (RTCHECK(ok_next(v, r))) {
unlink_large_chunk(m, v);
if (rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(m, v, (rsize + nb));
else {
set_size_and_pinuse_of_inuse_chunk(m, v, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
insert_chunk(m, r, rsize);
}
return chunk2mem(v);
}
}
CORRUPTION_ERROR_ACTION(m);
}
return 0;
}
/* allocate a small request from the best fitting chunk in a treebin */
static void* tmalloc_small(mstate m, size_t nb) {
tchunkptr t, v;
size_t rsize;
bindex_t i;
binmap_t leastbit = least_bit(m->treemap);
compute_bit2idx(leastbit, i);
v = t = *treebin_at(m, i);
rsize = chunksize(t) - nb;
while ((t = leftmost_child(t)) != 0) {
size_t trem = chunksize(t) - nb;
if (trem < rsize) {
rsize = trem;
v = t;
}
}
if (RTCHECK(ok_address(m, v))) {
mchunkptr r = chunk_plus_offset(v, nb);
assert(chunksize(v) == rsize + nb);
if (RTCHECK(ok_next(v, r))) {
unlink_large_chunk(m, v);
if (rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(m, v, (rsize + nb));
else {
set_size_and_pinuse_of_inuse_chunk(m, v, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
replace_dv(m, r, rsize);
}
return chunk2mem(v);
}
}
CORRUPTION_ERROR_ACTION(m);
return 0;
}
/* --------------------------- realloc support --------------------------- */
static void* internal_realloc(mstate m, void* oldmem, size_t bytes) {
if (bytes >= MAX_REQUEST) {
MALLOC_FAILURE_ACTION;
return 0;
}
if (!PREACTION(m)) {
mchunkptr oldp = mem2chunk(oldmem);
size_t oldsize = chunksize(oldp);
mchunkptr next = chunk_plus_offset(oldp, oldsize);
mchunkptr newp = 0;
void* extra = 0;
/* Try to either shrink or extend into top. Else malloc-copy-free */
if (RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) &&
ok_next(oldp, next) && ok_pinuse(next))) {
size_t nb = request2size(bytes);
if (is_mmapped(oldp))
newp = mmap_resize(m, oldp, nb);
else if (oldsize >= nb) { /* already big enough */
size_t rsize = oldsize - nb;
newp = oldp;
if (rsize >= MIN_CHUNK_SIZE) {
mchunkptr remainder = chunk_plus_offset(newp, nb);
set_inuse(m, newp, nb);
set_inuse(m, remainder, rsize);
extra = chunk2mem(remainder);
}
}
else if (next == m->top && oldsize + m->topsize > nb) {
/* Expand into top */
size_t newsize = oldsize + m->topsize;
size_t newtopsize = newsize - nb;
mchunkptr newtop = chunk_plus_offset(oldp, nb);
set_inuse(m, oldp, nb);
newtop->head = newtopsize |PINUSE_BIT;
m->top = newtop;
m->topsize = newtopsize;
newp = oldp;
}
}
else {
USAGE_ERROR_ACTION(m, oldmem);
POSTACTION(m);
return 0;
}
POSTACTION(m);
if (newp != 0) {
if (extra != 0) {
internal_free(m, extra);
}
check_inuse_chunk(m, newp);
return chunk2mem(newp);
}
else {
void* newmem = internal_malloc(m, bytes);
if (newmem != 0) {
size_t oc = oldsize - overhead_for(oldp);
memcpy(newmem, oldmem, (oc < bytes)? oc : bytes);
internal_free(m, oldmem);
}
return newmem;
}
}
return 0;
}
/* --------------------------- memalign support -------------------------- */
static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {
if (alignment <= MALLOC_ALIGNMENT) /* Can just use malloc */
return internal_malloc(m, bytes);
if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */
alignment = MIN_CHUNK_SIZE;
if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */
size_t a = MALLOC_ALIGNMENT << 1;
while (a < alignment) a <<= 1;
alignment = a;
}
if (bytes >= MAX_REQUEST - alignment) {
if (m != 0) { /* Test isn't needed but avoids compiler warning */
MALLOC_FAILURE_ACTION;
}
}
else {
size_t nb = request2size(bytes);
size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
char* mem = (char*)internal_malloc(m, req);
if (mem != 0) {
void* leader = 0;
void* trailer = 0;
mchunkptr p = mem2chunk(mem);
if (PREACTION(m)) return 0;
if ((((size_t)(mem)) % alignment) != 0) { /* misaligned */
/*
Find an aligned spot inside chunk. Since we need to give
back leading space in a chunk of at least MIN_CHUNK_SIZE, if
the first calculation places us at a spot with less than
MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
We've allocated enough total room so that this is always
possible.
*/
char* br = (char*)mem2chunk((size_t)(((size_t)(mem +
alignment -
SIZE_T_ONE)) &
-alignment));
char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?
br : br+alignment;
mchunkptr newp = (mchunkptr)pos;
size_t leadsize = pos - (char*)(p);
size_t newsize = chunksize(p) - leadsize;
if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */
newp->prev_foot = p->prev_foot + leadsize;
newp->head = (newsize|CINUSE_BIT);
}
else { /* Otherwise, give back leader, use the rest */
set_inuse(m, newp, newsize);
set_inuse(m, p, leadsize);
leader = chunk2mem(p);
}
p = newp;
}
/* Give back spare room at the end */
if (!is_mmapped(p)) {
size_t size = chunksize(p);
if (size > nb + MIN_CHUNK_SIZE) {
size_t remainder_size = size - nb;
mchunkptr remainder = chunk_plus_offset(p, nb);
set_inuse(m, p, nb);
set_inuse(m, remainder, remainder_size);
trailer = chunk2mem(remainder);
}
}
assert (chunksize(p) >= nb);
assert((((size_t)(chunk2mem(p))) % alignment) == 0);
check_inuse_chunk(m, p);
POSTACTION(m);
if (leader != 0) {
internal_free(m, leader);
}
if (trailer != 0) {
internal_free(m, trailer);
}
return chunk2mem(p);
}
}
return 0;
}
/* ------------------------ comalloc/coalloc support --------------------- */
static void** ialloc(mstate m,
size_t n_elements,
size_t* sizes,
int opts,
void* chunks[]) {
/*
This provides common support for independent_X routines, handling
all of the combinations that can result.
The opts arg has:
bit 0 set if all elements are same size (using sizes[0])
bit 1 set if elements should be zeroed
*/
size_t element_size; /* chunksize of each element, if all same */
size_t contents_size; /* total size of elements */
size_t array_size; /* request size of pointer array */
void* mem; /* malloced aggregate space */
mchunkptr p; /* corresponding chunk */
size_t remainder_size; /* remaining bytes while splitting */
void** marray; /* either "chunks" or malloced ptr array */
mchunkptr array_chunk; /* chunk for malloced ptr array */
flag_t was_enabled; /* to disable mmap */
size_t size;
size_t i;
/* compute array length, if needed */
if (chunks != 0) {
if (n_elements == 0)
return chunks; /* nothing to do */
marray = chunks;
array_size = 0;
}
else {
/* if empty req, must still return chunk representing empty array */
if (n_elements == 0)
return (void**)internal_malloc(m, 0);
marray = 0;
array_size = request2size(n_elements * (sizeof(void*)));
}
/* compute total element size */
if (opts & 0x1) { /* all-same-size */
element_size = request2size(*sizes);
contents_size = n_elements * element_size;
}
else { /* add up all the sizes */
element_size = 0;
contents_size = 0;
for (i = 0; i != n_elements; ++i)
contents_size += request2size(sizes[i]);
}
size = contents_size + array_size;
/*
Allocate the aggregate chunk. First disable direct-mmapping so
malloc won't use it, since we would not be able to later
free/realloc space internal to a segregated mmap region.
*/
was_enabled = use_mmap(m);
disable_mmap(m);
mem = internal_malloc(m, size - CHUNK_OVERHEAD);
if (was_enabled)
enable_mmap(m);
if (mem == 0)
return 0;
if (PREACTION(m)) return 0;
p = mem2chunk(mem);
remainder_size = chunksize(p);
assert(!is_mmapped(p));
if (opts & 0x2) { /* optionally clear the elements */
memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size);
}
/* If not provided, allocate the pointer array as final part of chunk */
if (marray == 0) {
size_t array_chunk_size;
array_chunk = chunk_plus_offset(p, contents_size);
array_chunk_size = remainder_size - contents_size;
marray = (void**) (chunk2mem(array_chunk));
set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);
remainder_size = contents_size;
}
/* split out elements */
for (i = 0; ; ++i) {
marray[i] = chunk2mem(p);
if (i != n_elements-1) {
if (element_size != 0)
size = element_size;
else
size = request2size(sizes[i]);
remainder_size -= size;
set_size_and_pinuse_of_inuse_chunk(m, p, size);
p = chunk_plus_offset(p, size);
}
else { /* the final element absorbs any overallocation slop */
set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);
break;
}
}
#if DEBUG
if (marray != chunks) {
/* final element must have exactly exhausted chunk */
if (element_size != 0) {
assert(remainder_size == element_size);
}
else {
assert(remainder_size == request2size(sizes[i]));
}
check_inuse_chunk(m, mem2chunk(marray));
}
for (i = 0; i != n_elements; ++i)
check_inuse_chunk(m, mem2chunk(marray[i]));
#endif /* DEBUG */
POSTACTION(m);
return marray;
}
/* -------------------------- public routines ---------------------------- */
#if !ONLY_MSPACES
void* dlmalloc(size_t bytes) {
/*
Basic algorithm:
If a small request (< 256 bytes minus per-chunk overhead):
1. If one exists, use a remainderless chunk in associated smallbin.
(Remainderless means that there are too few excess bytes to
represent as a chunk.)
2. If it is big enough, use the dv chunk, which is normally the
chunk adjacent to the one used for the most recent small request.
3. If one exists, split the smallest available chunk in a bin,
saving remainder in dv.
4. If it is big enough, use the top chunk.
5. If available, get memory from system and use it
Otherwise, for a large request:
1. Find the smallest available binned chunk that fits, and use it
if it is better fitting than dv chunk, splitting if necessary.
2. If better fitting than any binned chunk, use the dv chunk.
3. If it is big enough, use the top chunk.
4. If request size >= mmap threshold, try to directly mmap this chunk.
5. If available, get memory from system and use it
The ugly goto's here ensure that postaction occurs along all paths.
*/
if (!PREACTION(gm)) {
void* mem;
size_t nb;
if (bytes <= MAX_SMALL_REQUEST) {
bindex_t idx;
binmap_t smallbits;
nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
idx = small_index(nb);
smallbits = gm->smallmap >> idx;
if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
mchunkptr b, p;
idx += ~smallbits & 1; /* Uses next bin if idx empty */
b = smallbin_at(gm, idx);
p = b->fd;
assert(chunksize(p) == small_index2size(idx));
unlink_first_small_chunk(gm, b, p, idx);
set_inuse_and_pinuse(gm, p, small_index2size(idx));
mem = chunk2mem(p);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
else if (nb > gm->dvsize) {
if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
mchunkptr b, p, r;
size_t rsize;
bindex_t i;
binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
binmap_t leastbit = least_bit(leftbits);
compute_bit2idx(leastbit, i);
b = smallbin_at(gm, i);
p = b->fd;
assert(chunksize(p) == small_index2size(i));
unlink_first_small_chunk(gm, b, p, i);
rsize = small_index2size(i) - nb;
/* Fit here cannot be remainderless if 4byte sizes */
if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(gm, p, small_index2size(i));
else {
set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
r = chunk_plus_offset(p, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
replace_dv(gm, r, rsize);
}
mem = chunk2mem(p);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) {
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
}
}
else if (bytes >= MAX_REQUEST)
nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
else {
nb = pad_request(bytes);
if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
}
if (nb <= gm->dvsize) {
size_t rsize = gm->dvsize - nb;
mchunkptr p = gm->dv;
if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
mchunkptr r = gm->dv = chunk_plus_offset(p, nb);
gm->dvsize = rsize;
set_size_and_pinuse_of_free_chunk(r, rsize);
set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
}
else { /* exhaust dv */
size_t dvs = gm->dvsize;
gm->dvsize = 0;
gm->dv = 0;
set_inuse_and_pinuse(gm, p, dvs);
}
mem = chunk2mem(p);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
else if (nb < gm->topsize) { /* Split top */
size_t rsize = gm->topsize -= nb;
mchunkptr p = gm->top;
mchunkptr r = gm->top = chunk_plus_offset(p, nb);
r->head = rsize | PINUSE_BIT;
set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
mem = chunk2mem(p);
check_top_chunk(gm, gm->top);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
mem = sys_alloc(gm, nb);
postaction:
POSTACTION(gm);
return mem;
}
return 0;
}
void dlfree(void* mem) {
/*
Consolidate freed chunks with preceeding or succeeding bordering
free chunks, if they exist, and then place in a bin. Intermixed
with special cases for top, dv, mmapped chunks, and usage errors.
*/
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
#if FOOTERS
mstate fm = get_mstate_for(p);
if (!ok_magic(fm)) {
USAGE_ERROR_ACTION(fm, p);
return;
}
#else /* FOOTERS */
#define fm gm
#endif /* FOOTERS */
if (!PREACTION(fm)) {
check_inuse_chunk(fm, p);
if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
size_t psize = chunksize(p);
mchunkptr next = chunk_plus_offset(p, psize);
if (!pinuse(p)) {
size_t prevsize = p->prev_foot;
if ((prevsize & IS_MMAPPED_BIT) != 0) {
prevsize &= ~IS_MMAPPED_BIT;
psize += prevsize + MMAP_FOOT_PAD;
if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
fm->footprint -= psize;
goto postaction;
}
else {
mchunkptr prev = chunk_minus_offset(p, prevsize);
psize += prevsize;
p = prev;
if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
if (p != fm->dv) {
unlink_chunk(fm, p, prevsize);
}
else if ((next->head & INUSE_BITS) == INUSE_BITS) {
fm->dvsize = psize;
set_free_with_pinuse(p, psize, next);
goto postaction;
}
}
else
goto erroraction;
}
}
if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
if (!cinuse(next)) { /* consolidate forward */
if (next == fm->top) {
size_t tsize = fm->topsize += psize;
fm->top = p;
p->head = tsize | PINUSE_BIT;
if (p == fm->dv) {
fm->dv = 0;
fm->dvsize = 0;
}
if (should_trim(fm, tsize))
sys_trim(fm, 0);
goto postaction;
}
else if (next == fm->dv) {
size_t dsize = fm->dvsize += psize;
fm->dv = p;
set_size_and_pinuse_of_free_chunk(p, dsize);
goto postaction;
}
else {
size_t nsize = chunksize(next);
psize += nsize;
unlink_chunk(fm, next, nsize);
set_size_and_pinuse_of_free_chunk(p, psize);
if (p == fm->dv) {
fm->dvsize = psize;
goto postaction;
}
}
}
else
set_free_with_pinuse(p, psize, next);
if (is_small(psize)) {
insert_small_chunk(fm, p, psize);
check_free_chunk(fm, p);
}
else {
tchunkptr tp = (tchunkptr)p;
insert_large_chunk(fm, tp, psize);
check_free_chunk(fm, p);
if (--fm->release_checks == 0)
release_unused_segments(fm);
}
goto postaction;
}
}
erroraction:
USAGE_ERROR_ACTION(fm, p);
postaction:
POSTACTION(fm);
}
}
#if !FOOTERS
#undef fm
#endif /* FOOTERS */
}
void* dlcalloc(size_t n_elements, size_t elem_size) {
void* mem;
size_t req = 0;
if (n_elements != 0) {
req = n_elements * elem_size;
if (((n_elements | elem_size) & ~(size_t)0xffff) &&
(req / n_elements != elem_size))
req = MAX_SIZE_T; /* force downstream failure on overflow */
}
mem = dlmalloc(req);
if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
memset(mem, 0, req);
return mem;
}
void* dlrealloc(void* oldmem, size_t bytes) {
if (oldmem == 0)
return dlmalloc(bytes);
#ifdef REALLOC_ZERO_BYTES_FREES
if (bytes == 0) {
dlfree(oldmem);
return 0;
}
#endif /* REALLOC_ZERO_BYTES_FREES */
else {
#if ! FOOTERS
mstate m = gm;
#else /* FOOTERS */
mstate m = get_mstate_for(mem2chunk(oldmem));
if (!ok_magic(m)) {
USAGE_ERROR_ACTION(m, oldmem);
return 0;
}
#endif /* FOOTERS */
return internal_realloc(m, oldmem, bytes);
}
}
void* dlmemalign(size_t alignment, size_t bytes) {
return internal_memalign(gm, alignment, bytes);
}
void** dlindependent_calloc(size_t n_elements, size_t elem_size,
void* chunks[]) {
size_t sz = elem_size; /* serves as 1-element array */
return ialloc(gm, n_elements, &sz, 3, chunks);
}
void** dlindependent_comalloc(size_t n_elements, size_t sizes[],
void* chunks[]) {
return ialloc(gm, n_elements, sizes, 0, chunks);
}
void* dlvalloc(size_t bytes) {
size_t pagesz;
init_mparams();
pagesz = mparams.page_size;
return dlmemalign(pagesz, bytes);
}
void* dlpvalloc(size_t bytes) {
size_t pagesz;
init_mparams();
pagesz = mparams.page_size;
return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
}
int dlmalloc_trim(size_t pad) {
int result = 0;
if (!PREACTION(gm)) {
result = sys_trim(gm, pad);
POSTACTION(gm);
}
return result;
}
size_t dlmalloc_footprint(void) {
return gm->footprint;
}
size_t dlmalloc_max_footprint(void) {
return gm->max_footprint;
}
#if !NO_MALLINFO
struct mallinfo dlmallinfo(void) {
return internal_mallinfo(gm);
}
#endif /* NO_MALLINFO */
void dlmalloc_stats() {
internal_malloc_stats(gm);
}
size_t dlmalloc_usable_size(void* mem) {
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
if (cinuse(p))
return chunksize(p) - overhead_for(p);
}
return 0;
}
int dlmallopt(int param_number, int value) {
return change_mparam(param_number, value);
}
#endif /* !ONLY_MSPACES */
/* ----------------------------- user mspaces ---------------------------- */
#if MSPACES
static mstate init_user_mstate(char* tbase, size_t tsize) {
size_t msize = pad_request(sizeof(struct malloc_state));
mchunkptr mn;
mchunkptr msp = align_as_chunk(tbase);
mstate m = (mstate)(chunk2mem(msp));
memset(m, 0, msize);
INITIAL_LOCK(&m->mutex);
msp->head = (msize|PINUSE_BIT|CINUSE_BIT);
m->seg.base = m->least_addr = tbase;
m->seg.size = m->footprint = m->max_footprint = tsize;
m->magic = mparams.magic;
m->release_checks = MAX_RELEASE_CHECK_RATE;
m->mflags = mparams.default_mflags;
m->extp = 0;
m->exts = 0;
disable_contiguous(m);
init_bins(m);
mn = next_chunk(mem2chunk(m));
init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE);
check_top_chunk(m, m->top);
return m;
}
mspace create_mspace(size_t capacity, int locked) {
mstate m = 0;
size_t msize = pad_request(sizeof(struct malloc_state));
init_mparams(); /* Ensure pagesize etc initialized */
if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
size_t rs = ((capacity == 0)? mparams.granularity :
(capacity + TOP_FOOT_SIZE + msize));
size_t tsize = granularity_align(rs);
char* tbase = (char*)(CALL_MMAP(tsize));
if (tbase != CMFAIL) {
m = init_user_mstate(tbase, tsize);
m->seg.sflags = IS_MMAPPED_BIT;
set_lock(m, locked);
}
}
return (mspace)m;
}
mspace create_mspace_with_base(void* base, size_t capacity, int locked) {
mstate m = 0;
size_t msize = pad_request(sizeof(struct malloc_state));
init_mparams(); /* Ensure pagesize etc initialized */
if (capacity > msize + TOP_FOOT_SIZE &&
capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
m = init_user_mstate((char*)base, capacity);
m->seg.sflags = EXTERN_BIT;
set_lock(m, locked);
}
return (mspace)m;
}
size_t destroy_mspace(mspace msp) {
size_t freed = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
msegmentptr sp = &ms->seg;
while (sp != 0) {
char* base = sp->base;
size_t size = sp->size;
flag_t flag = sp->sflags;
sp = sp->next;
if ((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) &&
CALL_MUNMAP(base, size) == 0)
freed += size;
(void)base;
}
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return freed;
}
/*
mspace versions of routines are near-clones of the global
versions. This is not so nice but better than the alternatives.
*/
//#include <iostream> // TB edit
void* mspace_malloc(mspace msp, size_t bytes) {
mstate ms = (mstate)msp;
#if defined(__KERNEL__) && !defined(__STANDALONE__)
//printk(KERN_INFO "mspace_malloc called.\n");
#else // #if defined(__KERNEL__) && !defiend(__STANDALONE__)
//printf("mspace_malloc called.\n");
#endif // else from #if defined(__KERNEL__) && !defiend(__STANDALONE__)
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
//printk(KERN_INFO "MSPACE here.\n");
if (!PREACTION(ms)) {
//printk(KERN_INFO "MSPACE here2.\n");
void* mem;
size_t nb;
if (bytes <= MAX_SMALL_REQUEST) {
bindex_t idx;
binmap_t smallbits;
nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
idx = small_index(nb);
smallbits = ms->smallmap >> idx;
if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
mchunkptr b, p;
idx += ~smallbits & 1; /* Uses next bin if idx empty */
b = smallbin_at(ms, idx);
p = b->fd;
assert(chunksize(p) == small_index2size(idx));
unlink_first_small_chunk(ms, b, p, idx);
set_inuse_and_pinuse(ms, p, small_index2size(idx));
mem = chunk2mem(p);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
else if (nb > ms->dvsize) {
if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
mchunkptr b, p, r;
size_t rsize;
bindex_t i;
binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
binmap_t leastbit = least_bit(leftbits);
compute_bit2idx(leastbit, i);
b = smallbin_at(ms, i);
p = b->fd;
assert(chunksize(p) == small_index2size(i));
unlink_first_small_chunk(ms, b, p, i);
rsize = small_index2size(i) - nb;
/* Fit here cannot be remainderless if 4byte sizes */
if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(ms, p, small_index2size(i));
else {
set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
r = chunk_plus_offset(p, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
replace_dv(ms, r, rsize);
}
mem = chunk2mem(p);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) {
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
}
}
else if (bytes >= MAX_REQUEST)
nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
else {
nb = pad_request(bytes);
if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
}
if (nb <= ms->dvsize) {
size_t rsize = ms->dvsize - nb;
mchunkptr p = ms->dv;
if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
mchunkptr r = ms->dv = chunk_plus_offset(p, nb);
ms->dvsize = rsize;
set_size_and_pinuse_of_free_chunk(r, rsize);
set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
}
else { /* exhaust dv */
size_t dvs = ms->dvsize;
ms->dvsize = 0;
ms->dv = 0;
set_inuse_and_pinuse(ms, p, dvs);
}
mem = chunk2mem(p);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
else if (nb < ms->topsize) { /* Split top */
size_t rsize = ms->topsize -= nb;
mchunkptr p = ms->top;
mchunkptr r = ms->top = chunk_plus_offset(p, nb);
r->head = rsize | PINUSE_BIT;
set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
mem = chunk2mem(p);
check_top_chunk(ms, ms->top);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
mem = sys_alloc(ms, nb);
postaction:
POSTACTION(ms);
return mem;
}
return 0;
}
void mspace_free(mspace msp, void* mem) {
if (mem != 0) {
mchunkptr p;
mstate fm;
#if defined(__KERNEL__) && !defined(__STANDALONE__)
//printk("free\n");
#else // #if defined(__KERNEL__) && !defiend(__STANDALONE__)
//printf("free\n");
#endif // #if defined(__KERNEL__) && !defiend(__STANDALONE__)
p = mem2chunk(mem);
#if FOOTERS
fm = get_mstate_for(p);
#else /* FOOTERS */
fm = (mstate)msp;
#endif /* FOOTERS */
if (!ok_magic(fm)) {
USAGE_ERROR_ACTION(fm, p);
return;
}
if (!PREACTION(fm)) {
check_inuse_chunk(fm, p);
if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
size_t psize = chunksize(p);
mchunkptr next = chunk_plus_offset(p, psize);
if (!pinuse(p)) {
size_t prevsize = p->prev_foot;
if ((prevsize & IS_MMAPPED_BIT) != 0) {
prevsize &= ~IS_MMAPPED_BIT;
psize += prevsize + MMAP_FOOT_PAD;
if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
fm->footprint -= psize;
goto postaction;
}
else {
mchunkptr prev = chunk_minus_offset(p, prevsize);
psize += prevsize;
p = prev;
if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
if (p != fm->dv) {
unlink_chunk(fm, p, prevsize);
}
else if ((next->head & INUSE_BITS) == INUSE_BITS) {
fm->dvsize = psize;
set_free_with_pinuse(p, psize, next);
goto postaction;
}
}
else
goto erroraction;
}
}
if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
if (!cinuse(next)) { /* consolidate forward */
if (next == fm->top) {
size_t tsize = fm->topsize += psize;
fm->top = p;
p->head = tsize | PINUSE_BIT;
if (p == fm->dv) {
fm->dv = 0;
fm->dvsize = 0;
}
if (should_trim(fm, tsize))
sys_trim(fm, 0);
goto postaction;
}
else if (next == fm->dv) {
size_t dsize = fm->dvsize += psize;
fm->dv = p;
set_size_and_pinuse_of_free_chunk(p, dsize);
goto postaction;
}
else {
size_t nsize = chunksize(next);
psize += nsize;
unlink_chunk(fm, next, nsize);
set_size_and_pinuse_of_free_chunk(p, psize);
if (p == fm->dv) {
fm->dvsize = psize;
goto postaction;
}
}
}
else
set_free_with_pinuse(p, psize, next);
if (is_small(psize)) {
insert_small_chunk(fm, p, psize);
check_free_chunk(fm, p);
}
else {
tchunkptr tp = (tchunkptr)p;
insert_large_chunk(fm, tp, psize);
check_free_chunk(fm, p);
if (--fm->release_checks == 0)
release_unused_segments(fm);
}
goto postaction;
}
}
erroraction:
USAGE_ERROR_ACTION(fm, p);
postaction:
POSTACTION(fm);
}
}
}
void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) {
void* mem;
size_t req = 0;
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
if (n_elements != 0) {
req = n_elements * elem_size;
if (((n_elements | elem_size) & ~(size_t)0xffff) &&
(req / n_elements != elem_size))
req = MAX_SIZE_T; /* force downstream failure on overflow */
}
mem = internal_malloc(ms, req);
if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
memset(mem, 0, req);
return mem;
}
void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) {
if (oldmem == 0)
return mspace_malloc(msp, bytes);
#ifdef REALLOC_ZERO_BYTES_FREES
if (bytes == 0) {
mspace_free(msp, oldmem);
return 0;
}
#endif /* REALLOC_ZERO_BYTES_FREES */
else {
#if FOOTERS
mchunkptr p = mem2chunk(oldmem);
mstate ms = get_mstate_for(p);
#else /* FOOTERS */
mstate ms = (mstate)msp;
#endif /* FOOTERS */
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
return internal_realloc(ms, oldmem, bytes);
}
}
void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
return internal_memalign(ms, alignment, bytes);
}
void** mspace_independent_calloc(mspace msp, size_t n_elements,
size_t elem_size, void* chunks[]) {
size_t sz = elem_size; /* serves as 1-element array */
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
return ialloc(ms, n_elements, &sz, 3, chunks);
}
void** mspace_independent_comalloc(mspace msp, size_t n_elements,
size_t sizes[], void* chunks[]) {
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
return ialloc(ms, n_elements, sizes, 0, chunks);
}
int mspace_trim(mspace msp, size_t pad) {
int result = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
if (!PREACTION(ms)) {
result = sys_trim(ms, pad);
POSTACTION(ms);
}
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return result;
}
void mspace_malloc_stats(mspace msp) {
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
internal_malloc_stats(ms);
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
}
size_t mspace_footprint(mspace msp) {
size_t result = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
result = ms->footprint;
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return result;
}
size_t mspace_max_footprint(mspace msp) {
size_t result = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
result = ms->max_footprint;
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return result;
}
#if !NO_MALLINFO
struct mallinfo mspace_mallinfo(mspace msp) {
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
}
return internal_mallinfo(ms);
}
#endif /* NO_MALLINFO */
size_t mspace_usable_size(void* mem) {
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
if (cinuse(p))
return chunksize(p) - overhead_for(p);
}
return 0;
}
int mspace_mallopt(int param_number, int value) {
return change_mparam(param_number, value);
}
#endif /* MSPACES */
/* -------------------- Alternative MORECORE functions ------------------- */
/*
Guidelines for creating a custom version of MORECORE:
* For best performance, MORECORE should allocate in multiples of pagesize.
* MORECORE may allocate more memory than requested. (Or even less,
but this will usually result in a malloc failure.)
* MORECORE must not allocate memory when given argument zero, but
instead return one past the end address of memory from previous
nonzero call.
* For best performance, consecutive calls to MORECORE with positive
arguments should return increasing addresses, indicating that
space has been contiguously extended.
* Even though consecutive calls to MORECORE need not return contiguous
addresses, it must be OK for malloc'ed chunks to span multiple
regions in those cases where they do happen to be contiguous.
* MORECORE need not handle negative arguments -- it may instead
just return MFAIL when given negative arguments.
Negative arguments are always multiples of pagesize. MORECORE
must not misinterpret negative args as large positive unsigned
args. You can suppress all such calls from even occurring by defining
MORECORE_CANNOT_TRIM,
As an example alternative MORECORE, here is a custom allocator
kindly contributed for pre-OSX macOS. It uses virtually but not
necessarily physically contiguous non-paged memory (locked in,
present and won't get swapped out). You can use it by uncommenting
this section, adding some #includes, and setting up the appropriate
defines above:
#define MORECORE osMoreCore
There is also a shutdown routine that should somehow be called for
cleanup upon program exit.
#define MAX_POOL_ENTRIES 100
#define MINIMUM_MORECORE_SIZE (64 * 1024U)
static int next_os_pool;
void *our_os_pools[MAX_POOL_ENTRIES];
void *osMoreCore(int size)
{
void *ptr = 0;
static void *sbrk_top = 0;
if (size > 0)
{
if (size < MINIMUM_MORECORE_SIZE)
size = MINIMUM_MORECORE_SIZE;
if (CurrentExecutionLevel() == kTaskLevel)
ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
if (ptr == 0)
{
return (void *) MFAIL;
}
// save ptrs so they can be freed during cleanup
our_os_pools[next_os_pool] = ptr;
next_os_pool++;
ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
sbrk_top = (char *) ptr + size;
return ptr;
}
else if (size < 0)
{
// we don't currently support shrink behavior
return (void *) MFAIL;
}
else
{
return sbrk_top;
}
}
// cleanup any allocated memory pools
// called as last thing before shutting down driver
void osCleanupMem(void)
{
void **ptr;
for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
if (*ptr)
{
PoolDeallocate(*ptr);
*ptr = 0;
}
}
*/
/* -----------------------------------------------------------------------
History:
V2.8.4 (not yet released)
* Fix bad error check in mspace_footprint
* Adaptations for ptmalloc, courtesy of Wolfram Gloger.
* Reentrant spin locks, courtesy of Earl Chew and others
* Win32 improvements, courtesy of Niall Douglas and Earl Chew
* Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options
* Various small adjustments to reduce warnings on some compilers
* Extension hook in malloc_state
V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee)
* Add max_footprint functions
* Ensure all appropriate literals are size_t
* Fix conditional compilation problem for some #define settings
* Avoid concatenating segments with the one provided
in create_mspace_with_base
* Rename some variables to avoid compiler shadowing warnings
* Use explicit lock initialization.
* Better handling of sbrk interference.
* Simplify and fix segment insertion, trimming and mspace_destroy
* Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x
* Thanks especially to Dennis Flanagan for help on these.
V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee)
* Fix memalign brace error.
V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee)
* Fix improper #endif nesting in C++
* Add explicit casts needed for C++
V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee)
* Use trees for large bins
* Support mspaces
* Use segments to unify sbrk-based and mmap-based system allocation,
removing need for emulation on most platforms without sbrk.
* Default safety checks
* Optional footer checks. Thanks to William Robertson for the idea.
* Internal code refactoring
* Incorporate suggestions and platform-specific changes.
Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,
Aaron Bachmann, Emery Berger, and others.
* Speed up non-fastbin processing enough to remove fastbins.
* Remove useless cfree() to avoid conflicts with other apps.
* Remove internal memcpy, memset. Compilers handle builtins better.
* Remove some options that no one ever used and rename others.
V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)
* Fix malloc_state bitmap array misdeclaration
V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee)
* Allow tuning of FIRST_SORTED_BIN_SIZE
* Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
* Better detection and support for non-contiguousness of MORECORE.
Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
* Bypass most of malloc if no frees. Thanks To Emery Berger.
* Fix freeing of old top non-contiguous chunk im sysmalloc.
* Raised default trim and map thresholds to 256K.
* Fix mmap-related #defines. Thanks to Lubos Lunak.
* Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
* Branch-free bin calculation
* Default trim and mmap thresholds now 256K.
V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
* Introduce independent_comalloc and independent_calloc.
Thanks to Michael Pachos for motivation and help.
* Make optional .h file available
* Allow > 2GB requests on 32bit systems.
* new WIN32 sbrk, mmap, munmap, lock code from <[email protected]>.
Thanks also to Andreas Mueller <a.mueller at paradatec.de>,
and Anonymous.
* Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
helping test this.)
* memalign: check alignment arg
* realloc: don't try to shift chunks backwards, since this
leads to more fragmentation in some programs and doesn't
seem to help in any others.
* Collect all cases in malloc requiring system memory into sysmalloc
* Use mmap as backup to sbrk
* Place all internal state in malloc_state
* Introduce fastbins (although similar to 2.5.1)
* Many minor tunings and cosmetic improvements
* Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
* Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
Thanks to Tony E. Bennett <[email protected]> and others.
* Include errno.h to support default failure action.
V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
* return null for negative arguments
* Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>
* Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
(e.g. WIN32 platforms)
* Cleanup header file inclusion for WIN32 platforms
* Cleanup code to avoid Microsoft Visual C++ compiler complaints
* Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
memory allocation routines
* Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
* Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
usage of 'assert' in non-WIN32 code
* Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
avoid infinite loop
* Always call 'fREe()' rather than 'free()'
V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
* Fixed ordering problem with boundary-stamping
V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
* Added pvalloc, as recommended by H.J. Liu
* Added 64bit pointer support mainly from Wolfram Gloger
* Added anonymously donated WIN32 sbrk emulation
* Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
* malloc_extend_top: fix mask error that caused wastage after
foreign sbrks
* Add linux mremap support code from HJ Liu
V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
* Integrated most documentation with the code.
* Add support for mmap, with help from
Wolfram Gloger ([email protected]).
* Use last_remainder in more cases.
* Pack bins using idea from [email protected]
* Use ordered bins instead of best-fit threshhold
* Eliminate block-local decls to simplify tracing and debugging.
* Support another case of realloc via move into top
* Fix error occuring when initial sbrk_base not word-aligned.
* Rely on page size for units instead of SBRK_UNIT to
avoid surprises about sbrk alignment conventions.
* Add mallinfo, mallopt. Thanks to Raymond Nijssen
([email protected]) for the suggestion.
* Add `pad' argument to malloc_trim and top_pad mallopt parameter.
* More precautions for cases where other routines call sbrk,
courtesy of Wolfram Gloger ([email protected]).
* Added macros etc., allowing use in linux libc from
H.J. Lu ([email protected])
* Inverted this history list
V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
* Re-tuned and fixed to behave more nicely with V2.6.0 changes.
* Removed all preallocation code since under current scheme
the work required to undo bad preallocations exceeds
the work saved in good cases for most test programs.
* No longer use return list or unconsolidated bins since
no scheme using them consistently outperforms those that don't
given above changes.
* Use best fit for very large chunks to prevent some worst-cases.
* Added some support for debugging
V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
* Removed footers when chunks are in use. Thanks to
Paul Wilson ([email protected]) for the suggestion.
V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
* Added malloc_trim, with help from Wolfram Gloger
([email protected]).
V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
* realloc: try to expand in both directions
* malloc: swap order of clean-bin strategy;
* realloc: only conditionally expand backwards
* Try not to scavenge used bins
* Use bin counts as a guide to preallocation
* Occasionally bin return list chunks in first scan
* Add a few optimizations from [email protected]
V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
* faster bin computation & slightly different binning
* merged all consolidations to one part of malloc proper
(eliminating old malloc_find_space & malloc_clean_bin)
* Scan 2 returns chunks (not just 1)
* Propagate failure in realloc if malloc returns 0
* Add stuff to allow compilation on non-ANSI compilers
from [email protected]
V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
* removed potential for odd address access in prev_chunk
* removed dependency on getpagesize.h
* misc cosmetics and a bit more internal documentation
* anticosmetics: mangled names in macros to evade debugger strangeness
* tested on sparc, hp-700, dec-mips, rs6000
with gcc & native cc (hp, dec only) allowing
Detlefs & Zorn comparison study (in SIGPLAN Notices.)
Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
* Based loosely on libg++-1.2X malloc. (It retains some of the overall
structure of old version, but most details differ.)
*/
|
the_stack_data/88624.c
|
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
}
|
the_stack_data/175142567.c
|
/*******************************************************************************
*
* Copyright (C) 2014-2018 Wave Computing, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/*********************************************************************
@File strlen.c
@Title Character string length
@Platform Any
@Synopsis #include <string.h>
size_t strnlen(const char *str, size_t n);
@Description The strlen function works out the length of the string
starting at str by counting chararacters until it
reaches a NULL character or the maximum: <[n]> number of
characters have been inspected.
*********************************************************************/
#include <string.h>
size_t
strnlen(const char *str, size_t n)
{
size_t start = 0;
while (n-- > 0 && *str++)
start++;
return start;
}
|
the_stack_data/248580919.c
|
/* @author rLapz <[email protected]>
* @license MIT
*
* Simple program for split file into pieces
*
* NOTE: True 0, False = -1
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#define BUFFER_SIZE 4096
static int
split_by_number(char **argv);
static int
split_by_number(char **argv)
{
int8_t is_success = 0;
char filename[255] = {0};
unsigned char buffer[BUFFER_SIZE] = {0};
int byte_splitted = 0;
int fd_read = 0;
int fd_write = 0;
int split_to = 0;
size_t file_size = 0;
size_t write_size = 0;
ssize_t read_bytes = 0;
ssize_t written_bytes = 0;
struct stat file_stat;
if (stat(argv[1], &file_stat) < 0) {
perror(argv[1]);
return -1;
}
split_to = atoi(argv[2]);
file_size = (size_t)file_stat.st_size;
/* tolerance 1 byte for prevent part file not fully written */
byte_splitted = ((int)file_size / split_to) +1;
write_size = (size_t)(byte_splitted < BUFFER_SIZE ?
byte_splitted : BUFFER_SIZE);
if ((fd_read = open(argv[1], O_RDONLY)) < 0) {
perror("Open file");
return -1;
}
for (int iter = 1; iter <= split_to; iter++) {
snprintf(filename, 254, "%s.part%d", argv[1], iter);
if ((fd_write = open(filename, O_WRONLY|O_CREAT|O_TRUNC,
S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0) {
perror("Open file target");
is_success = -1;
break;
}
int tmp = byte_splitted;
while (tmp > 0) {
if ((read_bytes = read(fd_read, buffer,
write_size)) < 0) {
perror("Read file");
is_success = -1;
goto cleanup;
}
if (read_bytes > 0) {
if ((written_bytes = write(fd_write, buffer,
(size_t)read_bytes)) < 0) {
perror("Write file");
is_success = -1;
goto cleanup;
}
tmp -= read_bytes;
} else {
break;
}
}
memset(buffer, 0, sizeof(buffer));
close(fd_write);
}
cleanup:
if (fd_read > 0)
close(fd_read);
if (fd_write > 0)
close(fd_write);
if (is_success < 0)
return -1;
return 0;
}
int
main(int argc, char *argv[])
{
const char help[] = "Usage: \n"
"\t%s [file_source] [split_num]\n"
"Example: \n"
"\t%s file.mp4 5\n";
if (argc != 3) {
fprintf(stderr, help, argv[0], argv[0]);
return EXIT_FAILURE;
}
if (split_by_number(argv))
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
|
the_stack_data/20451218.c
|
#include <math.h>
void fgauss(float x, float a[], float *y, float dyda[], int na)
{
int i;
float fac,ex,arg;
*y=0.0;
for (i=1;i<=na-1;i+=3) {
arg=(x-a[i+1])/a[i+2];
ex=exp(-arg*arg);
fac=a[i]*ex*2.0*arg;
*y += a[i]*ex;
dyda[i]=ex;
dyda[i+1]=fac/a[i+2];
dyda[i+2]=fac*arg/a[i+2];
}
}
|
the_stack_data/237642560.c
|
#include <unistd.h>
int main(int argc, char *argv[])
{
int i;
for(i = 0; i < 60; i++) /* 一个循环,每次循环时休眠 */
{
sleep(1); /* 休眠一秒钟 */
}
return 0;
}
|
the_stack_data/87632.c
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
struct timeval startwtime, endwtime;
double seq_time;
int main(int argc, char** argv){
gettimeofday (&startwtime, NULL);
if(argc!=2){
printf("Usage: %s data_filename\n", argv[0]);
exit(1);
}
FILE *fp;
fp = fopen(argv[1],"r");
if(fp == NULL) {
fprintf(stderr,"ERROR: Cannot open the file");
exit(1);
}
// Read the data set and get the number of nodes (n)
int N,E;
char ch;
char str[100];
ch = getc(fp);
while(ch =='#'){
if(fgets(str,100-1,fp)==NULL){
fprintf(stderr,"ERROR: Cannot read from the file");
exit(1);
}
//Debug: print title of the data set
//printf("%s",str);
sscanf (str,"%*s %d %*s %d", &N, &E);
ch = getc(fp);
}
printf("Number of nodes: %d\nNumber of Edges: %d\n", N, E);
float **A;
int i, j, fromNodeId, toNodeId;
// Preallocate the adjacency matrix 'a' and allocate each element to 0
A = (float **) malloc(N*sizeof(float*));
for(i = 0; i < N; i++) {
A[i] = calloc(N, sizeof(float));
}
printf("Reading graph...\n");
//read and store graph
while(!feof(fp)){
if(fscanf(fp,"%d%d", &toNodeId, &fromNodeId)<2 && !feof(fp)){
printf("ERROR: Cannot read graph\n");
exit(1);
}
//printf("fromNodeId: %d, toNodeId: %d\n", fromNodeId, toNodeId);
//if there is a connection between the nodes, mark it in the adjency matrix
A[fromNodeId][toNodeId] = 1.0;
//printf("In matrix A[%d][%d]: %f\n", fromNodeId, toNodeId, A[fromNodeId][toNodeId]);
}
printf("Preparing PR, outBound, AT arrays...\n");
float *PR;
PR = (float *) malloc(N*sizeof(float));
// Initialize the PR[] vector
//each node gets an initial PR of 1/N
for(i=0; i<N; i++) {
PR[i] = 1.0/N;
}
int *outBound;
//initialize outBound[] vector
outBound = calloc(N, sizeof(int));
//set outBound
for(i=0; i<N; i++){
for(j=0; j<N; j++){
if(A[i][j] != 0.0){
outBound[i]++;
}
}
}
// Make the matrix stochastic
for(i=0; i<N; i++){
if(outBound[i] == 0){
// Deal with dangling nodes
for(j=0; j<N; j++){
A[i][j] = 1.0/N;
}
}
//Distribute the PR along the outBound links
else{
for(j=0; j<N; j++){
if (A[i][j] != 0) {
//if not 0, its 1 at this point
A[i][j] = A[i][j]/outBound[i];
}
}
}
}
float **AT;
//transpose A[][]. This way we get the array AT[how am i?][who points to me?]
//as opposed to the previous format A[how am i?][who do i point to?]
AT = (float **) malloc(N*sizeof(float*));
for(i=0; i<N; i++) {
AT[i] = (float *) malloc(N*sizeof(float));
}
for(i=0; i<N; i++){
for(j=0; j<N; j++){
AT[j][i]=A[i][j];
if(i==j) AT[i][j] = 0;
}
}
//A is no longer needed
free(A);
printf("Initializing PageRank algorithm...\n");
//damping factor
float a=0.85;
// Set the looping condition and the number of iterations
int loop = 1;
int niter = 0;
float error;
// Initialize PR_new[] vector
float *PR_new;
PR_new = (float *) malloc(N*sizeof(float));
while(loop){
//reset PR_new
for(i=0; i<N; i++){
PR_new[i] = 0;
}
//calculate PR_new using Gauss Seidel Method
for(i=0; i<N; i++){
//add (1-a)
PR_new[i] += 1-a;
for(j=0; j<N; j++){
if(j<i){
PR_new[i] += AT[i][j]*PR_new[j];
}
else if(j>i){
PR_new[i] += AT[i][j]*PR[j];
}
}
PR_new[i] *= a;
}
//check if we have to stop
error = 0.0;
for(i=0; i<N; i++){
error += fabs(PR_new[i] - PR[i]);
}
//if two consecutive instances of pagerank vector are almost identical, stop
if (error < 0.000001){
loop = 0;
}
// Update PR[]
for (i=0; i<N; i++){
PR[i] = PR_new[i];
}
niter++;
}
printf("Finished.\n");
gettimeofday (&endwtime, NULL);
seq_time = (double)((endwtime.tv_usec - startwtime.tv_usec)/1.0e6
+ endwtime.tv_sec - startwtime.tv_sec);
printf("Number of iterations: %d\n", niter);
printf("Wall clock time = %f\n", seq_time);
free(AT);
free(PR);
free(PR_new);
free(outBound);
return 0;
}
|
the_stack_data/680488.c
|
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the terms found in the LICENSE file in the root of this source tree.
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* [email protected]
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <execinfo.h>
#include <signal.h>
#include "backtrace.h"
/* Obtain a backtrace and print it to stdout. */
void display_backtrace(void) {
void *array[10];
size_t size;
char **strings;
size_t i;
size = backtrace(array, 10);
strings = backtrace_symbols(array, size);
printf("Obtained %zd stack frames.\n", size);
for (i = 0; i < size; i++) printf("%s\n", strings[i]);
free(strings);
}
void backtrace_handle_signal(siginfo_t *info) {
display_backtrace();
// exit(EXIT_FAILURE);
}
|
the_stack_data/121849.c
|
void f2() {}
|
the_stack_data/9513286.c
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
if (argc < 2) return 1;
int x = atoi(argv[1]);
int c, n;
srand(0);
printf("%d random numbers in [1,100]\n", x);
for (c = 1; c <= x; c++) {
n = rand() % 100 + 1;
printf("%d\n", n);
}
return 0;
}
|
the_stack_data/67374.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strcmp.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aborboll <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/12 13:06:54 by aborboll #+# #+# */
/* Updated: 2019/09/16 16:59:52 by aborboll ### ########.fr */
/* */
/* ************************************************************************** */
int ft_strcmp(char *s1, char *s2)
{
int i;
i = 0;
while (s1[i] != '\0')
{
if (s1[i] != s2[i])
return (s1[i] - s2[i]);
i++;
}
return (s1[i] - s2[i]);
}
|
the_stack_data/148183.c
|
#include <term.h>
#define init_1string tigetstr("is1")
/** terminal or printer initialization string **/
/*
TERMINFO_NAME(is1)
TERMCAP_NAME(i1)
XOPEN(400)
*/
|
the_stack_data/40432.c
|
/*
* Copyright 2016-2018,2020 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/**
* @par Description
* This file implements the SmCom T1oI2C communication layer.
*
*****************************************************************************/
#ifdef T1oI2C
#include <assert.h>
#include "smComT1oI2C.h"
#include "phNxpEse_Api.h"
#include "phNxpEseProto7816_3.h"
#include "i2c_a7.h"
#include "sm_printf.h"
#include "phEseStatus.h"
#include "sm_apdu.h"
#ifdef FLOW_VERBOSE
#define NX_LOG_ENABLE_SMCOM_DEBUG 1
#else
//#define NX_LOG_ENABLE_SMCOM_DEBUG 1
#endif
#include "nxLog_smCom.h"
#include "nxEnsure.h"
static U32 smComT1oI2C_Transceive(void* conn_ctx, apdu_t * pApdu);
static U32 smComT1oI2C_TransceiveRaw(void* conn_ctx, U8 * pTx, U16 txLen, U8 * pRx, U32 * pRxLen);
U16 smComT1oI2C_AnswerToReset(void* conn_ctx, U8 *T1oI2Catr, U16 *T1oI2CatrLen);
U16 smComT1oI2C_Close(void *conn_ctx, U8 mode)
{
ESESTATUS status;
status=phNxpEse_EndOfApdu(conn_ctx);
//status=phNxpEse_chipReset();
if(status ==ESESTATUS_SUCCESS)
{
status=phNxpEse_close(conn_ctx);
}
else
{
LOG_E("Failed to close session ");
return SMCOM_COM_FAILED;
}
return SMCOM_OK;
}
U16 smComT1oI2C_Init(void **conn_ctx, const char *pConnString)
{
ESESTATUS ret;
phNxpEse_initParams initParams;
initParams.initMode = ESE_MODE_NORMAL;
if(conn_ctx != NULL) {
*conn_ctx = NULL;
}
ret = phNxpEse_open(conn_ctx, initParams, pConnString);
if (ret != ESESTATUS_SUCCESS)
{
LOG_E(" Failed to create physical connection with ESE ");
return SMCOM_COM_FAILED;
}
return SMCOM_OK;
}
U16 smComT1oI2C_Open(void *conn_ctx, U8 mode, U8 seqCnt, U8 *T1oI2Catr, U16 *T1oI2CatrLen)
{
ESESTATUS ret;
phNxpEse_data AtrRsp;
phNxpEse_initParams initParams;
initParams.initMode = ESE_MODE_NORMAL;
AtrRsp.len = *T1oI2CatrLen;
AtrRsp.p_data = T1oI2Catr;
if (conn_ctx == NULL) {
smComT1oI2C_Init(NULL, NULL);
}
ret=phNxpEse_init(conn_ctx, initParams, &AtrRsp);
if (ret != ESESTATUS_SUCCESS)
{
*T1oI2CatrLen=0;
LOG_E(" Failed to Open session ");
return SMCOM_COM_FAILED;
}
else
{
*T1oI2CatrLen = AtrRsp.len ; /*Retrive INF FIELD*/
}
smCom_Init(&smComT1oI2C_Transceive, &smComT1oI2C_TransceiveRaw);
return SMCOM_OK;
}
static U32 smComT1oI2C_Transceive(void* conn_ctx, apdu_t * pApdu)
{
U32 respLen= MAX_APDU_BUF_LENGTH;
U32 retCode = SMCOM_COM_FAILED;
ENSURE_OR_GO_EXIT(pApdu != NULL);
retCode = smComT1oI2C_TransceiveRaw(conn_ctx, (U8 *)pApdu->pBuf, pApdu->buflen, pApdu->pBuf, &respLen);
pApdu->rxlen = (U16)respLen;
exit:
return retCode;
}
static U32 smComT1oI2C_TransceiveRaw(void* conn_ctx, U8 * pTx, U16 txLen, U8 * pRx, U32 * pRxLen)
{
phNxpEse_data pCmdTrans;
phNxpEse_data pRspTrans={0};
ESESTATUS txnStatus;
pCmdTrans.len = txLen;
pCmdTrans.p_data = pTx;
pRspTrans.len = *pRxLen;
pRspTrans.p_data = pRx;
LOG_MAU8_D("APDU Tx>", pTx, txLen);
txnStatus = phNxpEse_Transceive(conn_ctx, &pCmdTrans, &pRspTrans);
if ( txnStatus == ESESTATUS_SUCCESS )
{
*pRxLen = pRspTrans.len;
LOG_MAU8_D("APDU Rx<", pRx, pRspTrans.len);
}
else
{
*pRxLen = 0;
LOG_E(" Transcive Failed ");
return SMCOM_SND_FAILED;
}
return SMCOM_OK;
}
U16 smComT1oI2C_AnswerToReset(void* conn_ctx, U8 *T1oI2Catr, U16 *T1oI2CatrLen)
{
phNxpEse_data pRsp= {0};
ESESTATUS txnStatus;
U16 status = SMCOM_NO_ATR;
ENSURE_OR_GO_EXIT(T1oI2Catr != NULL);
ENSURE_OR_GO_EXIT(T1oI2CatrLen != NULL);
#if defined(T1oI2C_UM11225)
txnStatus= phNxpEse_getAtr(conn_ctx, &pRsp);
#elif defined(T1oI2C_GP1_0)
txnStatus= phNxpEse_getCip(conn_ctx, &pRsp);
#endif
if(txnStatus == ESESTATUS_SUCCESS)
{
*T1oI2CatrLen = pRsp.len;
if (pRsp.len > 0) {
memcpy(T1oI2Catr, pRsp.p_data, pRsp.len);
status = SMCOM_OK;
}
else {
LOG_E(" ATR/CIP Length is improper!!!");
}
}
else
{
*T1oI2CatrLen = 0;
LOG_E(" Failed to Retrieve ATR/CIP status ");
}
exit:
return status;
}
U16 smComT1oI2C_ComReset(void* conn_ctx)
{
ESESTATUS status = ESESTATUS_SUCCESS;
status = phNxpEse_deInit(conn_ctx);
if(status !=ESESTATUS_SUCCESS)
{
LOG_E("Failed to Reset 7816 protocol instance ");
return SMCOM_COM_FAILED;
}
return SMCOM_OK;
}
#endif /* T1oI2C */
|
the_stack_data/165765259.c
|
/*****************************************************************************/
/* FPUTWS.C */
/* */
/* Copyright (c) 2017 Texas Instruments Incorporated */
/* http://www.ti.com/ */
/* */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following conditions */
/* are met: */
/* */
/* Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* */
/* Redistributions in binary form must reproduce the above copyright */
/* notice, this list of conditions and the following disclaimer in */
/* the documentation and/or other materials provided with the */
/* distribution. */
/* */
/* Neither the name of Texas Instruments Incorporated nor the names */
/* of its contributors may be used to endorse or promote products */
/* derived from this software without specific prior written */
/* permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR */
/* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT */
/* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, */
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY */
/* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/*****************************************************************************/
#include <wchar.h>
#include <stdio.h>
#include <stdlib.h>
int fputws(const wchar_t* ws, FILE* stream)
{
size_t ws_len = wcslen(ws);
char* dest = (char*)malloc(ws_len);
mbstate_t ps;
int res;
if (wcsrtombs(dest, &ws, ws_len, &ps) == ((size_t)-1))
res = -1;
else
res = fputs(dest, stream);
free(dest);
return res;
}
|
the_stack_data/168892274.c
|
#include <stdio.h>
int main(){
printf("Dennis Ritchie is a \"big wet\"\n");
return 0;
}
|
the_stack_data/700871.c
|
const char *font[] = {
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00", /* */
"\x00\x08\x08\x08\x00\x08\x00\x00", /* ! */
"\x00\x14\x14\x00\x00\x00\x00\x00", /* " */
"\x00\x14\x3E\x14\x3E\x14\x00\x00", /* # */
"\x08\x1C\x02\x1C\x20\x1C\x08\x00", /* $ */
"\x44\x2A\x14\x28\x54\x22\x00\x00", /* % */
"\x0C\x12\x0C\x12\x22\x5C\x00\x00", /* & */
"\x00\x08\x08\x00\x00\x00\x00\x00", /* ' */
"\x00\x08\x04\x04\x04\x08\x00\x00", /* ( */
"\x00\x08\x10\x10\x10\x08\x00\x00", /* ) */
"\x00\x08\x3E\x08\x14\x00\x00\x00", /* * */
"\x00\x08\x08\x3E\x08\x08\x00\x00", /* + */
"\x00\x00\x00\x00\x08\x08\x04\x00", /* , */
"\x00\x00\x00\x3E\x00\x00\x00\x00", /* - */
"\x00\x00\x00\x00\x08\x08\x00\x00", /* . */
"\x00\x20\x10\x08\x04\x02\x00\x00", /* / */
"\x1E\x31\x29\x25\x23\x1E\x00\x00", /* 0 */
"\x08\x0C\x0A\x08\x08\x3E\x00\x00", /* 1 */
"\x1E\x21\x20\x1C\x02\x3F\x00\x00", /* 2 */
"\x1E\x21\x1C\x20\x21\x1E\x00\x00", /* 3 */
"\x10\x18\x14\x12\x3F\x10\x00\x00", /* 4 */
"\x3F\x01\x1F\x20\x20\x1F\x00\x00", /* 5 */
"\x3C\x02\x1F\x21\x21\x1E\x00\x00", /* 6 */
"\x3F\x20\x20\x10\x08\x08\x00\x00", /* 7 */
"\x1E\x21\x1E\x21\x21\x1E\x00\x00", /* 8 */
"\x1E\x21\x3E\x20\x20\x1E\x00\x00", /* 9 */
"\x00\x08\x00\x00\x08\x00\x00\x00", /* : */
"\x00\x08\x00\x00\x08\x08\x04\x00", /* ; */
"\x00\x20\x18\x04\x18\x20\x00\x00", /* < */
"\x00\x00\x3E\x00\x3E\x00\x00\x00", /* = */
"\x00\x02\x0C\x10\x0C\x02\x00\x00", /* > */
"\x1C\x22\x10\x08\x00\x08\x00\x00", /* ? */
"\x3E\x41\x59\x55\x79\x01\x1E\x00", /* @ */
"\x08\x14\x22\x41\x7F\x41\x00\x00", /* A */
"\x1F\x21\x1F\x21\x21\x1F\x00\x00", /* B */
"\x1E\x21\x01\x01\x21\x1E\x00\x00", /* C */
"\x1F\x21\x21\x21\x21\x1F\x00\x00", /* D */
"\x3F\x01\x0F\x01\x01\x3F\x00\x00", /* E */
"\x3F\x01\x0F\x01\x01\x01\x00\x00", /* F */
"\x1E\x21\x01\x39\x21\x3E\x00\x00", /* G */
"\x21\x21\x3F\x21\x21\x21\x00\x00", /* H */
"\x3E\x08\x08\x08\x08\x3E\x00\x00", /* I */
"\x3E\x20\x20\x20\x22\x1C\x00\x00", /* J */
"\x01\x11\x0B\x05\x09\x11\x00\x00", /* K */
"\x01\x01\x01\x01\x01\x3F\x00\x00", /* L */
"\x21\x33\x2D\x21\x21\x21\x00\x00", /* M */
"\x21\x23\x25\x29\x31\x21\x00\x00", /* N */
"\x1E\x21\x21\x21\x21\x1E\x00\x00", /* O */
"\x1F\x21\x21\x1F\x01\x01\x00\x00", /* P */
"\x1E\x21\x21\x21\x11\x2E\x00\x00", /* Q */
"\x1F\x21\x21\x1F\x11\x21\x00\x00", /* R */
"\x3E\x01\x1E\x20\x20\x1F\x00\x00", /* S */
"\x7F\x08\x08\x08\x08\x08\x00\x00", /* T */
"\x21\x21\x21\x21\x21\x1E\x00\x00", /* U */
"\x21\x21\x21\x21\x12\x0C\x00\x00", /* V */
"\x21\x21\x21\x2D\x33\x21\x00\x00", /* W */
"\x21\x12\x0C\x0C\x12\x21\x00\x00", /* X */
"\x41\x22\x14\x08\x08\x08\x00\x00", /* Y */
"\x3F\x10\x08\x04\x02\x3F\x00\x00", /* Z */
"\x1C\x04\x04\x04\x04\x1C\x00\x00", /* [ */
"\x00\x02\x04\x08\x10\x20\x00\x00", /* \ */
"\x1C\x10\x10\x10\x10\x1C\x00\x00", /* ] */
"\x08\x14\x22\x00\x00\x00\x00\x00", /* ^ */
"\x00\x00\x00\x00\x00\x00\x7F\x00", /* _ */
"\x04\x08\x00\x00\x00\x00\x00\x00", /* ` */
"\x00\x1C\x20\x3C\x22\x3C\x00\x00", /* a */
"\x00\x02\x02\x0E\x12\x0E\x00\x00", /* b */
"\x00\x00\x00\x0C\x02\x0C\x00\x00", /* c */
"\x00\x10\x10\x1C\x12\x1C\x00\x00", /* d */
"\x00\x1C\x22\x3E\x02\x3C\x00\x00", /* e */
"\x00\x0C\x02\x06\x02\x02\x00\x00", /* f */
"\x00\x00\x38\x24\x38\x20\x1C\x00", /* g */
"\x00\x02\x02\x0E\x12\x12\x00\x00", /* h */
"\x00\x08\x00\x08\x08\x1C\x00\x00", /* i */
"\x00\x08\x00\x08\x08\x08\x04\x00", /* j */
"\x00\x02\x12\x0E\x0A\x12\x00\x00", /* k */
"\x00\x0C\x08\x08\x08\x10\x00\x00", /* l */
"\x00\x00\x00\x16\x2A\x2A\x00\x00", /* m */
"\x00\x00\x00\x0E\x12\x12\x00\x00", /* n */
"\x00\x00\x0C\x12\x12\x0C\x00\x00", /* o */
"\x00\x00\x0E\x12\x12\x0E\x02\x00", /* p */
"\x00\x00\x1C\x12\x1C\x30\x10\x00", /* q */
"\x00\x00\x00\x0E\x12\x02\x00\x00", /* r */
"\x00\x1C\x02\x0C\x10\x0E\x00\x00", /* s */
"\x00\x02\x02\x06\x02\x0C\x00\x00", /* t */
"\x00\x00\x00\x12\x12\x1C\x00\x00", /* u */
"\x00\x00\x00\x22\x14\x08\x00\x00", /* v */
"\x00\x00\x00\x22\x2A\x14\x00\x00", /* w */
"\x00\x00\x00\x14\x08\x14\x00\x00", /* x */
"\x00\x00\x12\x12\x1C\x10\x0C\x00", /* y */
"\x00\x00\x1E\x08\x04\x1E\x00\x00", /* z */
"\x10\x08\x08\x04\x08\x08\x10\x00", /* { */
"\x08\x08\x08\x08\x08\x08\x00\x00", /* | */
"\x08\x10\x10\x20\x10\x10\x08\x00", /* } */
"\x00\x00\x04\x2A\x10\x00\x00\x00", /* ~ */
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
"\x00\x00\x00\x00\x00\x00\x00\x00",
};
|
the_stack_data/1260139.c
|
#include <stdio.h>
#include <stdlib.h>
__inline__
static int addemup ( int* arr )
{
int i, j = 0;
for (i = 0; i <= 10; i++)
j += arr[i];
return j;
}
int main ( void )
{
int sum;
int* a = calloc(10, sizeof(int));
sum = addemup(a);
printf("sum is %d\n", sum);
return 0;
}
|
the_stack_data/7479.c
|
/* text version of maze 'mazefiles/binary/hitel51.maz'
generated by mazetool (c) Peter Harrison 2018
o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o
| | | |
o o---o---o o o---o---o---o---o---o---o o---o---o---o o
| | | | | | |
o---o---o o o---o o o---o---o o o---o---o o o---o
| | | | | | | |
o o---o---o o---o---o o o o---o---o o---o---o---o o
| | | | | | | | | |
o o o o o o---o o o---o---o---o o o---o o o
| | | | | | | | | |
o o o o o o---o---o o---o---o o o o o---o o
| | | | | | | | | | | |
o o o---o---o o o---o---o o o o o o o o o
| | | | | | | | | | |
o o o o---o---o---o o---o o o o---o---o o---o o
| | | | | | | | | | |
o o o---o---o o o o o o o---o o o o---o o
| | | | | | | | | |
o o---o---o---o o o o---o---o o o---o---o o---o o
| | | | | | |
o o o o o o o o---o---o---o o o---o o---o o
| | | | | | | | | | | |
o o o o o o o---o---o o o o o o---o---o o
| | | | | | | | |
o o o o o o---o---o o---o---o---o---o o o---o o
| | | | | | | | | |
o o---o---o o o---o o---o---o---o---o o---o o o o
| | | | | | | |
o o o---o---o---o---o---o---o---o---o---o---o o o o o
| | | | | | | | | |
o o o o o o o o o o o o o---o---o---o o
| | | | | | | |
o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o
*/
int hitel51_maz[] ={
0x0E, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x09, 0x0C, 0x09,
0x0C, 0x0A, 0x09, 0x0C, 0x0A, 0x0A, 0x03, 0x0C, 0x0A, 0x0A, 0x0A, 0x0A, 0x09, 0x05, 0x05, 0x05,
0x06, 0x09, 0x05, 0x06, 0x0A, 0x0A, 0x09, 0x05, 0x0C, 0x09, 0x0C, 0x0A, 0x03, 0x06, 0x03, 0x05,
0x0C, 0x03, 0x06, 0x0A, 0x0A, 0x0A, 0x03, 0x05, 0x05, 0x05, 0x06, 0x0A, 0x0A, 0x0A, 0x08, 0x03,
0x06, 0x09, 0x0C, 0x0A, 0x08, 0x0A, 0x08, 0x02, 0x01, 0x06, 0x0A, 0x08, 0x09, 0x0D, 0x06, 0x09,
0x0C, 0x03, 0x07, 0x0D, 0x04, 0x0A, 0x02, 0x0A, 0x03, 0x0C, 0x09, 0x05, 0x05, 0x06, 0x09, 0x05,
0x06, 0x09, 0x0C, 0x03, 0x05, 0x0C, 0x08, 0x0A, 0x0A, 0x01, 0x05, 0x06, 0x02, 0x0A, 0x01, 0x05,
0x0C, 0x03, 0x05, 0x0C, 0x03, 0x05, 0x05, 0x0C, 0x09, 0x07, 0x04, 0x08, 0x0A, 0x0B, 0x05, 0x05,
0x06, 0x09, 0x05, 0x05, 0x0C, 0x03, 0x05, 0x06, 0x02, 0x0A, 0x01, 0x05, 0x0C, 0x09, 0x05, 0x05,
0x0C, 0x03, 0x05, 0x05, 0x06, 0x09, 0x06, 0x08, 0x0A, 0x0A, 0x03, 0x05, 0x05, 0x04, 0x03, 0x05,
0x06, 0x09, 0x05, 0x05, 0x0C, 0x02, 0x08, 0x03, 0x0C, 0x0A, 0x0A, 0x03, 0x07, 0x04, 0x0B, 0x05,
0x0C, 0x03, 0x04, 0x03, 0x06, 0x08, 0x03, 0x0C, 0x03, 0x0C, 0x0A, 0x0A, 0x0A, 0x01, 0x0C, 0x01,
0x05, 0x0C, 0x03, 0x0E, 0x08, 0x03, 0x0D, 0x06, 0x0B, 0x06, 0x0A, 0x08, 0x09, 0x05, 0x05, 0x05,
0x05, 0x04, 0x0A, 0x08, 0x01, 0x0C, 0x00, 0x0A, 0x0A, 0x0A, 0x0A, 0x01, 0x05, 0x06, 0x03, 0x05,
0x05, 0x06, 0x0A, 0x03, 0x05, 0x07, 0x05, 0x0D, 0x0D, 0x0C, 0x0B, 0x06, 0x03, 0x0C, 0x09, 0x07,
0x06, 0x0A, 0x0A, 0x0A, 0x02, 0x0A, 0x02, 0x02, 0x02, 0x02, 0x0A, 0x0A, 0x0A, 0x03, 0x06, 0x0B,
};
/* end of mazefile */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.