file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/165764637.c | /*
* Illustrates how to call the sum function we wrote in assembly language.
*/
#include <stdio.h>
#include <inttypes.h>
double sum(double[], uint64_t);
int main() {
double test[] = {
40.5, 26.7, 21.9, 1.5, -40.5, -23.4
};
printf("%20.7f\n", sum(test, 6));
printf("%20.7f\n", sum(test, 2));
printf("%20.7f\n", sum(test, 0));
printf("%20.7f\n", sum(test, 3));
return 0;
}
|
the_stack_data/28996.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ll long long
#define f(i,a,b) for(i=a;i<b;i++)
#define fd(i,b,a) for(i=b;i>a;i--)
#define nl '\n'
int main()
{
int a[7],i,l;
memset(a,-1,sizeof(a));
char s[100];
scanf("%s",s);
l = strlen(s);
f(i,0,l)
{
switch(s[i])
{
case 'g': { a[0]=i; break; }
case 'o': { if(a[1]==-1) {
a[1]=i; break;
}
else {
a[2]=i; break;
}
}
case 'd': { a[3]=i; break; }
case 'b': { a[4]=i; break; }
case 'y': { a[5]=i; break; }
case 'e': { a[6]=i; break; }
}
}
int flag=0;
f(i,0,5)
{
if((a[i]==-1)||(a[i]>a[i+1])) {
flag=1; break;
}
}
if(flag) printf("No\n");
else printf("Yes\n");
return 0;
} |
the_stack_data/76699999.c | #include <sys/epoll.h>
int main(int argc, char* argv[]) {
return 0;
} |
the_stack_data/9511833.c | #include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *s = "hello world";
#ifdef SEG
*s = 'H';
#else
printf("The line is: %s\n", s);
fflush(stdout);
#endif
}
|
the_stack_data/162644174.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int arr[] = { 1187898861, 1709463188, -102719713, 1917143680, -302005966, 1813565133, 1100086806, -1426930656, -880188594, -640487181, -1333854366, -1837940600, -1446206856, -1960819430, -769966052, -1066604514, -262220002, 71782855, 137816478, -670226473, 99933832, 2082310340, -1563311558, -1469852006, 1341327948, -863696992, 1472994747, 298142638, -1235385788, -631017202, 349763559, -2071552039, -869544450, 477566651, -350607110, -1041162370, 295799742, -2058479100, -2032926875, 1180086940, 714405362, -1192515517, -312663645, 296952844, 962505109, -1865472020, -1761795818, 1687924098, -316313595, 476922355, -111010879, 1984975485, -1572139315, -175697641, -1818396412, 1515480812, 1865754341, 1860467084, -583605730, 1207468419, -1857942890, 745574485, 109891635, -743154179, -1452233022, 1696506137, 705776988, -1616354481, 765490156, 506818484, 1060532719, 419966440, -1852404312, -1218428945, 176096363, -879878014, 1370578469, 951046643, 279259783, 2016268677, 1189029268, 1056839376, -655568893, 958267583, 835562392, 1606023994, 2011488101, 1193023929, -924053621, -2051500001, 631754003, 1146080090, 1792998347, 1134352055, -1552701798, 2033267000, -1367489217, -795178222, -1765993719, -180595129, -429528557, 2018657458, -2135207923, 1197075388, -1071471587, 385811074, 365347114, -1160255856, 1677857389, 431710302, -505322933, 1542139561, 1697300523, 1545035390, 1736520544, 1732113252, 1383888761, 1387649541, -936732693, -1438426346, -1988680525, 2042796050, 1694955364, -42608081, -427792176, 553670299, -539515040, -961504777, -475708243, 128307812, -907529649, -2119029873, 713700466, 919649901, 1344209939, 769927959, -1668292527, 1616674511, -622670101, -1264958162, 1179446370, 519950446, -900189513, 932602357, 1450802947, -2081147969, -1040306289, -776429969, 1683888396, -479911459, -1119638527, -280750690, -1074600885, -1201263781, -566772998, -1874947241, -799788824, -1947372301, -873013901, -1032867554, -1691407724, 1596801433, -1383680186, -705347343, -1092472711, -1080767766, 1111236826, -1727716605, 1817968304, -1312197307, -1407295837, 1460944959, -706503645, 1644264729, 94571746, 1997708438, 179057563, 274340735, -1301247660, -1216086099, 600447310, 180796055, 100652592, -1870667475, 1740688338, -1937064797, 1483595292, -1860213117, -1184014673, -1333101609, 153142897, 1422504666, 1867385513, -1662691797, -627233956, 1785793515, 492560196, 1607423982, 703143259, 1338709104, 254566477, -1761126495, 1566200262, 1027523354, 1522678065, 948823819, 609941232, 1000115437, -1436196806, -215565624, 1176505937, -923200352, 56167786, 679747902, -555660440, 1117601102, -483577332, 1648517202, 1047544017, 1591551084, 1834441160, 1079601666, -1420578680, -495545969, -1970637324, -1449868690, 868057486, 1544828495, 342026689, 2031894125, 83765028, 884594475, -903760054, -650897674, -1334931889, -250446341, -1658989517, -956005967, -341332403, -1204205837, -1061516120, 87721598, 1621746983, 1236531323, -1693278358, 923561674, 1778341314, -236879452, 1690989759, 1331101137, -712303520, 975007560, -1523714975, 1126720584, 380615531, 924529644, 599755599, 1747330254, -682875860, 1512983532, 877159372, 2119491015, 1895545712, 586402851, -2135055972, 891587785, -399796165, -99080548, -986083197, -412890463, -2011067896, 2036610972, -482104627, -142726089, 421202037, -1764760396, 1048879908, -1743486405, -534254927, 1013103794, -893608164, -1845019701, 2076511288, -1517624188, -1016775239, -389794285, -1114844372, 1578332798, 517675157, 596220387, -456277818, -793602202, -969413964, -1601143819, -891750102, -903019749, -20170908, 1852440826, -978844676, -331615038, 538231941, 1316834854, 1790840650, -764356300, 632998309, -2146479927, -1403727373, -1378856692, 406064449, 75573571, 422414120, -779492973, -156510016, 1197606542, -623452649, -1375787505, 1756941309, -1255191727, 1220920463, -218554965, 1592252580, 1500770982, 11807279, 1452573002, -1002924362, 892478975, -1293999141, 1560482841, -1954915243, 1401913734, -1089628872, 196172729, 1464526670, -1527803590, -1813664204, 831612448, -28357372, 1534287680, -1928713835, -1413343717, 233005155, -448037005, 56543991, -1592935401, -2047628911, -1840557363, -641355769, -1830886572, -531966698, 1112328673, 1948323956, 562666254, 902649358, -1629125529, 267485420, 1627982110, 336915681, -994462053, 1268179643, 1597863499, 1149679610, 413370316, -1308400988, 34222155, 1101348566, -1300774511, -463136474, 1300699935, 1348812080, -361557037, 60956277, -1027135168, -694878118, 1653768231, -340832707, 1841631657, -14001672, -1856553710, 921732050, -784255326, -758093047, 1508903791, -1652278594, 453057689, -224524961, -105641440, 978923004, -2146711870, 2116049981, -1069723782, -1850091357, 784947218, 1084759970, 1934606930, -99842318, 122141799, 676762074, -585140855, 535603546, 951101198, 808481126, 1266716144, 1190166690, 1207038283, 1541139273, 219147129, 1772593226, -414241408, 647345058, -316609196, -2101493825, -2024797320, 2130719511, 1815311932, -1992290316, 871694741, 931279081, -1429823162, 594434305, -92073224, -755226123, 187093346, 294623995, 1025966303, -11561723, 12365493, 309261379, -998612046, -2002776246, 1642719007, 550326167, -584418186, -1288845761, 288984454, -1259177186, 442594544, 1244774217, -1858166859, -1211073170, 877331902, 567192575, -338990545, 232283604, -295395386, 1564155126, -847110194, -70277498, 306664189, -10248222, -2019247807, -641133431, -802836327, -515704585, 1393601668, 1978730188, -1749538481, -650792334, -1981396432, 864896860, -228879894, -921382013, 690743633, -716762151, 1898599051, -983005458, 678569698, -293151940, 1973334436, 1281175398, 1975732058, 1147095427, -404284087, 1610941981, -317940386, -1799712188, 2129008532, -230850162, -612630970, 1744758559, -517261475, 575463515, -1369473005, 499798089, -87262410, -305336621, 1393392850, 1731651984, -1810125803, -356946206, -1115592635, -248273451, 1760549511, -501895394, 1737485684, 205892124, -844476241, -2027390495, -1347783646, 347360322, -1688319048, 2103080745, 350281692, -1189559205, -892060270, -1534985002, -1297778924, -2123708060, 1417964125, -1015385239, -222776912, 1302163939, -2108107965, -1643060162, 1480106784, -2050748609, -1330068279, -1063449499, 1955239193, 799106271, 1643903875, -165434223, -1096812230, 1425594014, 1741711147, -548036468, -1199213194, 1003697376, -1120562622, 2107789074, -1464266060, -1602126444, 782776946, -525319077, 890185740, -273617691, -938020997, 1821714209, 1187938480, 275839461, -1282787490, -1358646373, 1009835530, 533507366, -1264579379, -1936681661, 1303927510, -1553576747, -615838328, -286893190, 340491309, -937516043, 736253182, -434450403, -1421381607, -1256893184, -592302996, 533064717, 111328275, -804048455, -1361424387, -939559119, 855236196, -575064327, 1481949359, 825808425, -2146665020, 761905753, -1310903274, -686766657, 405323982, -2046127370, 93980725, -73078669, 1254464731, -1560983694, 1821453868, 461731011, -16355300, 939067269, -378630567, -1882304437, -1647133859, -1351104262, -139972533, -1148429507, 1901873494, -1244505339, -1726452573, 913150438, 1371002130, -1650082832, -1900837146, -864070895, 1612555078, 443049956, -180336570, -1806839146, 374549175, 1875138352, 1730158007, 1391790179, -691508365, -1348795693, -288380234, 392660310, 1178634858, 193558784, 781870685, 1392587944, -905095935, 1031707820, -1291043382, -897567215, -786268269, 1553647688, -770761105, 201583744, 2021245679, -345103559, 1959865513, 1049429427, 790151036, 306700893, 286160621, -295099976, -1384366589, -604500386, -1149122271, -1048556488, 694804477, 560494797, -1928859170, -1108558030, 856458611, -1786237949, -2037883401, -124132971, -954793372, -1170881135, 1201232704, -413125807, -1135258415, 1826239900, 411881155, 1488000037, 1718526768, -425497344, -713672299, 1869444848, -370024239, 706833728, -543810823, 1199004959, 1237290235, 1393936033, 1392474681, 949553707, 167456185, 1119505002, -376024776, -81281286, -1526491346, -1223516031, -1487582028, 1864713980, -119142936, -2104707878, 1376025527, 99124230, -228266979, 20777531, 2111709558, 200410934, -1271694359, -1745996447, 1271884907, 1804610261, 612911933, -1921352398, 40908312, 474908869, -506321963, -1639133754, 1068088460, -943054623, 1931513545, -1437374023, 724242698, -1290623839, -321202155, -2048839041, 1338413491, 512482379, -1289440332, 1861199858, -1643750733, -2140980372, 1778777969, 1519596802, 633021840, -1579559091, -1553419580, 1740551174, 276783552, -441700422, 947170608, 176830168, -1527474311, 982424605, 1982699999, -304389288, -1321617170, 2010180523, -697149365, -583846100, 1672165116, -170778469, -1464744766, -798843064, 331463747, -1917988566, 1419650655, -1707750368, -648052915, -1093962655, 108749813, -396624001, -2073360843, 990162762, -576240787, 570993873, -74796990, -1250524253, 822256474, 1354544811, -1532001525, -1833584415, -1910261646, -923468146, -1409506238, 1484804189, -637379320, 1031932167, 387999496, 1452656336, 247593332, 2005968985, -784878246, 1534317400, 135279858, -1231475245, -1816369876, -2145921544, -368461678, 566036103, -1300045571, -418800869, -1234334184, 2138576991, 1119537606, 973886720, -241288551, 1355706221, -1296240853, 1436995223, -1375131606, -1579184415, 1654603889, 1937457024, 211660247, 932922275, 2046457972, -1364400433, 1048911414, 1193863858, 1764253915, 1012571079, 2056125695, 770544988, 15595527, 1179164252, 946171105, 113421550, -885191245, 636470428, 913152605, -1296921851, -1918121551, -529100769, -555148353, 326711022, -2011900344, -579029113, -2116493195, 1883114479, -257808021, -853986685, 1529489320, 153154299, 145339425, 473924135, -1923171737, -1389585464, 531479944, 1625562097, -240378233, 1752504068, -213091432, -990597053, 1294167550, 473899683, 634733009, 886504536, 810861798, -1470040619, 383142204, 717531967, 2004738025, 363332221, -69684608, -885428152, 2100874225, 587277990, -855616737, -1561720221, 277254808, 628519170, 2079422440, 1331243294, -807782850, -757326849, -1255082091, 29732793, -424129867, 2015825456, 513563850, 637460430, -488810046, 1600816497, -296634427, 680540543, -660537711, 1581588647, 215775290, -748802216, 1180576346, 56202293, 864647475, -1953302839, 270063932, -1322209986, -949871032, -684693841, -1473332524, 1338993885, 263522063, -1372754593, -2126265538, 1750007851, 1259899860, -443776221, 1866573579, 647233377, 1129210540, -987572048, -1278604913, -504670155, 2005687347, 886451853, 1699431034, -551655106, -1476158137, -1346862833, -82454241, -998845366, 1585038275, 23838581, -1318238887, -617457374, -1740716099, 98260341, 1087068101, -1993388397, 1977767650, 1750811349, -833185368, 871086812, 900007557, -1391187664, -885563201, 1429168535, -2039396294, 243483148, 2074456162, 1930782505, -941546900, 1316772845, 1750239868, 1175263386, -1191591328, 1132329257, -2084506879, 293235777, -1951943541, 2110639212, -892893072, -871169469, 1160031754, -403569445, 1431192519, -1996484653, -1017849880, -1322709643, -2109945272, -255617559, -1435629499, 826056224, -1557762633, -1626320610, 2113370986, -420026277, 1201390595, -548246879, 1893616575, 1574701016, -1739970053, 1525976626, 1223971413, 1653893850, -749219020, -139734171, 1667306292, 321799218, -1108048078, -2012422015, 53744806, -1955165557, -251446673, -186138580, 1294186620, -771835106, -88454637, 128553067, 1919946295, -1538721066, 1099127462, 647556013, -579111848, 1099518480, -961060423, -73474696, -177787708, 213113508, -1919241121, -733424766, 1252282961, 598170371, 1351824345, 1105489730, -1962717310, -1097097999, 1783856417, -35010996, 713453034, -743314580, 1818120712, 230268217, -237767067, 371437554, 2144133972, 1284389286, -574748233, -1627749696, 1551933327, 485934128, -584336725, 2109192594, 596656127, -1900766816, 732355869, -48758713, -1862348965, 2143872137, 1435097769, -1344836815, 1739740008, -1946404071, 1883169107, -1638196162, 1944659783, 831357515, 1989092554, -1773955468, 515640391, -1008563874, -2127264855, 1988769763, -824218472, 359596080, -258344665, 338548583, -455313, -694767915, 1089051731, 2113072413, 684683273, -1282384741, 911781487, -2138981519, 1340787399, 1435704064, -1062733612, 1556372582, 1285700862, -896748269, 1276994458, -2122471826, 1449368449, 2050842030, 15831398, -27406538, 1989649691, 690713135, 330100493 };
int cmp_func(const void *lhs, const void *rhs)
{
int *__lhs = (int *)lhs;
int *__rhs = (int *)rhs;
if (*__lhs == *__rhs)
return 0;
else if (*__lhs < *__rhs)
return -1;
else
return 1;
}
int main()
{
int *a;
int n;
int i;
int sum;
n = sizeof(arr) / sizeof(int);
a = malloc(n * sizeof(int));
memcpy(a, arr, n * sizeof(int));
qsort(a, n, sizeof(int), cmp_func);
for (i = 0; i < n; i += 128)
sum = a[i];
free(a);
printf("%#x\n", sum);
return 0;
}
|
the_stack_data/105632.c | #include<stdio.h>
#include<math.h>
int main()
{
int n,i,j,a;
scanf("%d",&n);
for(i=n+1;;i++){
a = 0;
for(j=2;j<=i-1;j++){
if(i%j==0){
a++;break;
}
}
if(a==0){
printf("%d",j);break;
}
}
return 0;
} |
the_stack_data/122174.c |
#include <stdio.h>
#include "math.h"
int main() {
char* foo = "foo";
printf("%s\n", foo);
int x = 5;
int y = 5;
int z = add(x, y);
printf("%d\n", z);
}
|
the_stack_data/48575769.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
char name[]="klinsman";
char *ptr;
ptr=name;
while(*ptr !='\0')
{
printf("%c",*ptr);
ptr++;
}
printf("\n");
return 0;
}
|
the_stack_data/362326.c | //
// Created by lucas on 02/04/2021.
//
#include <stdio.h>
int main() {
double sm, novo_sm = 0;
printf("Digite seu saldo medio:");
scanf("%lf", &sm);
if ((sm >= 0) && (sm <= 200)) {
printf("Saldo de %.2lf\nNenhum credito disponivel\n", sm);
} else if ((sm >= 201) && (sm <= 400)) {
novo_sm = sm + (sm * 0.20);
} else if ((sm >= 401) && (sm <= 600)) {
novo_sm = sm + (sm * 0.30);
} else if (sm >= 601) {
novo_sm = sm + (sm * 0.40);
}
if (novo_sm > 0) {
printf("Saldo de %.2lf\nSaldo emprestimo é de %.2lf\n", sm, novo_sm);
}
} |
the_stack_data/70449820.c | /*
age.c
Determines an age in years when supplied with a birthday.
Written by Matthew Campbell on Wednesday January 2, 2019.
*/
#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Define DEBUG to get debugging output. */
#undef DEBUG
int main( void )
{
char week_days[ 7 ][ 10 ] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday",
"Saturday" };
int day, days, month, save_errno, this_year, year, years;
struct tm birthday, *current;
time_t birthday_time, current_time;
/* Fetch the current time from the system clock. */
current_time = time( NULL );
errno = 0;
current = localtime( ¤t_time );
if ( current == NULL )
{
save_errno = errno;
printf( "\
Sorry, something went wrong when attempting to determine the current time.\
\n" );
if ( save_errno != 0 )
{
printf( "Error: %s.\n", strerror( save_errno ) );
}
printf( "\n" );
exit( EXIT_FAILURE );
}
/* Gather input. */
printf( "Please enter the birthday as MM DD YYYY >> " );
fflush( stdout );
if ( scanf( "%d %d %d", &month, &day, &year ) != 3 )
{
printf( "\nSorry that is not a valid entty.\n\n" );
exit( EXIT_FAILURE );
}
printf( "\n" );
/* Make sure we have been given valid values. */
if ( year < 1900 )
{
printf( "The person's birthday is before the year 1900?\n" );
printf( "Yeah sure. Are they a vampire?\n\n" );
exit( EXIT_FAILURE );
}
if ( month < 1 || month > 12 )
{
printf( "You have entered an invalid month: %d.\n\n", month );
exit( EXIT_FAILURE );
}
if ( day < 1 || day > 31 )
{
printf( "You have entered an invalid day: %d.\n\n", day );
exit( EXIT_FAILURE );
}
if ( month == 2 )
{
/* Check to see of it's a leap year. */
if ( ( year % 100 ) == 0 )
{
if ( ( year % 400 ) == 0 )
{
if ( day > 29 )
{
printf( "\
You have entered an invalid day: %d.\n\n", day );
exit( EXIT_FAILURE );
}
}
else /* Not a leap year. */
{
if ( day > 28 )
{
printf( "\
You have entered an invalid day: %d.\n\n", day );
exit( EXIT_FAILURE );
}
}
}
else if ( ( year % 4 ) == 0 )
{
if ( day > 29 )
{
printf( "You have entered an invalid day: %d.\n\n",
day );
exit( EXIT_FAILURE );
}
}
else /* Not a leap year. */
{
if ( day > 28 )
{
printf( "You have entered an invalid day: %d.\n\n",
day );
exit( EXIT_FAILURE );
}
}
}
else if ( month == 4 || month == 6 || month == 9 || month == 11 )
{
if ( day > 30 )
{
printf( "You have entered an invalid day: %d.\n\n",
day );
exit( EXIT_FAILURE );
}
}
/* Put the birthday information into the structure. */
birthday.tm_sec = 0;
birthday.tm_min = 0;
birthday.tm_hour = 0;
birthday.tm_mday = day;
birthday.tm_mon = month - 1;
birthday.tm_year = year - 1900;
birthday.tm_wday = 0;
birthday.tm_yday = 0;
birthday.tm_isdst = 0;
/* Get the reference value in seconds for the birthday. */
errno = 0;
birthday_time = mktime( &birthday );
if ( birthday_time == ( -1 ) )
{
save_errno = errno;
printf( "\
Sorry, something went wrong when converting the birthday to seconds.\n" );
if ( save_errno != 0 )
{
printf( "Error: %s.\n", strerror( save_errno ) );
}
printf( "\n" );
exit( EXIT_FAILURE );
}
/* Make sure time travel wasn't involved. */
if ( birthday_time > current_time )
{
printf( "\
They don't have an age if they haven't been born yet.\n\n" );
exit( EXIT_FAILURE );
}
/* At this point we know the birthday is valid. */
/* Has the birthday already passed during this year? */
if ( current->tm_mon >= birthday.tm_mon &&
current->tm_mday >= birthday.tm_mday )
{
this_year = 1;
}
else
{
this_year = 0;
}
years = current->tm_year - birthday.tm_year;
if ( this_year == 0 )
{
years--;
}
days = ( current_time - birthday_time ) / 86400;
/* Print the results. */
if ( years == 1 )
{
printf( "Age: 1 year old.\n\n" );
}
else
{
printf( "Age: %d years old.\n\n", years );
}
printf( "In case you're curious, the age in days is " );
if ( days == 1 )
{
printf( "1 day" );
}
else
{
printf( "%d days", days );
}
printf( " old.\n\n" );
if ( birthday.tm_wday >= 0 && birthday.tm_wday <= 6 )
{
printf( "That birthday is on a %s.\n\n",
week_days[ birthday.tm_wday ] );
}
/* Print debugging output if requested. */
#ifdef DEBUG
printf( "current_time: %lu\n\n", current_time );
printf( " tm_sec: %d\n", current->tm_sec );
printf( " tm_min: %d\n", current->tm_min );
printf( " tm_hour: %d\n", current->tm_hour );
printf( " tm_mday: %d\n", current->tm_mday );
printf( " tm_mon: %d\n", current->tm_mon );
printf( " tm_year: %d\n", current->tm_year );
printf( " tm_wday: %d\n", current->tm_wday );
printf( " tm_yday: %d\n", current->tm_yday );
printf( "tm_isdst: %d\n", current->tm_isdst );
printf( "\n" );
printf( "birthday_time: %lu\n\n", birthday_time );
printf( " tm_sec: %d\n", birthday.tm_sec );
printf( " tm_min: %d\n", birthday.tm_min );
printf( " tm_hour: %d\n", birthday.tm_hour );
printf( " tm_mday: %d\n", birthday.tm_mday );
printf( " tm_mon: %d\n", birthday.tm_mon );
printf( " tm_year: %d\n", birthday.tm_year );
printf( " tm_wday: %d\n", birthday.tm_wday );
printf( " tm_yday: %d\n", birthday.tm_yday );
printf( "tm_isdst: %d\n", birthday.tm_isdst );
printf( "\n" );
#endif
/* And we're done. */
return 0;
}
/* EOF age.c */
|
the_stack_data/231392422.c | /**
******************************************************************************
* @file stm32g4xx_ll_lpuart.c
* @author MCD Application Team
* @brief LPUART 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_lpuart.h"
#include "stm32g4xx_ll_rcc.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
#if defined (LPUART1)
/** @addtogroup LPUART_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup LPUART_LL_Private_Constants
* @{
*/
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup LPUART_LL_Private_Macros
* @{
*/
/* Check of parameters for configuration of LPUART registers */
#define IS_LL_LPUART_PRESCALER(__VALUE__) (((__VALUE__) == LL_LPUART_PRESCALER_DIV1) \
|| ((__VALUE__) == LL_LPUART_PRESCALER_DIV2) \
|| ((__VALUE__) == LL_LPUART_PRESCALER_DIV4) \
|| ((__VALUE__) == LL_LPUART_PRESCALER_DIV6) \
|| ((__VALUE__) == LL_LPUART_PRESCALER_DIV8) \
|| ((__VALUE__) == LL_LPUART_PRESCALER_DIV10) \
|| ((__VALUE__) == LL_LPUART_PRESCALER_DIV12) \
|| ((__VALUE__) == LL_LPUART_PRESCALER_DIV16) \
|| ((__VALUE__) == LL_LPUART_PRESCALER_DIV32) \
|| ((__VALUE__) == LL_LPUART_PRESCALER_DIV64) \
|| ((__VALUE__) == LL_LPUART_PRESCALER_DIV128) \
|| ((__VALUE__) == LL_LPUART_PRESCALER_DIV256))
/* __BAUDRATE__ Depending on constraints applicable for LPUART BRR register */
/* value : */
/* - fck must be in the range [3 x baudrate, 4096 x baudrate] */
/* - LPUART_BRR register value should be >= 0x300 */
/* - LPUART_BRR register value should be <= 0xFFFFF (20 bits) */
/* Baudrate specified by the user should belong to [8, 50000000].*/
#define IS_LL_LPUART_BAUDRATE(__BAUDRATE__) (((__BAUDRATE__) <= 50000000U) && ((__BAUDRATE__) >= 8U))
/* __VALUE__ BRR content must be greater than or equal to 0x300. */
#define IS_LL_LPUART_BRR_MIN(__VALUE__) ((__VALUE__) >= 0x300U)
/* __VALUE__ BRR content must be lower than or equal to 0xFFFFF. */
#define IS_LL_LPUART_BRR_MAX(__VALUE__) ((__VALUE__) <= 0x000FFFFFU)
#define IS_LL_LPUART_DIRECTION(__VALUE__) (((__VALUE__) == LL_LPUART_DIRECTION_NONE) \
|| ((__VALUE__) == LL_LPUART_DIRECTION_RX) \
|| ((__VALUE__) == LL_LPUART_DIRECTION_TX) \
|| ((__VALUE__) == LL_LPUART_DIRECTION_TX_RX))
#define IS_LL_LPUART_PARITY(__VALUE__) (((__VALUE__) == LL_LPUART_PARITY_NONE) \
|| ((__VALUE__) == LL_LPUART_PARITY_EVEN) \
|| ((__VALUE__) == LL_LPUART_PARITY_ODD))
#define IS_LL_LPUART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_LPUART_DATAWIDTH_7B) \
|| ((__VALUE__) == LL_LPUART_DATAWIDTH_8B) \
|| ((__VALUE__) == LL_LPUART_DATAWIDTH_9B))
#define IS_LL_LPUART_STOPBITS(__VALUE__) (((__VALUE__) == LL_LPUART_STOPBITS_1) \
|| ((__VALUE__) == LL_LPUART_STOPBITS_2))
#define IS_LL_LPUART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_LPUART_HWCONTROL_NONE) \
|| ((__VALUE__) == LL_LPUART_HWCONTROL_RTS) \
|| ((__VALUE__) == LL_LPUART_HWCONTROL_CTS) \
|| ((__VALUE__) == LL_LPUART_HWCONTROL_RTS_CTS))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup LPUART_LL_Exported_Functions
* @{
*/
/** @addtogroup LPUART_LL_EF_Init
* @{
*/
/**
* @brief De-initialize LPUART registers (Registers restored to their default values).
* @param LPUARTx LPUART Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: LPUART registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_LPUART_DeInit(USART_TypeDef *LPUARTx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_LPUART_INSTANCE(LPUARTx));
if (LPUARTx == LPUART1)
{
/* Force reset of LPUART peripheral */
LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_LPUART1);
/* Release reset of LPUART peripheral */
LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_LPUART1);
}
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Initialize LPUART registers according to the specified
* parameters in LPUART_InitStruct.
* @note As some bits in LPUART configuration registers can only be written when
* the LPUART is disabled (USART_CR1_UE bit =0),
* LPUART Peripheral should be in disabled state prior calling this function.
* Otherwise, ERROR result will be returned.
* @note Baud rate value stored in LPUART_InitStruct BaudRate field, should be valid (different from 0).
* @param LPUARTx LPUART Instance
* @param LPUART_InitStruct pointer to a @ref LL_LPUART_InitTypeDef structure
* that contains the configuration information for the specified LPUART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: LPUART registers are initialized according to LPUART_InitStruct content
* - ERROR: Problem occurred during LPUART Registers initialization
*/
ErrorStatus LL_LPUART_Init(USART_TypeDef *LPUARTx, LL_LPUART_InitTypeDef *LPUART_InitStruct)
{
ErrorStatus status = ERROR;
uint32_t periphclk;
/* Check the parameters */
assert_param(IS_LPUART_INSTANCE(LPUARTx));
assert_param(IS_LL_LPUART_PRESCALER(LPUART_InitStruct->PrescalerValue));
assert_param(IS_LL_LPUART_BAUDRATE(LPUART_InitStruct->BaudRate));
assert_param(IS_LL_LPUART_DATAWIDTH(LPUART_InitStruct->DataWidth));
assert_param(IS_LL_LPUART_STOPBITS(LPUART_InitStruct->StopBits));
assert_param(IS_LL_LPUART_PARITY(LPUART_InitStruct->Parity));
assert_param(IS_LL_LPUART_DIRECTION(LPUART_InitStruct->TransferDirection));
assert_param(IS_LL_LPUART_HWCONTROL(LPUART_InitStruct->HardwareFlowControl));
/* LPUART needs to be in disabled state, in order to be able to configure some bits in
CRx registers. Otherwise (LPUART not in Disabled state) => return ERROR */
if (LL_LPUART_IsEnabled(LPUARTx) == 0U)
{
/*---------------------------- LPUART CR1 Configuration -----------------------
* Configure LPUARTx CR1 (LPUART Word Length, Parity and Transfer Direction bits) with parameters:
* - DataWidth: USART_CR1_M bits according to LPUART_InitStruct->DataWidth value
* - Parity: USART_CR1_PCE, USART_CR1_PS bits according to LPUART_InitStruct->Parity value
* - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to LPUART_InitStruct->TransferDirection value
*/
MODIFY_REG(LPUARTx->CR1,
(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE),
(LPUART_InitStruct->DataWidth | LPUART_InitStruct->Parity | LPUART_InitStruct->TransferDirection));
/*---------------------------- LPUART CR2 Configuration -----------------------
* Configure LPUARTx CR2 (Stop bits) with parameters:
* - Stop Bits: USART_CR2_STOP bits according to LPUART_InitStruct->StopBits value.
*/
LL_LPUART_SetStopBitsLength(LPUARTx, LPUART_InitStruct->StopBits);
/*---------------------------- LPUART CR3 Configuration -----------------------
* Configure LPUARTx CR3 (Hardware Flow Control) with parameters:
* - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according
* to LPUART_InitStruct->HardwareFlowControl value.
*/
LL_LPUART_SetHWFlowCtrl(LPUARTx, LPUART_InitStruct->HardwareFlowControl);
/*---------------------------- LPUART BRR Configuration -----------------------
* Retrieve Clock frequency used for LPUART Peripheral
*/
periphclk = LL_RCC_GetLPUARTClockFreq(LL_RCC_LPUART1_CLKSOURCE);
/* Configure the LPUART Baud Rate :
- prescaler value is required
- valid baud rate value (different from 0) is required
- Peripheral clock as returned by RCC service, should be valid (different from 0).
*/
if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO)
&& (LPUART_InitStruct->BaudRate != 0U))
{
status = SUCCESS;
LL_LPUART_SetBaudRate(LPUARTx,
periphclk,
LPUART_InitStruct->PrescalerValue,
LPUART_InitStruct->BaudRate);
/* Check BRR is greater than or equal to 0x300 */
assert_param(IS_LL_LPUART_BRR_MIN(LPUARTx->BRR));
/* Check BRR is lower than or equal to 0xFFFFF */
assert_param(IS_LL_LPUART_BRR_MAX(LPUARTx->BRR));
}
/*---------------------------- LPUART PRESC Configuration -----------------------
* Configure LPUARTx PRESC (Prescaler) with parameters:
* - PrescalerValue: LPUART_PRESC_PRESCALER bits according to LPUART_InitStruct->PrescalerValue value.
*/
LL_LPUART_SetPrescaler(LPUARTx, LPUART_InitStruct->PrescalerValue);
}
return (status);
}
/**
* @brief Set each @ref LL_LPUART_InitTypeDef field to default value.
* @param LPUART_InitStruct pointer to a @ref LL_LPUART_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_LPUART_StructInit(LL_LPUART_InitTypeDef *LPUART_InitStruct)
{
/* Set LPUART_InitStruct fields to default values */
LPUART_InitStruct->PrescalerValue = LL_LPUART_PRESCALER_DIV1;
LPUART_InitStruct->BaudRate = 9600U;
LPUART_InitStruct->DataWidth = LL_LPUART_DATAWIDTH_8B;
LPUART_InitStruct->StopBits = LL_LPUART_STOPBITS_1;
LPUART_InitStruct->Parity = LL_LPUART_PARITY_NONE ;
LPUART_InitStruct->TransferDirection = LL_LPUART_DIRECTION_TX_RX;
LPUART_InitStruct->HardwareFlowControl = LL_LPUART_HWCONTROL_NONE;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* LPUART1 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/13147.c | /* -*-c-*- */
/**********************************************************************
thread_pthread.c -
$Author: nobu $
Copyright (C) 2004-2007 Koichi Sasada
**********************************************************************/
#ifdef THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
#include "gc.h"
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
static void native_mutex_lock(pthread_mutex_t *lock);
static void native_mutex_unlock(pthread_mutex_t *lock);
static int native_mutex_trylock(pthread_mutex_t *lock);
static void native_mutex_initialize(pthread_mutex_t *lock);
static void native_mutex_destroy(pthread_mutex_t *lock);
static void native_cond_signal(pthread_cond_t *cond);
static void native_cond_broadcast(pthread_cond_t *cond);
static void native_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
static void native_cond_initialize(pthread_cond_t *cond);
static void native_cond_destroy(pthread_cond_t *cond);
static void
native_mutex_lock(pthread_mutex_t *lock)
{
int r;
if ((r = pthread_mutex_lock(lock)) != 0) {
rb_bug("pthread_mutex_lock: %d", r);
}
}
static void
native_mutex_unlock(pthread_mutex_t *lock)
{
int r;
if ((r = pthread_mutex_unlock(lock)) != 0) {
rb_bug("native_mutex_unlock return non-zero: %d", r);
}
}
static inline int
native_mutex_trylock(pthread_mutex_t *lock)
{
int r;
if ((r = pthread_mutex_trylock(lock)) != 0) {
if (r == EBUSY) {
return EBUSY;
}
else {
rb_bug("native_mutex_trylock return non-zero: %d", r);
}
}
return 0;
}
static void
native_mutex_initialize(pthread_mutex_t *lock)
{
int r = pthread_mutex_init(lock, 0);
if (r != 0) {
rb_bug("native_mutex_initialize return non-zero: %d", r);
}
}
static void
native_mutex_destroy(pthread_mutex_t *lock)
{
int r = pthread_mutex_destroy(lock);
if (r != 0) {
rb_bug("native_mutex_destroy return non-zero: %d", r);
}
}
static void
native_cond_initialize(pthread_cond_t *cond)
{
int r = pthread_cond_init(cond, 0);
if (r != 0) {
rb_bug("native_cond_initialize return non-zero: %d", r);
}
}
static void
native_cond_destroy(pthread_cond_t *cond)
{
int r = pthread_cond_destroy(cond);
if (r != 0) {
rb_bug("native_cond_destroy return non-zero: %d", r);
}
}
static void
native_cond_signal(pthread_cond_t *cond)
{
pthread_cond_signal(cond);
}
static void
native_cond_broadcast(pthread_cond_t *cond)
{
pthread_cond_broadcast(cond);
}
static void
native_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
pthread_cond_wait(cond, mutex);
}
static int
native_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *ts)
{
return pthread_cond_timedwait(cond, mutex, ts);
}
#define native_cleanup_push pthread_cleanup_push
#define native_cleanup_pop pthread_cleanup_pop
#ifdef HAVE_SCHED_YIELD
#define native_thread_yield() (void)sched_yield()
#else
#define native_thread_yield() ((void)0)
#endif
#ifndef __CYGWIN__
static void add_signal_thread_list(rb_thread_t *th);
#endif
static void remove_signal_thread_list(rb_thread_t *th);
static rb_thread_lock_t signal_thread_list_lock;
static pthread_key_t ruby_native_thread_key;
static void
null_func(int i)
{
/* null */
}
static rb_thread_t *
ruby_thread_from_native(void)
{
return pthread_getspecific(ruby_native_thread_key);
}
static int
ruby_thread_set_native(rb_thread_t *th)
{
return pthread_setspecific(ruby_native_thread_key, th) == 0;
}
static void
Init_native_thread(void)
{
rb_thread_t *th = GET_THREAD();
pthread_key_create(&ruby_native_thread_key, NULL);
th->thread_id = pthread_self();
native_cond_initialize(&th->native_thread_data.sleep_cond);
ruby_thread_set_native(th);
native_mutex_initialize(&signal_thread_list_lock);
posix_signal(SIGVTALRM, null_func);
}
static void
native_thread_destroy(rb_thread_t *th)
{
pthread_mutex_destroy(&th->interrupt_lock);
pthread_cond_destroy(&th->native_thread_data.sleep_cond);
}
#define USE_THREAD_CACHE 0
#if STACK_GROW_DIRECTION
#define STACK_GROW_DIR_DETECTION
#define STACK_DIR_UPPER(a,b) STACK_UPPER(0, a, b)
#else
#define STACK_GROW_DIR_DETECTION VALUE stack_grow_dir_detection
#define STACK_DIR_UPPER(a,b) STACK_UPPER(&stack_grow_dir_detection, a, b)
#endif
#if defined HAVE_PTHREAD_GETATTR_NP || defined HAVE_PTHREAD_ATTR_GET_NP
#define STACKADDR_AVAILABLE 1
#elif defined HAVE_PTHREAD_GET_STACKADDR_NP && defined HAVE_PTHREAD_GET_STACKSIZE_NP
#define STACKADDR_AVAILABLE 1
#elif defined HAVE_THR_STKSEGMENT || defined HAVE_PTHREAD_STACKSEG_NP
#define STACKADDR_AVAILABLE 1
#endif
#ifdef STACKADDR_AVAILABLE
static int
get_stack(void **addr, size_t *size)
{
#define CHECK_ERR(expr) \
{int err = (expr); if (err) return err;}
#if defined HAVE_PTHREAD_GETATTR_NP || defined HAVE_PTHREAD_ATTR_GET_NP
pthread_attr_t attr;
size_t guard = 0;
# ifdef HAVE_PTHREAD_GETATTR_NP
CHECK_ERR(pthread_getattr_np(pthread_self(), &attr));
# ifdef HAVE_PTHREAD_ATTR_GETSTACK
CHECK_ERR(pthread_attr_getstack(&attr, addr, size));
# else
CHECK_ERR(pthread_attr_getstackaddr(&attr, addr));
CHECK_ERR(pthread_attr_getstacksize(&attr, size));
# endif
if (pthread_attr_getguardsize(&attr, &guard) == 0) {
STACK_GROW_DIR_DETECTION;
STACK_DIR_UPPER((void)0, *addr = (char *)*addr + guard);
*size -= guard;
}
# else
CHECK_ERR(pthread_attr_init(&attr));
CHECK_ERR(pthread_attr_get_np(pthread_self(), &attr));
CHECK_ERR(pthread_attr_getstackaddr(&attr, addr));
CHECK_ERR(pthread_attr_getstacksize(&attr, size));
# endif
CHECK_ERR(pthread_attr_getguardsize(&attr, &guard));
# ifndef HAVE_PTHREAD_GETATTR_NP
pthread_attr_destroy(&attr);
# endif
size -= guard;
#elif defined HAVE_PTHREAD_GET_STACKADDR_NP && defined HAVE_PTHREAD_GET_STACKSIZE_NP
pthread_t th = pthread_self();
*addr = pthread_get_stackaddr_np(th);
*size = pthread_get_stacksize_np(th);
#elif defined HAVE_THR_STKSEGMENT || defined HAVE_PTHREAD_STACKSEG_NP
stack_t stk;
# if defined HAVE_THR_STKSEGMENT
CHECK_ERR(thr_stksegment(&stk));
# else
CHECK_ERR(pthread_stackseg_np(pthread_self(), &stk));
# endif
*addr = stk.ss_sp;
*size = stk.ss_size;
#endif
return 0;
#undef CHECK_ERR
}
#endif
static struct {
rb_thread_id_t id;
size_t stack_maxsize;
VALUE *stack_start;
#ifdef __ia64
VALUE *register_stack_start;
#endif
} native_main_thread;
#ifdef STACK_END_ADDRESS
extern void *STACK_END_ADDRESS;
#endif
#undef ruby_init_stack
void
ruby_init_stack(volatile VALUE *addr
#ifdef __ia64
, void *bsp
#endif
)
{
native_main_thread.id = pthread_self();
#ifdef STACK_END_ADDRESS
native_main_thread.stack_start = STACK_END_ADDRESS;
#else
if (!native_main_thread.stack_start ||
STACK_UPPER((VALUE *)(void *)&addr,
native_main_thread.stack_start > addr,
native_main_thread.stack_start < addr)) {
native_main_thread.stack_start = (VALUE *)addr;
}
#endif
#ifdef __ia64
if (!native_main_thread.register_stack_start ||
(VALUE*)bsp < native_main_thread.register_stack_start) {
native_main_thread.register_stack_start = (VALUE*)bsp;
}
#endif
#ifdef HAVE_GETRLIMIT
{
struct rlimit rlim;
if (getrlimit(RLIMIT_STACK, &rlim) == 0) {
size_t space = (size_t)(rlim.rlim_cur/5);
if (space > 1024*1024) space = 1024*1024;
native_main_thread.stack_maxsize = (size_t)rlim.rlim_cur - space;
}
}
#endif
}
#define CHECK_ERR(expr) \
{int err = (expr); if (err) {rb_bug("err: %d - %s", err, #expr);}}
static int
native_thread_init_stack(rb_thread_t *th)
{
rb_thread_id_t curr = pthread_self();
if (pthread_equal(curr, native_main_thread.id)) {
th->machine_stack_start = native_main_thread.stack_start;
th->machine_stack_maxsize = native_main_thread.stack_maxsize;
}
else {
#ifdef HAVE_PTHREAD_GETATTR_NP
pthread_attr_t attr;
void *start;
CHECK_ERR(pthread_getattr_np(curr, &attr));
# if defined HAVE_PTHREAD_ATTR_GETSTACK
CHECK_ERR(pthread_attr_getstack(&attr, &start, &th->machine_stack_maxsize));
# elif defined HAVE_PTHREAD_ATTR_GETSTACKSIZE && defined HAVE_PTHREAD_ATTR_GETSTACKADDR
CHECK_ERR(pthread_attr_getstackaddr(&attr, &start));
CHECK_ERR(pthread_attr_getstacksize(&attr, &th->machine_stack_maxsize));
# endif
th->machine_stack_start = start;
#else
rb_raise(rb_eNotImpError, "ruby engine can initialize only in the main thread");
#endif
}
#ifdef __ia64
th->machine_register_stack_start = native_main_thread.register_stack_start;
th->machine_stack_maxsize /= 2;
th->machine_register_stack_maxsize = th->machine_stack_maxsize;
#endif
return 0;
}
static void *
thread_start_func_1(void *th_ptr)
{
#if USE_THREAD_CACHE
thread_start:
#endif
{
rb_thread_t *th = th_ptr;
VALUE stack_start;
/* run */
thread_start_func_2(th, &stack_start, rb_ia64_bsp());
}
#if USE_THREAD_CACHE
if (1) {
/* cache thread */
rb_thread_t *th;
static rb_thread_t *register_cached_thread_and_wait(void);
if ((th = register_cached_thread_and_wait()) != 0) {
th_ptr = (void *)th;
th->thread_id = pthread_self();
goto thread_start;
}
}
#endif
return 0;
}
void rb_thread_create_control_thread(void);
struct cached_thread_entry {
volatile rb_thread_t **th_area;
pthread_cond_t *cond;
struct cached_thread_entry *next;
};
#if USE_THREAD_CACHE
static pthread_mutex_t thread_cache_lock = PTHREAD_MUTEX_INITIALIZER;
struct cached_thread_entry *cached_thread_root;
static rb_thread_t *
register_cached_thread_and_wait(void)
{
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
volatile rb_thread_t *th_area = 0;
struct cached_thread_entry *entry =
(struct cached_thread_entry *)malloc(sizeof(struct cached_thread_entry));
struct timeval tv;
struct timespec ts;
gettimeofday(&tv, 0);
ts.tv_sec = tv.tv_sec + 60;
ts.tv_nsec = tv.tv_usec * 1000;
pthread_mutex_lock(&thread_cache_lock);
{
entry->th_area = &th_area;
entry->cond = &cond;
entry->next = cached_thread_root;
cached_thread_root = entry;
pthread_cond_timedwait(&cond, &thread_cache_lock, &ts);
{
struct cached_thread_entry *e = cached_thread_root;
struct cached_thread_entry *prev = cached_thread_root;
while (e) {
if (e == entry) {
if (prev == cached_thread_root) {
cached_thread_root = e->next;
}
else {
prev->next = e->next;
}
break;
}
prev = e;
e = e->next;
}
}
free(entry); /* ok */
pthread_cond_destroy(&cond);
}
pthread_mutex_unlock(&thread_cache_lock);
return (rb_thread_t *)th_area;
}
#endif
static int
use_cached_thread(rb_thread_t *th)
{
int result = 0;
#if USE_THREAD_CACHE
struct cached_thread_entry *entry;
if (cached_thread_root) {
pthread_mutex_lock(&thread_cache_lock);
entry = cached_thread_root;
{
if (cached_thread_root) {
cached_thread_root = entry->next;
*entry->th_area = th;
result = 1;
}
}
if (result) {
pthread_cond_signal(entry->cond);
}
pthread_mutex_unlock(&thread_cache_lock);
}
#endif
return result;
}
enum {
#ifdef __SYMBIAN32__
RUBY_STACK_MIN_LIMIT = 64 * 1024, /* 64KB: Let's be slightly more frugal on mobile platform */
#else
RUBY_STACK_MIN_LIMIT = 512 * 1024, /* 512KB */
#endif
RUBY_STACK_MIN = (
#ifdef PTHREAD_STACK_MIN
(RUBY_STACK_MIN_LIMIT < PTHREAD_STACK_MIN) ? PTHREAD_STACK_MIN * 2 :
#endif
RUBY_STACK_MIN_LIMIT),
RUBY_STACK_SPACE_LIMIT = 1024 * 1024,
RUBY_STACK_SPACE = (RUBY_STACK_MIN/5 > RUBY_STACK_SPACE_LIMIT ?
RUBY_STACK_SPACE_LIMIT : RUBY_STACK_MIN/5)
};
static int
native_thread_create(rb_thread_t *th)
{
int err = 0;
if (use_cached_thread(th)) {
thread_debug("create (use cached thread): %p\n", (void *)th);
}
else {
pthread_attr_t attr;
const size_t stack_size = RUBY_STACK_MIN;
const size_t space = RUBY_STACK_SPACE;
th->machine_stack_maxsize = stack_size - space;
#ifdef __ia64
th->machine_stack_maxsize /= 2;
th->machine_register_stack_maxsize = th->machine_stack_maxsize;
#endif
CHECK_ERR(pthread_attr_init(&attr));
#ifdef PTHREAD_STACK_MIN
thread_debug("create - stack size: %lu\n", (unsigned long)stack_size);
CHECK_ERR(pthread_attr_setstacksize(&attr, stack_size));
#endif
#ifdef HAVE_PTHREAD_ATTR_SETINHERITSCHED
CHECK_ERR(pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
#endif
CHECK_ERR(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
err = pthread_create(&th->thread_id, &attr, thread_start_func_1, th);
thread_debug("create: %p (%d)", (void *)th, err);
CHECK_ERR(pthread_attr_destroy(&attr));
if (!err) {
pthread_cond_init(&th->native_thread_data.sleep_cond, 0);
}
}
return err;
}
static void
native_thread_join(pthread_t th)
{
int err = pthread_join(th, 0);
if (err) {
rb_raise(rb_eThreadError, "native_thread_join() failed (%d)", err);
}
}
#if USE_NATIVE_THREAD_PRIORITY
static void
native_thread_apply_priority(rb_thread_t *th)
{
#if defined(_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING > 0)
struct sched_param sp;
int policy;
int priority = 0 - th->priority;
int max, min;
pthread_getschedparam(th->thread_id, &policy, &sp);
max = sched_get_priority_max(policy);
min = sched_get_priority_min(policy);
if (min > priority) {
priority = min;
}
else if (max < priority) {
priority = max;
}
sp.sched_priority = priority;
pthread_setschedparam(th->thread_id, policy, &sp);
#else
/* not touched */
#endif
}
#endif /* USE_NATIVE_THREAD_PRIORITY */
static void
ubf_pthread_cond_signal(void *ptr)
{
rb_thread_t *th = (rb_thread_t *)ptr;
thread_debug("ubf_pthread_cond_signal (%p)\n", (void *)th);
pthread_cond_signal(&th->native_thread_data.sleep_cond);
}
#if !defined(__CYGWIN__) && !defined(__SYMBIAN32__)
static void
ubf_select_each(rb_thread_t *th)
{
thread_debug("ubf_select_each (%p)\n", (void *)th->thread_id);
if (th) {
pthread_kill(th->thread_id, SIGVTALRM);
}
}
static void
ubf_select(void *ptr)
{
rb_thread_t *th = (rb_thread_t *)ptr;
add_signal_thread_list(th);
ubf_select_each(th);
}
#else
#define ubf_select 0
#endif
#define PER_NANO 1000000000
static void
native_sleep(rb_thread_t *th, struct timeval *tv)
{
struct timespec ts;
struct timeval tvn;
if (tv) {
gettimeofday(&tvn, NULL);
ts.tv_sec = tvn.tv_sec + tv->tv_sec;
ts.tv_nsec = (tvn.tv_usec + tv->tv_usec) * 1000;
if (ts.tv_nsec >= PER_NANO){
ts.tv_sec += 1;
ts.tv_nsec -= PER_NANO;
}
}
thread_debug("native_sleep %ld\n", tv ? tv->tv_sec : -1);
GVL_UNLOCK_BEGIN();
{
pthread_mutex_lock(&th->interrupt_lock);
th->unblock.func = ubf_pthread_cond_signal;
th->unblock.arg = th;
if (RUBY_VM_INTERRUPTED(th)) {
/* interrupted. return immediate */
thread_debug("native_sleep: interrupted before sleep\n");
}
else {
if (tv == 0 || ts.tv_sec < tvn.tv_sec /* overflow */ ) {
int r;
thread_debug("native_sleep: pthread_cond_wait start\n");
r = pthread_cond_wait(&th->native_thread_data.sleep_cond,
&th->interrupt_lock);
if (r) rb_bug("pthread_cond_wait: %d", r);
thread_debug("native_sleep: pthread_cond_wait end\n");
}
else {
int r;
thread_debug("native_sleep: pthread_cond_timedwait start (%ld, %ld)\n",
(unsigned long)ts.tv_sec, ts.tv_nsec);
r = pthread_cond_timedwait(&th->native_thread_data.sleep_cond,
&th->interrupt_lock, &ts);
if (r && r != ETIMEDOUT) rb_bug("pthread_cond_timedwait: %d", r);
thread_debug("native_sleep: pthread_cond_timedwait end (%d)\n", r);
}
}
th->unblock.func = 0;
th->unblock.arg = 0;
pthread_mutex_unlock(&th->interrupt_lock);
}
GVL_UNLOCK_END();
thread_debug("native_sleep done\n");
}
struct signal_thread_list {
rb_thread_t *th;
struct signal_thread_list *prev;
struct signal_thread_list *next;
};
#ifndef __CYGWIN__
static struct signal_thread_list signal_thread_list_anchor = {
0, 0, 0,
};
#endif
#define FGLOCK(lock, body) do { \
native_mutex_lock(lock); \
{ \
body; \
} \
native_mutex_unlock(lock); \
} while (0)
#if 0 /* for debug */
static void
print_signal_list(char *str)
{
struct signal_thread_list *list =
signal_thread_list_anchor.next;
thread_debug("list (%s)> ", str);
while(list){
thread_debug("%p (%p), ", list->th, list->th->thread_id);
list = list->next;
}
thread_debug("\n");
}
#endif
#ifndef __CYGWIN__
static void
add_signal_thread_list(rb_thread_t *th)
{
if (!th->native_thread_data.signal_thread_list) {
FGLOCK(&signal_thread_list_lock, {
struct signal_thread_list *list =
malloc(sizeof(struct signal_thread_list));
if (list == 0) {
fprintf(stderr, "[FATAL] failed to allocate memory\n");
exit(1);
}
list->th = th;
list->prev = &signal_thread_list_anchor;
list->next = signal_thread_list_anchor.next;
if (list->next) {
list->next->prev = list;
}
signal_thread_list_anchor.next = list;
th->native_thread_data.signal_thread_list = list;
});
}
}
#endif
static void
remove_signal_thread_list(rb_thread_t *th)
{
if (th->native_thread_data.signal_thread_list) {
FGLOCK(&signal_thread_list_lock, {
struct signal_thread_list *list =
(struct signal_thread_list *)
th->native_thread_data.signal_thread_list;
list->prev->next = list->next;
if (list->next) {
list->next->prev = list->prev;
}
th->native_thread_data.signal_thread_list = 0;
list->th = 0;
free(list); /* ok */
});
}
else {
/* */
}
}
static pthread_t timer_thread_id;
static pthread_cond_t timer_thread_cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t timer_thread_lock = PTHREAD_MUTEX_INITIALIZER;
static struct timespec *
get_ts(struct timespec *ts, unsigned long nsec)
{
struct timeval tv;
gettimeofday(&tv, 0);
ts->tv_sec = tv.tv_sec;
ts->tv_nsec = tv.tv_usec * 1000 + nsec;
if (ts->tv_nsec >= PER_NANO) {
ts->tv_sec++;
ts->tv_nsec -= PER_NANO;
}
return ts;
}
static void *
thread_timer(void *dummy)
{
struct timespec ts;
native_mutex_lock(&timer_thread_lock);
native_cond_broadcast(&timer_thread_cond);
#define WAIT_FOR_10MS() native_cond_timedwait(&timer_thread_cond, &timer_thread_lock, get_ts(&ts, PER_NANO/100))
while (system_working > 0) {
int err = WAIT_FOR_10MS();
if (err == ETIMEDOUT);
else if (err == 0 || err == EINTR) {
if (rb_signal_buff_size() == 0) break;
}
else rb_bug("thread_timer/timedwait: %d", err);
#if !defined(__CYGWIN__) && !defined(__SYMBIAN32__)
if (signal_thread_list_anchor.next) {
FGLOCK(&signal_thread_list_lock, {
struct signal_thread_list *list;
list = signal_thread_list_anchor.next;
while (list) {
ubf_select_each(list->th);
list = list->next;
}
});
}
#endif
timer_thread_function(dummy);
}
native_mutex_unlock(&timer_thread_lock);
return NULL;
}
static void
rb_thread_create_timer_thread(void)
{
rb_enable_interrupt();
if (!timer_thread_id) {
pthread_attr_t attr;
int err;
pthread_attr_init(&attr);
#ifdef PTHREAD_STACK_MIN
pthread_attr_setstacksize(&attr,
PTHREAD_STACK_MIN + (THREAD_DEBUG ? BUFSIZ : 0));
#endif
native_mutex_lock(&timer_thread_lock);
err = pthread_create(&timer_thread_id, &attr, thread_timer, 0);
if (err != 0) {
native_mutex_unlock(&timer_thread_lock);
fprintf(stderr, "[FATAL] Failed to create timer thread (errno: %d)\n", err);
exit(EXIT_FAILURE);
}
native_cond_wait(&timer_thread_cond, &timer_thread_lock);
native_mutex_unlock(&timer_thread_lock);
}
rb_disable_interrupt(); /* only timer thread recieve signal */
}
static int
native_stop_timer_thread(void)
{
int stopped;
native_mutex_lock(&timer_thread_lock);
stopped = --system_working <= 0;
if (stopped) {
native_cond_signal(&timer_thread_cond);
}
native_mutex_unlock(&timer_thread_lock);
if (stopped) {
native_thread_join(timer_thread_id);
}
return stopped;
}
static void
native_reset_timer_thread(void)
{
timer_thread_id = 0;
}
#ifdef HAVE_SIGALTSTACK
int
ruby_stack_overflowed_p(const rb_thread_t *th, const void *addr)
{
void *base;
size_t size;
const size_t water_mark = 1024 * 1024;
STACK_GROW_DIR_DETECTION;
if (th) {
size = th->machine_stack_maxsize;
base = (char *)th->machine_stack_start - STACK_DIR_UPPER(0, size);
}
#ifdef STACKADDR_AVAILABLE
else if (get_stack(&base, &size) == 0) {
STACK_DIR_UPPER(base = (char *)base + size, (void)0);
}
#endif
else {
return 0;
}
size /= 5;
if (size > water_mark) size = water_mark;
if (STACK_DIR_UPPER(1, 0)) {
if (size > ~(size_t)base+1) size = ~(size_t)base+1;
if (addr > base && addr <= (void *)((char *)base + size)) return 1;
}
else {
if (size > (size_t)base) size = (size_t)base;
if (addr > (void *)((char *)base - size) && addr <= base) return 1;
}
return 0;
}
#endif
#endif /* THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION */
|
the_stack_data/34601.c | #include <stdio.h>
int main(void){
printf("Hello world!\n");
return 0;
}
|
the_stack_data/35589.c | const char *__asan_default_options() {
return "detect_stack_use_after_return=1";
}
__attribute__((noinline)) volatile int* f() {
int val;
return &val;
}
int main() {
*f() = 1;
}
|
the_stack_data/87639264.c | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
// Complete the code to print the pattern.
int len = n*2 - 1;
for(int i=0;i<len;i++){
for(int j=0;j<len;j++){
int min = i < j ? i : j;
min = min < len-i ? min : len-i-1;
min = min < len-j-1 ? min : len-j-1;
printf("%d ", n-min);
}
printf("\n");
}
return 0;
}
|
the_stack_data/159514522.c | //===------ SparcDisassembler.cpp - Disassembler for PowerPC ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/* Capstone Disassembly Engine */
/* By Nguyen Anh Quynh <[email protected]>, 2013-2015 */
#ifdef CAPSTONE_HAS_SPARC
#include <stdio.h> // DEBUG
#include <stdlib.h>
#include <string.h>
#include "../../cs_priv.h"
#include "../../utils.h"
#include "../../MCInst.h"
#include "../../MCInstrDesc.h"
#include "../../MCFixedLenDisassembler.h"
#include "../../MCRegisterInfo.h"
#include "../../MCDisassembler.h"
#include "../../MathExtras.h"
#define GET_REGINFO_MC_DESC
#define GET_REGINFO_ENUM
#include "SparcGenRegisterInfo.inc"
static const unsigned IntRegDecoderTable[] = {
SP_G0, SP_G1, SP_G2, SP_G3,
SP_G4, SP_G5, SP_G6, SP_G7,
SP_O0, SP_O1, SP_O2, SP_O3,
SP_O4, SP_O5, SP_O6, SP_O7,
SP_L0, SP_L1, SP_L2, SP_L3,
SP_L4, SP_L5, SP_L6, SP_L7,
SP_I0, SP_I1, SP_I2, SP_I3,
SP_I4, SP_I5, SP_I6, SP_I7
};
static const unsigned FPRegDecoderTable[] = {
SP_F0, SP_F1, SP_F2, SP_F3,
SP_F4, SP_F5, SP_F6, SP_F7,
SP_F8, SP_F9, SP_F10, SP_F11,
SP_F12, SP_F13, SP_F14, SP_F15,
SP_F16, SP_F17, SP_F18, SP_F19,
SP_F20, SP_F21, SP_F22, SP_F23,
SP_F24, SP_F25, SP_F26, SP_F27,
SP_F28, SP_F29, SP_F30, SP_F31
};
static const unsigned DFPRegDecoderTable[] = {
SP_D0, SP_D16, SP_D1, SP_D17,
SP_D2, SP_D18, SP_D3, SP_D19,
SP_D4, SP_D20, SP_D5, SP_D21,
SP_D6, SP_D22, SP_D7, SP_D23,
SP_D8, SP_D24, SP_D9, SP_D25,
SP_D10, SP_D26, SP_D11, SP_D27,
SP_D12, SP_D28, SP_D13, SP_D29,
SP_D14, SP_D30, SP_D15, SP_D31
};
static const unsigned QFPRegDecoderTable[] = {
SP_Q0, SP_Q8, ~0U, ~0U,
SP_Q1, SP_Q9, ~0U, ~0U,
SP_Q2, SP_Q10, ~0U, ~0U,
SP_Q3, SP_Q11, ~0U, ~0U,
SP_Q4, SP_Q12, ~0U, ~0U,
SP_Q5, SP_Q13, ~0U, ~0U,
SP_Q6, SP_Q14, ~0U, ~0U,
SP_Q7, SP_Q15, ~0U, ~0U
};
static const unsigned FCCRegDecoderTable[] = {
SP_FCC0, SP_FCC1, SP_FCC2, SP_FCC3
};
static uint64_t getFeatureBits(int mode)
{
// support everything
return (uint64_t)-1;
}
static DecodeStatus DecodeIntRegsRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned Reg;
if (RegNo > 31)
return MCDisassembler_Fail;
Reg = IntRegDecoderTable[RegNo];
MCOperand_CreateReg0(Inst, Reg);
return MCDisassembler_Success;
}
static DecodeStatus DecodeI64RegsRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned Reg;
if (RegNo > 31)
return MCDisassembler_Fail;
Reg = IntRegDecoderTable[RegNo];
MCOperand_CreateReg0(Inst, Reg);
return MCDisassembler_Success;
}
static DecodeStatus DecodeFPRegsRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned Reg;
if (RegNo > 31)
return MCDisassembler_Fail;
Reg = FPRegDecoderTable[RegNo];
MCOperand_CreateReg0(Inst, Reg);
return MCDisassembler_Success;
}
static DecodeStatus DecodeDFPRegsRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned Reg;
if (RegNo > 31)
return MCDisassembler_Fail;
Reg = DFPRegDecoderTable[RegNo];
MCOperand_CreateReg0(Inst, Reg);
return MCDisassembler_Success;
}
static DecodeStatus DecodeQFPRegsRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
unsigned Reg;
if (RegNo > 31)
return MCDisassembler_Fail;
Reg = QFPRegDecoderTable[RegNo];
if (Reg == ~0U)
return MCDisassembler_Fail;
MCOperand_CreateReg0(Inst, Reg);
return MCDisassembler_Success;
}
static DecodeStatus DecodeFCCRegsRegisterClass(MCInst *Inst, unsigned RegNo,
uint64_t Address, const void *Decoder)
{
if (RegNo > 3)
return MCDisassembler_Fail;
MCOperand_CreateReg0(Inst, FCCRegDecoderTable[RegNo]);
return MCDisassembler_Success;
}
static DecodeStatus DecodeLoadInt(MCInst *Inst, unsigned insn, uint64_t Address,
const void *Decoder);
static DecodeStatus DecodeLoadFP(MCInst *Inst, unsigned insn, uint64_t Address,
const void *Decoder);
static DecodeStatus DecodeLoadDFP(MCInst *Inst, unsigned insn, uint64_t Address,
const void *Decoder);
static DecodeStatus DecodeLoadQFP(MCInst *Inst, unsigned insn, uint64_t Address,
const void *Decoder);
static DecodeStatus DecodeStoreInt(MCInst *Inst, unsigned insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeStoreFP(MCInst *Inst, unsigned insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeStoreDFP(MCInst *Inst, unsigned insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeStoreQFP(MCInst *Inst, unsigned insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeCall(MCInst *Inst, unsigned insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeSIMM13(MCInst *Inst, unsigned insn,
uint64_t Address, const void *Decoder);
static DecodeStatus DecodeJMPL(MCInst *Inst, unsigned insn, uint64_t Address,
const void *Decoder);
static DecodeStatus DecodeReturn(MCInst *MI, unsigned insn, uint64_t Address,
const void *Decoder);
static DecodeStatus DecodeSWAP(MCInst *Inst, unsigned insn, uint64_t Address,
const void *Decoder);
#define GET_SUBTARGETINFO_ENUM
#include "SparcGenSubtargetInfo.inc"
#include "SparcGenDisassemblerTables.inc"
/// readInstruction - read four bytes and return 32 bit word.
static DecodeStatus readInstruction32(const uint8_t *code, size_t len, uint32_t *Insn)
{
if (len < 4)
// not enough data
return MCDisassembler_Fail;
// Encoded as a big-endian 32-bit word in the stream.
*Insn = (code[3] << 0) |
(code[2] << 8) |
(code[1] << 16) |
((uint32_t) code[0] << 24);
return MCDisassembler_Success;
}
bool Sparc_getInstruction(csh ud, const uint8_t *code, size_t code_len, MCInst *MI,
uint16_t *size, uint64_t address, void *info)
{
uint32_t Insn;
DecodeStatus Result;
Result = readInstruction32(code, code_len, &Insn);
if (Result == MCDisassembler_Fail)
return false;
if (MI->flat_insn->detail) {
memset(MI->flat_insn->detail, 0, sizeof(cs_detail));
}
Result = decodeInstruction_4(DecoderTableSparc32, MI, Insn, address,
(MCRegisterInfo *)info, 0);
if (Result != MCDisassembler_Fail) {
*size = 4;
return true;
}
return false;
}
typedef DecodeStatus (*DecodeFunc)(MCInst *MI, unsigned insn, uint64_t Address,
const void *Decoder);
static DecodeStatus DecodeMem(MCInst *MI, unsigned insn, uint64_t Address,
const void *Decoder,
bool isLoad, DecodeFunc DecodeRD)
{
DecodeStatus status;
unsigned rd = fieldFromInstruction_4(insn, 25, 5);
unsigned rs1 = fieldFromInstruction_4(insn, 14, 5);
bool isImm = fieldFromInstruction_4(insn, 13, 1) != 0;
unsigned rs2 = 0;
unsigned simm13 = 0;
if (isImm)
simm13 = SignExtend32(fieldFromInstruction_4(insn, 0, 13), 13);
else
rs2 = fieldFromInstruction_4(insn, 0, 5);
if (isLoad) {
status = DecodeRD(MI, rd, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
}
// Decode rs1.
status = DecodeIntRegsRegisterClass(MI, rs1, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
// Decode imm|rs2.
if (isImm)
MCOperand_CreateImm0(MI, simm13);
else {
status = DecodeIntRegsRegisterClass(MI, rs2, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
}
if (!isLoad) {
status = DecodeRD(MI, rd, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
}
return MCDisassembler_Success;
}
static DecodeStatus DecodeLoadInt(MCInst *Inst, unsigned insn, uint64_t Address,
const void *Decoder)
{
return DecodeMem(Inst, insn, Address, Decoder, true,
DecodeIntRegsRegisterClass);
}
static DecodeStatus DecodeLoadFP(MCInst *Inst, unsigned insn, uint64_t Address,
const void *Decoder)
{
return DecodeMem(Inst, insn, Address, Decoder, true,
DecodeFPRegsRegisterClass);
}
static DecodeStatus DecodeLoadDFP(MCInst *Inst, unsigned insn, uint64_t Address,
const void *Decoder)
{
return DecodeMem(Inst, insn, Address, Decoder, true,
DecodeDFPRegsRegisterClass);
}
static DecodeStatus DecodeLoadQFP(MCInst *Inst, unsigned insn, uint64_t Address,
const void *Decoder)
{
return DecodeMem(Inst, insn, Address, Decoder, true,
DecodeQFPRegsRegisterClass);
}
static DecodeStatus DecodeStoreInt(MCInst *Inst, unsigned insn,
uint64_t Address, const void *Decoder)
{
return DecodeMem(Inst, insn, Address, Decoder, false,
DecodeIntRegsRegisterClass);
}
static DecodeStatus DecodeStoreFP(MCInst *Inst, unsigned insn, uint64_t Address,
const void *Decoder)
{
return DecodeMem(Inst, insn, Address, Decoder, false,
DecodeFPRegsRegisterClass);
}
static DecodeStatus DecodeStoreDFP(MCInst *Inst, unsigned insn,
uint64_t Address, const void *Decoder)
{
return DecodeMem(Inst, insn, Address, Decoder, false,
DecodeDFPRegsRegisterClass);
}
static DecodeStatus DecodeStoreQFP(MCInst *Inst, unsigned insn,
uint64_t Address, const void *Decoder)
{
return DecodeMem(Inst, insn, Address, Decoder, false,
DecodeQFPRegsRegisterClass);
}
static DecodeStatus DecodeCall(MCInst *MI, unsigned insn,
uint64_t Address, const void *Decoder)
{
unsigned tgt = fieldFromInstruction_4(insn, 0, 30);
tgt <<= 2;
MCOperand_CreateImm0(MI, tgt);
return MCDisassembler_Success;
}
static DecodeStatus DecodeSIMM13(MCInst *MI, unsigned insn,
uint64_t Address, const void *Decoder)
{
unsigned tgt = SignExtend32(fieldFromInstruction_4(insn, 0, 13), 13);
MCOperand_CreateImm0(MI, tgt);
return MCDisassembler_Success;
}
static DecodeStatus DecodeJMPL(MCInst *MI, unsigned insn, uint64_t Address,
const void *Decoder)
{
DecodeStatus status;
unsigned rd = fieldFromInstruction_4(insn, 25, 5);
unsigned rs1 = fieldFromInstruction_4(insn, 14, 5);
unsigned isImm = fieldFromInstruction_4(insn, 13, 1);
unsigned rs2 = 0;
unsigned simm13 = 0;
if (isImm)
simm13 = SignExtend32(fieldFromInstruction_4(insn, 0, 13), 13);
else
rs2 = fieldFromInstruction_4(insn, 0, 5);
// Decode RD.
status = DecodeIntRegsRegisterClass(MI, rd, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
// Decode RS1.
status = DecodeIntRegsRegisterClass(MI, rs1, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
// Decode RS1 | SIMM13.
if (isImm)
MCOperand_CreateImm0(MI, simm13);
else {
status = DecodeIntRegsRegisterClass(MI, rs2, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
}
return MCDisassembler_Success;
}
static DecodeStatus DecodeReturn(MCInst *MI, unsigned insn, uint64_t Address,
const void *Decoder)
{
DecodeStatus status;
unsigned rs1 = fieldFromInstruction_4(insn, 14, 5);
unsigned isImm = fieldFromInstruction_4(insn, 13, 1);
unsigned rs2 = 0;
unsigned simm13 = 0;
if (isImm)
simm13 = SignExtend32(fieldFromInstruction_4(insn, 0, 13), 13);
else
rs2 = fieldFromInstruction_4(insn, 0, 5);
// Decode RS1.
status = DecodeIntRegsRegisterClass(MI, rs1, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
// Decode RS2 | SIMM13.
if (isImm)
MCOperand_CreateImm0(MI, simm13);
else {
status = DecodeIntRegsRegisterClass(MI, rs2, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
}
return MCDisassembler_Success;
}
static DecodeStatus DecodeSWAP(MCInst *MI, unsigned insn, uint64_t Address,
const void *Decoder)
{
DecodeStatus status;
unsigned rd = fieldFromInstruction_4(insn, 25, 5);
unsigned rs1 = fieldFromInstruction_4(insn, 14, 5);
unsigned isImm = fieldFromInstruction_4(insn, 13, 1);
unsigned rs2 = 0;
unsigned simm13 = 0;
if (isImm)
simm13 = SignExtend32(fieldFromInstruction_4(insn, 0, 13), 13);
else
rs2 = fieldFromInstruction_4(insn, 0, 5);
// Decode RD.
status = DecodeIntRegsRegisterClass(MI, rd, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
// Decode RS1.
status = DecodeIntRegsRegisterClass(MI, rs1, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
// Decode RS1 | SIMM13.
if (isImm)
MCOperand_CreateImm0(MI, simm13);
else {
status = DecodeIntRegsRegisterClass(MI, rs2, Address, Decoder);
if (status != MCDisassembler_Success)
return status;
}
return MCDisassembler_Success;
}
void Sparc_init(MCRegisterInfo *MRI)
{
/*
InitMCRegisterInfo(SparcRegDesc, 119, RA, PC,
SparcMCRegisterClasses, 8,
SparcRegUnitRoots,
86,
SparcRegDiffLists,
SparcRegStrings,
SparcSubRegIdxLists,
7,
SparcSubRegIdxRanges,
SparcRegEncodingTable);
*/
MCRegisterInfo_InitMCRegisterInfo(MRI, SparcRegDesc, 119,
0, 0,
SparcMCRegisterClasses, 8,
0, 0,
SparcRegDiffLists,
0,
SparcSubRegIdxLists, 7,
0);
}
#endif
|
the_stack_data/49286.c | // All things arithmetic
// JJM 051104
const int g_nSin_FP_16_16[360]=
{ 0x0000, 0x0477, 0x08EF, 0x0D65, 0x11DB, 0x164F, 0x1AC2, 0x1F32, 0x23A0, 0x280C, 0x2C74, 0x30D8, 0x3539, 0x3996, 0x3DEE, 0x4241, 0x4690,
0x4AD8, 0x4F1B, 0x5358, 0x578E, 0x5BBD, 0x5FE6, 0x6406, 0x681F, 0x6C30, 0x7039, 0x7438, 0x782F, 0x7C1C, 0x7FFF, 0x83D9, 0x87A8,
0x8B6D, 0x8F27, 0x92D5, 0x9679, 0x9A10, 0x9D9B, 0xA11B, 0xA48D, 0xA7F3, 0xAB4C, 0xAE97, 0xB1D5, 0xB504, 0xB826, 0xBB39, 0xBE3E,
0xC134, 0xC41B, 0xC6F3, 0xC9BB, 0xCC73, 0xCF1B, 0xD1B3, 0xD43B, 0xD6B3, 0xD919, 0xDB6F, 0xDDB3, 0xDFE7, 0xE208, 0xE418, 0xE617,
0xE803, 0xE9DE, 0xEBA6, 0xED5B, 0xEEFF, 0xF08F, 0xF20D, 0xF378, 0xF4D0, 0xF615, 0xF746, 0xF865, 0xF970, 0xFA67, 0xFB4B, 0xFC1C,
0xFCD9, 0xFD82, 0xFE17, 0xFE98, 0xFF06, 0xFF60, 0xFFA6, 0xFFD8, 0xFFF6, 0xFFFF, 0xFFF6, 0xFFD8, 0xFFA6, 0xFF60, 0xFF06, 0xFE98,
0xFE17, 0xFD82, 0xFCD9, 0xFC1C, 0xFB4B, 0xFA67, 0xF970, 0xF865, 0xF746, 0xF615, 0xF4D0, 0xF378, 0xF20D, 0xF08F, 0xEEFF, 0xED5B,
0xEBA6, 0xE9DE, 0xE803, 0xE617, 0xE419, 0xE208, 0xDFE7, 0xDDB3, 0xDB6F, 0xD919, 0xD6B3, 0xD43B, 0xD1B4, 0xCF1B, 0xCC73, 0xC9BB,
0xC6F3, 0xC41B, 0xC134, 0xBE3E, 0xBB3A, 0xB826, 0xB505, 0xB1D5, 0xAE97, 0xAB4C, 0xA7F3, 0xA48D, 0xA11B, 0x9D9C, 0x9A10, 0x9679,
0x92D6, 0x8F27, 0x8B6D, 0x87A8, 0x83D9, 0x8000, 0x7C1C, 0x782F, 0x7438, 0x7039, 0x6C30, 0x6820, 0x6407, 0x5FE6, 0x5BBE, 0x578E,
0x5358, 0x4F1B, 0x4AD9, 0x4690, 0x4242, 0x3DEE, 0x3996, 0x3539, 0x30D9, 0x2C74, 0x280C, 0x23A1, 0x1F32, 0x1AC2, 0x1650, 0x11DB,
0x0D66, 0x08EF, 0x0477, 0x0000, 0xFFFFFB89, 0xFFFFF712, 0xFFFFF29B, 0xFFFFEE25, 0xFFFFE9B1, 0xFFFFE53E, 0xFFFFE0CE, 0xFFFFDC60, 0xFFFFD7F5, 0xFFFFD38C, 0xFFFFCF28, 0xFFFFCAC7,
0xFFFFC66A, 0xFFFFC212, 0xFFFFBDBF, 0xFFFFB971, 0xFFFFB528, 0xFFFFB0E5, 0xFFFFACA8, 0xFFFFA872, 0xFFFFA443, 0xFFFFA01A, 0xFFFF9BFA, 0xFFFF97E1, 0xFFFF93D0, 0xFFFF8FC8, 0xFFFF8BC8, 0xFFFF87D1,
0xFFFF83E4, 0xFFFF8001, 0xFFFF7C27, 0xFFFF7858, 0xFFFF7493, 0xFFFF70D9, 0xFFFF6D2B, 0xFFFF6988, 0xFFFF65F0, 0xFFFF6265, 0xFFFF5EE6, 0xFFFF5B73, 0xFFFF580D, 0xFFFF54B5, 0xFFFF5169, 0xFFFF4E2C,
0xFFFF4AFC, 0xFFFF47DA, 0xFFFF44C7, 0xFFFF41C2, 0xFFFF3ECC, 0xFFFF3BE5, 0xFFFF390E, 0xFFFF3646, 0xFFFF338D, 0xFFFF30E5, 0xFFFF2E4D, 0xFFFF2BC5, 0xFFFF294E, 0xFFFF26E7, 0xFFFF2491, 0xFFFF224D,
0xFFFF201A, 0xFFFF1DF8, 0xFFFF1BE8, 0xFFFF19E9, 0xFFFF17FD, 0xFFFF1622, 0xFFFF145A, 0xFFFF12A5, 0xFFFF1101, 0xFFFF0F71, 0xFFFF0DF3, 0xFFFF0C88, 0xFFFF0B30, 0xFFFF09EB, 0xFFFF08BA, 0xFFFF079B,
0xFFFF0690, 0xFFFF0599, 0xFFFF04B5, 0xFFFF03E4, 0xFFFF0327, 0xFFFF027E, 0xFFFF01E9, 0xFFFF0168, 0xFFFF00FA, 0xFFFF00A0, 0xFFFF005A, 0xFFFF0028, 0xFFFF000A, 0xFFFF0001, 0xFFFF000A, 0xFFFF0028,
0xFFFF005A, 0xFFFF00A0, 0xFFFF00FA, 0xFFFF0167, 0xFFFF01E9, 0xFFFF027E, 0xFFFF0327, 0xFFFF03E4, 0xFFFF04B5, 0xFFFF0599, 0xFFFF0690, 0xFFFF079B, 0xFFFF08BA, 0xFFFF09EB, 0xFFFF0B30, 0xFFFF0C88,
0xFFFF0DF3, 0xFFFF0F71, 0xFFFF1101, 0xFFFF12A4, 0xFFFF145A, 0xFFFF1622, 0xFFFF17FD, 0xFFFF19E9, 0xFFFF1BE7, 0xFFFF1DF8, 0xFFFF2019, 0xFFFF224D, 0xFFFF2491, 0xFFFF26E7, 0xFFFF294D, 0xFFFF2BC5,
0xFFFF2E4C, 0xFFFF30E5, 0xFFFF338D, 0xFFFF3645, 0xFFFF390D, 0xFFFF3BE5, 0xFFFF3ECC, 0xFFFF41C2, 0xFFFF44C6, 0xFFFF47DA, 0xFFFF4AFB, 0xFFFF4E2B, 0xFFFF5169, 0xFFFF54B4, 0xFFFF580D, 0xFFFF5B73,
0xFFFF5EE5, 0xFFFF6264, 0xFFFF65F0, 0xFFFF6987, 0xFFFF6D2A, 0xFFFF70D9, 0xFFFF7493, 0xFFFF7857, 0xFFFF7C27, 0xFFFF8000, 0xFFFF83E4, 0xFFFF87D1, 0xFFFF8BC7, 0xFFFF8FC7, 0xFFFF93CF, 0xFFFF97E0,
0xFFFF9BF9, 0xFFFFA01A, 0xFFFFA442, 0xFFFFA872, 0xFFFFACA8, 0xFFFFB0E4, 0xFFFFB527, 0xFFFFB970, 0xFFFFBDBE, 0xFFFFC212, 0xFFFFC66A, 0xFFFFCAC6, 0xFFFFCF27, 0xFFFFD38C, 0xFFFFD7F4, 0xFFFFDC5F,
0xFFFFE0CD, 0xFFFFE53E, 0xFFFFE9B0, 0xFFFFEE25, 0xFFFFF29A, 0xFFFFF711, 0xFFFFFB88,
};
const int g_nCos_FP_16_16[360]=
{ 0x10000, 0xFFF6, 0xFFD8, 0xFFA6, 0xFF60, 0xFF06, 0xFE98, 0xFE17, 0xFD82, 0xFCD9, 0xFC1C, 0xFB4B, 0xFA67, 0xF970, 0xF865, 0xF746, 0xF615,
0xF4D0, 0xF378, 0xF20D, 0xF08F, 0xEEFF, 0xED5B, 0xEBA6, 0xE9DE, 0xE803, 0xE617, 0xE419, 0xE208, 0xDFE7, 0xDDB3, 0xDB6F, 0xD919,
0xD6B3, 0xD43B, 0xD1B3, 0xCF1B, 0xCC73, 0xC9BB, 0xC6F3, 0xC41B, 0xC134, 0xBE3E, 0xBB3A, 0xB826, 0xB504, 0xB1D5, 0xAE97, 0xAB4C,
0xA7F3, 0xA48D, 0xA11B, 0x9D9C, 0x9A10, 0x9679, 0x92D5, 0x8F27, 0x8B6D, 0x87A8, 0x83D9, 0x8000, 0x7C1C, 0x782F, 0x7438, 0x7039,
0x6C30, 0x681F, 0x6407, 0x5FE6, 0x5BBE, 0x578E, 0x5358, 0x4F1B, 0x4AD8, 0x4690, 0x4242, 0x3DEE, 0x3996, 0x3539, 0x30D8, 0x2C74,
0x280C, 0x23A0, 0x1F32, 0x1AC2, 0x164F, 0x11DB, 0x0D65, 0x08EF, 0x0477, 0x0000, 0xFFFFFB89, 0xFFFFF711, 0xFFFFF29B, 0xFFFFEE25, 0xFFFFE9B1, 0xFFFFE53E,
0xFFFFE0CE, 0xFFFFDC60, 0xFFFFD7F5, 0xFFFFD38C, 0xFFFFCF28, 0xFFFFCAC7, 0xFFFFC66A, 0xFFFFC212, 0xFFFFBDBF, 0xFFFFB970, 0xFFFFB528, 0xFFFFB0E5, 0xFFFFACA8, 0xFFFFA872, 0xFFFFA443, 0xFFFFA01A,
0xFFFF9BFA, 0xFFFF97E1, 0xFFFF93D0, 0xFFFF8FC8, 0xFFFF8BC8, 0xFFFF87D1, 0xFFFF83E4, 0xFFFF8001, 0xFFFF7C27, 0xFFFF7858, 0xFFFF7493, 0xFFFF70D9, 0xFFFF6D2B, 0xFFFF6988, 0xFFFF65F0, 0xFFFF6265,
0xFFFF5EE5, 0xFFFF5B73, 0xFFFF580D, 0xFFFF54B4, 0xFFFF5169, 0xFFFF4E2B, 0xFFFF4AFC, 0xFFFF47DA, 0xFFFF44C7, 0xFFFF41C2, 0xFFFF3ECC, 0xFFFF3BE5, 0xFFFF390E, 0xFFFF3646, 0xFFFF338D, 0xFFFF30E5,
0xFFFF2E4D, 0xFFFF2BC5, 0xFFFF294D, 0xFFFF26E7, 0xFFFF2491, 0xFFFF224D, 0xFFFF2019, 0xFFFF1DF8, 0xFFFF1BE8, 0xFFFF19E9, 0xFFFF17FD, 0xFFFF1622, 0xFFFF145A, 0xFFFF12A5, 0xFFFF1101, 0xFFFF0F71,
0xFFFF0DF3, 0xFFFF0C88, 0xFFFF0B30, 0xFFFF09EB, 0xFFFF08BA, 0xFFFF079B, 0xFFFF0690, 0xFFFF0599, 0xFFFF04B5, 0xFFFF03E4, 0xFFFF0327, 0xFFFF027E, 0xFFFF01E9, 0xFFFF0168, 0xFFFF00FA, 0xFFFF00A0,
0xFFFF005A, 0xFFFF0028, 0xFFFF000A, 0xFFFF0001, 0xFFFF000A, 0xFFFF0028, 0xFFFF005A, 0xFFFF00A0, 0xFFFF00FA, 0xFFFF0167, 0xFFFF01E9, 0xFFFF027E, 0xFFFF0327, 0xFFFF03E4, 0xFFFF04B5, 0xFFFF0599,
0xFFFF0690, 0xFFFF079B, 0xFFFF08BA, 0xFFFF09EB, 0xFFFF0B30, 0xFFFF0C88, 0xFFFF0DF3, 0xFFFF0F71, 0xFFFF1101, 0xFFFF12A5, 0xFFFF145A, 0xFFFF1622, 0xFFFF17FD, 0xFFFF19E9, 0xFFFF1BE7, 0xFFFF1DF8,
0xFFFF2019, 0xFFFF224D, 0xFFFF2491, 0xFFFF26E7, 0xFFFF294D, 0xFFFF2BC5, 0xFFFF2E4C, 0xFFFF30E5, 0xFFFF338D, 0xFFFF3645, 0xFFFF390D, 0xFFFF3BE5, 0xFFFF3ECC, 0xFFFF41C2, 0xFFFF44C6, 0xFFFF47DA,
0xFFFF4AFB, 0xFFFF4E2B, 0xFFFF5169, 0xFFFF54B4, 0xFFFF580D, 0xFFFF5B73, 0xFFFF5EE5, 0xFFFF6264, 0xFFFF65F0, 0xFFFF6987, 0xFFFF6D2A, 0xFFFF70D9, 0xFFFF7493, 0xFFFF7858, 0xFFFF7C27, 0xFFFF8000,
0xFFFF83E4, 0xFFFF87D1, 0xFFFF8BC8, 0xFFFF8FC7, 0xFFFF93D0, 0xFFFF97E0, 0xFFFF9BF9, 0xFFFFA01A, 0xFFFFA442, 0xFFFFA872, 0xFFFFACA8, 0xFFFFB0E5, 0xFFFFB527, 0xFFFFB970, 0xFFFFBDBE, 0xFFFFC212,
0xFFFFC66A, 0xFFFFCAC7, 0xFFFFCF27, 0xFFFFD38C, 0xFFFFD7F4, 0xFFFFDC5F, 0xFFFFE0CD, 0xFFFFE53E, 0xFFFFE9B0, 0xFFFFEE25, 0xFFFFF29A, 0xFFFFF711, 0xFFFFFB88, 0x0000, 0x0477, 0x08EE,
0x0D65, 0x11DB, 0x164F, 0x1AC2, 0x1F32, 0x23A0, 0x280B, 0x2C73, 0x30D8, 0x3539, 0x3996, 0x3DEE, 0x4241, 0x468F, 0x4AD8, 0x4F1B,
0x5358, 0x578E, 0x5BBD, 0x5FE5, 0x6406, 0x681F, 0x6C30, 0x7038, 0x7438, 0x782F, 0x7C1C, 0x7FFF, 0x83D9, 0x87A8, 0x8B6D, 0x8F27,
0x92D5, 0x9678, 0x9A10, 0x9D9B, 0xA11A, 0xA48D, 0xA7F3, 0xAB4B, 0xAE97, 0xB1D4, 0xB504, 0xB826, 0xBB39, 0xBE3E, 0xC134, 0xC41B,
0xC6F2, 0xC9BA, 0xCC73, 0xCF1B, 0xD1B3, 0xD43B, 0xD6B2, 0xD919, 0xDB6F, 0xDDB3, 0xDFE6, 0xE208, 0xE418, 0xE617, 0xE803, 0xE9DD,
0xEBA6, 0xED5B, 0xEEFF, 0xF08F, 0xF20D, 0xF378, 0xF4D0, 0xF615, 0xF746, 0xF865, 0xF970, 0xFA67, 0xFB4B, 0xFC1C, 0xFCD9, 0xFD82,
0xFE17, 0xFE98, 0xFF06, 0xFF60, 0xFFA6, 0xFFD8, 0xFFF6,
}; |
the_stack_data/141737.c | const unsigned char* key = {
0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x79, 0xa7, 0xc9,
0x57, 0x19, 0x7b, 0xa6, 0xd0, 0x70, 0x13, 0x1a, 0x4f, 0x86,
0xa7, 0xfc, 0xcc, 0xc7, 0xd5, 0x06, 0xe4, 0xac, 0x6e, 0xf5,
0x83, 0x38, 0x6f, 0x69, 0x1f, 0x8e, 0xdc, 0x7e, 0xd7
};
|
the_stack_data/151704883.c | #include<stdio.h>
#include<time.h>
#include<stdlib.h>
// function to merge the sub-arrays
void merge(int a[],int low,int mid ,int high)
{
int b[20]; //same size of a[]
int i, j, k;
i = low, j = mid + 1,k = low;
while(i <= mid && j <= high)
{
if(a[i]<=a[j])
b[k++]=a[i++];
else
b[k++]=a[j++]; //copying the elements
}
while (i<=mid)
b[k++]=a[i++];
while
(j<=high) b[k++]=a[j++];
for (k=low;k<=high;k++)
a[k]=b[k];
}
// merge sort function
void mergesort(int a[],int low,int high)
{
int mid;
if(low>=high)
return;
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
// main fucntion
int main()
{
int a[7] = {83, 20, 9, 50, 115, 61, 17};
int n = 7;
mergesort(a, 0, n-1);
printf("\n Sorted numbers are: ");
// function to print the sorted array
int k;
for(k = 0; k < 7; k++)
printf("%d, ",a[k]);
return 0;
}
|
the_stack_data/1119028.c | // program to copy one array to another using pointers.
#include <stdio.h>
#define SIZE 50
int print(int n, int *arr)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", *(arr + i));
}
int copyArray(int n, int *ptr1)
{
int arr2[n], i;
int *ptr2 = arr2;
for (i = 0; i <= n; i++)
*(ptr2 + i) = *(ptr1 + i);
printf("Output array:\n");
print(n, arr2);
}
int main()
{
int n, i, a[SIZE];
// input
printf("Enter the size of array:");
scanf("%d", &n);
printf("Enter the elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
copyArray(n, a);
return 0;
}
|
the_stack_data/190766929.c | #include <stdio.h>
int main(void) {
int i = 1;
char *p = (char *)&i;
puts(*p ? "LittleEndian" : "BigEndian");
return 0;
}
|
the_stack_data/326223.c | int main(){
int a,b;
a = 10;
b = 5;
a = a/b;
return a;
}
|
the_stack_data/93888640.c | extern int mumble;
extern void abort (void);
extern void exit (int);
int
main ()
{
if (++mumble != 42)
abort ();
exit (0);
}
|
the_stack_data/1028657.c | #include <stdlib.h>
#include <time.h>
#include <string.h>
#define NUM_PARTICLES (1 << 27) // 2^27
#define BLOCK_SIZE (1 << 12) // 2^12
#define NB_BLOCKS (1 << 15) // 2^15
#define K1 1.33
#define K2 3.07
#define DENSITY 0.2
typedef struct {
// Position
float x, y, z;
// Velocity
float vx, vy, vz;
// Charge
float c;
// Mass, volume (unused)
float m, v;
} particle;
particle *data;
int *counts;
int main(int argc, char **argv) {
char *mode = argv[1];
data = (particle *) calloc(NUM_PARTICLES, sizeof(particle));
counts = (int *) calloc(NB_BLOCKS, sizeof(int));
// Do something to all particles.
if (strcmp(mode, "apply_action") == 0) {
for (int i = 0; i < NUM_PARTICLES; i++) {
data[i].x += data[i].vx;
data[i].y += data[i].vy + K1 * data[i].c;
data[i].z += data[i].vz * K2;
}
// Populate the scene with particles in random positions.
} else if (strcmp(mode, "populate") == 0) {
srand(time(NULL));
for (int i = 0; i < NUM_PARTICLES * DENSITY; ) {
int block_index = rand() % NB_BLOCKS;
int *count = &(counts[block_index]);
if (*count < BLOCK_SIZE) {
int index = block_index + *count;
data[index].x = (float) rand();
data[index].y = (float) rand();
data[index].z = (float) rand();
data[index].vx = (float) rand();
data[index].vy = (float) rand();
data[index].vz = (float) rand();
data[index].c = (float) rand();
data[index].m = (float) rand();
data[index].v = (float) rand();
(*count)++;
i++;
}
}
}
free(data);
free(counts);
return 0;
}
|
the_stack_data/206392004.c | #include <stdio.h>
const char *my_array[] = {
"string1",
"str2",
"foobar"
};
int main(int argc, const char *argv[])
{
/* Directly passing my_array[1] works but shows a warning */
printf("%s\n", my_array[1]);
return 0;
}
|
the_stack_data/103264893.c | #include<stdio.h>
int main(void)
{
int n;
scanf("%d",&n);
int f[60]={0,1,1,2,3,5,8,3,1,4,5,9,4,3,7,0,7,7,4,1,5,6,1,7,8,5,3,8,1,9,0,9,9,8,7,5,2,7,9,6,5,1,6,7,3,0,3,3,6,9,5,4,9,3,2,5,7,2,9,1};
while(n--)
{
long long int k;
scanf("%lld",&k);
long long int res,r = 1;
for (int i=0; i<8*sizeof(long long unsigned int); i++)
{
long long int curr = r << i;
if (curr > k)
break;
res = curr;
}
printf("%d\n",f[(res-1)%60] );
}
return 0;
}
|
the_stack_data/90242.c | #include <stdio.h>
#include <math.h>
int iszs(int n)
{
int i,np = (int)(sqrt(n) + 1);
for (i = 2;i<np;i++)
{ if (n % i == 0)return 0; }
return 1;
}
int main()
{
int n;
scanf("%d",&n);
while (!iszs(++n));
printf("%d",n);
return 0;
} |
the_stack_data/1106164.c | #include <stdio.h>
#include <sys/types.h> // For opendir()
#include <dirent.h> // For opendir()
#include <stdlib.h> // For exit()
#include <sys/stat.h>
#include <unistd.h>
#include <time.h> // For ctime()
#include <grp.h> // For getgrgid()
#include <errno.h>
int filepermissions(char* str_path)
{
char str[] = "---------";
struct stat buf;
if( lstat(str_path, &buf) < 0)
{
perror("lstat failed on file\n");
return errno;
}
mode_t mode = buf.st_mode;
str[0] = (mode & S_IRUSR) ? 'r' : '-';
str[1] = (mode & S_IWUSR) ? 'w' : '-';
str[2] = (mode & S_IXUSR) ? 'x' : '-';
str[3] = (mode & S_IRUSR) ? 'r' : '-';
str[4] = (mode & S_IWGRP) ? 'w' : '-';
str[5] = (mode & S_IXGRP) ? 'x' : '-';
str[6] = (mode & S_IROTH) ? 'r' : '-';
str[7] = (mode & S_IWOTH) ? 'w' : '-';
str[8] = (mode & S_IXOTH) ? 'x' : '-';
printf("%s\t", str);
char* ptr;
if( S_ISREG(buf.st_mode)) ptr = "regular file";
else if (S_ISDIR(buf.st_mode)) ptr = "directory";
else if (S_ISCHR(buf.st_mode)) ptr = "character special";
else if (S_ISBLK(buf.st_mode)) ptr = "block special";
else if (S_ISFIFO(buf.st_mode)) ptr = "fifo";
#ifdef S_ISLNK
else if (S_ISLNK(buf.st_mode)) ptr = "symbolic link";
#endif
#ifdef S_ISSOCK
else if (S_ISSOCK(buf.st_mode)) ptr = "socket";
#endif
else
ptr = "unknown file bro :(";
printf("%s\t", ptr);
return 0;
}
int filetimes(char* str_path)
{
struct stat buf;
if (lstat(str_path, &buf) < 0)
{
perror("lstat failed");
return errno;
}
time_t accesstime = buf.st_atime;
char* timeptr = ctime(&accesstime);
printf("Access Time: %s", timeptr);
time_t modifytime = buf.st_mtime;
timeptr = ctime(&modifytime);
printf("Modify Time: %s", timeptr);
time_t statuschangetime = buf.st_ctime;
timeptr = ctime(&statuschangetime);
printf("Status Time: %s", timeptr);
return 0;
}
int filesizes(char* str_path)
{
struct stat buf;
if (lstat(str_path, &buf) < 0)
{
perror("stat() failed");
return errno;
}
off_t filesize = buf.st_size;
printf("%5llub\t", filesize);
printf("%s\n", str_path);
return 0;
}
int fileownership(char* str_path)
{
struct stat buf;
if (lstat(str_path, &buf ) < 0 )
{
perror("stat() failed");
return -1;
}
gid_t grpid = buf.st_gid;
uid_t usrid = buf.st_uid;
printf("%5d\t", grpid);
printf("%5d\t", usrid);
return 0;
}
int main( int argc, char* argv[] )
{
DIR *p_dir;
struct dirent *p_dirent;
if( (argc < 2) || ( strcmp( argv[1], "-h") == 0 ) || (argc > 3) )
{
printf("Usage: %s <dir name>\n", argv[0]);
printf("-h \t Show help\n");
printf("-vvv \t Be Very Verbose (default)\n");
printf("-P \t Be Precise\n");
exit(1);
}
if( (p_dir = opendir(argv[1])) == NULL )
{
printf("opendir(%s) failed\n", argv[1]);
exit(1);
}
while( (p_dirent = readdir(p_dir)) != NULL )
{
char *str_path = p_dirent->d_name;
if ( str_path == NULL )
{
printf("Null pointer found!\n");
exit(2);
}
if( filepermissions(str_path) != 0 )
printf("Something went wrong! Errno: %d\n", errno);
if( fileownership(str_path) != 0 )
printf("Something went wrong! Errno: %d\n", errno);
if( filesizes(str_path) != 0 )
printf("Something went wrong! Errno: %d\n", errno);
if( ! ((argv[2]) && strcmp(argv[2], "-p")) )
if( filetimes(str_path) != 0 )
printf("[filetimes]: Something went wrong! Errno: %d\n", errno);
}
closedir(p_dir);
return 0;
}
|
the_stack_data/1227901.c | // RUN: %clang_cc1 -triple i386-unknown-unknown %s -emit-llvm -o - | FileCheck %s
struct foo {
void *a;
int b;
};
// CHECK: @u = global %union.anon zeroinitializer
union { int i; float f; } u = { };
// CHECK: @u2 = global { i32, [4 x i8] } { i32 0, [4 x i8] undef }
union { int i; double f; } u2 = { };
// CHECK: @u3 = global %union.anon.1 zeroinitializer
union { double f; int i; } u3 = { };
// CHECK: @b = global [2 x i32] [i32 0, i32 22]
int b[2] = {
[1] = 22
};
// PR6955
struct ds {
struct {
struct {
short a;
};
short b;
struct {
short c;
};
};
};
// Traditional C anonymous member init
struct ds ds0 = { { { .a = 0 } } };
// C1X lookup-based anonymous member init cases
struct ds ds1 = { { .a = 1 } };
struct ds ds2 = { { .b = 1 } };
struct ds ds3 = { .a = 0 };
// CHECK: @ds4 = global %struct.ds { %struct.anon.3 { %struct.anon zeroinitializer, i16 0, %struct.anon.2 { i16 1 } } }
struct ds ds4 = { .c = 1 };
struct ds ds5 = { { { .a = 0 } }, .b = 1 };
struct ds ds6 = { { .a = 0, .b = 1 } };
// CHECK: @ds7 = global %struct.ds { %struct.anon.3 { %struct.anon { i16 2 }, i16 3, %struct.anon.2 zeroinitializer } }
struct ds ds7 = {
{ {
.a = 1
} },
.a = 2,
.b = 3
};
void test1(int argc, char **argv)
{
// CHECK: internal global %struct.foo { i8* null, i32 1024 }
static struct foo foo = {
.b = 1024,
};
// CHECK: bitcast %union.anon.4* %u2
// CHECK: call void @llvm.memset
union { int i; float f; } u2 = { };
// CHECK-NOT: call void @llvm.memset
union { int i; float f; } u3;
// CHECK: ret void
}
// PR7151
struct S {
int nkeys;
int *keys;
union {
void *data;
};
};
void test2() {
struct S *btkr;
*btkr = (struct S) {
.keys = 0,
{ .data = 0 },
};
}
|
the_stack_data/672.c | #include <stdint.h>
#include <unwind.h>
typedef _Unwind_Reason_Code (*__personality_routine)(
int version, _Unwind_Action actions, uint64_t exception_class,
struct _Unwind_Exception *exception_object,
struct _Unwind_Context *context);
_Unwind_Reason_Code __gxx_personality_v0(int version, _Unwind_Action actions,
uint64_t exception_class,
struct _Unwind_Exception *ue_header,
struct _Unwind_Context *context);
_Unwind_Reason_Code __cilk_personality_internal(
__personality_routine std_lib_personality, int version,
_Unwind_Action actions, uint64_t exception_class,
struct _Unwind_Exception *ue_header, struct _Unwind_Context *context);
_Unwind_Reason_Code __cilk_personality_cpp_v0(
int version, _Unwind_Action actions, uint64_t exception_class,
struct _Unwind_Exception *ue_header, struct _Unwind_Context *context) {
return __cilk_personality_internal(__gxx_personality_v0, version, actions,
exception_class, ue_header, context);
}
_Unwind_Reason_Code __cilk_personality_v0(int version, _Unwind_Action actions,
uint64_t exception_class,
struct _Unwind_Exception *ue_header,
struct _Unwind_Context *context) {
return __cilk_personality_cpp_v0(version, actions, exception_class,
ue_header, context);
}
|
the_stack_data/70704.c | /* Public domain. */
static void foo(void *yv, long long ylen) {
char *y = yv;
while (ylen > 0) { *y++ = 0; --ylen; }
__asm__ __volatile__("" : : "r"(yv) : "memory");
}
int main(void) {
char x[16];
foo(x, sizeof x);
return 0;
}
|
the_stack_data/57042.c | #include <stdio.h>
int min(int *a, int n) {
int i;
int min;
// ひとまず最初の値を最小値とみなす
min = *a;
for(i = 1; i < n; i++){
// minより小さい数が現れたらその値で更新する
min = min > *(a + i) ? *(a + i) : min;
}
return min;
}
int main() {
int a[] = {3, 10, 4, 1, 5, 9, 2, 6, 5};
printf("min=%d\n", min(a, sizeof(a) / sizeof(*a)));
return 0;
}
|
the_stack_data/1064588.c | /* Example code for Think OS.
Copyright 2014 Allen Downey
License: GNU GPLv3
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_CHILDREN 2
void perror_exit(char *s)
{
perror(s);
exit(-1);
}
void *check_malloc(int size)
{
void *p = malloc(size);
if (p == NULL) {
perror_exit("malloc failed");
}
return p;
}
typedef struct {
int counter;
int end;
int *array;
} Shared;
Shared *make_shared(int end)
{
int i;
Shared *shared = check_malloc(sizeof(Shared));
shared->counter = 0;
shared->end = end;
shared->array = check_malloc(shared->end * sizeof(int));
for (i=0; i<shared->end; i++) {
shared->array[i] = 0;
}
return shared;
}
pthread_t make_thread(void *(*entry)(void *), Shared *shared)
{
int ret;
pthread_t thread;
ret = pthread_create(&thread, NULL, entry, (void *) shared);
if (ret != 0) {
perror_exit("pthread_create failed");
}
return thread;
}
void join_thread(pthread_t thread)
{
int ret = pthread_join(thread, NULL);
if (ret == -1) {
perror_exit("pthread_join failed");
}
}
void child_code(Shared *shared)
{
/* printf("Starting child at counter %d\n", shared->counter); */
while (1) {
if (shared->counter >= shared->end) {
return;
}
shared->array[shared->counter]++;
shared->counter++;
if (shared->counter % 10000 == 0) {
/* printf("%d\n", shared->counter); */
}
}
}
void *entry(void *arg)
{
Shared *shared = (Shared *) arg;
child_code(shared);
/* printf("Child done.\n"); */
pthread_exit(NULL);
}
void check_array(Shared *shared)
{
int i, errors=0;
/* printf("Checking...\n"); */
for (i=0; i<shared->end; i++) {
if (shared->array[i] != 1) errors++;
}
/* printf("%d errors.\n", errors); */
}
int main()
{
int i;
pthread_t child[NUM_CHILDREN];
Shared *shared = make_shared(1000000);
for (i=0; i<NUM_CHILDREN; i++) {
child[i] = make_thread(entry, shared);
}
for (i=0; i<NUM_CHILDREN; i++) {
join_thread(child[i]);
}
check_array(shared);
return 0;
}
|
the_stack_data/592100.c |
#if defined (DM_TOOLCHAIN_ARDUINO)
#include <avr/pgmspace.h>
const unsigned char font[1520] PROGMEM=
#else
const unsigned char font[1520] =
#endif
{
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x00,0x00,0x18,0x18,0x00,0x00,
0x00,0x48,0x6C,0x24,0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x24,0x24,0x24,0x7F,0x12,0x12,0x12,0x7F,0x12,0x12,0x12,0x00,0x00,
0x00,0x00,0x08,0x1C,0x2A,0x2A,0x0A,0x0C,0x18,0x28,0x28,0x2A,0x2A,0x1C,0x08,0x08,
0x00,0x00,0x00,0x22,0x25,0x15,0x15,0x15,0x2A,0x58,0x54,0x54,0x54,0x22,0x00,0x00,
0x00,0x00,0x00,0x0C,0x12,0x12,0x12,0x0A,0x76,0x25,0x29,0x11,0x91,0x6E,0x00,0x00,
0x00,0x06,0x06,0x04,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x40,0x20,0x10,0x10,0x08,0x08,0x08,0x08,0x08,0x08,0x10,0x10,0x20,0x40,0x00,
0x00,0x02,0x04,0x08,0x08,0x10,0x10,0x10,0x10,0x10,0x10,0x08,0x08,0x04,0x02,0x00,
0x00,0x00,0x00,0x00,0x08,0x08,0x6B,0x1C,0x1C,0x6B,0x08,0x08,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x08,0x08,0x08,0x08,0x7F,0x08,0x08,0x08,0x08,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x04,0x03,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFE,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x00,0x00,
0x00,0x00,0x80,0x40,0x40,0x20,0x20,0x10,0x10,0x08,0x08,0x04,0x04,0x02,0x02,0x00,
0x00,0x00,0x00,0x18,0x24,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x24,0x18,0x00,0x00,
0x00,0x00,0x00,0x08,0x0E,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x3E,0x00,0x00,
0x00,0x00,0x00,0x3C,0x42,0x42,0x42,0x20,0x20,0x10,0x08,0x04,0x42,0x7E,0x00,0x00,
0x00,0x00,0x00,0x3C,0x42,0x42,0x20,0x18,0x20,0x40,0x40,0x42,0x22,0x1C,0x00,0x00,
0x00,0x00,0x00,0x20,0x30,0x28,0x24,0x24,0x22,0x22,0x7E,0x20,0x20,0x78,0x00,0x00,
0x00,0x00,0x00,0x7E,0x02,0x02,0x02,0x1A,0x26,0x40,0x40,0x42,0x22,0x1C,0x00,0x00,
0x00,0x00,0x00,0x38,0x24,0x02,0x02,0x1A,0x26,0x42,0x42,0x42,0x24,0x18,0x00,0x00,
0x00,0x00,0x00,0x7E,0x22,0x22,0x10,0x10,0x08,0x08,0x08,0x08,0x08,0x08,0x00,0x00,
0x00,0x00,0x00,0x3C,0x42,0x42,0x42,0x24,0x18,0x24,0x42,0x42,0x42,0x3C,0x00,0x00,
0x00,0x00,0x00,0x18,0x24,0x42,0x42,0x42,0x64,0x58,0x40,0x40,0x24,0x1C,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x18,0x00,0x00,0x00,0x00,0x18,0x18,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x08,0x08,0x04,
0x00,0x00,0x00,0x40,0x20,0x10,0x08,0x04,0x02,0x04,0x08,0x10,0x20,0x40,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0x00,0x00,0x00,0x7F,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x02,0x04,0x08,0x10,0x20,0x40,0x20,0x10,0x08,0x04,0x02,0x00,0x00,
0x00,0x00,0x00,0x3C,0x42,0x42,0x46,0x40,0x20,0x10,0x10,0x00,0x18,0x18,0x00,0x00,
0x00,0x00,0x00,0x1C,0x22,0x5A,0x55,0x55,0x55,0x55,0x2D,0x42,0x22,0x1C,0x00,0x00,
0x00,0x00,0x00,0x08,0x08,0x18,0x14,0x14,0x24,0x3C,0x22,0x42,0x42,0xE7,0x00,0x00,
0x00,0x00,0x00,0x1F,0x22,0x22,0x22,0x1E,0x22,0x42,0x42,0x42,0x22,0x1F,0x00,0x00,
0x00,0x00,0x00,0x7C,0x42,0x42,0x01,0x01,0x01,0x01,0x01,0x42,0x22,0x1C,0x00,0x00,
0x00,0x00,0x00,0x1F,0x22,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x22,0x1F,0x00,0x00,
0x00,0x00,0x00,0x3F,0x42,0x12,0x12,0x1E,0x12,0x12,0x02,0x42,0x42,0x3F,0x00,0x00,
0x00,0x00,0x00,0x3F,0x42,0x12,0x12,0x1E,0x12,0x12,0x02,0x02,0x02,0x07,0x00,0x00,
0x00,0x00,0x00,0x3C,0x22,0x22,0x01,0x01,0x01,0x71,0x21,0x22,0x22,0x1C,0x00,0x00,
0x00,0x00,0x00,0xE7,0x42,0x42,0x42,0x42,0x7E,0x42,0x42,0x42,0x42,0xE7,0x00,0x00,
0x00,0x00,0x00,0x3E,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x3E,0x00,0x00,
0x00,0x00,0x00,0x7C,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x11,0x0F,
0x00,0x00,0x00,0x77,0x22,0x12,0x0A,0x0E,0x0A,0x12,0x12,0x22,0x22,0x77,0x00,0x00,
0x00,0x00,0x00,0x07,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x42,0x7F,0x00,0x00,
0x00,0x00,0x00,0x77,0x36,0x36,0x36,0x36,0x2A,0x2A,0x2A,0x2A,0x2A,0x6B,0x00,0x00,
0x00,0x00,0x00,0xE3,0x46,0x46,0x4A,0x4A,0x52,0x52,0x52,0x62,0x62,0x47,0x00,0x00,
0x00,0x00,0x00,0x1C,0x22,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x22,0x1C,0x00,0x00,
0x00,0x00,0x00,0x3F,0x42,0x42,0x42,0x42,0x3E,0x02,0x02,0x02,0x02,0x07,0x00,0x00,
0x00,0x00,0x00,0x1C,0x22,0x41,0x41,0x41,0x41,0x41,0x4D,0x53,0x32,0x1C,0x60,0x00,
0x00,0x00,0x00,0x3F,0x42,0x42,0x42,0x3E,0x12,0x12,0x22,0x22,0x42,0xC7,0x00,0x00,
0x00,0x00,0x00,0x7C,0x42,0x42,0x02,0x04,0x18,0x20,0x40,0x42,0x42,0x3E,0x00,0x00,
0x00,0x00,0x00,0x7F,0x49,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x1C,0x00,0x00,
0x00,0x00,0x00,0xE7,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x3C,0x00,0x00,
0x00,0x00,0x00,0xE7,0x42,0x42,0x22,0x24,0x24,0x14,0x14,0x18,0x08,0x08,0x00,0x00,
0x00,0x00,0x00,0x6B,0x49,0x49,0x49,0x49,0x55,0x55,0x36,0x22,0x22,0x22,0x00,0x00,
0x00,0x00,0x00,0xE7,0x42,0x24,0x24,0x18,0x18,0x18,0x24,0x24,0x42,0xE7,0x00,0x00,
0x00,0x00,0x00,0x77,0x22,0x22,0x14,0x14,0x08,0x08,0x08,0x08,0x08,0x1C,0x00,0x00,
0x00,0x00,0x00,0x7E,0x21,0x20,0x10,0x10,0x08,0x04,0x04,0x42,0x42,0x3F,0x00,0x00,
0x00,0x78,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x78,0x00,
0x00,0x00,0x02,0x02,0x04,0x04,0x08,0x08,0x08,0x10,0x10,0x20,0x20,0x20,0x40,0x40,
0x00,0x1E,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x1E,0x00,
0x00,0x38,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,
0x00,0x06,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3C,0x42,0x78,0x44,0x42,0x42,0xFC,0x00,0x00,
0x00,0x00,0x00,0x03,0x02,0x02,0x02,0x1A,0x26,0x42,0x42,0x42,0x26,0x1A,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x44,0x02,0x02,0x02,0x44,0x38,0x00,0x00,
0x00,0x00,0x00,0x60,0x40,0x40,0x40,0x78,0x44,0x42,0x42,0x42,0x64,0xD8,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3C,0x42,0x7E,0x02,0x02,0x42,0x3C,0x00,0x00,
0x00,0x00,0x00,0xF0,0x88,0x08,0x08,0x7E,0x08,0x08,0x08,0x08,0x08,0x3E,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7C,0x22,0x22,0x1C,0x02,0x3C,0x42,0x42,0x3C,
0x00,0x00,0x00,0x03,0x02,0x02,0x02,0x3A,0x46,0x42,0x42,0x42,0x42,0xE7,0x00,0x00,
0x00,0x00,0x00,0x0C,0x0C,0x00,0x00,0x0E,0x08,0x08,0x08,0x08,0x08,0x3E,0x00,0x00,
0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x38,0x20,0x20,0x20,0x20,0x20,0x20,0x22,0x1E,
0x00,0x00,0x00,0x03,0x02,0x02,0x02,0x72,0x12,0x0A,0x16,0x12,0x22,0x77,0x00,0x00,
0x00,0x00,0x00,0x0E,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x3E,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0x92,0x92,0x92,0x92,0x92,0xB7,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3B,0x46,0x42,0x42,0x42,0x42,0xE7,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3C,0x42,0x42,0x42,0x42,0x42,0x3C,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1B,0x26,0x42,0x42,0x42,0x22,0x1E,0x02,0x07,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x78,0x44,0x42,0x42,0x42,0x44,0x78,0x40,0xE0,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x4C,0x04,0x04,0x04,0x04,0x1F,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7C,0x42,0x02,0x3C,0x40,0x42,0x3E,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x08,0x08,0x3E,0x08,0x08,0x08,0x08,0x08,0x30,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x63,0x42,0x42,0x42,0x42,0x62,0xDC,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE7,0x42,0x24,0x24,0x14,0x08,0x08,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xEB,0x49,0x49,0x55,0x55,0x22,0x22,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x76,0x24,0x18,0x18,0x18,0x24,0x6E,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE7,0x42,0x24,0x24,0x14,0x18,0x08,0x08,0x07,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7E,0x22,0x10,0x08,0x08,0x44,0x7E,0x00,0x00,
0x00,0xC0,0x20,0x20,0x20,0x20,0x20,0x10,0x20,0x20,0x20,0x20,0x20,0x20,0xC0,0x00,
0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,
0x00,0x06,0x08,0x08,0x08,0x08,0x08,0x10,0x08,0x08,0x08,0x08,0x08,0x08,0x06,0x00,
0x0C,0x32,0xC2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
|
the_stack_data/75138752.c | // Copyright (c) 2016 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
#include "malloc.h"
#include <stdio.h>
#include <string.h>
#ifdef JEMALLOC
#include <jemalloc/jemalloc.h>
const char* je_malloc_conf = "narenas:2";
void writecb(void *ref, const char *s) {
stats_buf *buf = (stats_buf *)(ref);
int len;
len = strlen(s);
if (buf->offset + len >= buf->size) {
buf->size *=2;
buf->buf = realloc(buf->buf, buf->size);
}
strncpy(buf->buf + buf->offset, s, len);
buf->offset += len;
}
char *doStats() {
stats_buf buf;
buf.size = 1024;
buf.buf = malloc(buf.size);
buf.offset = 0;
je_malloc_stats_print(writecb, &buf, NULL);
buf.buf[buf.offset] = 0;
return buf.buf;
}
#endif
void *mm_malloc(size_t sz) {
#ifdef JEMALLOC
return je_calloc(1, sz);
#else
return calloc(1, sz);
#endif
}
void mm_free(void *p) {
#ifdef JEMALLOC
return je_free(p);
#else
return free(p);
#endif
}
char *mm_stats() {
#ifdef JEMALLOC
return doStats();
#else
return NULL;
#endif
}
size_t mm_sizeat(void *p) {
#ifdef JEMALLOC
return je_sallocx(p, 0);
#else
return 0;
#endif
}
size_t mm_size() {
size_t resident, sz;
sz = sizeof(size_t);
#ifdef JEMALLOC
// Force stats cache flush
uint64_t epoch = 1;
sz = sizeof(epoch);
je_mallctl("epoch", &epoch, &sz, &epoch, sz);
je_mallctl("stats.resident", &resident, &sz, NULL, 0);
return resident;
#else
return 0;
#endif
}
int mm_free2os() {
#ifdef JEMALLOC
char buf[100];
unsigned int narenas;
size_t len = sizeof(narenas);
je_mallctl("arenas.narenas", &narenas, &len, NULL, 0);
sprintf(buf, "arena.%u.purge", narenas);
return je_mallctl(buf, NULL, NULL, NULL, 0);
#endif
return 0;
}
|
the_stack_data/218893843.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
static int leniv=4;
static int useshex;
static char *myfgets(char *str, int len, FILE *file) {
char *pt, *end;
int ch;
for ( pt = str, end = str+len-1; pt<end && (ch=getc(file))!=EOF && ch!='\r' && ch!='\n';
*pt++ = ch );
if ( ch=='\n' )
*pt++ = '\n';
else if ( ch=='\r' ) {
*pt++ = '\n';
if ((ch=getc(file))!='\n' )
ungetc(ch,file);
}
if ( pt==str )
return( NULL );
*pt = '\0';
return( str );
}
static int hex(int ch1, int ch2) {
if ( ch1>='0' && ch1<='9' )
ch1 -= '0';
else if ( ch1>='a' )
ch1 -= 'a'-10;
else
ch1 -= 'A'-10;
if ( ch2>='0' && ch2<='9' )
ch2 -= '0';
else if ( ch2>='a' )
ch2 -= 'a'-10;
else
ch2 -= 'A'-10;
return( (ch1<<4)|ch2 );
}
static int hexline=0;
static void tohex(FILE *out,int ch) {
int ch1, ch2;
ch1 = ch>>4;
if ( ch1<=9 )
putc('0'+ch1,out);
else
putc('A'-10+ch1,out);
ch2 = ch&0xf;
if ( ch2<=9 )
putc('0'+ch2,out);
else
putc('A'-10+ch2,out);
hexline += 2;
if ( hexline>70 ) {
putc('\n',out);
hexline = 0;
}
}
static unsigned short r;
#define c1 (unsigned short) 52845
#define c2 (unsigned short) 22719
static void initcode() {
r = 55665;
}
static int decode(unsigned char cypher) {
unsigned char plain = ( cypher ^ (r>>8));
r = (cypher + r) * c1 + c2;
return( plain );
}
static int encode(unsigned char plain) {
unsigned char cypher = ( plain ^ (r>>8));
r = (cypher + r) * c1 + c2;
return( cypher );
}
static void dumpzeros(FILE *out, unsigned char *zeros, int zcnt) {
while ( --zcnt >= 0 )
fputc(*zeros++,out);
}
static void decodestr(unsigned char *str, int len) {
unsigned short r = 4330;
unsigned char plain, cypher;
while ( len-->0 ) {
cypher = *str;
plain = ( cypher ^ (r>>8));
r = (cypher + r) * c1 + c2;
*str++ = plain;
}
}
static void encodestr(unsigned char *str, int len) {
unsigned short r = 4330;
unsigned char plain, cypher;
while ( len-->0 ) {
plain = *str;
cypher = ( plain ^ (r>>8));
r = (cypher + r) * c1 + c2;
*str++ = cypher;
}
}
static void decodebytes(FILE *out,unsigned char *binpt, int binlen ) {
unsigned char *end = binpt+binlen;
static char *commands[32] = { "?0", "hstem", "?2", "vstem", "vmoveto",
"rlineto", "hlineto", "vlineto", "rrcurveto", "closepath",
"callsubr", "return", "escape", "hsbw", "endchar", "?15", "?16",
"?17", "?18", "?19", "?20", "rmoveto", "hmoveto", "?23", "?24",
"?25", "?26", "?27", "?28", "?29", "vhcurveto", "hvcurveto" };
decodestr(binpt,binlen);
binpt += leniv;
while ( binpt<end ) {
int ch = *binpt++;
if ( ch>=32 && ch<=246 ) {
fprintf( out, " %d", ch-139 );
} else if ( ch>=247 && ch<=250 ) {
int ch2 = *binpt++;
fprintf( out, " %d", (ch-247)*256+ch2+108 );
} else if ( ch>=251 && ch<=254 ) {
int ch2 = *binpt++;
fprintf( out, " %d", -(ch-251)*256-ch2-108 );
} else if ( ch==255 ) {
int val;
val = *binpt++;
val = (val<<8) | *binpt++;
val = (val<<8) | *binpt++;
val = (val<<8) | *binpt++;
fprintf( out, " %d", val );
} else if ( ch!=12 ) {
fprintf( out, " %s", commands[ch]);
} else {
int ch2 = *binpt++;
if ( ch2==0 )
fprintf( out, " dotsection" );
else if ( ch2==1 )
fprintf( out, " vstem3" );
else if ( ch2==2 )
fprintf( out, " hstem3" );
else if ( ch2==6 )
fprintf( out, " seac" );
else if ( ch2==7 )
fprintf( out, " sbw" );
else if ( ch2==12 )
fprintf( out, " div" );
else if ( ch2==16 )
fprintf( out, " callothersubr" );
else if ( ch2==17 )
fprintf( out, " pop" );
else if ( ch2==33 )
fprintf( out, " setcurrentpoint" );
else
fprintf( out, " ?12-%d", ch2 );
}
}
}
/* In the book the token which starts a character description is always RD but*/
/* it's just the name of a subroutine which is defined in the private diction*/
/* and it could be anything. in one case it was "-|" (hyphen bar) so we can't*/
/* just look for RD we must be a bit smarter and figure out what the token is*/
/* It's defined as {string currentfile exch readstring pop} so look for that */
static int glorpline(FILE *temp, FILE *out,char *rdtok) {
char buffer[3000], *pt, *binstart;
int binlen;
int ch;
int innum, val, inbinary, inhex, cnt, inr, wasspace, nownum, nowr, nowspace, sptok;
char *rdline = "{string currentfile exch readstring pop}", *rpt;
char *rdline2 = "{string currentfile exch readhexstring pop}";
char *tokpt = NULL, *rdpt;
char temptok[255];
int intok, first, willbehex = 0;
int nibble=0, firstnibble=1;
ch = getc(temp);
if ( ch==EOF )
return( 0 );
ungetc(ch,temp);
innum = inr = 0; wasspace = 0; inbinary = inhex = 0; rpt = NULL; rdpt = NULL;
pt = buffer; binstart=NULL; binlen = 0; intok=0; sptok=0; first=1;
while ( (ch=getc(temp))!=EOF ) {
*pt++ = ch;
if ( pt>=buffer+sizeof(buffer)) {
fprintf(stderr,"Buffer overrun\n" );
exit(1);
}
nownum = nowspace = nowr = 0;
if ( rpt!=NULL && ch!=*rpt && ch=='h' && rpt-rdline>25 && rpt-rdline<30 &&
rdline2[rpt-rdline]=='h' ) {
rpt = rdline2 + (rpt-rdline);
willbehex = 1;
}
if ( inbinary ) {
if ( --cnt==0 )
inbinary = 0;
} else if ( inhex ) {
if ( isdigit(ch) || (ch>='a'&&ch<='f') || (ch>='A' && ch<='F')) {
int h;
if ( isdigit(ch)) h = ch-'0';
else if ( ch>='a' && ch<='f' ) h = ch-'a'+10;
else h = ch-'A'+10;
if ( firstnibble ) {
nibble = h;
--pt;
} else {
pt[-1] = (nibble<<4)|h;
if ( --cnt==0 )
inbinary = inhex = 0;
}
firstnibble = !firstnibble;
} else {
--pt;
/* skip everything not hex */
}
} else if ( ch=='/' ) {
intok = 1;
tokpt = temptok;
} else if ( intok && !isspace(ch) && ch!='{' && ch!='[' ) {
*tokpt++ = ch;
} else if ( (intok||sptok) && (ch=='{' || ch=='[')) {
*tokpt = '\0';
rpt = rdline+1;
intok = sptok = 0;
} else if ( intok ) {
*tokpt = '\0';
intok = 0;
sptok = 1;
} else if ( sptok && isspace(ch)) {
nowspace = 1;
if ( ch=='\n' || ch=='\r' )
break;
} else if ( sptok && !isdigit(ch) )
sptok = 0;
else if ( rpt!=NULL && ch==*rpt ) {
if ( *++rpt=='\0' ) {
/* it matched the character definition string so this is the */
/* token we want to search for */
strcpy(rdtok,temptok);
useshex = willbehex;
}
} else if ( isdigit(ch)) {
nownum = 1;
sptok = 0;
if ( innum )
val = 10*val + ch-'0';
else
val = ch-'0';
} else if ( isspace(ch)) {
nowspace = 1;
if ( ch=='\n' || ch=='\r' )
break;
} else if ( wasspace && ch==*rdtok ) {
nowr = 1;
rdpt = rdtok+1;
} else if ( inr && ch==*rdpt ) {
if ( *++rdpt =='\0' ) {
ch = getc(temp);
*pt++ = ch;
if ( isspace(ch) && val!=0 ) {
inhex = useshex;
inbinary = !useshex;
cnt = val;
binstart = pt;
binlen = val;
if ( binlen>sizeof(buffer)) {
fprintf(stderr, "Buffer overflow needs to be at least %d\ndying gracefully.\n", binlen);
exit(1);
}
}
} else
nowr = 1;
}
innum = nownum; wasspace = nowspace; inr = nowr;
first = 0;
}
if ( ch=='\r' ) {
ch=getc(temp);
if ( ch!='\n' )
ungetc(ch,temp);
pt[-1]='\n';
}
*pt = '\0';
if ( binstart==NULL ) {
if (( pt = strstr(buffer,"/lenIV"))!=NULL )
leniv = strtol(pt+6,NULL,0);
fputs(buffer,out);
} else {
for ( pt=buffer; pt<binstart; ++pt )
putc(*pt,out);
decodebytes(out,(unsigned char *) binstart,binlen);
for ( pt=binstart+binlen; *pt; ++pt )
putc(*pt,out);
}
return( 1 );
}
static int nrandombytes[4];
#define EODMARKLEN 16
#define bgetc(extra,in) (*(extra)=='\0' ? getc(in) : (unsigned char ) *(extra)++ )
static void decrypteexec(FILE *in,FILE *temp, int hassectionheads, char *extra) {
int ch1, ch2, ch3, ch4, binary;
int zcnt;
unsigned char zeros[EODMARKLEN+6+1];
int sect_len;
while ( (ch1=bgetc(extra,in))!=EOF && (ch1==' ' || ch1=='\t' || ch1=='\n' || ch1=='\r'));
/* Mac POST resources also have 6 bytes inserted here. They appear to be */
/* a four byte length followed by ^B ^@ */
if ( ch1==0200 && hassectionheads ) {
/* skip the 6 byte section header in pfb files that follows eexec */
ch1 = bgetc(extra,in);
sect_len = bgetc(extra,in);
sect_len |= bgetc(extra,in)<<8;
sect_len |= bgetc(extra,in)<<16;
sect_len |= bgetc(extra,in)<<24;
sect_len -= 3;
ch1 = bgetc(extra,in);
}
ch2 = bgetc(extra,in); ch3 = bgetc(extra,in); ch4 = bgetc(extra,in);
binary = 0;
if ( ch1<'0' || (ch1>'9' && ch1<'A') || ( ch1>'F' && ch1<'a') || (ch1>'f') ||
ch2<'0' || (ch2>'9' && ch2<'A') || (ch2>'F' && ch2<'a') || (ch2>'f') ||
ch3<'0' || (ch3>'9' && ch3<'A') || (ch3>'F' && ch3<'a') || (ch3>'f') ||
ch4<'0' || (ch4>'9' && ch4<'A') || (ch4>'F' && ch4<'a') || (ch4>'f') )
binary = 1;
if ( ch1==EOF || ch2==EOF || ch3==EOF || ch4==EOF ) {
return;
}
initcode();
if ( binary ) {
nrandombytes[0] = decode(ch1);
nrandombytes[1] = decode(ch2);
nrandombytes[2] = decode(ch3);
nrandombytes[3] = decode(ch4);
zcnt = 0;
while (( ch1=bgetc(extra,in))!=EOF ) {
--sect_len;
if ( hassectionheads ) {
if ( sect_len==0 && ch1==0200 ) {
ch1 = bgetc(extra,in);
sect_len = bgetc(extra,in);
sect_len |= bgetc(extra,in)<<8;
sect_len |= bgetc(extra,in)<<16;
sect_len |= bgetc(extra,in)<<24;
sect_len += 1;
if ( ch1=='\1' )
break;
} else {
zcnt = 0;
putc(decode(ch1),temp);
}
} else {
if ( ch1=='0' ) ++zcnt; else {dumpzeros(temp,zeros,zcnt); zcnt = 0; }
if ( zcnt>EODMARKLEN )
break;
if ( zcnt==0 )
putc(decode(ch1),temp);
else
zeros[zcnt-1] = decode(ch1);
}
}
} else {
nrandombytes[0] = decode(hex(ch1,ch2));
nrandombytes[1] = decode(hex(ch3,ch4));
ch1 = bgetc(extra,in); ch2 = bgetc(extra,in); ch3 = bgetc(extra,in); ch4 = bgetc(extra,in);
nrandombytes[2] = decode(hex(ch1,ch2));
nrandombytes[3] = decode(hex(ch3,ch4));
zcnt = 0;
while (( ch1=bgetc(extra,in))!=EOF ) {
while ( ch1!=EOF && isspace(ch1)) ch1 = bgetc(extra,in);
while ( (ch2=bgetc(extra,in))!=EOF && isspace(ch2));
if ( ch1=='0' && ch2=='0' ) ++zcnt; else { dumpzeros(temp,zeros,zcnt); zcnt = 0;}
if ( zcnt>EODMARKLEN )
break;
if ( zcnt==0 )
putc(decode(hex(ch1,ch2)),temp);
else
zeros[zcnt-1] = decode(hex(ch1,ch2));
}
}
while (( ch1=bgetc(extra,in))=='0' || isspace(ch1) );
if ( ch1!=EOF ) ungetc(ch1,in);
}
static void decryptbinary(FILE *in,FILE *temp, char *line, long solpos) {
int i, cnt, ch;
char *pt;
fprintf( stderr, "This program does not handled cid-keyed fonts. Sorry\n" );
exit(1);
pt = strstr(line,"(Binary)");
pt += strlen("(Binary)");
cnt = strtol(pt,NULL,10);
pt = strstr(line,"StartData ");
pt += strlen("StartData ");
solpos += pt-line;
fseek(in,SEEK_SET,solpos);
initcode();
nrandombytes[0] = decode(getc(in));
nrandombytes[1] = decode(getc(in));
nrandombytes[2] = decode(getc(in));
nrandombytes[3] = decode(getc(in));
for ( i = 0; ( ch=getc(in))!=EOF && i<cnt; ++i )
putc(decode(ch),temp);
}
#if 0
static void encrypteexec(FILE *temp,FILE *out) {
int glorped, i;
initcode();
tohex(out,encode(nrandombytes[0]));
tohex(out,encode(nrandombytes[1]));
tohex(out,encode(nrandombytes[2]));
tohex(out,encode(nrandombytes[3]));
/* read till we get /CharStrings */
while (( glorped=glorpline(temp,out,0))==0 );
/* read till end of temp file */
while (( glorped=glorpline(temp,out,1))!=-1 );
/* output 512 zeros */
putc('\n',out);
for ( i = 0; i<8; ++i )
fputs("0000000000000000000000000000000000000000000000000000000000000000\n", out);
}
#endif
static void decryptagain(FILE *temp,FILE *out) {
char rdtok[255];
strcpy(rdtok,"RD");
while ( glorpline(temp,out,rdtok));
}
static void doubledecrypt(char *outputfile,char *fontname) {
FILE *in, *temp, *out;
char buffer[256]/*, *tempname*/;
char *pt;
int first, hassectionheads;
int mightbegsf = 1;
long oldpos;
leniv = 4;
useshex = 0;
in = fopen(fontname,"r");
if ( in==NULL ) {
fprintf( stderr, "Cannot open %s\n", fontname );
return;
}
if ( outputfile==NULL ) {
pt = strrchr(fontname,'/'); if ( pt==NULL ) pt = fontname; else ++pt;
sprintf( buffer,"%s.decrypt", pt);
outputfile=buffer;
}
out = fopen(outputfile,"w");
if ( out==NULL ) {
fprintf( stderr, "Cannot open %s for output\n", outputfile );
fclose(in);
return;
}
#if 0
tempname = tempnam(NULL,"dcrpt");
sprintf( buffer,"%s.decrypt", pt);
temp = fopen(tempname,"w+");
if ( temp==NULL ) {
fprintf( stderr, "Cannot open %s for temp\n", tempname );
fclose(in); fclose(out);
return;
}
#else
temp = tmpfile();
if ( temp==NULL ) {
fprintf( stderr, "Cannot open temporary file\n" );
fclose(in); fclose(out);
return;
}
#endif
first = 1; hassectionheads = 0;
oldpos = ftell(in);
while ( myfgets(buffer,sizeof(buffer),in)!=NULL ) {
/* Mac POST resources also have 6 bytes inserted here. They appear to be */
/* a four byte length followed by ^A ^@ */
if ( first && buffer[0]=='\200' ) {
hassectionheads = 1;
fputs(buffer+6,out);
} else
fputs(buffer,out);
first = 0;
if ( strstr(buffer,"currentfile")!=NULL && strstr(buffer, "eexec")!=NULL )
break;
if ( strstr(buffer,"(Binary)")!=NULL && strstr(buffer, "StartData")!=NULL )
break;
if ( strstr(buffer,"Blend")!=NULL )
mightbegsf = 0;
if ( mightbegsf ) {
if ( strstr(buffer,"/Private")!=NULL || strstr(buffer,"/Subrs")!=NULL ||
strstr(buffer,"/CharStrings")!=NULL )
break;
if ( strstr(buffer,"/CIDInit")!=NULL )
mightbegsf = 0;
}
oldpos = ftell(in);
}
if ( strstr(buffer,"currentfile")!=NULL && strstr(buffer, "eexec")!=NULL ) {
decrypteexec(in,temp,hassectionheads,strstr(buffer, "eexec")+5);
rewind(temp);
decryptagain(temp,out);
} else if ( strstr(buffer,"(Binary)")!=NULL && strstr(buffer, "StartData")!=NULL ) {
decryptbinary(in,temp,buffer,oldpos);
rewind(temp);
decryptagain(temp,out);
} else
decryptagain(in,out);
while ( myfgets(buffer,sizeof(buffer),in)!=NULL ) {
if ( buffer[0]!='\200' || !hassectionheads )
fputs(buffer,out);
}
fclose(in); fclose(out); fclose(temp);
#if 0
unlink(tempname); free(tempname);
#endif
}
int main( int argc, char **argv) {
int i;
char *outputfile=NULL;
for ( i=1; i<argc; ++i ) {
if ( strcmp("-o",argv[i])==0 )
outputfile = argv[++i];
else {
doubledecrypt(outputfile,argv[i]);
}
}
return( 0 );
}
|
the_stack_data/941809.c |
void vectormul ( volatile int *cmd, volatile int *resp, int a[4096], int b[4096], int result[4096] ) {
#pragma HLS INTERFACE ap_ctrl_none port=return
#pragma HLS INTERFACE axis port=cmd
#pragma HLS INTERFACE axis port=resp
#pragma HLS INTERFACE bram depth=1024 port=a
#pragma HLS INTERFACE bram depth=1024 port=b
#pragma HLS INTERFACE bram depth=1024 port=result
#pragma HLS RESOURCE variable=a core=RAM_1P_BRAM
#pragma HLS RESOURCE variable=b core=RAM_1P_BRAM
#pragma HLS RESOURCE variable=result core=RAM_1P_BRAM
int i,op, start,end;
// Accumulate each channel
For_Loop: while (1) {
op= *cmd; //get the start command
end= *cmd;
start =*cmd;
if (op==1)
add_Loop: for (i=start;i<end;i++) {
result[i]= a[i]*b[i];
if (i == end-1)
*resp= 1; //means I am done.
}
else if (op==2)
sub_Loop: for (i=start;i<end;i++) {
result[i]= a[i] / b[i];
if (i == end-1)
*resp= 1; //means I am done.
}
}
}
|
the_stack_data/98576710.c | #include<stdio.h>
int main(void)
{
float salary;
printf("\aEnter your desired monthly salary:");
printf(" $________\b\b\b\b\b\b\b\b");
scanf("%f", &salary);
printf("\n\t$%.2f a month is $%.2f a year.", salary, salary * 12.0);
printf("\rGee!\n");
return 0;
}
|
the_stack_data/200143235.c | /* { dg-do run { target { stdint_types } } } */
#include <stdint.h>
extern void abort (void);
int main()
{
int i = 1;
int *p = &i;
uintptr_t iptr;
iptr = (uintptr_t)p - (uintptr_t)&iptr;
p = (int *)((uintptr_t)&iptr + iptr);
if (*p != 1)
abort ();
return 0;
}
|
the_stack_data/484039.c | #include <stdio.h>
int main(){
int c, i,repit=0, vetor[10];
for (c=0;c<=9;c++){
printf("Digite um numero");
scanf("%d", &vetor[c]);
}
for(i=0; i<=9; i++){
for(c=i+1;c<=9;c++){
if(vetor[i] == vetor[c]){
repit++;
}
}
}
printf("aconteceu %d repeticoes",repit);
return 0;
}
|
the_stack_data/181393113.c | #include <stdio.h>
#define SIZE 10
int main()
{
int x[SIZE], i, max, min, sum = 0;
printf("Enter 10 integers:\n");
for (i = 0; i < SIZE; i++)
{
printf("%d:", i + 1);
scanf("%d", &x[i]);
}
return 0;
}
|
the_stack_data/92329044.c | #ifdef STM32G4xx
#include "stm32g4xx_ll_cordic.c"
#endif
|
the_stack_data/818434.c | #include <stdio.h>
#include <stddef.h>
static struct sss{
size_t f;
long long snd;
} sss;
#define _offsetof(st,f) ((char *)&((st *) 16)->f - (char *) 16)
int main (void) {
printf ("+++Struct size_t-longlong:\n");
printf ("size=%d,align=%d,offset-size_t=%d,offset-longlong=%d,\nalign-size_t=%d,align-longlong=%d\n",
sizeof (sss), __alignof__ (sss),
_offsetof (struct sss, f), _offsetof (struct sss, snd),
__alignof__ (sss.f), __alignof__ (sss.snd));
return 0;
}
|
the_stack_data/443239.c | /* { dg-options "-mxl-gp-opt -G 16" } */
/* { dg-final { scan-assembler "\.sbss\[^2]+" } } */
struct test_s {
int a;
int b;
int c;
int d;
} global;
int testfunc ()
{
/* { dg-final { scan-assembler "\lwi\tr(\[0-9]\|\[1-2]\[0-9]\|3\[0-1]),r13" } } */
return global.a;
}
|
the_stack_data/37636546.c | #include <stdio.h>
/*
* Just a simple program so I can inspect the assembly code.
* gcc -m32 -S -c main.c
*/
int main(int argc, char *argv[]) {
printf("I like the number %d.\n", 4 * 6);
return 0xf00d;
} |
the_stack_data/23597.c | #if 0
mini_getdents
mini_buf 128
globals_on_stack
mini_start
shrinkelf
INCLUDESRC
LDSCRIPT default
OPTFLAG -Os
return
#endif
int main(){
volatile int ret=42;
volatile unsigned int a1=0;
volatile struct dirent * a2=0;
volatile unsigned int a3=0;
getdents(a1,a2,a3);
return(ret);
}
|
the_stack_data/198581258.c | #include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
uint64_t *scores;
struct marble {
uint32_t value;
struct marble *prev, *next;
} *current;
uint32_t addmarble(uint32_t marble) {
if (marble % 23 == 0) {
uint32_t score = marble;
current = current->prev->prev->prev->prev->prev->prev;
score += current->prev->value;
current->prev->prev->next = current;
free(current->prev);
current->prev = current->prev->prev;
return score;
} else {
struct marble *m = malloc(sizeof *m);
m->value = marble;
m->next = current->next->next;
m->prev = current->next;
current->next->next->prev = m;
current->next->next = m;
current = m;
return 0;
}
}
#ifdef DEBUG
void printmarbles(struct marble *initial) {
struct marble *tmp = initial;
do {
printf("%" PRIu32 " ", tmp->value);
tmp = tmp->next;
} while (tmp != initial);
}
#endif
int main(int argc, char **argv) {
long players = strtol(argv[1], NULL, 10);
uint32_t marbles = (uint32_t)strtol(argv[2], NULL, 10);
scores = malloc(players * sizeof *scores);
memset(scores, 0, players * sizeof *scores);
current = malloc(sizeof *current);
#ifdef DEBUG
struct marble *initial = current;
#endif
current->value = 0;
current->prev = current->next = current;
size_t bestplayer;
uint32_t maxscore = 0;
for (uint32_t m = 1; m <= marbles; m++) {
#ifdef DEBUG
printf("[%" PRIu32 "] [P %ld] ", m, (m - 1) % players);
printmarbles(initial);
printf("\n");
#endif
uint32_t score = addmarble(m);
if (score) {
size_t player = (m - 1) % players;
scores[player] += score;
if (scores[player] > maxscore) {
maxscore = scores[player];
bestplayer = player;
}
}
}
printf("Winner: Player #%zd Score %" PRIu32 "\n", bestplayer + 1, maxscore);
return 0;
}
|
the_stack_data/182952023.c | #include <stdio.h>
#include <string.h>
#include <errno.h> // for errno
#include <math.h>
#include <limits.h> // for INT_MAX
#include <stdlib.h> // for strtol
#include <time.h>
#include <omp.h>
typedef unsigned int ValueType;
typedef unsigned int* UnsignedVector;
ValueType threads_number;
void print_order(UnsignedVector vector, long size){
printf("%u", vector[0]);
for (int i = 1; i < size; ++i) {
printf(", %u", vector[i]);
}
}
void print_and_validade_order(UnsignedVector vector, long size){
printf("%u", vector[0]);
int less = vector[0];
for (int i = 1; i < size; ++i) {
printf(", %u", vector[i]);
if(less > vector[i]){
printf("\nNot sorted!\n");
exit(-1);
}
less = vector[i];
}
}
void validade_order(UnsignedVector vector, long size){
int less = vector[0];
for (int i = 1; i < size; ++i) {
if(less > vector[i]){
printf("Not sorted!\n");
exit(-1);
}
less = vector[i];
}
}
void merge_vector(UnsignedVector vector, ValueType left, ValueType mid, ValueType right) {
ValueType size_A = right - left + 1;
ValueType size_L = mid - left + 1;
ValueType size_R = size_A - size_L;
ValueType* L_aux = malloc(size_L*sizeof(ValueType));
ValueType* R_aux = malloc(size_R*sizeof(ValueType));
memcpy(L_aux, vector + left , sizeof(ValueType)*size_L);
memcpy(R_aux, vector + (mid + 1), sizeof(ValueType)*size_R);
ValueType i = 0;
ValueType j = 0;
ValueType k = left;
while(i < size_L && j < size_R) {
vector[k++] = (L_aux[i] < R_aux[j]) ? L_aux[i++] : R_aux[j++];
}
if(i < size_L) {
memcpy(vector + k, L_aux + i, sizeof(ValueType)*(size_L-i));
}
else {
memcpy(vector + k, R_aux + j, sizeof(ValueType)*(size_R-j));
}
free(L_aux);
free(R_aux);
}
void merge_sort_vector_internal(UnsignedVector vector, ValueType left, ValueType right) {
if(right > left) {
ValueType mid = left + (right - left) / 2;
merge_sort_vector_internal(vector, left, mid);
merge_sort_vector_internal(vector, mid + 1, right);
merge_vector(vector, left, mid, right);
}
}
void merge_vectors(UnsignedVector vector, UnsignedVector limits, ValueType size) {
if(size == 2){
merge_vector(vector, limits[0], limits[1]-1, limits[2]-1);
return;
}
if(size == 3){
merge_vector(vector, limits[0], limits[1]-1, limits[2]-1);
merge_vector(vector, limits[0], limits[2]-1, limits[3]-1);
return;
}
#pragma omp parallel sections num_threads(threads_number) default(none) shared(vector, limits, size)
{
#pragma omp section
{
merge_vectors(vector, limits, (size/2) );
}
#pragma omp section
{
merge_vectors(vector, limits + (size/2), (size/2));
}
}
if(size % 2 == 0) {
merge_vector(vector, limits[0], limits[(size/2)]-1, limits[size]-1);
} else {
merge_vector(vector, limits[0], limits[(size/2)]-1, limits[size-1]-1);
merge_vector(vector, limits[0], limits[size-1]-1, limits[size]-1);
}
}
void merge_sort_vector(UnsignedVector vector, ValueType left, ValueType right) {
ValueType distance = (right - left) / threads_number;
UnsignedVector limits = malloc((threads_number+1)*sizeof(double));
for (ValueType i = 0; i < threads_number; ++i) {
limits[i] = (left + i*distance);
}
limits[threads_number] = right;
#pragma omp parallel num_threads(threads_number) default(none) shared(vector, limits, threads_number)
{
#pragma omp for schedule(guided)
for (ValueType j = 0; j < threads_number; ++j) {
merge_sort_vector_internal(vector, limits[j], limits[j+1]-1);
}
}
merge_vectors(vector, limits, threads_number);
free(limits);
}
long convert_str_long(char *str){
char *p;
errno = 0;
long conv = strtol(str, &p, 10);
if (errno != 0 || *p != '\0')
{
printf("%s não é um número!\n", str);
exit(-1);
}
return (long)conv;
}
int main( int argc, char **argv ) {
if (argc != 5) {
printf("É necessário informar 3 argumentos na seguinte ordem:\n");
printf("1º Seed para gerar os números pseudo-aleatórios\n2º Tamanho do vetor\n3º 1 se o resultado da ordenação deve ser exibido e 0 caso contrário\n");
return -1;
}
threads_number = convert_str_long(argv[1]);
ValueType seed = convert_str_long(argv[2]);
ValueType size = convert_str_long(argv[3]);
int print_result = convert_str_long(argv[4]);
srand(seed);
UnsignedVector vector = malloc(size*sizeof(ValueType));
for (int i = 0; i < size; ++i) {
vector[i] = rand();
}
double t = omp_get_wtime();
merge_sort_vector(vector, 0, size);
t = omp_get_wtime() - t;
if (print_result == 1){
printf("{\"Vetor\": [");
print_and_validade_order(vector, size);
printf("], \"time\": %.10lf}\n", t);
} else {
validade_order(vector, size);
printf("%.10lf\n", t);
}
free(vector);
return 0;
} /* main */ |
the_stack_data/857930.c | int main() {
int x1 = -6;
int x2 = 41;
int x3 = 0;
int x4 = 1248;
int x5 = 0;
int x6 = 0;
int x7 = 14234;
int x8 = 0;
int x9 = 0;
int x10 = 12341;
int x11 = 432;
int x12 = 0;
int x13 = x9 + x11 + x12 + x5 + x7;
int x14 = x1 + x2 + x3 + x9 + x6;
int x15 = x9 + x14 + x10 + x13 * x12;
printf("%d", x15);
return 0;
}
|
the_stack_data/262201.c | #include <stdio.h>
#include <stdlib.h>
// 3) Faça um programa que leia 2 valores inteiros e chame uma função que receba estas 2 variáveis e troque o seu conteúdo (por referência), ou seja, esta função é chamada passando duas variáveis A e B por exemplo e, após a execução da função, A conterá o valor de B e B conterá o valor de A.
void trocaValores();
int main() {
system("cls");
int a, b;
printf(">>> POINTEIROS\n\n");
printf("Digite o valor de A: \t");
scanf("%d", &a);
printf("Digite o valor de B: \t");
scanf("%d", &b);
printf("\n\nAntes de trocar os valores: \n");
printf("A: %d \t | \t B: %d\n\n", a, b);
trocaValores(&a, &b);
printf("Apos a troca de valores: \n");
printf("A: %d \t | \t B: %d\n\n", a, b);
return 0;
}
void trocaValores(int *a, int *b) {
int b_value = *b;
*b = *a;
*a = b_value;
} |
the_stack_data/103776.c | #define _GNU_SOURCE
#define __CRT__NO_INLINE
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
int vasprintf(char ** __restrict__ ret,
const char * __restrict__ format,
va_list ap) {
int len;
/* Get Length */
len = _vsnprintf(NULL,0,format,ap);
if (len < 0) return -1;
/* +1 for \0 terminator. */
*ret = malloc(len + 1);
/* Check malloc fail*/
if (!*ret) return -1;
/* Write String */
_vsnprintf(*ret,len+1,format,ap);
/* Terminate explicitly */
(*ret)[len] = '\0';
return len;
}
|
the_stack_data/162642030.c | // RUN: %theta -checks=signed-overflow "%s" | FileCheck "%s"
// CHECK: Verification FAILED
int __VERIFIER_nondet_int();
int main(void)
{
int x = __VERIFIER_nondet_int();
int y = __VERIFIER_nondet_int();
// CHECK: Signed integer overflow in {{.*}}overflow_simple.c at line [[# @LINE + 1]] column 14
return x + y;
}
|
the_stack_data/51701484.c | /*
* Copyright (c) Microsoft Corporation
* SPDX-License-Identifier: MIT
*/
#pragma clang section text = "xdp_prog"
int
func()
{
return 42;
}
|
the_stack_data/124030.c | /*
// Copyright (c) 2016-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#ifdef OC_SECURITY
#include <stdarg.h>
#include <stdint.h>
#include <string.h>
#include "mbedtls/config.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/entropy.h"
#include "mbedtls/md.h"
#include "mbedtls/oid.h"
#include "mbedtls/pkcs5.h"
#include "mbedtls/ssl.h"
#include "mbedtls/ssl_cookie.h"
#include "mbedtls/ssl_internal.h"
#include "mbedtls/timing.h"
#ifdef OC_DEBUG
#include "mbedtls/debug.h"
#include "mbedtls/error.h"
#include "mbedtls/platform.h"
#endif /* OC_DEBUG */
#include "api/oc_events.h"
#include "api/oc_main.h"
#include "api/oc_session_events_internal.h"
#include "messaging/coap/engine.h"
#include "messaging/coap/observe.h"
#include "oc_acl_internal.h"
#include "oc_api.h"
#include "oc_audit.h"
#include "oc_buffer.h"
#include "oc_client_state.h"
#include "oc_config.h"
#include "oc_core_res.h"
#include "oc_cred_internal.h"
#include "oc_doxm.h"
#include "oc_endpoint.h"
#include "oc_pstat.h"
#include "oc_roles.h"
#include "oc_svr.h"
#include "oc_tls.h"
#ifdef OC_OSCORE
#include "oc_oscore.h"
#endif /* OC_OSCORE */
OC_PROCESS(oc_tls_handler, "TLS Process");
OC_MEMB(tls_peers_s, oc_tls_peer_t, OC_MAX_TLS_PEERS);
OC_LIST(tls_peers);
static mbedtls_entropy_context entropy_ctx;
static mbedtls_ctr_drbg_context ctr_drbg_ctx;
static mbedtls_ssl_cookie_ctx cookie_ctx;
static oc_random_pin_t random_pin;
unsigned char PIN[8];
#define PIN_LEN (8)
void
oc_tls_generate_random_pin(void)
{
int p = 0;
while (p < PIN_LEN) {
PIN[p++] = oc_random_value() % 10 + 48;
}
if (random_pin.cb) {
random_pin.cb(PIN, PIN_LEN, random_pin.data);
}
}
void
oc_set_random_pin_callback(oc_random_pin_cb_t cb, void *data)
{
random_pin.cb = cb;
random_pin.data = data;
}
#ifdef OC_CLIENT
static bool use_pin_obt_psk_identity = false;
void
oc_tls_use_pin_obt_psk_identity(void)
{
use_pin_obt_psk_identity = true;
}
#endif /* OC_CLIENT */
#ifdef OC_PKI
static bool auto_assert_all_roles = true;
void
oc_auto_assert_roles(bool auto_assert)
{
auto_assert_all_roles = auto_assert;
}
typedef struct oc_x509_cacrt_t
{
struct oc_x509_cacrt_t *next;
size_t device;
oc_sec_cred_t *cred;
mbedtls_x509_crt *cert;
} oc_x509_cacrt_t;
OC_MEMB(ca_certs_s, oc_x509_cacrt_t, OC_MAX_NUM_DEVICES);
OC_LIST(ca_certs);
typedef struct oc_x509_crt_t
{
struct oc_x509_crt_t *next;
size_t device;
oc_sec_cred_t *cred;
mbedtls_x509_crt cert;
mbedtls_pk_context pk;
oc_x509_cacrt_t *ctx;
} oc_x509_crt_t;
#include "oc_certs.h"
OC_MEMB(identity_certs_s, oc_x509_crt_t, 2 * OC_MAX_NUM_DEVICES);
OC_LIST(identity_certs);
mbedtls_x509_crt trust_anchors;
#endif /* OC_PKI */
#ifndef OC_DYNAMIC_ALLOCATION
#define MBEDTLS_ALLOC_BUF_SIZE (20000)
#include "mbedtls/memory_buffer_alloc.h"
static unsigned char alloc_buf[MBEDTLS_ALLOC_BUF_SIZE];
#endif /* !OC_DYNAMIC_ALLOCATION */
#define PERSONALIZATION_DATA "IoTivity-Lite-TLS"
#define CCM_MAC_KEY_LENGTH (0)
#define CBC_IV_LENGTH (0)
#define CCM_IV_LENGTH (4)
#define GCM_IV_LENGTH (12)
#define AES128_KEY_LENGTH (16)
#define AES256_KEY_LENGTH (32)
#define SHA256_MAC_KEY_LENGTH (32)
static int *ciphers = NULL;
#ifdef OC_PKI
static int selected_mfg_cred = -1;
static int selected_id_cred = -1;
#ifdef OC_CLOUD
static const int default_priority[12] = {
#else /* OC_CLOUD */
static const int default_priority[6] = {
#endif /* !OC_CLOUD */
#else /* OC_PKI */
static const int default_priority[2] = {
#endif /* !OC_PKI */
MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
#ifdef OC_PKI
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
#ifdef OC_CLOUD
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
#endif /* OC_CLOUD */
#endif /* OC_PKI */
0
};
#ifdef OC_CLIENT
static const int psk_priority[2] = {
MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, 0
};
static const int anon_ecdh_priority[2] = {
MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256, 0
};
#endif /* OC_CLIENT */
static const int jw_otm_priority[2] = {
MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256, 0
};
static const int pin_otm_priority[2] = {
MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, 0
};
#ifdef OC_PKI
static const int cert_otm_priority[5] = {
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM, 0
};
#endif /* OC_PKI */
#ifdef OC_CLIENT
#ifdef OC_PKI
#ifdef OC_CLOUD
static const int cloud_priority[7] = {
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
0
};
#endif /* OC_CLOUD */
static const int cert_priority[5] = {
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM, 0
};
#endif /* OC_PKI */
#endif /* OC_CLIENT */
#ifdef OC_PKI
mbedtls_x509_crt *
oc_tls_get_trust_anchors(void)
{
return &trust_anchors;
}
#endif /* OC_PKI */
#ifdef OC_DEBUG
static void
oc_mbedtls_debug(void *ctx, int level, const char *file, int line,
const char *str)
{
(void)ctx;
(void)level;
PRINT("mbedtls_log: %s:%04d: %s", file, line, str);
}
#endif /* OC_DEBUG */
static bool
is_peer_active(oc_tls_peer_t *peer)
{
oc_tls_peer_t *p = (oc_tls_peer_t *)oc_list_head(tls_peers);
while (p != NULL) {
if (p == peer) {
return true;
}
p = p->next;
}
return false;
}
static oc_event_callback_retval_t
reset_in_RFOTM(void *data)
{
size_t device = (size_t)data;
oc_pstat_reset_device(device, true);
return OC_EVENT_DONE;
}
static oc_event_callback_retval_t oc_tls_inactive(void *data);
#ifdef OC_CLIENT
static void
oc_tls_free_invalid_peer(oc_tls_peer_t *peer)
{
OC_DBG("\noc_tls: removing invalid peer");
oc_list_remove(tls_peers, peer);
size_t device = peer->endpoint.device;
oc_sec_pstat_t *pstat = oc_sec_get_pstat(device);
if (pstat->s == OC_DOS_RFOTM) {
oc_set_delayed_callback((void *)device, &reset_in_RFOTM, 0);
}
oc_ri_remove_timed_event_callback(peer, oc_tls_inactive);
mbedtls_ssl_free(&peer->ssl_ctx);
oc_message_t *message = (oc_message_t *)oc_list_pop(peer->send_q);
while (message != NULL) {
oc_message_unref(message);
message = (oc_message_t *)oc_list_pop(peer->send_q);
}
message = (oc_message_t *)oc_list_pop(peer->recv_q);
while (message != NULL) {
oc_message_unref(message);
message = (oc_message_t *)oc_list_pop(peer->recv_q);
}
#ifdef OC_PKI
oc_free_string(&peer->public_key);
#endif /* OC_PKI */
#ifdef OC_TCP
if (peer->processed_recv_message != NULL) {
oc_message_unref(peer->processed_recv_message);
}
#endif
mbedtls_ssl_config_free(&peer->ssl_conf);
oc_etimer_stop(&peer->timer.fin_timer);
oc_memb_free(&tls_peers_s, peer);
}
#endif /* OC_CLIENT */
static void
oc_tls_free_peer(oc_tls_peer_t *peer, bool inactivity_cb)
{
OC_DBG("\noc_tls: removing peer");
oc_list_remove(tls_peers, peer);
size_t device = peer->endpoint.device;
oc_sec_pstat_t *pstat = oc_sec_get_pstat(device);
if (pstat->s == OC_DOS_RFOTM) {
oc_set_delayed_callback((void *)device, &reset_in_RFOTM, 0);
}
#ifdef OC_SERVER
/* remove all observations by this peer */
coap_remove_observer_by_client(&peer->endpoint);
#endif /* OC_SERVER */
/* remove all open transactions associated to this endpoint */
coap_free_transactions_by_endpoint(&peer->endpoint);
#ifdef OC_CLIENT
/* remove all remaining client_cbs awaiting a response from this endpoint and
* notify a 5.03 status to the application.
*/
oc_ri_free_client_cbs_by_endpoint(&peer->endpoint);
#endif /* OC_CLIENT */
#ifdef OC_PKI
/* Free all roles bound to this (D)TLS session */
oc_sec_free_roles(peer);
#endif /* OC_PKI */
#ifdef OC_TCP
if (peer->processed_recv_message != NULL) {
oc_message_unref(peer->processed_recv_message);
}
if (peer->endpoint.flags & TCP) {
oc_connectivity_end_session(&peer->endpoint);
} else
#endif /* OC_TCP */
{
oc_handle_session(&peer->endpoint, OC_SESSION_DISCONNECTED);
}
if (!inactivity_cb) {
oc_ri_remove_timed_event_callback(peer, oc_tls_inactive);
}
mbedtls_ssl_free(&peer->ssl_ctx);
oc_message_t *message = (oc_message_t *)oc_list_pop(peer->send_q);
while (message != NULL) {
oc_message_unref(message);
message = (oc_message_t *)oc_list_pop(peer->send_q);
}
message = (oc_message_t *)oc_list_pop(peer->recv_q);
while (message != NULL) {
oc_message_unref(message);
message = (oc_message_t *)oc_list_pop(peer->recv_q);
}
#ifdef OC_PKI
oc_free_string(&peer->public_key);
#endif /* OC_PKI */
mbedtls_ssl_config_free(&peer->ssl_conf);
oc_etimer_stop(&peer->timer.fin_timer);
oc_memb_free(&tls_peers_s, peer);
}
oc_tls_peer_t *
oc_tls_get_peer(oc_endpoint_t *endpoint)
{
oc_tls_peer_t *peer = oc_list_head(tls_peers);
while (peer != NULL) {
if (oc_endpoint_compare(&peer->endpoint, endpoint) == 0) {
return peer;
}
peer = peer->next;
}
return NULL;
}
void
oc_tls_remove_peer(oc_endpoint_t *endpoint)
{
oc_tls_peer_t *peer = oc_tls_get_peer(endpoint);
if (peer) {
oc_tls_free_peer(peer, false);
}
}
bool
oc_tls_is_pin_otm_supported(size_t device)
{
(void)device;
if (random_pin.cb) {
return true;
}
return false;
}
#ifdef OC_PKI
bool
oc_tls_is_cert_otm_supported(size_t device)
{
oc_x509_crt_t *crt = (oc_x509_crt_t *)oc_list_head(identity_certs);
while (crt) {
if (crt->device == device &&
crt->cred->credusage == OC_CREDUSAGE_MFG_CERT) {
return true;
}
crt = crt->next;
}
return false;
}
#endif /* OC_PKI */
static void
oc_tls_handler_schedule_read(oc_tls_peer_t *peer)
{
oc_process_post(&oc_tls_handler, oc_events[TLS_READ_DECRYPTED_DATA], peer);
}
#ifdef OC_CLIENT
static void
oc_tls_handler_schedule_write(oc_tls_peer_t *peer)
{
oc_process_post(&oc_tls_handler, oc_events[TLS_WRITE_APPLICATION_DATA], peer);
}
#endif /* OC_CLIENT */
static oc_event_callback_retval_t
oc_tls_inactive(void *data)
{
OC_DBG("oc_tls: DTLS inactivity callback");
oc_tls_peer_t *peer = (oc_tls_peer_t *)data;
if (is_peer_active(peer)) {
oc_clock_time_t time = oc_clock_time();
time -= peer->timestamp;
if (time < (oc_clock_time_t)OC_DTLS_INACTIVITY_TIMEOUT *
(oc_clock_time_t)OC_CLOCK_SECOND) {
OC_DBG("oc_tls: Resetting DTLS inactivity callback");
return OC_EVENT_CONTINUE;
}
mbedtls_ssl_close_notify(&peer->ssl_ctx);
if ((peer->endpoint.flags & TCP) == 0) {
mbedtls_ssl_close_notify(&peer->ssl_ctx);
}
oc_tls_free_peer(peer, true);
}
OC_DBG("oc_tls: Terminating DTLS inactivity callback");
return OC_EVENT_DONE;
}
static int
ssl_recv(void *ctx, unsigned char *buf, size_t len)
{
oc_tls_peer_t *peer = (oc_tls_peer_t *)ctx;
oc_message_t *message = (oc_message_t *)oc_list_head(peer->recv_q);
if (message) {
size_t recv_len = 0;
#ifdef OC_TCP
if (message->endpoint.flags & TCP) {
recv_len = message->length - message->read_offset;
recv_len = (recv_len < len) ? recv_len : len;
memcpy(buf, message->data + message->read_offset, recv_len);
message->read_offset += recv_len;
if (message->read_offset == message->length) {
oc_list_remove(peer->recv_q, message);
oc_message_unref(message);
}
} else
#endif /* OC_TCP */
{
recv_len = (message->length < len) ? message->length : len;
memcpy(buf, message->data, recv_len);
oc_list_remove(peer->recv_q, message);
oc_message_unref(message);
}
return (int)recv_len;
}
return MBEDTLS_ERR_SSL_WANT_READ;
}
static int
ssl_send(void *ctx, const unsigned char *buf, size_t len)
{
oc_tls_peer_t *peer = (oc_tls_peer_t *)ctx;
peer->timestamp = oc_clock_time();
oc_message_t message;
#if defined(OC_DYNAMIC_ALLOCATION) && !defined(OC_INOUT_BUFFER_SIZE)
message.data = malloc(OC_PDU_SIZE);
if (!message.data)
return 0;
#endif /* OC_DYNAMIC_ALLOCATION && !OC_INOUT_BUFFER_SIZE */
memcpy(&message.endpoint, &peer->endpoint, sizeof(oc_endpoint_t));
size_t send_len = (len < (unsigned)OC_PDU_SIZE) ? len : (unsigned)OC_PDU_SIZE;
memcpy(message.data, buf, send_len);
message.length = send_len;
message.encrypted = 1;
int ret = oc_send_buffer(&message);
#if defined(OC_DYNAMIC_ALLOCATION) && !defined(OC_INOUT_BUFFER_SIZE)
free(message.data);
#endif /* OC_DYNAMIC_ALLOCATION && !OC_INOUT_BUFER_SIZE */
return ret;
}
static void
check_retr_timers(void)
{
oc_tls_peer_t *peer = (oc_tls_peer_t *)oc_list_head(tls_peers), *next;
while (peer != NULL) {
next = peer->next;
if (peer->ssl_ctx.state != MBEDTLS_SSL_HANDSHAKE_OVER) {
if (oc_etimer_expired(&peer->timer.fin_timer)) {
int ret = mbedtls_ssl_handshake(&peer->ssl_ctx);
if (ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) {
mbedtls_ssl_session_reset(&peer->ssl_ctx);
if (peer->role == MBEDTLS_SSL_IS_SERVER &&
mbedtls_ssl_set_client_transport_id(
&peer->ssl_ctx, (const unsigned char *)&peer->endpoint.addr,
sizeof(peer->endpoint.addr)) != 0) {
oc_tls_free_peer(peer, false);
peer = next;
continue;
}
}
if (ret < 0 && ret != MBEDTLS_ERR_SSL_WANT_READ &&
ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
#ifdef OC_DEBUG
char buf[256];
mbedtls_strerror(ret, buf, 256);
OC_ERR("oc_tls: mbedtls_error: %s", buf);
#endif /* OC_DEBUG */
oc_tls_free_peer(peer, false);
}
}
}
peer = next;
}
}
static void
ssl_set_timer(void *ctx, uint32_t int_ms, uint32_t fin_ms)
{
if (fin_ms != 0) {
oc_tls_retr_timer_t *timer = (oc_tls_retr_timer_t *)ctx;
timer->int_ticks = (oc_clock_time_t)((int_ms * OC_CLOCK_SECOND) / 1.e03);
oc_etimer_stop(&timer->fin_timer);
timer->fin_timer.timer.interval =
(oc_clock_time_t)((fin_ms * OC_CLOCK_SECOND) / 1.e03);
OC_PROCESS_CONTEXT_BEGIN(&oc_tls_handler);
oc_etimer_restart(&timer->fin_timer);
OC_PROCESS_CONTEXT_END(&oc_tls_handler);
}
}
int
oc_tls_pbkdf2(const unsigned char *pin, size_t pin_len, oc_uuid_t *uuid,
unsigned int c, uint8_t *key, uint32_t key_len)
{
mbedtls_md_context_t hmac_SHA256;
mbedtls_md_init(&hmac_SHA256);
mbedtls_md_setup(&hmac_SHA256, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256),
1);
memset(key, 0, key_len);
int ret = mbedtls_pkcs5_pbkdf2_hmac(&hmac_SHA256, pin, pin_len,
(const unsigned char *)uuid->id, 16, c,
key_len, key);
mbedtls_md_free(&hmac_SHA256);
if (ret != 0) {
ret = -1;
}
return ret;
}
static void
oc_tls_audit_log(const char *aeid, const char *message, uint8_t category,
uint8_t priority, oc_tls_peer_t *peer)
{
char buff[IPADDR_BUFF_SIZE];
if (peer) {
SNPRINTFipaddr(buff, IPADDR_BUFF_SIZE, peer->endpoint);
} else {
buff[0] = '\0';
}
char *aux[] = { buff };
oc_audit_log((peer) ? peer->endpoint.device : 0, aeid, message, category,
priority, (const char **)aux, 1);
}
static int
get_psk_cb(void *data, mbedtls_ssl_context *ssl, const unsigned char *identity,
size_t identity_len)
{
(void)data;
(void)identity_len;
OC_DBG("oc_tls: In PSK callback");
oc_tls_peer_t *peer = oc_list_head(tls_peers);
while (peer != NULL) {
if (&peer->ssl_ctx == ssl) {
break;
}
peer = peer->next;
}
if (peer) {
OC_DBG("oc_tls: Found peer object");
oc_sec_pstat_t *ps = oc_sec_get_pstat(peer->endpoint.device);
/* To an OBT performing the PIN OTM, a device signals its identity
* with the oic.sec.doxm.rdp: prefix.
*/
if (ps->s == OC_DOS_RFNOP && identity_len > 16 &&
memcmp(identity, "oic.sec.doxm.rdp:", 17) == 0) {
identity += 17;
identity_len -= 17;
}
oc_sec_cred_t *cred =
oc_sec_find_cred((oc_uuid_t *)identity, OC_CREDTYPE_PSK,
OC_CREDUSAGE_NULL, peer->endpoint.device);
if (cred) {
OC_DBG("oc_tls: Found peer credential");
memcpy(peer->uuid.id, identity, 16);
OC_DBG("oc_tls: Setting the key:");
OC_LOGbytes(oc_string(cred->privatedata.data), 16);
if (mbedtls_ssl_set_hs_psk(
ssl, oc_cast(cred->privatedata.data, const uint8_t), 16) != 0) {
return -1;
}
OC_DBG("oc_tls: Set peer credential to SSL handle");
return 0;
} else {
oc_sec_doxm_t *doxm = oc_sec_get_doxm(peer->endpoint.device);
if (ps->s == OC_DOS_RFOTM && doxm->oxmsel == OC_OXMTYPE_RDP) {
if (identity_len != 16 ||
memcmp(identity, "oic.sec.doxm.rdp", 16) != 0) {
OC_ERR("oc_tls: OBT identity incorrectly set for PIN OTM");
return -1;
}
OC_DBG("oc_tls: deriving PPSK for PIN OTM");
memcpy(peer->uuid.id, identity, 16);
uint8_t key[16];
if (oc_tls_pbkdf2(PIN, PIN_LEN, &doxm->deviceuuid, 1000, key, 16) !=
0) {
OC_ERR("oc_tls: error deriving PPSK");
return -1;
}
if (mbedtls_ssl_set_hs_psk(ssl, key, 16) != 0) {
OC_ERR("oc_tls: error applying PPSK to current handshake");
return -1;
}
return 0;
}
}
}
OC_ERR("oc_tls: could not find peer credential");
oc_tls_audit_log("AUTH-1",
"DLTS handshake error, could not find peer credential", 0x08,
1, peer);
return -1;
}
static int
ssl_get_timer(void *ctx)
{
oc_tls_retr_timer_t *timer = (oc_tls_retr_timer_t *)ctx;
if (timer->fin_timer.timer.interval == 0)
return -1;
if (oc_etimer_expired(&timer->fin_timer)) {
timer->fin_timer.timer.interval = 0;
timer->int_ticks = 0;
return 2;
} else if (oc_clock_time() >
(timer->fin_timer.timer.start + timer->int_ticks)) {
return 1;
}
return 0;
}
#ifdef OC_PKI
typedef bool (*check_if_known_cert_cb)(oc_sec_cred_t *cred);
typedef void (*add_new_cert_cb)(oc_sec_cred_t *cred, size_t device);
static void
oc_tls_refresh_certs(oc_sec_credusage_t credusage,
check_if_known_cert_cb is_known_cert,
add_new_cert_cb add_new_cert)
{
size_t device;
for (device = 0; device < oc_core_get_num_devices(); device++) {
oc_sec_creds_t *creds = oc_sec_get_creds(device);
oc_sec_cred_t *cred = (oc_sec_cred_t *)oc_list_head(creds->creds);
for (; cred != NULL; cred = cred->next) {
/* Pick all "leaf" certficiates with matching credusage */
if ((cred->credusage & credusage) != 0 && !cred->child) {
if (is_known_cert(cred)) {
continue;
}
add_new_cert(cred, device);
}
}
}
}
static bool
is_known_identity_cert(oc_sec_cred_t *cred)
{
oc_x509_crt_t *certs = (oc_x509_crt_t *)oc_list_head(identity_certs);
/* Look for a matching end-entity cert chain */
for (; certs != NULL; certs = certs->next) {
if (certs->cred == cred) {
break;
}
}
if (!certs) {
OC_DBG("identity cert chain not found in known list; Tracking new identity "
"cert chain...");
return false;
}
/* Identity cert chain currently tracked by mbedTLS */
mbedtls_x509_crt *id_cert = &certs->cert;
mbedtls_x509_crt cert_in_cred;
mbedtls_x509_crt *cert = &cert_in_cred;
next_cred_in_chain:
while (cred) {
mbedtls_x509_crt_init(cert);
/* Parse cert in cred entry for matching below */
size_t cert_len = oc_string_len(cred->publicdata.data);
if (cred->publicdata.encoding == OC_ENCODING_PEM) {
cert_len++;
}
int ret = mbedtls_x509_crt_parse(
cert, (const unsigned char *)oc_string(cred->publicdata.data), cert_len);
if (ret < 0) {
OC_ERR("could not parse identity cert from cred");
return true;
}
/* Walk through chain of tracked identity certs and match against
* chain of certs currently within and/or spread across cred entries
* to identify new (and recently provisioned) certs via new cred
* entries and accordingly add them. Once added, the new chain is
* presented during future TLS handshakes that employ the cert chain.
*/
while (id_cert && cert) {
if (id_cert->raw.len == cert->raw.len &&
memcmp(id_cert->raw.p, cert->raw.p, cert->raw.len) == 0) {
if (cert->next) {
OC_DBG("found matching cert..proceeding further down the chain");
cert = cert->next;
continue;
} else {
OC_DBG("found matching cert..proceeding further down the chain");
cred = cred->chain;
mbedtls_x509_crt_free(&cert_in_cred);
goto next_cred_in_chain;
}
} else if (!id_cert->next) {
OC_DBG("new cert chains to known cert chain; Add cert to chain and "
"proceed...");
ret =
mbedtls_x509_crt_parse_der(&certs->cert, cert->raw.p, cert->raw.len);
if (ret < 0) {
OC_WRN("could not parse cert in provided chain");
mbedtls_x509_crt_free(&cert_in_cred);
return true;
}
#ifdef OC_DEBUG
mbedtls_x509_crt *c = &certs->cert;
int chain_length = 0;
while (c) {
chain_length++;
c = c->next;
}
OC_DBG("identity cert chain is now of size %d", chain_length);
#endif /* OC_DEBUG */
if (cert->next) {
OC_DBG("processing other new certs, if any, further down the chain");
cert = cert->next;
continue;
} else {
OC_DBG("processing other new certs, if any, further down the chain");
mbedtls_x509_crt_free(&cert_in_cred);
cred = cred->chain;
goto next_cred_in_chain;
}
}
id_cert = id_cert->next;
}
cred = cred->chain;
}
return true;
}
static void
add_new_identity_cert(oc_sec_cred_t *cred, size_t device)
{
oc_x509_crt_t *cert = oc_memb_alloc(&identity_certs_s);
if (!cert) {
OC_WRN("could not allocate memory for identity cert");
return;
}
cert->device = device;
cert->cred = cred;
mbedtls_x509_crt_init(&cert->cert);
while (cred) {
size_t len = oc_string_len(cred->publicdata.data);
if (cred->publicdata.encoding == OC_ENCODING_PEM) {
len++;
}
int ret = mbedtls_x509_crt_parse(
&cert->cert, (const unsigned char *)oc_string(cred->publicdata.data),
len);
if (ret < 0) {
OC_ERR("could not parse identity cert");
goto add_new_identity_cert_error;
}
if (oc_string_len(cred->privatedata.data) > 0) {
ret = mbedtls_pk_parse_key(
&cert->pk,
(const unsigned char *)oc_cast(cred->privatedata.data, uint8_t),
oc_string_len(cred->privatedata.data) + 1, NULL, 0);
if (ret != 0) {
OC_ERR("could not parse private key %zd",
oc_string_len(cred->privatedata.data));
goto add_new_identity_cert_error;
}
}
cred = cred->chain;
}
#ifdef OC_DEBUG
mbedtls_x509_crt *c = &cert->cert;
int chain_length = 0;
while (c) {
chain_length++;
c = c->next;
}
OC_DBG("adding new identity cert chain of size %d", chain_length);
#endif /* OC_DEBUG */
oc_list_add(identity_certs, cert);
return;
add_new_identity_cert_error:
OC_ERR("error adding identity cert");
mbedtls_x509_crt_free(&cert->cert);
mbedtls_pk_free(&cert->pk);
oc_memb_free(&identity_certs_s, cert);
}
void
oc_tls_refresh_identity_certs(void)
{
OC_DBG("refreshing identity certs");
oc_tls_refresh_certs(OC_CREDUSAGE_MFG_CERT | OC_CREDUSAGE_IDENTITY_CERT,
is_known_identity_cert, add_new_identity_cert);
}
void
oc_tls_remove_identity_cert(oc_sec_cred_t *cred)
{
oc_x509_crt_t *cert = (oc_x509_crt_t *)oc_list_head(identity_certs);
while (cert != NULL && cert->cred != cred) {
cert = cert->next;
}
if (cert) {
oc_list_remove(identity_certs, cert);
mbedtls_x509_crt_free(&cert->cert);
mbedtls_pk_free(&cert->pk);
oc_memb_free(&identity_certs_s, cert);
}
}
void
oc_tls_remove_trust_anchor(oc_sec_cred_t *cred)
{
oc_x509_cacrt_t *cert = (oc_x509_cacrt_t *)oc_list_head(ca_certs);
while (cert && cert->cred != cred) {
cert = cert->next;
}
if (cert) {
oc_list_remove(ca_certs, cert);
oc_memb_free(&ca_certs_s, cert);
}
mbedtls_x509_crt_free(&trust_anchors);
mbedtls_x509_crt_init(&trust_anchors);
oc_tls_refresh_trust_anchors();
}
static int
oc_tls_configure_end_entity_cert_chain(mbedtls_ssl_config *conf, size_t device,
oc_sec_credusage_t credusage, int credid)
{
oc_x509_crt_t *cert = (oc_x509_crt_t *)oc_list_head(identity_certs);
while (cert != NULL) {
if (cert->device == device && cert->cred->credusage == credusage &&
(credid == -1 || cert->cred->credid == credid)) {
break;
}
cert = cert->next;
}
if (!cert || mbedtls_ssl_conf_own_cert(conf, &cert->cert, &cert->pk) != 0) {
OC_WRN("error configuring identity cert");
return -1;
}
return 0;
}
static int
oc_tls_load_mfg_cert_chain(mbedtls_ssl_config *conf, size_t device, int credid)
{
OC_DBG("loading manufacturer cert chain");
return oc_tls_configure_end_entity_cert_chain(conf, device,
OC_CREDUSAGE_MFG_CERT, credid);
}
static int
oc_tls_load_identity_cert_chain(mbedtls_ssl_config *conf, size_t device,
int credid)
{
OC_DBG("loading identity cert chain");
return oc_tls_configure_end_entity_cert_chain(
conf, device, OC_CREDUSAGE_IDENTITY_CERT, credid);
}
static bool
is_known_trust_anchor(oc_sec_cred_t *cred)
{
oc_x509_cacrt_t *cert = (oc_x509_cacrt_t *)oc_list_head(ca_certs);
for (; cert != NULL; cert = cert->next) {
if (cert->cred == cred) {
return true;
}
}
return false;
}
static void
add_new_trust_anchor(oc_sec_cred_t *cred, size_t device)
{
(void)device;
int ret = mbedtls_x509_crt_parse(
&trust_anchors, (const unsigned char *)oc_string(cred->publicdata.data),
oc_string_len(cred->publicdata.data) + 1);
if (ret != 0) {
OC_WRN("could not parse an trustca/mfgtrustca root certificate %d", ret);
return;
}
oc_x509_cacrt_t *cert = oc_memb_alloc(&ca_certs_s);
if (!cert) {
OC_WRN("could not allocate memory for new trust anchor");
return;
}
cert->device = device;
cert->cred = cred;
mbedtls_x509_crt *c = &trust_anchors;
while (c->next) {
c = c->next;
}
cert->cert = c;
oc_list_add(ca_certs, cert);
OC_DBG("adding new trust anchor");
}
void
oc_tls_refresh_trust_anchors(void)
{
OC_DBG("refreshing trust anchors");
oc_tls_refresh_certs(OC_CREDUSAGE_MFG_TRUSTCA | OC_CREDUSAGE_TRUSTCA,
is_known_trust_anchor, add_new_trust_anchor);
}
#ifdef OC_CLIENT
void
oc_tls_select_cert_ciphersuite(void)
{
OC_DBG("oc_tls: client requesting cert ciphersuite priority");
ciphers = (int *)cert_priority;
}
#ifdef OC_CLOUD
void
oc_tls_select_cloud_ciphersuite(void)
{
OC_DBG("oc_tls: client requesting cloud ciphersuite priority");
ciphers = (int *)cloud_priority;
}
#endif /* OC_CLOUD */
#endif /* OC_CLIENT */
void
oc_tls_select_mfg_cert_chain(int credid)
{
selected_mfg_cred = credid;
}
void
oc_tls_select_identity_cert_chain(int credid)
{
selected_id_cred = credid;
}
static oc_x509_crt_t *
get_identity_cert_for_session(const mbedtls_ssl_config *conf)
{
oc_x509_crt_t *cert = (oc_x509_crt_t *)oc_list_head(identity_certs);
while (cert != NULL) {
if (&cert->cert == conf->key_cert->cert) {
return cert;
}
cert = cert->next;
}
return NULL;
}
#endif /* OC_PKI */
static void
oc_tls_set_ciphersuites(mbedtls_ssl_config *conf, oc_endpoint_t *endpoint)
{
(void)endpoint;
#ifdef OC_PKI
mbedtls_ssl_conf_ca_chain(conf, &trust_anchors, NULL);
#ifdef OC_CLIENT
bool loaded_chain = false;
#endif /* OC_CLIENT */
size_t device = endpoint->device;
oc_sec_doxm_t *doxm = oc_sec_get_doxm(device);
/* Decide between configuring the identity cert chain vs manufacturer cert
* chain for this device based on device ownership status.
*/
if (doxm->owned &&
oc_tls_load_identity_cert_chain(conf, device, selected_id_cred) == 0) {
#ifdef OC_CLIENT
loaded_chain = true;
#endif /* OC_CLIENT */
} else if (oc_tls_load_mfg_cert_chain(conf, device, selected_mfg_cred) == 0) {
#ifdef OC_CLIENT
loaded_chain = true;
#endif /* OC_CLIENT */
}
selected_mfg_cred = -1;
selected_id_cred = -1;
#endif /* OC_PKI */
oc_sec_pstat_t *ps = oc_sec_get_pstat(endpoint->device);
if (conf->endpoint == MBEDTLS_SSL_IS_SERVER && ps->s == OC_DOS_RFOTM) {
OC_DBG(
"oc_tls_set_ciphersuites: server selecting OTM ciphersuite priority");
oc_sec_doxm_t *d = oc_sec_get_doxm(endpoint->device);
switch (d->oxmsel) {
case OC_OXMTYPE_JW:
OC_DBG("oc_tls: selected JW OTM priority");
ciphers = (int *)jw_otm_priority;
break;
case OC_OXMTYPE_RDP:
OC_DBG("oc_tls: selected PIN OTM priority");
ciphers = (int *)pin_otm_priority;
break;
#ifdef OC_PKI
case OC_OXMTYPE_MFG_CERT:
OC_DBG("oc_tls: selected cert OTM priority");
ciphers = (int *)cert_otm_priority;
break;
#endif /* OC_PKI */
default:
OC_DBG("oc_tls: selected default OTM priority");
ciphers = (int *)default_priority;
break;
}
} else if (!ciphers) {
OC_DBG("oc_tls_set_ciphersuites: server selecting default ciphersuite "
"priority");
ciphers = (int *)default_priority;
#ifdef OC_CLIENT
if (conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
oc_sec_cred_t *cred =
oc_sec_find_creds_for_subject(&endpoint->di, NULL, endpoint->device);
if (cred && cred->credtype == OC_CREDTYPE_PSK) {
OC_DBG("oc_tls_set_ciphersuites: client selecting PSK ciphersuite "
"priority");
ciphers = (int *)psk_priority;
}
#ifdef OC_PKI
else if (loaded_chain) {
OC_DBG("oc_tls_set_ciphersuites: client selecting cert ciphersuite "
"priority");
ciphers = (int *)cert_priority;
}
#endif /* OC_PKI */
}
#endif /* OC_CLIENT */
}
mbedtls_ssl_conf_ciphersuites(conf, ciphers);
ciphers = NULL;
OC_DBG("oc_tls: resetting ciphersuite selection for next handshakes");
}
#ifdef OC_CLIENT
void
oc_tls_select_psk_ciphersuite(void)
{
OC_DBG("oc_tls: client requesting PSK ciphersuite priority");
ciphers = (int *)psk_priority;
}
void
oc_tls_select_anon_ciphersuite(void)
{
OC_DBG("oc_tls: client requesting anon ECDH ciphersuite priority");
ciphers = (int *)anon_ecdh_priority;
}
#endif /* OC_CLIENT */
#ifdef OC_PKI
static int
verify_certificate(void *opq, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
{
(void)opq;
(void)flags;
oc_tls_peer_t *peer = (oc_tls_peer_t *)opq;
OC_DBG("verifying certificate at depth %d", depth);
if (depth > 0) {
/* For D2D handshakes involving identity certificates:
* Find a trusted root that matches the peer's root and store it
* as context accompanying the identity certificate. This is queried
* after validating the end-entity certificate to authorize the
* the peer per the OCF Specification. */
oc_x509_crt_t *id_cert = get_identity_cert_for_session(&peer->ssl_conf);
oc_sec_pstat_t *ps = oc_sec_get_pstat(peer->endpoint.device);
if (oc_certs_validate_non_end_entity_cert(crt, true, ps->s == OC_DOS_RFOTM,
depth) < 0) {
if (oc_certs_validate_non_end_entity_cert(
crt, false, ps->s == OC_DOS_RFOTM, depth) < 0) {
OC_ERR("failed to verify root or intermediate cert");
oc_tls_audit_log(
"AUTH-1",
"DLTS handshake error, failed to verify root or intermediate cert",
0x08, 1, peer);
return -1;
}
} else {
if (id_cert && id_cert->cred->credusage == OC_CREDUSAGE_IDENTITY_CERT) {
oc_x509_cacrt_t *ca_cert = (oc_x509_cacrt_t *)oc_list_head(ca_certs);
while (ca_cert) {
if (ca_cert->device == id_cert->device &&
ca_cert->cred->credusage == OC_CREDUSAGE_TRUSTCA &&
crt->raw.len == ca_cert->cert->raw.len &&
memcmp(crt->raw.p, ca_cert->cert->raw.p, crt->raw.len) == 0) {
id_cert->ctx = ca_cert;
break;
}
ca_cert = ca_cert->next;
}
}
}
} else if (oc_certs_validate_end_entity_cert(crt) < 0) {
OC_ERR("failed to verify end entity cert");
oc_tls_audit_log("AUTH-1",
"DLTS handshake error, failed to verify end entity cert",
0x08, 1, peer);
return -1;
}
if (depth == 0) {
oc_x509_crt_t *id_cert = get_identity_cert_for_session(&peer->ssl_conf);
/* Parse the peer's subjectuuid from its end-entity certificate */
oc_string_t uuid;
if (oc_certs_parse_CN_for_UUID(crt, &uuid) < 0) {
if (id_cert && id_cert->cred->credusage == OC_CREDUSAGE_IDENTITY_CERT) {
OC_ERR("unable to retrieve UUID from the cert's CN");
return -1;
} else {
peer->uuid.id[0] = '*';
OC_DBG("attempting to connect with peer *");
}
} else {
oc_str_to_uuid(oc_string(uuid), &peer->uuid);
OC_DBG("attempting to connect with peer %s", oc_string(uuid));
oc_free_string(&uuid);
}
if (oc_certs_extract_public_key(crt, &peer->public_key) < 0) {
OC_ERR("unable to extract public key from cert");
return -1;
}
if (id_cert && id_cert->cred->credusage != OC_CREDUSAGE_MFG_CERT) {
OC_DBG("checking if peer is authorized to connect with us");
oc_uuid_t wildcard_sub;
memset(&wildcard_sub, 0, sizeof(oc_uuid_t));
wildcard_sub.id[0] = '*';
/* Get a handle to the peer's root certificate */
if (!id_cert->ctx || !id_cert->ctx->cert) {
OC_DBG("could not find peer's root certificate");
return -1;
}
mbedtls_x509_crt *root_crt = id_cert->ctx->cert;
OC_DBG(
"looking for a matching trustca entry currently tracked by oc_tls");
oc_x509_cacrt_t *ca_cert = (oc_x509_cacrt_t *)oc_list_head(ca_certs);
for (; ca_cert != NULL && ca_cert->device == id_cert->device &&
ca_cert->cred->credusage == OC_CREDUSAGE_TRUSTCA;
ca_cert = ca_cert->next) {
if (root_crt->raw.len == ca_cert->cert->raw.len &&
memcmp(root_crt->raw.p, ca_cert->cert->raw.p, root_crt->raw.len) ==
0) {
} else {
OC_DBG("trustca mismatch, check next known trustca");
continue;
}
OC_DBG("found matching trustca; check if trustca's cred entry has a "
"UUID matching with the peer's UUID, or *");
#ifdef OC_DEBUG
if (ca_cert->cred->subjectuuid.id[0] != '*') {
char ca_uuid[37];
oc_uuid_to_str(&ca_cert->cred->subjectuuid, ca_uuid, 37);
OC_DBG("trustca cred UUID is %s", ca_uuid);
} else {
OC_DBG("trustca cred UUID is the wildcard *");
}
#endif /* OC_DEBUG */
if (memcmp(ca_cert->cred->subjectuuid.id, peer->uuid.id, 16) != 0) {
if (memcmp(ca_cert->cred->subjectuuid.id, wildcard_sub.id, 16) != 0) {
OC_DBG("trustca cred's UUID does not match with with peer's UUID "
"or the wildcard subject *; checking next known trustca");
continue;
} else {
OC_DBG("trustca cred entry bears the wildcard subject * -> "
"authorization successful");
break;
}
} else {
OC_DBG("trustca cred entry has subjectuuid that matches with the "
"peer's UUID -> authorization successful");
break;
}
}
if (!ca_cert) {
OC_ERR("could not find authorizing trustca cred for peer");
return -1;
}
}
}
OC_DBG("verified certificate at depth %d", depth);
return 0;
}
#endif /* OC_PKI */
static int
oc_tls_populate_ssl_config(mbedtls_ssl_config *conf, size_t device, int role,
int transport_type)
{
mbedtls_ssl_config_init(conf);
if (mbedtls_ssl_config_defaults(conf, role, transport_type,
MBEDTLS_SSL_PRESET_DEFAULT) != 0) {
return -1;
}
oc_uuid_t *device_id = oc_core_get_device_id(device);
#ifdef OC_CLIENT
if (role == MBEDTLS_SSL_IS_CLIENT && use_pin_obt_psk_identity) {
use_pin_obt_psk_identity = false;
if (mbedtls_ssl_conf_psk(conf, device_id->id, 1,
(const unsigned char *)"oic.sec.doxm.rdp",
16) != 0) {
return -1;
}
} else
#endif /* OC_CLIENT */
{
unsigned char identity_hint[33];
size_t identity_hint_len = 33;
oc_sec_doxm_t *doxm = oc_sec_get_doxm(device);
oc_sec_pstat_t *pstat = oc_sec_get_pstat(device);
if (pstat->s == OC_DOS_RFOTM && doxm->oxmsel == OC_OXMTYPE_RDP) {
memcpy(identity_hint, "oic.sec.doxm.rdp:", 17);
memcpy(identity_hint + 17, device_id->id, 16);
identity_hint_len = 33;
} else {
memcpy(identity_hint, device_id->id, 16);
identity_hint_len = 16;
}
if (mbedtls_ssl_conf_psk(conf, identity_hint, 1, identity_hint,
identity_hint_len) != 0) {
return -1;
}
}
#ifdef OC_DEBUG
mbedtls_ssl_conf_dbg(conf, oc_mbedtls_debug, stdout);
#endif /* OC_DEBUG */
mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, &ctr_drbg_ctx);
mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
MBEDTLS_SSL_MINOR_VERSION_3);
oc_sec_pstat_t *ps = oc_sec_get_pstat(device);
if ((ps->s > OC_DOS_RFOTM) || (role != MBEDTLS_SSL_IS_SERVER)) {
mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
}
mbedtls_ssl_conf_psk_cb(conf, get_psk_cb, NULL);
if (transport_type == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
mbedtls_ssl_conf_dtls_cookies(conf, mbedtls_ssl_cookie_write,
mbedtls_ssl_cookie_check, &cookie_ctx);
mbedtls_ssl_conf_handshake_timeout(conf, 2500, 20000);
}
return 0;
}
int
oc_tls_num_peers(size_t device)
{
int num_peers = 0;
oc_tls_peer_t *peer = (oc_tls_peer_t *)oc_list_head(tls_peers);
while (peer) {
if (peer->endpoint.device == device) {
++num_peers;
}
peer = peer->next;
}
return num_peers;
}
static oc_tls_peer_t *
oc_tls_add_peer(oc_endpoint_t *endpoint, int role)
{
oc_tls_peer_t *peer = oc_tls_get_peer(endpoint);
if (!peer) {
/* Check if this a Device Ownership Connection (DOC) */
bool doc = false;
oc_sec_doxm_t *doxm = oc_sec_get_doxm(endpoint->device);
oc_sec_pstat_t *pstat = oc_sec_get_pstat(endpoint->device);
if (pstat->s == OC_DOS_RFOTM) {
if (doxm->oxmsel == 4) {
/* Prior to a successful anonymous Update of "oxmsel" in
* "/oic/sec/doxm", all attempts to establish new DTLS connections
* shall be rejected.
*/
return NULL;
}
if (oc_list_length(tls_peers) == 0) {
doc = true;
} else {
/* Allow only a single DOC */
return NULL;
}
}
peer = oc_memb_alloc(&tls_peers_s);
if (peer) {
OC_DBG("oc_tls: Allocating new peer");
memcpy(&peer->endpoint, endpoint, sizeof(oc_endpoint_t));
OC_LIST_STRUCT_INIT(peer, recv_q);
OC_LIST_STRUCT_INIT(peer, send_q);
peer->next = 0;
peer->doc = doc;
peer->role = role;
memset(&peer->timer, 0, sizeof(oc_tls_retr_timer_t));
mbedtls_ssl_init(&peer->ssl_ctx);
int transport_type = (endpoint->flags & TCP)
? MBEDTLS_SSL_TRANSPORT_STREAM
: MBEDTLS_SSL_TRANSPORT_DATAGRAM;
if (oc_tls_populate_ssl_config(&peer->ssl_conf, endpoint->device, role,
transport_type) < 0) {
OC_ERR("oc_tls: error in tls_populate_ssl_config");
oc_tls_free_peer(peer, false);
return NULL;
}
#ifdef OC_PKI
#if defined(OC_CLOUD) && defined(OC_CLIENT)
if (ciphers != cloud_priority) {
#endif /* OC_CLOUD && OC_CLIENT */
mbedtls_ssl_conf_verify(&peer->ssl_conf, verify_certificate, peer);
#if defined(OC_CLOUD) && defined(OC_CLIENT)
}
#endif /* OC_CLOUD && OC_CLIENT */
#endif /* OC_PKI */
#ifdef OC_TCP
peer->processed_recv_message = NULL;
#endif
oc_tls_set_ciphersuites(&peer->ssl_conf, endpoint);
int err = mbedtls_ssl_setup(&peer->ssl_ctx, &peer->ssl_conf);
if (err != 0) {
OC_ERR("oc_tls: error in mbedtls_ssl_setup: %d", err);
oc_tls_free_peer(peer, false);
return NULL;
}
/* Fix maximum size of outgoing encrypted application payloads when sent
* over UDP */
if (transport_type == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
mbedtls_ssl_set_mtu(
&peer->ssl_ctx,
(OC_PDU_SIZE > UINT16_MAX ? UINT16_MAX : OC_PDU_SIZE));
}
mbedtls_ssl_set_bio(&peer->ssl_ctx, peer, ssl_send, ssl_recv, NULL);
if (role == MBEDTLS_SSL_IS_SERVER &&
mbedtls_ssl_set_client_transport_id(
&peer->ssl_ctx, (const unsigned char *)&endpoint->addr,
sizeof(endpoint->addr)) != 0) {
oc_tls_free_peer(peer, false);
return NULL;
}
oc_list_add(tls_peers, peer);
if (!(endpoint->flags & TCP)) {
mbedtls_ssl_set_timer_cb(&peer->ssl_ctx, &peer->timer, ssl_set_timer,
ssl_get_timer);
oc_ri_add_timed_event_callback_seconds(
peer, oc_tls_inactive, (oc_clock_time_t)OC_DTLS_INACTIVITY_TIMEOUT);
}
} else {
OC_WRN("TLS peers exhausted");
}
}
return peer;
}
void
oc_tls_shutdown(void)
{
oc_tls_peer_t *p = oc_list_pop(tls_peers);
while (p != NULL) {
oc_tls_free_peer(p, false);
p = oc_list_pop(tls_peers);
}
#ifdef OC_PKI
oc_x509_crt_t *cert = (oc_x509_crt_t *)oc_list_pop(identity_certs);
while (cert != NULL) {
mbedtls_x509_crt_free(&cert->cert);
mbedtls_pk_free(&cert->pk);
oc_memb_free(&identity_certs_s, cert);
cert = (oc_x509_crt_t *)oc_list_pop(identity_certs);
}
oc_x509_cacrt_t *ca = (oc_x509_cacrt_t *)oc_list_pop(ca_certs);
while (ca) {
oc_memb_free(&ca_certs_s, ca);
ca = (oc_x509_cacrt_t *)oc_list_pop(ca_certs);
}
mbedtls_x509_crt_free(&trust_anchors);
#endif /* OC_PKI */
mbedtls_ctr_drbg_free(&ctr_drbg_ctx);
mbedtls_ssl_cookie_free(&cookie_ctx);
mbedtls_entropy_free(&entropy_ctx);
}
int
oc_tls_init_context(void)
{
#ifndef OC_DYNAMIC_ALLOCATION
mbedtls_memory_buffer_alloc_init(alloc_buf, sizeof(alloc_buf));
#endif /* !OC_DYNAMIC_ALLOCATION */
#ifdef OC_DEBUG
#if defined(_WIN32) || defined(_WIN64)
// mbedtls debug logs fail if snprintf is not specified
mbedtls_platform_set_snprintf(snprintf);
#endif /* _WIN32 or _WIN64 */
mbedtls_debug_set_threshold(4);
#endif /* OC_DEBUG */
mbedtls_entropy_init(&entropy_ctx);
mbedtls_ssl_cookie_init(&cookie_ctx);
mbedtls_ctr_drbg_init(&ctr_drbg_ctx);
if (mbedtls_ctr_drbg_seed(&ctr_drbg_ctx, mbedtls_entropy_func, &entropy_ctx,
(const unsigned char *)PERSONALIZATION_DATA,
strlen(PERSONALIZATION_DATA)) != 0) {
OC_ERR("error initializing RNG");
goto dtls_init_err;
}
if (mbedtls_ssl_cookie_setup(&cookie_ctx, mbedtls_ctr_drbg_random,
&ctr_drbg_ctx) != 0) {
goto dtls_init_err;
}
#ifdef OC_PKI
mbedtls_x509_crt_init(&trust_anchors);
#endif /* OC_PKI */
return 0;
dtls_init_err:
OC_ERR("oc_tls: TLS initialization error");
oc_tls_shutdown();
return -1;
}
void
oc_tls_close_connection(oc_endpoint_t *endpoint)
{
oc_tls_peer_t *peer = oc_tls_get_peer(endpoint);
if (peer) {
mbedtls_ssl_close_notify(&peer->ssl_ctx);
if ((peer->endpoint.flags & TCP) == 0) {
mbedtls_ssl_close_notify(&peer->ssl_ctx);
}
oc_tls_free_peer(peer, false);
}
}
static int
oc_tls_prf(const uint8_t *secret, size_t secret_len, uint8_t *output,
size_t output_len, size_t num_message_fragments, ...)
{
#define MBEDTLS_MD(func, ...) \
do { \
if (func(__VA_ARGS__) != 0) { \
gen_output = -1; \
goto exit_tls_prf; \
} \
} while (0)
uint8_t A[MBEDTLS_MD_MAX_SIZE], buf[MBEDTLS_MD_MAX_SIZE];
size_t i, msg_len;
int gen_output = 0, copy_len,
hash_len =
mbedtls_md_get_size(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256));
mbedtls_md_context_t hmacA, hmacA_next;
va_list msg_list;
const uint8_t *msg;
mbedtls_md_init(&hmacA);
mbedtls_md_init(&hmacA_next);
MBEDTLS_MD(mbedtls_md_setup, &hmacA,
mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
MBEDTLS_MD(mbedtls_md_setup, &hmacA_next,
mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
MBEDTLS_MD(mbedtls_md_hmac_starts, &hmacA, secret, secret_len);
va_start(msg_list, num_message_fragments);
for (i = 0; i < num_message_fragments; i++) {
msg = va_arg(msg_list, const uint8_t *);
msg_len = va_arg(msg_list, size_t);
MBEDTLS_MD(mbedtls_md_hmac_update, &hmacA, msg, msg_len);
}
va_end(msg_list);
MBEDTLS_MD(mbedtls_md_hmac_finish, &hmacA, A);
while (gen_output < (int)output_len) {
MBEDTLS_MD(mbedtls_md_hmac_reset, &hmacA);
MBEDTLS_MD(mbedtls_md_hmac_starts, &hmacA, secret, secret_len);
MBEDTLS_MD(mbedtls_md_hmac_update, &hmacA, A, hash_len);
va_start(msg_list, num_message_fragments);
for (i = 0; i < num_message_fragments; i++) {
msg = va_arg(msg_list, const uint8_t *);
msg_len = va_arg(msg_list, size_t);
MBEDTLS_MD(mbedtls_md_hmac_update, &hmacA, msg, msg_len);
}
va_end(msg_list);
MBEDTLS_MD(mbedtls_md_hmac_finish, &hmacA, buf);
copy_len = (((int)output_len - gen_output) < hash_len)
? ((int)output_len - gen_output)
: hash_len;
memcpy(output + gen_output, buf, copy_len);
gen_output += copy_len;
if (copy_len == hash_len) {
MBEDTLS_MD(mbedtls_md_hmac_reset, &hmacA_next);
MBEDTLS_MD(mbedtls_md_hmac_starts, &hmacA_next, secret, secret_len);
MBEDTLS_MD(mbedtls_md_hmac_update, &hmacA_next, A, hash_len);
MBEDTLS_MD(mbedtls_md_hmac_finish, &hmacA_next, A);
}
}
exit_tls_prf:
#undef MBEDTLS_MD
va_end(msg_list);
mbedtls_md_free(&hmacA);
mbedtls_md_free(&hmacA_next);
return gen_output;
}
bool
oc_sec_derive_owner_psk(oc_endpoint_t *endpoint, const uint8_t *oxm,
const size_t oxm_len, const uint8_t *server_uuid,
const size_t server_uuid_len, const uint8_t *obt_uuid,
const size_t obt_uuid_len, uint8_t *key,
const size_t key_len)
{
oc_tls_peer_t *peer = oc_tls_get_peer(endpoint);
if (!peer) {
return false;
}
if (!peer->ssl_ctx.session) {
return false;
}
size_t j;
for (j = 0; j < 48; j++) {
if (peer->master_secret[j] != 0) {
break;
}
}
if (j == 48) {
return false;
}
for (j = 0; j < 64; j++) {
if (peer->client_server_random[j] != 0) {
break;
}
}
if (j == 64) {
return false;
}
uint8_t key_block[184];
uint8_t label[] = { 0x6b, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70,
0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e };
// key_block_len set up according to OIC 1.1 Security Specification Section
// 7.3.2
int mac_key_len = 0;
int iv_size = 0;
int key_size = 0;
int key_block_len = 0;
if (MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 ==
peer->ssl_ctx.session->ciphersuite ||
MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 ==
peer->ssl_ctx.session->ciphersuite ||
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 ==
peer->ssl_ctx.session->ciphersuite) {
// 2 * ( 32 + 0 + 16 ) = 96
mac_key_len = SHA256_MAC_KEY_LENGTH;
iv_size = CBC_IV_LENGTH;
key_size = AES128_KEY_LENGTH;
} else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM ==
peer->ssl_ctx.session->ciphersuite ||
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ==
peer->ssl_ctx.session->ciphersuite) {
// 2 * ( 0 + 4 + 16 ) = 40
mac_key_len = CCM_MAC_KEY_LENGTH;
iv_size = CCM_IV_LENGTH;
key_size = AES128_KEY_LENGTH;
} else if (peer->ssl_ctx.session->ciphersuite ==
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM ||
peer->ssl_ctx.session->ciphersuite ==
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8) {
// 2 * (0 + 4 + 32) = 72
mac_key_len = CCM_MAC_KEY_LENGTH;
iv_size = CCM_IV_LENGTH;
key_size = AES256_KEY_LENGTH;
} else if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ==
peer->ssl_ctx.session->ciphersuite) {
// 2 * ( 32 + 12 + 16 ) = 120
mac_key_len = SHA256_MAC_KEY_LENGTH;
iv_size = GCM_IV_LENGTH;
key_size = AES128_KEY_LENGTH;
}
key_block_len = 2 * (mac_key_len + key_size + iv_size);
if (oc_tls_prf(peer->master_secret, 48, key_block, key_block_len, 3, label,
sizeof(label), peer->client_server_random + 32, (size_t)32,
peer->client_server_random, (size_t)32) != key_block_len) {
return false;
}
if (oc_tls_prf(key_block, key_block_len, key, key_len, 3, oxm, oxm_len,
obt_uuid, obt_uuid_len, server_uuid,
server_uuid_len) != (int)key_len) {
return false;
}
OC_DBG("oc_tls: master secret:");
OC_LOGbytes(peer->master_secret, 48);
OC_DBG("oc_tls: client_server_random:");
OC_LOGbytes(peer->client_server_random, 64);
OC_DBG("oc_tls: key_block");
OC_LOGbytes(key_block, key_block_len);
OC_DBG("oc_tls: PSK ");
OC_LOGbytes(key, key_len);
return true;
}
#ifdef OC_TCP
static int
ssl_write_tcp(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
{
size_t length = 0;
while (length < len) {
int ret = mbedtls_ssl_write(ssl, buf + length, len - length);
if (ret < 0) {
if (ret == MBEDTLS_ERR_SSL_WANT_READ &&
ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
continue;
}
return ret;
}
length += ret;
}
return (int)length;
}
#endif
size_t
oc_tls_send_message(oc_message_t *message)
{
size_t length = 0;
oc_tls_peer_t *peer = oc_tls_get_peer(&message->endpoint);
if (peer) {
int ret = 0;
#ifdef OC_TCP
if (peer->endpoint.flags & TCP) {
ret = ssl_write_tcp(&peer->ssl_ctx, (unsigned char *)message->data,
message->length);
} else
#endif
{
ret = mbedtls_ssl_write(&peer->ssl_ctx, (unsigned char *)message->data,
message->length);
}
if (ret < 0 && ret != MBEDTLS_ERR_SSL_WANT_READ &&
ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
#ifdef OC_DEBUG
char buf[256];
mbedtls_strerror(ret, buf, 256);
OC_ERR("oc_tls: mbedtls_error: %s", buf);
#endif /* OC_DEBUG */
oc_tls_free_peer(peer, false);
} else {
length = message->length;
}
}
oc_message_unref(message);
return length;
}
#ifdef OC_CLIENT
static void
write_application_data(oc_tls_peer_t *peer)
{
if (!is_peer_active(peer)) {
OC_DBG("oc_tls: write_application_data: Peer not active");
return;
}
oc_message_t *message = (oc_message_t *)oc_list_pop(peer->send_q);
while (message != NULL) {
int ret = 0;
#ifdef OC_TCP
if (peer->endpoint.flags & TCP) {
ret = ssl_write_tcp(&peer->ssl_ctx, (unsigned char *)message->data,
message->length);
} else
#endif
{
ret = mbedtls_ssl_write(&peer->ssl_ctx, (unsigned char *)message->data,
message->length);
}
oc_message_unref(message);
if (ret < 0 && ret != MBEDTLS_ERR_SSL_WANT_READ &&
ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
#ifdef OC_DEBUG
char buf[256];
mbedtls_strerror(ret, buf, 256);
OC_ERR("oc_tls: mbedtls_error: %s", buf);
#endif /* OC_DEBUG */
oc_tls_free_peer(peer, false);
break;
}
message = (oc_message_t *)oc_list_pop(peer->send_q);
}
}
static void
oc_tls_init_connection(oc_message_t *message)
{
oc_sec_pstat_t *pstat = oc_sec_get_pstat(message->endpoint.device);
if (pstat->s != OC_DOS_RFNOP) {
oc_message_unref(message);
return;
}
oc_tls_peer_t *peer = oc_tls_get_peer(&message->endpoint);
if (peer && peer->role != MBEDTLS_SSL_IS_CLIENT) {
oc_tls_free_invalid_peer(peer);
peer = NULL;
}
if (!peer) {
peer = oc_tls_add_peer(&message->endpoint, MBEDTLS_SSL_IS_CLIENT);
}
if (peer) {
oc_message_t *duplicate = oc_list_head(peer->send_q);
while (duplicate != NULL) {
if (duplicate == message) {
break;
}
duplicate = duplicate->next;
}
if (duplicate == NULL) {
oc_message_add_ref(message);
oc_list_add(peer->send_q, message);
}
int ret = mbedtls_ssl_handshake(&peer->ssl_ctx);
if (ret < 0 && ret != MBEDTLS_ERR_SSL_WANT_READ &&
ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
#ifdef OC_DEBUG
char buf[256];
mbedtls_strerror(ret, buf, 256);
OC_ERR("oc_tls: mbedtls_error: %s", buf);
#endif /* OC_DEBUG */
oc_tls_free_peer(peer, false);
} else if (ret == 0) {
oc_tls_handler_schedule_write(peer);
}
}
oc_message_unref(message);
}
#endif /* OC_CLIENT */
bool
oc_tls_uses_psk_cred(oc_tls_peer_t *peer)
{
if (!peer) {
return false;
}
if (!peer->ssl_ctx.session) {
return false;
}
int cipher = peer->ssl_ctx.session->ciphersuite;
if (MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 == cipher ||
MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256 == cipher) {
return true;
}
return false;
}
oc_uuid_t *
oc_tls_get_peer_uuid(oc_endpoint_t *endpoint)
{
oc_tls_peer_t *peer = oc_tls_get_peer(endpoint);
if (peer) {
return &peer->uuid;
}
return NULL;
}
bool
oc_tls_connected(oc_endpoint_t *endpoint)
{
oc_tls_peer_t *peer = oc_tls_get_peer(endpoint);
if (peer) {
return (peer->ssl_ctx.state == MBEDTLS_SSL_HANDSHAKE_OVER);
}
return false;
}
#if defined(OC_PKI) && defined(OC_CLIENT)
static void
assert_all_roles_internal(oc_client_response_t *data)
{
oc_tls_handler_schedule_write(data->user_data);
}
#endif /* OC_PKI && OC_CLIENT */
#ifdef OC_TCP
#define DEFAULT_RECEIVE_SIZE \
(COAP_TCP_DEFAULT_HEADER_LEN + COAP_TCP_MAX_EXTENDED_LENGTH_LEN)
static void
read_application_data_tcp(oc_tls_peer_t *peer)
{
if (peer->processed_recv_message == NULL) {
peer->processed_recv_message = oc_allocate_message();
if (peer->processed_recv_message) {
peer->processed_recv_message->encrypted = 0;
memcpy(&peer->processed_recv_message->endpoint, &peer->endpoint,
sizeof(oc_endpoint_t));
}
}
while (true) {
if (peer->processed_recv_message) {
size_t want_read = 0;
size_t total_length = 0;
if (peer->processed_recv_message->length < DEFAULT_RECEIVE_SIZE) {
want_read = DEFAULT_RECEIVE_SIZE - peer->processed_recv_message->length;
} else {
total_length =
coap_tcp_get_packet_size(peer->processed_recv_message->data);
if (total_length > (size_t)OC_PDU_SIZE) {
OC_ERR("oc_tls_tcp: total receive length(%ld) is bigger than max pdu "
"size(%ld)",
total_length, OC_PDU_SIZE);
oc_tls_free_peer(peer, false);
return;
}
want_read = total_length - peer->processed_recv_message->length;
}
OC_DBG("oc_tls_tcp: mbedtls_ssl_read want read: %d", (int)want_read);
int ret = mbedtls_ssl_read(&peer->ssl_ctx,
peer->processed_recv_message->data +
peer->processed_recv_message->length,
want_read);
OC_DBG("oc_tls_tcp: mbedtls_ssl_read returns: %d", ret);
if (ret <= 0) {
if (ret == 0 || ret == MBEDTLS_ERR_SSL_WANT_READ ||
ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
OC_DBG("oc_tls_tcp: Received WantRead/WantWrite");
return;
}
oc_message_unref(peer->processed_recv_message);
peer->processed_recv_message = NULL;
if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
OC_DBG("oc_tls_tcp: Close-Notify received");
} else if (ret == MBEDTLS_ERR_SSL_CLIENT_RECONNECT) {
OC_DBG("oc_tls_tcp: Client wants to reconnect");
} else {
#ifdef OC_DEBUG
char buf[256];
mbedtls_strerror(ret, buf, 256);
OC_ERR("oc_tls_tcp: mbedtls_error: %s", buf);
#endif /* OC_DEBUG */
}
if (peer->role == MBEDTLS_SSL_IS_SERVER &&
(peer->endpoint.flags & TCP) == 0) {
mbedtls_ssl_close_notify(&peer->ssl_ctx);
mbedtls_ssl_close_notify(&peer->ssl_ctx);
}
oc_tls_free_peer(peer, false);
return;
}
peer->processed_recv_message->length += ret;
if (total_length &&
peer->processed_recv_message->length == total_length) {
OC_DBG("oc_tls_tcp: Decrypted incoming message %d",
(int)(total_length));
peer->processed_recv_message->encrypted = 0;
memcpy(peer->processed_recv_message->endpoint.di.id, peer->uuid.id, 16);
if (oc_process_post(&coap_engine, oc_events[INBOUND_RI_EVENT],
peer->processed_recv_message) ==
OC_PROCESS_ERR_FULL) {
oc_message_unref(peer->processed_recv_message);
}
peer->processed_recv_message = NULL;
return;
}
} else {
return;
}
}
}
#endif
static void
read_application_data(oc_tls_peer_t *peer)
{
OC_DBG("oc_tls: In read_application_data");
if (!is_peer_active(peer)) {
OC_DBG("oc_tls: read_application_data: Peer not active");
return;
}
if (peer->ssl_ctx.state != MBEDTLS_SSL_HANDSHAKE_OVER) {
int ret = 0;
do {
ret = mbedtls_ssl_handshake_step(&peer->ssl_ctx);
if (peer->ssl_ctx.state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC ||
peer->ssl_ctx.state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC) {
memcpy(peer->master_secret, peer->ssl_ctx.session_negotiate->master,
sizeof(peer->master_secret));
OC_DBG("oc_tls: Got master secret");
OC_LOGbytes(peer->master_secret, 48);
}
if (peer->ssl_ctx.state == MBEDTLS_SSL_CLIENT_KEY_EXCHANGE ||
peer->ssl_ctx.state == MBEDTLS_SSL_SERVER_KEY_EXCHANGE) {
memcpy(peer->client_server_random, peer->ssl_ctx.handshake->randbytes,
sizeof(peer->client_server_random));
OC_DBG("oc_tls: Got nonce");
OC_LOGbytes(peer->client_server_random, 64);
}
if (ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) {
mbedtls_ssl_session_reset(&peer->ssl_ctx);
/* For HelloVerifyRequest cookies */
if (peer->role == MBEDTLS_SSL_IS_SERVER &&
mbedtls_ssl_set_client_transport_id(
&peer->ssl_ctx, (const unsigned char *)&peer->endpoint.addr,
sizeof(peer->endpoint.addr)) != 0) {
oc_tls_free_peer(peer, false);
return;
}
} else if (ret < 0 && ret != MBEDTLS_ERR_SSL_WANT_READ &&
ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
#ifdef OC_DEBUG
char buf[256];
mbedtls_strerror(ret, buf, 256);
OC_ERR("oc_tls: mbedtls_error: %s", buf);
#endif /* OC_DEBUG */
oc_tls_free_peer(peer, false);
return;
}
} while (ret == 0 && peer->ssl_ctx.state != MBEDTLS_SSL_HANDSHAKE_OVER);
if (peer->ssl_ctx.state == MBEDTLS_SSL_HANDSHAKE_OVER) {
OC_DBG("oc_tls: (D)TLS Session is connected via ciphersuite [0x%x]",
peer->ssl_ctx.session->ciphersuite);
oc_handle_session(&peer->endpoint, OC_SESSION_CONNECTED);
#ifdef OC_CLIENT
#if defined(OC_CLOUD) && defined(OC_PKI)
if (!peer->ssl_conf.f_vrfy) {
const mbedtls_x509_crt *cert =
mbedtls_ssl_get_peer_cert(&peer->ssl_ctx);
oc_string_t uuid;
if (oc_certs_parse_CN_for_UUID(cert, &uuid) < 0) {
peer->uuid.id[0] = '*';
} else {
oc_str_to_uuid(oc_string(uuid), &peer->uuid);
oc_free_string(&uuid);
}
}
#endif /* OC_CLOUD && OC_PKI */
#ifdef OC_PKI
if (auto_assert_all_roles && !oc_tls_uses_psk_cred(peer) &&
oc_get_all_roles()) {
oc_assert_all_roles(&peer->endpoint, assert_all_roles_internal, peer);
} else
#endif /* OC_PKI */
{
oc_tls_handler_schedule_write(peer);
}
#endif /* OC_CLIENT */
}
} else {
#ifdef OC_TCP
if (peer->endpoint.flags & TCP) {
read_application_data_tcp(peer);
return;
}
#endif
#ifdef OC_INOUT_BUFFER_SIZE
oc_message_t message[1];
#else /* OC_INOUT_BUFFER_SIZE */
oc_message_t *message = oc_allocate_message();
if (message) {
#endif /* !OC_INOUT_BUFFER_SIZE */
memcpy(&message->endpoint, &peer->endpoint, sizeof(oc_endpoint_t));
int ret = mbedtls_ssl_read(&peer->ssl_ctx, message->data, OC_PDU_SIZE);
if (ret <= 0) {
#ifndef OC_INOUT_BUFFER_SIZE
oc_message_unref(message);
#endif /* OC_INOUT_BUFFER_SIZE */
if (ret == 0 || ret == MBEDTLS_ERR_SSL_WANT_READ ||
ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
OC_DBG("oc_tls: Received WantRead/WantWrite");
return;
}
if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
OC_DBG("oc_tls: Close-Notify received");
} else if (ret == MBEDTLS_ERR_SSL_CLIENT_RECONNECT) {
OC_DBG("oc_tls: Client wants to reconnect");
} else {
#ifdef OC_DEBUG
char buf[256];
mbedtls_strerror(ret, buf, 256);
OC_ERR("oc_tls: mbedtls_error: %s", buf);
#endif /* OC_DEBUG */
}
if (peer->role == MBEDTLS_SSL_IS_SERVER &&
(peer->endpoint.flags & TCP) == 0) {
mbedtls_ssl_close_notify(&peer->ssl_ctx);
mbedtls_ssl_close_notify(&peer->ssl_ctx);
}
oc_tls_free_peer(peer, false);
return;
}
message->length = ret;
message->encrypted = 0;
oc_message_t *msg = message;
#ifdef OC_INOUT_BUFFER_SIZE
msg = oc_allocate_message();
if (!msg) {
OC_WRN("oc_tls: could not allocate incoming message buffer");
return;
}
#endif /* OC_INOUT_BUFFER_SIZE */
memcpy(&msg->endpoint, &message->endpoint, sizeof(oc_endpoint_t));
memcpy(&msg->endpoint.di.id, &peer->uuid.id, 16);
msg->length = message->length;
memcpy(msg->data, message->data, message->length);
#ifdef OC_OSCORE
if (oc_process_post(&oc_oscore_handler, oc_events[INBOUND_OSCORE_EVENT],
msg) == OC_PROCESS_ERR_FULL) {
#ifndef OC_INOUT_BUFFER_SIZE
oc_message_unref(msg);
#endif /* !OC_INOUT_BUFFER_SIZE */
}
#else /* OC_OSCORE */
if (oc_process_post(&coap_engine, oc_events[INBOUND_RI_EVENT], msg) ==
OC_PROCESS_ERR_FULL) {
#ifndef OC_INOUT_BUFFER_SIZE
oc_message_unref(msg);
#endif /* !OC_INOUT_BUFFER_SIZE */
}
#endif /* !OC_OSCORE */
}
OC_DBG("oc_tls: Decrypted incoming message");
#ifndef OC_INOUT_BUFFER_SIZE
}
#endif /* !OC_INOUT_BUFFER_SIZE */
}
static void
oc_tls_recv_message(oc_message_t *message)
{
oc_tls_peer_t *peer =
oc_tls_add_peer(&message->endpoint, MBEDTLS_SSL_IS_SERVER);
if (peer) {
#ifdef OC_DEBUG
char u[OC_UUID_LEN];
oc_uuid_to_str(&peer->uuid, u, OC_UUID_LEN);
OC_DBG("oc_tls: Received message from device %s", u);
if (peer->endpoint.flags & TCP) {
OC_DBG("oc_tls_recv_message_tcp: %d %ld", (int)message->length, peer);
}
#endif /* OC_DEBUG */
oc_list_add(peer->recv_q, message);
peer->timestamp = oc_clock_time();
oc_tls_handler_schedule_read(peer);
} else {
oc_message_unref(message);
}
}
static void
close_all_tls_sessions_for_device(size_t device)
{
OC_DBG("oc_tls: closing all open (D)TLS sessions on device %zd", device);
oc_tls_peer_t *p = oc_list_head(tls_peers), *next;
while (p != NULL) {
next = p->next;
if (p->endpoint.device == device) {
oc_tls_close_connection(&p->endpoint);
}
p = next;
}
}
static void
close_all_tls_sessions(void)
{
OC_DBG("oc_tls: closing all open (D)TLS sessions on all devices");
oc_tls_peer_t *p = oc_list_head(tls_peers), *next;
while (p != NULL) {
next = p->next;
oc_tls_close_connection(&p->endpoint);
p = next;
}
}
OC_PROCESS_THREAD(oc_tls_handler, ev, data)
{
OC_PROCESS_POLLHANDLER(close_all_tls_sessions());
OC_PROCESS_BEGIN();
while (1) {
OC_PROCESS_YIELD();
if (ev == oc_events[UDP_TO_TLS_EVENT]) {
oc_tls_recv_message(data);
}
#ifdef OC_CLIENT
else if (ev == oc_events[INIT_TLS_CONN_EVENT]) {
oc_tls_init_connection(data);
}
#endif /* OC_CLIENT */
else if (ev == oc_events[RI_TO_TLS_EVENT]) {
oc_tls_send_message(data);
} else if (ev == OC_PROCESS_EVENT_TIMER) {
check_retr_timers();
} else if (ev == oc_events[TLS_READ_DECRYPTED_DATA]) {
read_application_data(data);
}
#ifdef OC_CLIENT
else if (ev == oc_events[TLS_WRITE_APPLICATION_DATA]) {
write_application_data(data);
}
#endif /* OC_CLIENT */
else if (ev == oc_events[TLS_CLOSE_ALL_SESSIONS]) {
size_t device = (size_t)data;
close_all_tls_sessions_for_device(device);
}
}
OC_PROCESS_END();
}
#endif /* OC_SECURITY */
|
the_stack_data/73575110.c | /* { dg-do compile } */
/* { dg-require-effective-target arm_thumb1_ok } */
/* { dg-skip-if "do not override -mcpu" { *-*-* } { "-mcpu=*" "-march=*" } { "-mcpu=cortex-m0.small-multiply" } } */
/* { dg-options "-mcpu=cortex-m0.small-multiply -mthumb -Os" } */
int
test (int a)
{
return a * 0x123456;
}
/* { dg-final { scan-assembler "\[\\t \]+mul" } } */
|
the_stack_data/50136823.c | #include<stdio.h>
#include<stdlib.h>
struct node{
int key;
struct node *left;
struct node *right;
};
typedef struct node NODE;
NODE* getnode()
{
NODE *newnode;
newnode=(NODE*)malloc(sizeof(NODE));
if(newnode==NULL)
{
printf("there is no space for a new node\n");
return 0;
}
newnode->left=NULL;
newnode->right=NULL;
printf("enter a key element to newnode\n");
scanf("%d",&newnode->key);
return newnode;
}
NODE *root=NULL;
//code for implimentation of tree without recursion.
/*
void insertnode()
{
NODE* child,*cur_root;
cur_root=root;
child=getnode();
if(root==NULL)
{
root=child;
}
else
{
while(cur_root!=NULL){
if(child->key>cur_root->key)
{ if( cur_root->right==NULL){
cur_root->right=child;
return;}
else
cur_root=cur_root->right;
}
else if(child->key<cur_root->key)
{
if(cur_root->left==NULL){
root->left=child;
return;}
else
cur_root=cur_root->left;
}
else
{
printf("not possible!");
}
}
}
return;
}*/
// implimentation of binary search tree using recursion.
void insertnode(NODE *child, NODE *root)
{
if(child->key>root->key)
{
if(root->right==NULL){
root->right=child;
return;}
insertnode(child,root->right);
}
else if(child->key<root->key)
{
if(root->left==NULL)
{
root->left=child;
return;
}
insertnode(child,root->left);
}
else
{
printf("not possible!\n");
return;
}
}
//tree methods of traversing a binary search tree.
void preorder(NODE* Root)
{
if(Root==NULL)
{
return;
}
printf("%d ",Root->key);
preorder(Root->left);
preorder(Root->right);
}
void inorder(NODE *Root)
{
if(Root==NULL)
return;
inorder(Root->left);
printf("%d ",Root->key);
inorder(Root->right);
}
void postorder(NODE *Root)
{
if(Root==NULL)
return;
postorder(Root->left);
postorder(Root->right);
printf("%d ",Root->key);
}
void main()
{
int choice;
do{
printf("enter your choice\n ");
printf("1. for insert a node\n 2. for preorder\n 3.inorder\n 4. postorder\n 5. exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
NODE* child,*cur_root;
cur_root=root;
child=getnode();
if(root==NULL)
{
root=child;
}
else
insertnode(child,root);
break;
}
case 2:
{
preorder(root);
break;
}
case 3:
{
inorder(root);
break;
}
case 4:
{
postorder(root);
break;
}
}
}while(choice<=4&&choice>=1);
}
|
the_stack_data/231394566.c | #include <stdio.h>
#include <string.h>
#define STRLEN 1100
int valid(char *s);
int main(void)
{
int n, i;
char s[STRLEN];
scanf("%d", &n);
getchar();
for (i = 0; i < n; i++) {
fgets(s, STRLEN, stdin);
if (strlen(s) == 1 || valid(s)) {
printf("Case %d: Yes\n", i + 1);
}
else {
printf("Case %d: No\n", i + 1);
}
}
return 0;
}
int valid(char *s)
{
char t[STRLEN];
int i ,top;
for (i = top = 0; i < strlen(s)-1; i++) {
switch (s[i]) {
case '{':
case '[':
case '<':
case '(':
t[top++] = s[i];
break;
case '}':
if (top == 0 || t[top-1] != '{') {
return 0;
}
--top;
break;
case ')':
if (top == 0 || t[top-1] != '(') {
return 0;
}
--top;
break;
case '>':
if (top == 0 || t[top-1] != '<') {
return 0;
}
--top;
break;
case ']':
if (top == 0 || t[top-1] != '[') {
return 0;
}
--top;
break;
}
}
if (top != 0) {
return 0;
}
return 1;
}
|
the_stack_data/73574298.c |
#if 0 /* in case someone actually tries to compile this */
/* example.c - an example of using libpng
* Last changed in libpng 1.2.37 [June 4, 2009]
* This file has been placed in the public domain by the authors.
* Maintained 1998-2010 Glenn Randers-Pehrson
* Maintained 1996, 1997 Andreas Dilger)
* Written 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*/
/* This is an example of how to use libpng to read and write PNG files.
* The file libpng.txt is much more verbose then this. If you have not
* read it, do so first. This was designed to be a starting point of an
* implementation. This is not officially part of libpng, is hereby placed
* in the public domain, and therefore does not require a copyright notice.
*
* This file does not currently compile, because it is missing certain
* parts, like allocating memory to hold an image. You will have to
* supply these parts to get it to compile. For an example of a minimal
* working PNG reader/writer, see pngtest.c, included in this distribution;
* see also the programs in the contrib directory.
*/
#include "png.h"
/* The png_jmpbuf() macro, used in error handling, became available in
* libpng version 1.0.6. If you want to be able to run your code with older
* versions of libpng, you must define the macro yourself (but only if it
* is not already defined by libpng!).
*/
#ifndef png_jmpbuf
# define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
#endif
/* Check to see if a file is a PNG file using png_sig_cmp(). png_sig_cmp()
* returns zero if the image is a PNG and nonzero if it isn't a PNG.
*
* The function check_if_png() shown here, but not used, returns nonzero (true)
* if the file can be opened and is a PNG, 0 (false) otherwise.
*
* If this call is successful, and you are going to keep the file open,
* you should call png_set_sig_bytes(png_ptr, PNG_BYTES_TO_CHECK); once
* you have created the png_ptr, so that libpng knows your application
* has read that many bytes from the start of the file. Make sure you
* don't call png_set_sig_bytes() with more than 8 bytes read or give it
* an incorrect number of bytes read, or you will either have read too
* many bytes (your fault), or you are telling libpng to read the wrong
* number of magic bytes (also your fault).
*
* Many applications already read the first 2 or 4 bytes from the start
* of the image to determine the file type, so it would be easiest just
* to pass the bytes to png_sig_cmp() or even skip that if you know
* you have a PNG file, and call png_set_sig_bytes().
*/
#define PNG_BYTES_TO_CHECK 4
int check_if_png(char *file_name, FILE **fp)
{
char buf[PNG_BYTES_TO_CHECK];
/* Open the prospective PNG file. */
if ((*fp = fopen(file_name, "rb")) == NULL)
return 0;
/* Read in some of the signature bytes */
if (fread(buf, 1, PNG_BYTES_TO_CHECK, *fp) != PNG_BYTES_TO_CHECK)
return 0;
/* Compare the first PNG_BYTES_TO_CHECK bytes of the signature.
Return nonzero (true) if they match */
return(!png_sig_cmp(buf, (png_size_t)0, PNG_BYTES_TO_CHECK));
}
/* Read a PNG file. You may want to return an error code if the read
* fails (depending upon the failure). There are two "prototypes" given
* here - one where we are given the filename, and we need to open the
* file, and the other where we are given an open file (possibly with
* some or all of the magic bytes read - see comments above).
*/
#ifdef open_file /* prototype 1 */
void read_png(char *file_name) /* We need to open the file */
{
png_structp png_ptr;
png_infop info_ptr;
unsigned int sig_read = 0;
png_uint_32 width, height;
int bit_depth, color_type, interlace_type;
FILE *fp;
if ((fp = fopen(file_name, "rb")) == NULL)
return (ERROR);
#else no_open_file /* prototype 2 */
void read_png(FILE *fp, unsigned int sig_read) /* File is already open */
{
png_structp png_ptr;
png_infop info_ptr;
png_uint_32 width, height;
int bit_depth, color_type, interlace_type;
#endif no_open_file /* Only use one prototype! */
/* Create and initialize the png_struct with the desired error handler
* functions. If you want to use the default stderr and longjump method,
* you can supply NULL for the last three parameters. We also supply the
* the compiler header file version, so that we know if the application
* was compiled with a compatible version of the library. REQUIRED
*/
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
png_voidp user_error_ptr, user_error_fn, user_warning_fn);
if (png_ptr == NULL)
{
fclose(fp);
return (ERROR);
}
/* Allocate/initialize the memory for image information. REQUIRED. */
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
{
fclose(fp);
png_destroy_read_struct(&png_ptr, png_infopp_NULL, png_infopp_NULL);
return (ERROR);
}
/* Set error handling if you are using the setjmp/longjmp method (this is
* the normal method of doing things with libpng). REQUIRED unless you
* set up your own error handlers in the png_create_read_struct() earlier.
*/
if (setjmp(png_jmpbuf(png_ptr)))
{
/* Free all of the memory associated with the png_ptr and info_ptr */
png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
fclose(fp);
/* If we get here, we had a problem reading the file */
return (ERROR);
}
/* One of the following I/O initialization methods is REQUIRED */
#ifdef streams /* PNG file I/O method 1 */
/* Set up the input control if you are using standard C streams */
png_init_io(png_ptr, fp);
#else no_streams /* PNG file I/O method 2 */
/* If you are using replacement read functions, instead of calling
* png_init_io() here you would call:
*/
png_set_read_fn(png_ptr, (void *)user_io_ptr, user_read_fn);
/* where user_io_ptr is a structure you want available to the callbacks */
#endif no_streams /* Use only one I/O method! */
/* If we have already read some of the signature */
png_set_sig_bytes(png_ptr, sig_read);
#ifdef hilevel
/*
* If you have enough memory to read in the entire image at once,
* and you need to specify only transforms that can be controlled
* with one of the PNG_TRANSFORM_* bits (this presently excludes
* dithering, filling, setting background, and doing gamma
* adjustment), then you can read the entire image (including
* pixels) into the info structure with this call:
*/
png_read_png(png_ptr, info_ptr, png_transforms, png_voidp_NULL);
#else
/* OK, you're doing it the hard way, with the lower-level functions */
/* The call to png_read_info() gives us all of the information from the
* PNG file before the first IDAT (image data chunk). REQUIRED
*/
png_read_info(png_ptr, info_ptr);
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
&interlace_type, int_p_NULL, int_p_NULL);
/* Set up the data transformations you want. Note that these are all
* optional. Only call them if you want/need them. Many of the
* transformations only work on specific types of images, and many
* are mutually exclusive.
*/
/* Tell libpng to strip 16 bit/color files down to 8 bits/color */
png_set_strip_16(png_ptr);
/* Strip alpha bytes from the input data without combining with the
* background (not recommended).
*/
png_set_strip_alpha(png_ptr);
/* Extract multiple pixels with bit depths of 1, 2, and 4 from a single
* byte into separate bytes (useful for paletted and grayscale images).
*/
png_set_packing(png_ptr);
/* Change the order of packed pixels to least significant bit first
* (not useful if you are using png_set_packing). */
png_set_packswap(png_ptr);
/* Expand paletted colors into true RGB triplets */
if (color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
/* Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel */
if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
png_set_expand_gray_1_2_4_to_8(png_ptr);
/* Expand paletted or RGB images with transparency to full alpha channels
* so the data will be available as RGBA quartets.
*/
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
png_set_tRNS_to_alpha(png_ptr);
/* Set the background color to draw transparent and alpha images over.
* It is possible to set the red, green, and blue components directly
* for paletted images instead of supplying a palette index. Note that
* even if the PNG file supplies a background, you are not required to
* use it - you should use the (solid) application background if it has one.
*/
png_color_16 my_background, *image_background;
if (png_get_bKGD(png_ptr, info_ptr, &image_background))
png_set_background(png_ptr, image_background,
PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
else
png_set_background(png_ptr, &my_background,
PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
/* Some suggestions as to how to get a screen gamma value
*
* Note that screen gamma is the display_exponent, which includes
* the CRT_exponent and any correction for viewing conditions
*/
if (/* We have a user-defined screen gamma value */)
{
screen_gamma = user-defined screen_gamma;
}
/* This is one way that applications share the same screen gamma value */
else if ((gamma_str = getenv("SCREEN_GAMMA")) != NULL)
{
screen_gamma = atof(gamma_str);
}
/* If we don't have another value */
else
{
screen_gamma = 2.2; /* A good guess for a PC monitor in a dimly
lit room */
screen_gamma = 1.7 or 1.0; /* A good guess for Mac systems */
}
/* Tell libpng to handle the gamma conversion for you. The final call
* is a good guess for PC generated images, but it should be configurable
* by the user at run time by the user. It is strongly suggested that
* your application support gamma correction.
*/
int intent;
if (png_get_sRGB(png_ptr, info_ptr, &intent))
png_set_gamma(png_ptr, screen_gamma, 0.45455);
else
{
double image_gamma;
if (png_get_gAMA(png_ptr, info_ptr, &image_gamma))
png_set_gamma(png_ptr, screen_gamma, image_gamma);
else
png_set_gamma(png_ptr, screen_gamma, 0.45455);
}
/* Dither RGB files down to 8 bit palette or reduce palettes
* to the number of colors available on your screen.
*/
if (color_type & PNG_COLOR_MASK_COLOR)
{
int num_palette;
png_colorp palette;
/* This reduces the image to the application supplied palette */
if (/* We have our own palette */)
{
/* An array of colors to which the image should be dithered */
png_color std_color_cube[MAX_SCREEN_COLORS];
png_set_dither(png_ptr, std_color_cube, MAX_SCREEN_COLORS,
MAX_SCREEN_COLORS, png_uint_16p_NULL, 0);
}
/* This reduces the image to the palette supplied in the file */
else if (png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette))
{
png_uint_16p histogram = NULL;
png_get_hIST(png_ptr, info_ptr, &histogram);
png_set_dither(png_ptr, palette, num_palette,
max_screen_colors, histogram, 0);
}
}
/* Invert monochrome files to have 0 as white and 1 as black */
png_set_invert_mono(png_ptr);
/* If you want to shift the pixel values from the range [0,255] or
* [0,65535] to the original [0,7] or [0,31], or whatever range the
* colors were originally in:
*/
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
{
png_color_8p sig_bit_p;
png_get_sBIT(png_ptr, info_ptr, &sig_bit_p);
png_set_shift(png_ptr, sig_bit_p);
}
/* Flip the RGB pixels to BGR (or RGBA to BGRA) */
if (color_type & PNG_COLOR_MASK_COLOR)
png_set_bgr(png_ptr);
/* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
png_set_swap_alpha(png_ptr);
/* Swap bytes of 16 bit files to least significant byte first */
png_set_swap(png_ptr);
/* Add filler (or alpha) byte (before/after each RGB triplet) */
png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
/* Turn on interlace handling. REQUIRED if you are not using
* png_read_image(). To see how to handle interlacing passes,
* see the png_read_row() method below:
*/
number_passes = png_set_interlace_handling(png_ptr);
/* Optional call to gamma correct and add the background to the palette
* and update info structure. REQUIRED if you are expecting libpng to
* update the palette for you (ie you selected such a transform above).
*/
png_read_update_info(png_ptr, info_ptr);
/* Allocate the memory to hold the image using the fields of info_ptr. */
/* The easiest way to read the image: */
png_bytep row_pointers[height];
/* Clear the pointer array */
for (row = 0; row < height; row++)
row_pointers[row] = NULL;
for (row = 0; row < height; row++)
row_pointers[row] = png_malloc(png_ptr, png_get_rowbytes(png_ptr,
info_ptr));
/* Now it's time to read the image. One of these methods is REQUIRED */
#ifdef entire /* Read the entire image in one go */
png_read_image(png_ptr, row_pointers);
#else no_entire /* Read the image one or more scanlines at a time */
/* The other way to read images - deal with interlacing: */
for (pass = 0; pass < number_passes; pass++)
{
#ifdef single /* Read the image a single row at a time */
for (y = 0; y < height; y++)
{
png_read_rows(png_ptr, &row_pointers[y], png_bytepp_NULL, 1);
}
#else no_single /* Read the image several rows at a time */
for (y = 0; y < height; y += number_of_rows)
{
#ifdef sparkle /* Read the image using the "sparkle" effect. */
png_read_rows(png_ptr, &row_pointers[y], png_bytepp_NULL,
number_of_rows);
#else no_sparkle /* Read the image using the "rectangle" effect */
png_read_rows(png_ptr, png_bytepp_NULL, &row_pointers[y],
number_of_rows);
#endif no_sparkle /* Use only one of these two methods */
}
/* If you want to display the image after every pass, do so here */
#endif no_single /* Use only one of these two methods */
}
#endif no_entire /* Use only one of these two methods */
/* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
png_read_end(png_ptr, info_ptr);
#endif hilevel
/* At this point you have read the entire image */
/* Clean up after the read, and free any memory allocated - REQUIRED */
png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
/* Close the file */
fclose(fp);
/* That's it */
return (OK);
}
/* Progressively read a file */
int
initialize_png_reader(png_structp *png_ptr, png_infop *info_ptr)
{
/* Create and initialize the png_struct with the desired error handler
* functions. If you want to use the default stderr and longjump method,
* you can supply NULL for the last three parameters. We also check that
* the library version is compatible in case we are using dynamically
* linked libraries.
*/
*png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
png_voidp user_error_ptr, user_error_fn, user_warning_fn);
if (*png_ptr == NULL)
{
*info_ptr = NULL;
return (ERROR);
}
*info_ptr = png_create_info_struct(png_ptr);
if (*info_ptr == NULL)
{
png_destroy_read_struct(png_ptr, info_ptr, png_infopp_NULL);
return (ERROR);
}
if (setjmp(png_jmpbuf((*png_ptr))))
{
png_destroy_read_struct(png_ptr, info_ptr, png_infopp_NULL);
return (ERROR);
}
/* This one's new. You will need to provide all three
* function callbacks, even if you aren't using them all.
* If you aren't using all functions, you can specify NULL
* parameters. Even when all three functions are NULL,
* you need to call png_set_progressive_read_fn().
* These functions shouldn't be dependent on global or
* static variables if you are decoding several images
* simultaneously. You should store stream specific data
* in a separate struct, given as the second parameter,
* and retrieve the pointer from inside the callbacks using
* the function png_get_progressive_ptr(png_ptr).
*/
png_set_progressive_read_fn(*png_ptr, (void *)stream_data,
info_callback, row_callback, end_callback);
return (OK);
}
int
process_data(png_structp *png_ptr, png_infop *info_ptr,
png_bytep buffer, png_uint_32 length)
{
if (setjmp(png_jmpbuf((*png_ptr))))
{
/* Free the png_ptr and info_ptr memory on error */
png_destroy_read_struct(png_ptr, info_ptr, png_infopp_NULL);
return (ERROR);
}
/* This one's new also. Simply give it chunks of data as
* they arrive from the data stream (in order, of course).
* On segmented machines, don't give it any more than 64K.
* The library seems to run fine with sizes of 4K, although
* you can give it much less if necessary (I assume you can
* give it chunks of 1 byte, but I haven't tried with less
* than 256 bytes yet). When this function returns, you may
* want to display any rows that were generated in the row
* callback, if you aren't already displaying them there.
*/
png_process_data(*png_ptr, *info_ptr, buffer, length);
return (OK);
}
info_callback(png_structp png_ptr, png_infop info)
{
/* Do any setup here, including setting any of the transformations
* mentioned in the Reading PNG files section. For now, you _must_
* call either png_start_read_image() or png_read_update_info()
* after all the transformations are set (even if you don't set
* any). You may start getting rows before png_process_data()
* returns, so this is your last chance to prepare for that.
*/
}
row_callback(png_structp png_ptr, png_bytep new_row,
png_uint_32 row_num, int pass)
{
/*
* This function is called for every row in the image. If the
* image is interlaced, and you turned on the interlace handler,
* this function will be called for every row in every pass.
*
* In this function you will receive a pointer to new row data from
* libpng called new_row that is to replace a corresponding row (of
* the same data format) in a buffer allocated by your application.
*
* The new row data pointer "new_row" may be NULL, indicating there is
* no new data to be replaced (in cases of interlace loading).
*
* If new_row is not NULL then you need to call
* png_progressive_combine_row() to replace the corresponding row as
* shown below:
*/
/* Check if row_num is in bounds. */
if ((row_num >= 0) && (row_num < height))
{
/* Get pointer to corresponding row in our
* PNG read buffer.
*/
png_bytep old_row = ((png_bytep *)our_data)[row_num];
/* If both rows are allocated then copy the new row
* data to the corresponding row data.
*/
if ((old_row != NULL) && (new_row != NULL))
png_progressive_combine_row(png_ptr, old_row, new_row);
}
/*
* The rows and passes are called in order, so you don't really
* need the row_num and pass, but I'm supplying them because it
* may make your life easier.
*
* For the non-NULL rows of interlaced images, you must call
* png_progressive_combine_row() passing in the new row and the
* old row, as demonstrated above. You can call this function for
* NULL rows (it will just return) and for non-interlaced images
* (it just does the png_memcpy for you) if it will make the code
* easier. Thus, you can just do this for all cases:
*/
png_progressive_combine_row(png_ptr, old_row, new_row);
/* where old_row is what was displayed for previous rows. Note
* that the first pass (pass == 0 really) will completely cover
* the old row, so the rows do not have to be initialized. After
* the first pass (and only for interlaced images), you will have
* to pass the current row as new_row, and the function will combine
* the old row and the new row.
*/
}
end_callback(png_structp png_ptr, png_infop info)
{
/* This function is called when the whole image has been read,
* including any chunks after the image (up to and including
* the IEND). You will usually have the same info chunk as you
* had in the header, although some data may have been added
* to the comments and time fields.
*
* Most people won't do much here, perhaps setting a flag that
* marks the image as finished.
*/
}
/* Write a png file */
void write_png(char *file_name /* , ... other image information ... */)
{
FILE *fp;
png_structp png_ptr;
png_infop info_ptr;
png_colorp palette;
/* Open the file */
fp = fopen(file_name, "wb");
if (fp == NULL)
return (ERROR);
/* Create and initialize the png_struct with the desired error handler
* functions. If you want to use the default stderr and longjump method,
* you can supply NULL for the last three parameters. We also check that
* the library version is compatible with the one used at compile time,
* in case we are using dynamically linked libraries. REQUIRED.
*/
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
png_voidp user_error_ptr, user_error_fn, user_warning_fn);
if (png_ptr == NULL)
{
fclose(fp);
return (ERROR);
}
/* Allocate/initialize the image information data. REQUIRED */
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
{
fclose(fp);
png_destroy_write_struct(&png_ptr, png_infopp_NULL);
return (ERROR);
}
/* Set error handling. REQUIRED if you aren't supplying your own
* error handling functions in the png_create_write_struct() call.
*/
if (setjmp(png_jmpbuf(png_ptr)))
{
/* If we get here, we had a problem writing the file */
fclose(fp);
png_destroy_write_struct(&png_ptr, &info_ptr);
return (ERROR);
}
/* One of the following I/O initialization functions is REQUIRED */
#ifdef streams /* I/O initialization method 1 */
/* Set up the output control if you are using standard C streams */
png_init_io(png_ptr, fp);
#else no_streams /* I/O initialization method 2 */
/* If you are using replacement write functions, instead of calling
* png_init_io() here you would call
*/
png_set_write_fn(png_ptr, (void *)user_io_ptr, user_write_fn,
user_IO_flush_function);
/* where user_io_ptr is a structure you want available to the callbacks */
#endif no_streams /* Only use one initialization method */
#ifdef hilevel
/* This is the easy way. Use it if you already have all the
* image info living in the structure. You could "|" many
* PNG_TRANSFORM flags into the png_transforms integer here.
*/
png_write_png(png_ptr, info_ptr, png_transforms, png_voidp_NULL);
#else
/* This is the hard way */
/* Set the image information here. Width and height are up to 2^31,
* bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
* the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
* PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
* or PNG_COLOR_TYPE_RGB_ALPHA. interlace is either PNG_INTERLACE_NONE or
* PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
* currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
*/
png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, PNG_COLOR_TYPE_???,
PNG_INTERLACE_????, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
/* Set the palette if there is one. REQUIRED for indexed-color images */
palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH
* png_sizeof(png_color));
/* ... Set palette colors ... */
png_set_PLTE(png_ptr, info_ptr, palette, PNG_MAX_PALETTE_LENGTH);
/* You must not free palette here, because png_set_PLTE only makes a link to
* the palette that you malloced. Wait until you are about to destroy
* the png structure.
*/
/* Optional significant bit (sBIT) chunk */
png_color_8 sig_bit;
/* If we are dealing with a grayscale image then */
sig_bit.gray = true_bit_depth;
/* Otherwise, if we are dealing with a color image then */
sig_bit.red = true_red_bit_depth;
sig_bit.green = true_green_bit_depth;
sig_bit.blue = true_blue_bit_depth;
/* If the image has an alpha channel then */
sig_bit.alpha = true_alpha_bit_depth;
png_set_sBIT(png_ptr, info_ptr, &sig_bit);
/* Optional gamma chunk is strongly suggested if you have any guess
* as to the correct gamma of the image.
*/
png_set_gAMA(png_ptr, info_ptr, gamma);
/* Optionally write comments into the image */
text_ptr[0].key = "Title";
text_ptr[0].text = "Mona Lisa";
text_ptr[0].compression = PNG_TEXT_COMPRESSION_NONE;
text_ptr[1].key = "Author";
text_ptr[1].text = "Leonardo DaVinci";
text_ptr[1].compression = PNG_TEXT_COMPRESSION_NONE;
text_ptr[2].key = "Description";
text_ptr[2].text = "<long text>";
text_ptr[2].compression = PNG_TEXT_COMPRESSION_zTXt;
#ifdef PNG_iTXt_SUPPORTED
text_ptr[0].lang = NULL;
text_ptr[1].lang = NULL;
text_ptr[2].lang = NULL;
#endif
png_set_text(png_ptr, info_ptr, text_ptr, 3);
/* Other optional chunks like cHRM, bKGD, tRNS, tIME, oFFs, pHYs */
/* Note that if sRGB is present the gAMA and cHRM chunks must be ignored
* on read and, if your application chooses to write them, they must
* be written in accordance with the sRGB profile
*/
/* Write the file header information. REQUIRED */
png_write_info(png_ptr, info_ptr);
/* If you want, you can write the info in two steps, in case you need to
* write your private chunk ahead of PLTE:
*
* png_write_info_before_PLTE(write_ptr, write_info_ptr);
* write_my_chunk();
* png_write_info(png_ptr, info_ptr);
*
* However, given the level of known- and unknown-chunk support in 1.2.0
* and up, this should no longer be necessary.
*/
/* Once we write out the header, the compression type on the text
* chunks gets changed to PNG_TEXT_COMPRESSION_NONE_WR or
* PNG_TEXT_COMPRESSION_zTXt_WR, so it doesn't get written out again
* at the end.
*/
/* Set up the transformations you want. Note that these are
* all optional. Only call them if you want them.
*/
/* Invert monochrome pixels */
png_set_invert_mono(png_ptr);
/* Shift the pixels up to a legal bit depth and fill in
* as appropriate to correctly scale the image.
*/
png_set_shift(png_ptr, &sig_bit);
/* Pack pixels into bytes */
png_set_packing(png_ptr);
/* Swap location of alpha bytes from ARGB to RGBA */
png_set_swap_alpha(png_ptr);
/* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
* RGB (4 channels -> 3 channels). The second parameter is not used.
*/
png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
/* Flip BGR pixels to RGB */
png_set_bgr(png_ptr);
/* Swap bytes of 16-bit files to most significant byte first */
png_set_swap(png_ptr);
/* Swap bits of 1, 2, 4 bit packed pixel formats */
png_set_packswap(png_ptr);
/* Turn on interlace handling if you are not using png_write_image() */
if (interlacing)
number_passes = png_set_interlace_handling(png_ptr);
else
number_passes = 1;
/* The easiest way to write the image (you may have a different memory
* layout, however, so choose what fits your needs best). You need to
* use the first method if you aren't handling interlacing yourself.
*/
png_uint_32 k, height, width;
png_byte image[height][width*bytes_per_pixel];
png_bytep row_pointers[height];
if (height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
png_error (png_ptr, "Image is too tall to process in memory");
for (k = 0; k < height; k++)
row_pointers[k] = image + k*width*bytes_per_pixel;
/* One of the following output methods is REQUIRED */
#ifdef entire /* Write out the entire image data in one call */
png_write_image(png_ptr, row_pointers);
/* The other way to write the image - deal with interlacing */
#else no_entire /* Write out the image data by one or more scanlines */
/* The number of passes is either 1 for non-interlaced images,
* or 7 for interlaced images.
*/
for (pass = 0; pass < number_passes; pass++)
{
/* Write a few rows at a time. */
png_write_rows(png_ptr, &row_pointers[first_row], number_of_rows);
/* If you are only writing one row at a time, this works */
for (y = 0; y < height; y++)
png_write_rows(png_ptr, &row_pointers[y], 1);
}
#endif no_entire /* Use only one output method */
/* You can write optional chunks like tEXt, zTXt, and tIME at the end
* as well. Shouldn't be necessary in 1.2.0 and up as all the public
* chunks are supported and you can use png_set_unknown_chunks() to
* register unknown chunks into the info structure to be written out.
*/
/* It is REQUIRED to call this to finish writing the rest of the file */
png_write_end(png_ptr, info_ptr);
#endif hilevel
/* If you png_malloced a palette, free it here (don't free info_ptr->palette,
* as recommended in versions 1.0.5m and earlier of this example; if
* libpng mallocs info_ptr->palette, libpng will free it). If you
* allocated it with malloc() instead of png_malloc(), use free() instead
* of png_free().
*/
png_free(png_ptr, palette);
palette = NULL;
/* Similarly, if you png_malloced any data that you passed in with
* png_set_something(), such as a hist or trans array, free it here,
* when you can be sure that libpng is through with it.
*/
png_free(png_ptr, trans);
trans = NULL;
/* Whenever you use png_free() it is a good idea to set the pointer to
* NULL in case your application inadvertently tries to png_free() it
* again. When png_free() sees a NULL it returns without action, thus
* avoiding the double-free security problem.
*/
/* Clean up after the write, and free any memory allocated */
png_destroy_write_struct(&png_ptr, &info_ptr);
/* Close the file */
fclose(fp);
/* That's it */
return (OK);
}
#endif /* if 0 */
|
the_stack_data/63885.c | #include "stdio.h"
#include "stdlib.h"
int main(int argc, char const *argv[]) {
int* nums;
int i=1;
nums = (int*)malloc(sizeof(int));
do {
nums = (int*)realloc( nums, sizeof(int) * i+1);
scanf("%d\n", &nums[i-1] );
i++;
} while(nums[i-2] != 42);
printf("\n");
i=0;
do {
printf("%d\n", nums[i]);
i++;
} while(nums[i] != 42);
free(nums);
return 0;
}
|
the_stack_data/92326052.c | /******************************************************************************
* $Id$
*
* Project: MapServer
* Purpose: OpenGIS Web Coverage Server (WCS) 2.0 implementation.
* Author: Stephan Meissl <[email protected]>
* Fabian Schindler <[email protected]>
* and the MapServer team.
*
******************************************************************************
* Copyright (c) 2010, 2011 EOX IT Services GmbH, Austria
*
* 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 of this Software or works derived from this 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.
****************************************************************************/
#if defined(USE_WCS_SVR)
#include <assert.h>
#include "mapserver.h"
#include "maperror.h"
#include "mapthread.h"
#include "mapwcs.h"
#include <float.h>
#include "gdal.h"
#include "cpl_port.h"
#include "maptime.h"
#include "mapprimitive.h"
#include "cpl_string.h"
#include <proj_api.h>
#include <string.h>
#if defined(USE_LIBXML2)
#include <libxml/tree.h>
#include "maplibxml2.h"
#include <libxml/parser.h>
#endif /* defined(USE_LIBXML2) */
/************************************************************************/
/* msStringParseInteger() */
/* */
/* Tries to parse a string as a integer value. If not possible */
/* the value MS_WCS20_UNBOUNDED is stored as value. */
/* If no characters could be parsed, MS_FAILURE is returned. If at */
/* least some characters could be parsed, MS_DONE is returned and */
/* only if all characters could be parsed, MS_SUCCESS is returned. */
/************************************************************************/
static int msStringParseInteger(const char *string, int *dest)
{
char *parse_check;
*dest = (int)strtol(string, &parse_check, 0);
if(parse_check == string) {
return MS_FAILURE;
} else if(parse_check - strlen(string) != string) {
return MS_DONE;
}
return MS_SUCCESS;
}
/************************************************************************/
/* msStringParseDouble() */
/* */
/* Tries to parse a string as a double value. If not possible */
/* the value 0 is stored as value. */
/* If no characters could be parsed, MS_FAILURE is returned. If at */
/* least some characters could be parsed, MS_DONE is returned and */
/* only if all characters could be parsed, MS_SUCCESS is returned. */
/************************************************************************/
static int msStringParseDouble(const char *string, double *dest)
{
char *parse_check = NULL;
*dest = strtod(string, &parse_check);
if(parse_check == string) {
return MS_FAILURE;
} else if(parse_check - strlen(string) != string) {
return MS_DONE;
}
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSParseTimeOrScalar20() */
/* */
/* Parses a string, either as a time or a scalar value and */
/* writes the output into the timeScalarUnion. */
/************************************************************************/
static int msWCSParseTimeOrScalar20(timeScalarUnion *u, const char *string)
{
struct tm time;
if (string) {
while(*string == ' ')
string ++;
}
if (!string || strlen(string) == 0 || !u) {
msSetError(MS_WCSERR, "Invalid string", "msWCSParseTimeOrScalar20()");
return MS_WCS20_ERROR_VALUE;
}
/* if the string is equal to "*" it means the value
* of the interval is unbounded */
if (EQUAL(string, "*")) {
u->scalar = MS_WCS20_UNBOUNDED;
u->unbounded = 1;
return MS_WCS20_UNDEFINED_VALUE;
}
/* if returned a valid value, use it */
if (msStringParseDouble(string, &(u->scalar)) == MS_SUCCESS) {
return MS_WCS20_SCALAR_VALUE;
}
/* otherwise it might be a time value */
msTimeInit(&time);
if (msParseTime(string, &time) == MS_TRUE) {
u->time = mktime(&time);
return MS_WCS20_TIME_VALUE;
}
/* the value could neither be parsed as a double nor as a time value */
else {
msSetError(MS_WCSERR,
"String %s could not be parsed to a time or scalar value",
"msWCSParseTimeOrScalar20()");
return MS_WCS20_ERROR_VALUE;
}
}
/************************************************************************/
/* msWCSCreateSubsetObj20() */
/* */
/* Creates a new wcs20SubsetObj and initializes it to standard */
/* values. */
/************************************************************************/
static wcs20SubsetObjPtr msWCSCreateSubsetObj20()
{
wcs20SubsetObjPtr subset = (wcs20SubsetObjPtr) malloc(sizeof(wcs20SubsetObj));
MS_CHECK_ALLOC(subset, sizeof(wcs20SubsetObj), NULL);
subset->axis = NULL;
subset->crs = NULL;
subset->min.scalar = subset->max.scalar = MS_WCS20_UNBOUNDED;
subset->min.unbounded = subset->max.unbounded = 0;
subset->operation = MS_WCS20_SLICE;
return subset;
}
/************************************************************************/
/* msWCSFreeSubsetObj20() */
/* */
/* Frees a wcs20SubsetObj and releases all linked resources. */
/************************************************************************/
static void msWCSFreeSubsetObj20(wcs20SubsetObjPtr subset)
{
if (NULL == subset) {
return;
}
msFree(subset->axis);
msFree(subset->crs);
msFree(subset);
}
/************************************************************************/
/* msWCSCreateAxisObj20() */
/* */
/* Creates a new wcs20AxisObj and initializes it to standard */
/* values. */
/************************************************************************/
static wcs20AxisObjPtr msWCSCreateAxisObj20()
{
wcs20AxisObj *axis = (wcs20AxisObjPtr)malloc(sizeof(wcs20AxisObj));
MS_CHECK_ALLOC(axis, sizeof(wcs20AxisObj), NULL);
axis->name = NULL;
axis->size = 0;
axis->resolution = MS_WCS20_UNBOUNDED;
axis->resolutionUOM = NULL;
axis->subset = NULL;
return axis;
}
/************************************************************************/
/* msWCSFreeAxisObj20() */
/* */
/* Frees a wcs20AxisObj and releases all linked resources. */
/************************************************************************/
static void msWCSFreeAxisObj20(wcs20AxisObjPtr axis)
{
if(NULL == axis) {
return;
}
msFree(axis->name);
msFree(axis->resolutionUOM);
msWCSFreeSubsetObj20(axis->subset);
msFree(axis);
}
/************************************************************************/
/* msWCSFindAxis20() */
/* */
/* Helper function to retrieve an axis by the name from a params */
/* object. */
/************************************************************************/
static wcs20AxisObjPtr msWCSFindAxis20(wcs20ParamsObjPtr params,
const char *name)
{
int i = 0;
for(i = 0; i < params->numaxes; ++i) {
if(EQUAL(params->axes[i]->name, name)) {
return params->axes[i];
}
}
return NULL;
}
/************************************************************************/
/* msWCSInsertAxisObj20() */
/* */
/* Helper function to insert an axis object into the axes list of */
/* a params object. */
/************************************************************************/
static void msWCSInsertAxisObj20(wcs20ParamsObjPtr params, wcs20AxisObjPtr axis)
{
params->numaxes++;
params->axes = (wcs20AxisObjPtr*) msSmallRealloc(params->axes,
sizeof(wcs20AxisObjPtr) * (params->numaxes));
params->axes[params->numaxes - 1] = axis;
}
/************************************************************************/
/* msWCSCreateParamsObj20() */
/* */
/* Creates a new wcs20ParamsObj and initializes it to standard */
/* values. */
/************************************************************************/
wcs20ParamsObjPtr msWCSCreateParamsObj20()
{
wcs20ParamsObjPtr params
= (wcs20ParamsObjPtr) malloc(sizeof(wcs20ParamsObj));
MS_CHECK_ALLOC(params, sizeof(wcs20ParamsObj), NULL);
params->version = NULL;
params->request = NULL;
params->service = NULL;
params->accept_versions = NULL;
params->sections = NULL;
params->updatesequence = NULL;
params->ids = NULL;
params->width = 0;
params->height = 0;
params->resolutionX = MS_WCS20_UNBOUNDED;
params->resolutionY = MS_WCS20_UNBOUNDED;
params->resolutionUnits = NULL;
params->numaxes = 0;
params->axes = NULL;
params->format = NULL;
params->multipart = 0;
params->interpolation = NULL;
params->outputcrs = NULL;
params->subsetcrs = NULL;
params->bbox.minx = params->bbox.miny = -DBL_MAX;
params->bbox.maxx = params->bbox.maxy = DBL_MAX;
params->range_subset = NULL;
return params;
}
/************************************************************************/
/* msWCSFreeParamsObj20() */
/* */
/* Frees a wcs20ParamsObj and releases all linked resources. */
/************************************************************************/
void msWCSFreeParamsObj20(wcs20ParamsObjPtr params)
{
if (NULL == params) {
return;
}
msFree(params->version);
msFree(params->request);
msFree(params->service);
CSLDestroy(params->accept_versions);
CSLDestroy(params->sections);
msFree(params->updatesequence);
CSLDestroy(params->ids);
msFree(params->resolutionUnits);
msFree(params->format);
msFree(params->interpolation);
msFree(params->outputcrs);
msFree(params->subsetcrs);
while(params->numaxes > 0) {
params->numaxes -= 1;
msWCSFreeAxisObj20(params->axes[params->numaxes]);
}
msFree(params->axes);
CSLDestroy(params->range_subset);
msFree(params);
}
/************************************************************************/
/* msWCSParseSubset20() */
/* */
/* Parses several string parameters and fills them into the */
/* subset object. */
/************************************************************************/
static int msWCSParseSubset20(wcs20SubsetObjPtr subset, const char *axis,
const char *crs, const char *min, const char *max)
{
int ts1, ts2;
ts1 = ts2 = MS_WCS20_UNDEFINED_VALUE;
if (subset == NULL) {
return MS_FAILURE;
}
if (axis == NULL || strlen(axis) == 0) {
msSetError(MS_WCSERR, "Subset axis is not given.",
"msWCSParseSubset20()");
return MS_FAILURE;
}
subset->axis = msStrdup(axis);
if (crs != NULL) {
subset->crs = msStrdup(crs);
}
/* Parse first (probably only) part of interval/point;
* check whether its a time value or a scalar value */
ts1 = msWCSParseTimeOrScalar20(&(subset->min), min);
if (ts1 == MS_WCS20_ERROR_VALUE) {
return MS_FAILURE;
}
/* check if its an interval */
/* if there is a comma, then it is */
if (max != NULL && strlen(max) > 0) {
subset->operation = MS_WCS20_TRIM;
/* Parse the second value of the interval */
ts2 = msWCSParseTimeOrScalar20(&(subset->max), max);
if (ts2 == MS_WCS20_ERROR_VALUE) {
return MS_FAILURE;
}
/* if at least one boundary is defined, use that value */
if ((ts1 == MS_WCS20_UNDEFINED_VALUE) ^ (ts2
== MS_WCS20_UNDEFINED_VALUE)) {
if (ts1 == MS_WCS20_UNDEFINED_VALUE) {
ts1 = ts2;
}
}
/* if time and scalar values do not fit, throw an error */
else if (ts1 != MS_WCS20_UNDEFINED_VALUE && ts2
!= MS_WCS20_UNDEFINED_VALUE && ts1 != ts2) {
msSetError(MS_WCSERR,
"Interval error: minimum is a %s value, maximum is a %s value",
"msWCSParseSubset20()", ts1 ? "time" : "scalar",
ts2 ? "time" : "scalar");
return MS_FAILURE;
}
/* if both min and max are unbounded -> throw an error */
if (subset->min.unbounded && subset->max.unbounded) {
msSetError(MS_WCSERR, "Invalid values: no bounds could be parsed",
"msWCSParseSubset20()");
return MS_FAILURE;
}
}
/* there is no second value, therefore it is a point.
* consequently set the operation to slice */
else {
subset->operation = MS_WCS20_SLICE;
if (ts1 == MS_WCS20_UNDEFINED_VALUE) {
msSetError(MS_WCSERR, "Invalid point value given",
"msWCSParseSubset20()");
return MS_FAILURE;
}
}
subset->timeOrScalar = ts1;
/* check whether the min is smaller than the max */
if (subset->operation == MS_WCS20_TRIM) {
if(subset->timeOrScalar == MS_WCS20_SCALAR_VALUE && subset->min.scalar == MS_WCS20_UNBOUNDED) {
subset->min.scalar = -MS_WCS20_UNBOUNDED;
}
if (subset->timeOrScalar == MS_WCS20_TIME_VALUE && subset->min.time
> subset->max.time) {
msSetError(MS_WCSERR,
"Minimum value of subset axis %s is larger than maximum value",
"msWCSParseSubset20()", subset->axis);
return MS_FAILURE;
}
if (subset->timeOrScalar == MS_WCS20_SCALAR_VALUE && subset->min.scalar > subset->max.scalar) {
msSetError(MS_WCSERR,
"Minimum value (%f) of subset axis '%s' is larger than maximum value (%f).",
"msWCSParseSubset20()", subset->min.scalar, subset->axis, subset->max.scalar);
return MS_FAILURE;
}
}
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSParseSubsetKVPString20() */
/* */
/* Creates a new wcs20SubsetObj, parses a string and fills */
/* the parsed values into the object. Returns NULL on failure. */
/* Subset string: axis [ , crs ] ( intervalOrPoint ) */
/************************************************************************/
static int msWCSParseSubsetKVPString20(wcs20SubsetObjPtr subset, char *string)
{
char *axis, *crs, *min, *max;
axis = string;
crs = NULL;
min = NULL;
max = NULL;
/* find first '(' */
min = strchr(string, '(');
/* if min could not be found, the string is invalid */
if (min == NULL) {
msSetError(MS_WCSERR, "Invalid axis subset string: '%s'",
"msWCSParseSubsetKVPString20()", string);
return MS_FAILURE;
}
/* set min to first letter */
*min = '\0';
++min;
/* cut the trailing ')' */
if (min[strlen(min) - 1] == ')') {
min[strlen(min) - 1] = '\0';
}
/* look if also a max is defined */
max = strchr(min, ',');
if (max != NULL) {
*max = '\0';
++max;
}
/* look if also a crs is defined */
crs = strchr(axis, ',');
if (crs != NULL) {
*crs = '\0';
++crs;
}
return msWCSParseSubset20(subset, axis, crs, min, max);
}
/************************************************************************/
/* msWCSParseSizeString20() */
/* */
/* Parses a string containing the axis and the size as an integer. */
/* Size string: axis ( size ) */
/************************************************************************/
static int msWCSParseSizeString20(char *string, char *outAxis, size_t axisStringLen, int *outSize)
{
char *number = NULL;
char *check = NULL;
/* find first '(', the character before the number */
number = strchr(string, '(');
if(NULL == number) {
msSetError(MS_WCSERR, "Invalid size parameter value.",
"msWCSParseSize20()");
return MS_FAILURE;
}
/* cut trailing ')' */
check = strchr(string, ')');
if(NULL == check) {
msSetError(MS_WCSERR, "Invalid size parameter value.",
"msWCSParseSize20()");
return MS_FAILURE;
}
*number = '\0';
++number;
*check = '\0';
strlcpy(outAxis, string, axisStringLen);
/* parse size value */
if(msStringParseInteger(number, outSize) != MS_SUCCESS) {
msSetError(MS_WCSERR, "Parameter value '%s' is not a valid integer.",
"msWCSParseSize20()", number);
return MS_FAILURE;
}
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSParseResolutionString20() */
/* */
/* Parses a resolution string and returns the axis, the units of */
/* measure and the resolution value. */
/* Subset string: axis ( value ) */
/************************************************************************/
static int msWCSParseResolutionString20(char *string,
char *outAxis, size_t axisStringLen, double *outResolution)
{
char *number = NULL;
char *check = NULL;
/* find brackets */
number = strchr(string, '(');
if(NULL == number) {
msSetError(MS_WCSERR, "Invalid resolution parameter value.",
"msWCSParseSize20()", string);
return MS_FAILURE;
}
/* cut trailing ')' */
check = strchr(string, ')');
if(NULL == check) {
msSetError(MS_WCSERR, "Invalid size parameter value.",
"msWCSParseSize20()");
return MS_FAILURE;
}
*number = '\0';
++number;
*check = '\0';
strlcpy(outAxis, string, axisStringLen);
if(msStringParseDouble(number, outResolution) != MS_SUCCESS) {
*outResolution = MS_WCS20_UNBOUNDED;
msSetError(MS_WCSERR, "Invalid resolution parameter value.",
"msWCSParseSize20()", string);
return MS_FAILURE;
}
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSParseRequest20_XMLGetCapabilities() */
/* */
/* Parses a DOM element, representing a GetCapabilities-request */
/* to a params object. */
/************************************************************************/
#if defined(USE_LIBXML2)
static int msWCSParseRequest20_XMLGetCapabilities(
xmlNodePtr root, wcs20ParamsObjPtr params)
{
xmlNodePtr child;
char *content = NULL;
XML_FOREACH_CHILD(root, child) {
XML_LOOP_IGNORE_COMMENT_OR_TEXT(child)
else if (EQUAL((char *)child->name, "AcceptVersions")) {
xmlNodePtr versionNode = NULL;
XML_FOREACH_CHILD(child, versionNode) {
/* for(child = firstChild->children; child != NULL; child = child->next) */
XML_LOOP_IGNORE_COMMENT_OR_TEXT(versionNode);
XML_ASSERT_NODE_NAME(versionNode, "Version");
content = (char *)xmlNodeGetContent(versionNode);
params->accept_versions = CSLAddString(params->accept_versions, content);
xmlFree(content);
}
} else if(EQUAL((char *)child->name, "Sections")) {
xmlNodePtr sectionNode = NULL;
XML_FOREACH_CHILD(child, sectionNode) {
XML_LOOP_IGNORE_COMMENT_OR_TEXT(sectionNode)
XML_ASSERT_NODE_NAME(sectionNode, "Section");
content = (char *)xmlNodeGetContent(sectionNode);
params->sections = CSLAddString(params->sections, content);
xmlFree(content);
}
} else if(EQUAL((char *)child->name, "UpdateSequence")) {
params->updatesequence =
(char *)xmlNodeGetContent(child);
} else if(EQUAL((char *)child->name, "AcceptFormats")) {
/* Maybe not necessary, since only format is xml. */
/* At least ignore it, to not generate an error. */
} else if(EQUAL((char *)child->name, "AcceptLanguages")) {
/* ignore */
} else {
XML_UNKNOWN_NODE_ERROR(child);
}
}
return MS_SUCCESS;
}
#endif
/************************************************************************/
/* msWCSParseRequest20_XMLDescribeCoverage() */
/* */
/* Parses a DOM element, representing a DescribeCoverage-request */
/* to a params object. */
/************************************************************************/
#if defined(USE_LIBXML2)
static int msWCSParseRequest20_XMLDescribeCoverage(
xmlNodePtr root, wcs20ParamsObjPtr params)
{
xmlNodePtr child;
int numIds = 0;
char *id;
XML_FOREACH_CHILD(root, child) {
XML_LOOP_IGNORE_COMMENT_OR_TEXT(child)
XML_ASSERT_NODE_NAME(child, "CoverageID");
/* Node content is the coverage ID */
id = (char *)xmlNodeGetContent(child);
if (id == NULL || strlen(id) == 0) {
msSetError(MS_WCSERR, "CoverageID could not be parsed.",
"msWCSParseRequest20_XMLDescribeCoverage()");
return MS_FAILURE;
}
/* insert coverage ID into the list */
++numIds;
params->ids = CSLAddString(params->ids, (char *)id);
xmlFree(id);
}
return MS_SUCCESS;
}
#endif
/************************************************************************/
/* msWCSParseRequest20_XMLGetCoverage() */
/* */
/* Parses a DOM element, representing a GetCoverage-request to a */
/* params object. */
/************************************************************************/
#if defined(USE_LIBXML2)
static int msWCSParseRequest20_XMLGetCoverage(
xmlNodePtr root, wcs20ParamsObjPtr params)
{
xmlNodePtr child;
int numIds = 0;
char *id;
XML_FOREACH_CHILD(root, child) {
XML_LOOP_IGNORE_COMMENT_OR_TEXT(child)
else if (EQUAL((char *)child->name, "CoverageID")) {
/* Node content is the coverage ID */
id = (char *)xmlNodeGetContent(child);
if (id == NULL || strlen(id) == 0) {
msSetError(MS_WCSERR, "CoverageID could not be parsed.",
"msWCSParseRequest20_XMLGetCoverage()");
return MS_FAILURE;
}
/* insert coverage ID into the list */
++numIds;
params->ids = CSLAddString(params->ids, (char *)id);
xmlFree(id);
} else if (EQUAL((char *) child->name, "Format")) {
params->format = (char *)xmlNodeGetContent(child);
} else if (EQUAL((char *) child->name, "Mediatype")) {
char *content = (char *)xmlNodeGetContent(child);
if(content != NULL && (EQUAL(content, "multipart/mixed")
|| EQUAL(content, "multipart/related"))) {
params->multipart = MS_TRUE;
}
xmlFree(content);
} else if (EQUAL((char *) child->name, "DimensionTrim")) {
wcs20AxisObjPtr axis = NULL;
wcs20SubsetObjPtr subset = NULL;
xmlNodePtr node = NULL;
char *axisName = NULL, *min = NULL, *max = NULL, *crs = NULL;
/* get strings for axis, min and max */
XML_FOREACH_CHILD(child, node) {
XML_LOOP_IGNORE_COMMENT_OR_TEXT(node)
else if (EQUAL((char *)node->name, "Dimension")) {
if (axisName != NULL) {
msSetError(MS_WCSERR,
"Parameter 'Dimension' is already set.",
"msWCSParseRequest20_XMLGetCoverage()");
return MS_FAILURE;
}
axisName = (char *) xmlNodeGetContent(node);
crs = (char *) xmlGetProp(node, BAD_CAST "crs");
} else if (EQUAL((char *)node->name, "trimLow")) {
min = (char *) xmlNodeGetContent(node);
} else if (EQUAL((char *)node->name, "trimHigh")) {
max = (char *) xmlNodeGetContent(node);
} else {
msFree(axisName);
msFree(min);
msFree(max);
msFree(crs);
XML_UNKNOWN_NODE_ERROR(node);
}
}
if(NULL == (subset = msWCSCreateSubsetObj20())) {
msFree(axisName);
msFree(min);
msFree(max);
msFree(crs);
return MS_FAILURE;
}
/* min and max have to have a value */
if(min == NULL ) {
min = msStrdup("*");
}
if(max == NULL) {
max = msStrdup("*");
}
if (msWCSParseSubset20(subset, axisName, crs, min, max)
== MS_FAILURE) {
msWCSFreeSubsetObj20(subset);
return MS_FAILURE;
}
if(NULL == (axis = msWCSFindAxis20(params, subset->axis))) {
if(NULL == (axis = msWCSCreateAxisObj20())) {
msFree(axisName);
msFree(min);
msFree(max);
msFree(crs);
return MS_FAILURE;
}
axis->name = msStrdup(subset->axis);
msWCSInsertAxisObj20(params, axis);
}
axis->subset = subset;
/* cleanup */
msFree(axisName);
msFree(min);
msFree(max);
msFree(crs);
} else if(EQUAL((char *) child->name, "DimensionSlice")) {
msSetError(MS_WCSERR, "Operation '%s' is not supported by MapServer.",
"msWCSParseRequest20_XMLGetCoverage()", (char *)child->name);
return MS_FAILURE;
} else if(EQUAL((char *) child->name, "Size")) {
wcs20AxisObjPtr axis;
char *axisName;
char *content;
if(NULL == (axisName = (char *) xmlGetProp(child, BAD_CAST "dimension")) ) {
msSetError(MS_WCSERR, "Attribute 'dimension' is missing in element 'Size'.",
"msWCSParseRequest20_XMLGetCoverage()");
return MS_FAILURE;
}
if(NULL == (axis = msWCSFindAxis20(params, axisName))) {
if(NULL == (axis = msWCSCreateAxisObj20())) {
return MS_FAILURE;
}
axis->name = msStrdup(axisName);
msWCSInsertAxisObj20(params, axis);
}
content = (char *)xmlNodeGetContent(child);
if(msStringParseInteger(content, &(axis->size)) != MS_SUCCESS) {
msSetError(MS_WCSERR, "Value of element 'Size' could not "
"be parsed to a valid integer.",
"msWCSParseRequest20_XMLGetCoverage()");
return MS_FAILURE;
}
xmlFree(content);
} else if(EQUAL((char *) child->name, "Resolution")) {
wcs20AxisObjPtr axis;
char *axisName;
char *content;
if(NULL == (axisName = (char *) xmlGetProp(child, BAD_CAST "dimension"))) {
msSetError(MS_WCSERR, "Attribute 'dimension' is missing "
"in element 'Resolution'.",
"msWCSParseRequest20_XMLGetCoverage()", (char *)child->name);
return MS_FAILURE;
}
if(NULL == (axis = msWCSFindAxis20(params, axisName))) {
if(NULL == (axis = msWCSCreateAxisObj20())) {
return MS_FAILURE;
}
axis->name = msStrdup(axisName);
msWCSInsertAxisObj20(params, axis);
}
axis->resolutionUOM = (char *) xmlGetProp(child, BAD_CAST "uom");
content = (char *)xmlNodeGetContent(child);
if(msStringParseDouble(content, &(axis->resolution)) != MS_SUCCESS) {
msSetError(MS_WCSERR, "Value of element 'Resolution' could not "
"be parsed to a valid value.",
"msWCSParseRequest20_XMLGetCoverage()");
xmlFree(content);
return MS_FAILURE;
}
xmlFree(content);
} else if(EQUAL((char *) child->name, "Interpolation")) {
params->interpolation = (char *) xmlNodeGetContent(child);
} else if(EQUAL((char *) child->name, "OutputCRS")) {
params->outputcrs = (char *) xmlNodeGetContent(child);
} else if(EQUAL((char *) child->name, "rangeSubset")) {
xmlNodePtr bandNode = NULL;
XML_FOREACH_CHILD(child, bandNode) {
char *content = NULL;
XML_ASSERT_NODE_NAME(bandNode, "band");
content = (char *)xmlNodeGetContent(bandNode);
params->range_subset =
CSLAddString(params->range_subset, content);
xmlFree(content);
}
} else {
XML_UNKNOWN_NODE_ERROR(child);
}
}
return MS_SUCCESS;
}
#endif
/************************************************************************/
/* msWCSParseRequest20() */
/* */
/* Parses a CGI-request to a WCS 20 params object. It is */
/* either a POST or a GET request. In case of a POST request */
/* the xml content has to be parsed to a DOM structure */
/* before the parameters can be extracted. */
/************************************************************************/
int msWCSParseRequest20(mapObj *map,
cgiRequestObj *request,
owsRequestObj *ows_request,
wcs20ParamsObjPtr params)
{
int i;
if (params == NULL || request == NULL || ows_request == NULL) {
msSetError(MS_WCSERR, "Internal error.", "msWCSParseRequest20()");
return MS_FAILURE;
}
/* Copy arbitrary service, version and request. */
params->service = msStrdup(ows_request->service);
if(ows_request->version != NULL) {
params->version = msStrdup(ows_request->version);
}
params->request = msStrdup(ows_request->request);
/* Parse the POST request */
if (request->type == MS_POST_REQUEST) {
#if defined(USE_LIBXML2)
xmlDocPtr doc = ows_request->document;
xmlNodePtr root = NULL;
const char *validate;
int ret = MS_SUCCESS;
/* parse to DOM-Structure and get root element */
if(doc == NULL) {
xmlErrorPtr error = xmlGetLastError();
msSetError(MS_WCSERR, "XML parsing error: %s",
"msWCSParseRequest20()", error->message);
return MS_FAILURE;
}
root = xmlDocGetRootElement(doc);
validate = msOWSLookupMetadata(&(map->web.metadata), "CO", "validate_xml");
if (validate != NULL && EQUAL(validate, "TRUE")) {
char *schema_dir = msStrdup(msOWSLookupMetadata(&(map->web.metadata),
"CO", "schemas_dir"));
if (schema_dir != NULL
&& (params->version == NULL ||
EQUALN(params->version, "2.0", 3))) {
schema_dir = msStringConcatenate(schema_dir,
"wcs/2.0.0/wcsAll.xsd");
if (msOWSSchemaValidation(schema_dir, request->postrequest) != 0) {
msSetError(MS_WCSERR, "Invalid POST request. "
"XML is not valid",
"msWCSParseRequest20()");
return MS_FAILURE;
}
}
msFree(schema_dir);
}
if(EQUAL(params->request, "GetCapabilities")) {
ret = msWCSParseRequest20_XMLGetCapabilities(root, params);
} else if(params->version != NULL && EQUALN(params->version, "2.0", 3)) {
if(EQUAL(params->request, "DescribeCoverage")) {
ret = msWCSParseRequest20_XMLDescribeCoverage(root, params);
} else if(EQUAL(params->request, "GetCoverage")) {
ret = msWCSParseRequest20_XMLGetCoverage(root, params);
}
}
return ret;
#else /* defined(USE_LIBXML2) */
/* TODO: maybe with CPLXML? */
return MS_DONE;
#endif /* defined(USE_LIBXML2) */
}
/* Parse the KVP GET request */
for (i = 0; i < request->NumParams; ++i) {
char *key = NULL, *value = NULL;
char **tokens;
int num, j;
key = request->ParamNames[i];
value = request->ParamValues[i];
if (EQUAL(key, "VERSION")) {
continue;
} else if (EQUAL(key, "REQUEST")) {
continue;
} else if (EQUAL(key, "SERVICE")) {
continue;
} else if (EQUAL(key, "ACCEPTVERSIONS")) {
tokens = msStringSplit(value, ',', &num);
for(j = 0; j < num; ++j) {
params->accept_versions =
CSLAddString(params->accept_versions, tokens[j]);
}
msFreeCharArray(tokens, num);
} else if (EQUAL(key, "SECTIONS")) {
tokens = msStringSplit(value, ',', &num);
for(j = 0; j < num; ++j) {
params->sections =
CSLAddString(params->sections, tokens[j]);
}
msFreeCharArray(tokens, num);
} else if (EQUAL(key, "UPDATESEQUENCE")) {
params->updatesequence = msStrdup(value);
} else if (EQUAL(key, "ACCEPTFORMATS")) {
/* ignore */
} else if (EQUAL(key, "ACCEPTLANGUAGES")) {
/* ignore */
} else if (EQUAL(key, "COVERAGEID")) {
if (params->ids != NULL) {
msSetError(MS_WCSERR, "Parameter 'CoverageID' is already set. "
"For multiple IDs use a comma separated list.",
"msWCSParseRequest20()");
return MS_FAILURE;
}
params->ids = CSLTokenizeString2(value, ",",0);
} else if (EQUAL(key, "FORMAT")) {
params->format = msStrdup(value);
} else if (EQUAL(key, "MEDIATYPE")) {
if(EQUAL(value, "multipart/mixed") || EQUAL(value, "multipart/related")) {
params->multipart = MS_TRUE;
}
} else if (EQUAL(key, "INTERPOLATION")) {
params->interpolation = msStrdup(value);
} else if (EQUAL(key, "OUTPUTCRS")) {
params->outputcrs = msStrdup(value);
} else if (EQUALN(key, "SIZE", 4)) {
wcs20AxisObjPtr axis = NULL;
char axisName[500];
int size = 0;
if(msWCSParseSizeString20(value, axisName, sizeof(axisName), &size) == MS_FAILURE) {
return MS_FAILURE;
}
if(NULL == (axis = msWCSFindAxis20(params, axisName))) {
if(NULL == (axis = msWCSCreateAxisObj20())) {
return MS_FAILURE;
}
axis->name = msStrdup(axisName);
msWCSInsertAxisObj20(params, axis);
}
/* check if the size of the axis is already set */
if(axis->size != 0) {
msSetError(MS_WCSERR, "The size of the axis is already set.",
"msWCSParseRequest20()");
return MS_FAILURE;
}
axis->size = size;
} else if (EQUALN(key, "RESOLUTION", 10)) {
wcs20AxisObjPtr axis = NULL;
char axisName[500];
double resolution = 0;
if(msWCSParseResolutionString20(value, axisName, sizeof(axisName), &resolution) == MS_FAILURE) {
return MS_FAILURE;
}
/* check if axis object already exists, otherwise create a new one */
if(NULL == (axis = msWCSFindAxis20(params, axisName))) {
if(NULL == (axis = msWCSCreateAxisObj20())) {
return MS_FAILURE;
}
axis->name = msStrdup(axisName);
msWCSInsertAxisObj20(params, axis);
}
/* check if the resolution of the axis is already set */
if(axis->resolution != MS_WCS20_UNBOUNDED) {
msSetError(MS_WCSERR, "The resolution of the axis is already set.",
"msWCSParseRequest20()");
return MS_FAILURE;
}
axis->resolution = resolution;
} else if (EQUALN(key, "SUBSET", 6)) {
wcs20AxisObjPtr axis = NULL;
wcs20SubsetObjPtr subset = msWCSCreateSubsetObj20();
if(NULL == subset) {
return MS_FAILURE;
}
if (msWCSParseSubsetKVPString20(subset, value) == MS_FAILURE) {
msWCSFreeSubsetObj20(subset);
return MS_FAILURE;
}
if(NULL == (axis = msWCSFindAxis20(params, subset->axis))) {
if(NULL == (axis = msWCSCreateAxisObj20())) {
return MS_FAILURE;
}
axis->name = msStrdup(subset->axis);
msWCSInsertAxisObj20(params, axis);
}
if(NULL != axis->subset) {
msSetError(MS_WCSERR, "The axis '%s' is already subsetted.",
"msWCSParseRequest20()", axis->name);
msWCSFreeSubsetObj20(subset);
return MS_FAILURE;
}
axis->subset = subset;
} else if(EQUAL(key, "RANGESUBSET")) {
tokens = msStringSplit(value, ',', &num);
for(j = 0; j < num; ++j) {
params->range_subset =
CSLAddString(params->range_subset, tokens[j]);
}
msFreeCharArray(tokens, num);
}
/* Ignore all other parameters here */
}
return MS_SUCCESS;
}
#if defined(USE_LIBXML2)
/************************************************************************/
/* msWCSValidateAndFindSubsets20() */
/* */
/* Iterates over every axis in the parameters and checks if the */
/* axis name is in any string list. If found, but there already is */
/* a sample found for this axis, an Error is returned. Also if no */
/* axis is found for a given axis, an error is returned. */
/************************************************************************/
static int msWCSValidateAndFindAxes20(
wcs20ParamsObjPtr params,
char*** validAxisNames,
int numAxis,
wcs20AxisObjPtr outAxes[])
{
int iParamAxis, iAcceptedAxis, iName, i;
for(i = 0; i < numAxis; ++i) {
outAxes[i] = NULL;
}
/* iterate over all subsets */
for(iParamAxis = 0; iParamAxis < params->numaxes; ++iParamAxis) {
int found = 0;
/* check if subset is valid */
if(params->axes[iParamAxis]->subset != NULL) {
if(params->axes[iParamAxis]->subset->timeOrScalar == MS_WCS20_TIME_VALUE) {
msSetError(MS_WCSERR, "Time values for subsets are not supported. ",
"msWCSCreateBoundingBox20()");
return MS_FAILURE;
}
if(params->axes[iParamAxis]->subset->operation == MS_WCS20_SLICE) {
msSetError(MS_WCSERR, "Subset operation 'slice' is not supported.",
"msWCSCreateBoundingBox20()");
return MS_FAILURE;
}
}
/* iterate over all given axes */
for(iAcceptedAxis = 0; iAcceptedAxis < numAxis; ++iAcceptedAxis ) {
/* iterate over all possible names for the current axis */
for(iName = 0; validAxisNames[iAcceptedAxis][iName] != NULL ; ++iName) {
/* compare axis name with current possible name */
if(EQUAL(params->axes[iParamAxis]->name, validAxisNames[iAcceptedAxis][iName])) {
/* if there is already a sample for the axis, throw error */
if(outAxes[iAcceptedAxis] != NULL) {
msSetError(MS_WCSERR, "The axis with the name '%s' corresponds "
"to the same axis as the subset with the name '%s'.",
"msWCSValidateAndFindSubsets20()",
outAxes[iAcceptedAxis]->name, params->axes[iParamAxis]->name);
return MS_FAILURE;
}
/* if match is found, save it */
outAxes[iAcceptedAxis] = params->axes[iParamAxis];
found = 1;
break;
}
}
if (found) {
break;
}
}
/* no valid representation for current subset found */
/* exit and throw error */
if(found == 0) {
msSetError(MS_WCSERR, "Invalid subset axis '%s'.",
"msWCSValidateAndFindSubsets20()", params->axes[iParamAxis]->name);
return MS_FAILURE;
}
}
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSPrepareNamespaces20() */
/* */
/* Inserts namespace definitions into the root node of a DOM */
/* structure. */
/************************************************************************/
static void msWCSPrepareNamespaces20(xmlDocPtr pDoc, xmlNodePtr psRootNode, mapObj* map)
{
xmlNsPtr psXsiNs;
char *schemaLocation = NULL;
char *xsi_schemaLocation = NULL;
xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_WCS_20_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX));
xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_20_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );
xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_WCS_20_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_GML_32_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX);
xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_GMLCOV_10_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_GMLCOV_NAMESPACE_PREFIX);
xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_SWE_20_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_SWE_NAMESPACE_PREFIX);
psXsiNs = xmlSearchNs(pDoc, psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
schemaLocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
xsi_schemaLocation = msStrdup(MS_OWSCOMMON_WCS_20_NAMESPACE_URI);
xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, MS_OWSCOMMON_WCS_20_SCHEMAS_LOCATION);
xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
xmlNewNsProp(psRootNode, psXsiNs, BAD_CAST "schemaLocation", BAD_CAST xsi_schemaLocation);
msFree(schemaLocation);
msFree(xsi_schemaLocation);
}
/************************************************************************/
/* msWCSGetFormatList20() */
/* */
/* Copied from mapwcs.c. */
/************************************************************************/
static char *msWCSGetFormatsList20( mapObj *map, layerObj *layer )
{
char *format_list = msStrdup("");
char **tokens = NULL, **formats = NULL;
int i, numtokens = 0, numformats;
char *value;
/* -------------------------------------------------------------------- */
/* Parse from layer metadata. */
/* -------------------------------------------------------------------- */
if( layer != NULL
&& (value = msOWSGetEncodeMetadata( &(layer->metadata),"CO","formats",
NULL )) != NULL ) {
tokens = msStringSplit(value, ' ', &numtokens);
msFree(value);
}
/* -------------------------------------------------------------------- */
/* Parse from map.web metadata. */
/* -------------------------------------------------------------------- */
else if((value = msOWSGetEncodeMetadata( &(map->web.metadata), "CO", "formats",
NULL)) != NULL ) {
tokens = msStringSplit(value, ' ', &numtokens);
msFree(value);
}
/* -------------------------------------------------------------------- */
/* Or generate from all configured raster output formats that */
/* look plausible. */
/* -------------------------------------------------------------------- */
else {
tokens = (char **) msSmallCalloc(map->numoutputformats,sizeof(char*));
for( i = 0; i < map->numoutputformats; i++ ) {
switch( map->outputformatlist[i]->renderer ) {
/* seemingly normal raster format */
#ifdef USE_GD
case MS_RENDER_WITH_GD:
#endif
case MS_RENDER_WITH_AGG:
case MS_RENDER_WITH_RAWDATA:
tokens[numtokens++] = msStrdup(map->outputformatlist[i]->name);
break;
/* rest of formats aren't really WCS compatible */
default:
break;
}
}
}
/* -------------------------------------------------------------------- */
/* Convert outputFormatObj names into mime types and remove */
/* duplicates. */
/* -------------------------------------------------------------------- */
numformats = 0;
formats = (char **) msSmallCalloc(sizeof(char*),numtokens);
for( i = 0; i < numtokens; i++ ) {
int format_i, j;
const char *mimetype;
for( format_i = 0; format_i < map->numoutputformats; format_i++ ) {
if( EQUAL(map->outputformatlist[format_i]->name, tokens[i]) )
break;
}
if( format_i == map->numoutputformats ) {
msDebug("Failed to find outputformat info on format '%s', ignore.\n",
tokens[i] );
continue;
}
mimetype = map->outputformatlist[format_i]->mimetype;
if( mimetype == NULL || strlen(mimetype) == 0 ) {
msDebug("No mimetime for format '%s', ignoring.\n",
tokens[i] );
continue;
}
for( j = 0; j < numformats; j++ ) {
if( EQUAL(mimetype,formats[j]) )
break;
}
if( j < numformats ) {
msDebug( "Format '%s' ignored since mimetype '%s' duplicates another outputFormatObj.\n",
tokens[i], mimetype );
continue;
}
formats[numformats++] = msStrdup(mimetype);
}
msFreeCharArray(tokens,numtokens);
/* -------------------------------------------------------------------- */
/* Turn mimetype list into comma delimited form for easy use */
/* with xml functions. */
/* -------------------------------------------------------------------- */
for(i = 0; i < numformats; i++) {
if(i > 0) {
format_list = msStringConcatenate(format_list, (char *) ",");
}
format_list = msStringConcatenate(format_list, formats[i]);
}
msFreeCharArray(formats,numformats);
return format_list;
}
/************************************************************************/
/* msWCSSwapAxes20 */
/* */
/* Helper function to determine if a SRS mandates swapped axes. */
/************************************************************************/
static int msWCSSwapAxes20(char *srs_uri)
{
int srid = 0;
/* get SRID from the srs uri */
if(srs_uri != NULL && strlen(srs_uri) > 0) {
if(sscanf(srs_uri, "http://www.opengis.net/def/crs/EPSG/0/%d", &srid) != EOF)
;
else if(sscanf(srs_uri, "http://www.opengis.net/def/crs/%d", &srid) != EOF)
;
else
srid = 0;
}
if (srid == 0)
return MS_FALSE;
return msIsAxisInverted(srid);
}
/************************************************************************/
/* msWCSCommon20_CreateBoundedBy() */
/* */
/* Inserts the BoundedBy section into an existing DOM structure. */
/************************************************************************/
static void msWCSCommon20_CreateBoundedBy(layerObj *layer, wcs20coverageMetadataObjPtr cm,
xmlNsPtr psGmlNs, xmlNodePtr psRoot, projectionObj *projection, int swapAxes)
{
xmlNodePtr psBoundedBy, psEnvelope;
char lowerCorner[100], upperCorner[100], axisLabels[100], uomLabels[100];
psBoundedBy = xmlNewChild( psRoot, psGmlNs, BAD_CAST "boundedBy", NULL);
{
psEnvelope = xmlNewChild(psBoundedBy, psGmlNs, BAD_CAST "Envelope", NULL);
{
xmlNewProp(psEnvelope, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
if(projection->proj != NULL && pj_is_latlong(projection->proj)) {
if (swapAxes == MS_FALSE) {
strlcpy(axisLabels, "long lat", sizeof(axisLabels));
} else {
strlcpy(axisLabels, "lat long", sizeof(axisLabels));
}
strlcpy(uomLabels, "deg deg", sizeof(uomLabels));
} else {
if (swapAxes == MS_FALSE) {
strlcpy(axisLabels, "x y", sizeof(axisLabels));
} else {
strlcpy(axisLabels, "y x", sizeof(axisLabels));
}
strlcpy(uomLabels, "m m", sizeof(uomLabels));
}
xmlNewProp(psEnvelope, BAD_CAST "axisLabels", BAD_CAST axisLabels);
xmlNewProp(psEnvelope, BAD_CAST "uomLabels", BAD_CAST uomLabels);
xmlNewProp(psEnvelope, BAD_CAST "srsDimension", BAD_CAST "2");
if (swapAxes == MS_FALSE) {
snprintf(lowerCorner, sizeof(lowerCorner), "%.15g %.15g", cm->extent.minx, cm->extent.miny);
snprintf(upperCorner, sizeof(upperCorner), "%.15g %.15g", cm->extent.maxx, cm->extent.maxy);
} else {
snprintf(lowerCorner, sizeof(lowerCorner), "%.15g %.15g", cm->extent.miny, cm->extent.minx);
snprintf(upperCorner, sizeof(upperCorner), "%.15g %.15g", cm->extent.maxy, cm->extent.maxx);
}
xmlNewChild(psEnvelope, psGmlNs, BAD_CAST "lowerCorner", BAD_CAST lowerCorner);
xmlNewChild(psEnvelope, psGmlNs, BAD_CAST "upperCorner", BAD_CAST upperCorner);
}
}
}
/************************************************************************/
/* msWCSCommon20_CreateDomainSet() */
/* */
/* Inserts the DomainSet section into an existing DOM structure. */
/************************************************************************/
static void msWCSCommon20_CreateDomainSet(layerObj* layer, wcs20coverageMetadataObjPtr cm,
xmlNsPtr psGmlNs, xmlNodePtr psRoot, projectionObj *projection, int swapAxes)
{
xmlNodePtr psDomainSet, psGrid, psLimits, psGridEnvelope, psOrigin,
psOffsetX, psOffsetY;
char low[100], high[100], id[100], point[100], resx[100], resy[100], axisLabels[100];
psDomainSet = xmlNewChild( psRoot, psGmlNs, BAD_CAST "domainSet", NULL);
{
psGrid = xmlNewChild(psDomainSet, psGmlNs, BAD_CAST "RectifiedGrid", NULL);
{
xmlNewProp(psGrid, BAD_CAST "dimension", BAD_CAST "2");
snprintf(id, sizeof(id), "grid_%s", layer->name);
xmlNewNsProp(psGrid, psGmlNs, BAD_CAST "id", BAD_CAST id);
psLimits = xmlNewChild(psGrid, psGmlNs, BAD_CAST "limits", NULL);
{
psGridEnvelope = xmlNewChild(psLimits, psGmlNs, BAD_CAST "GridEnvelope", NULL);
{
strlcpy(low, "0 0", sizeof(low));
snprintf(high, sizeof(high), "%d %d", cm->xsize - 1, cm->ysize - 1);
xmlNewChild(psGridEnvelope, psGmlNs, BAD_CAST "low", BAD_CAST low);
xmlNewChild(psGridEnvelope, psGmlNs, BAD_CAST "high", BAD_CAST high);
}
}
if(projection->proj != NULL && pj_is_latlong(projection->proj)) {
if (swapAxes == MS_FALSE) {
strlcpy(axisLabels, "long lat", sizeof(axisLabels));
} else {
strlcpy(axisLabels, "lat long", sizeof(axisLabels));
}
} else {
if (swapAxes == MS_FALSE) {
strlcpy(axisLabels, "x y", sizeof(axisLabels));
} else {
strlcpy(axisLabels, "y x", sizeof(axisLabels));
}
}
xmlNewChild(psGrid, psGmlNs, BAD_CAST "axisLabels", BAD_CAST axisLabels);
psOrigin = xmlNewChild(psGrid, psGmlNs, BAD_CAST "origin", NULL);
{
if (swapAxes == MS_FALSE) {
snprintf(point, sizeof(point), "%f %f", cm->extent.minx, cm->extent.maxy);
} else {
snprintf(point, sizeof(point), "%f %f", cm->extent.maxy, cm->extent.minx);
}
psOrigin = xmlNewChild(psOrigin, psGmlNs, BAD_CAST "Point", NULL);
snprintf(id, sizeof(id), "grid_origin_%s", layer->name);
xmlNewNsProp(psOrigin, psGmlNs, BAD_CAST "id", BAD_CAST id);
xmlNewProp(psOrigin, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
xmlNewChild(psOrigin, psGmlNs, BAD_CAST "pos", BAD_CAST point);
}
if (swapAxes == MS_FALSE) {
snprintf(resx, sizeof(resx), "%f 0", cm->xresolution);
snprintf(resy, sizeof(resy), "0 %f", -fabs(cm->yresolution));
} else {
snprintf(resx, sizeof(resx), "0 %f", cm->xresolution);
snprintf(resy, sizeof(resy), "%f 0", -fabs(cm->yresolution));
}
psOffsetX = xmlNewChild(psGrid, psGmlNs, BAD_CAST "offsetVector", BAD_CAST resx);
psOffsetY = xmlNewChild(psGrid, psGmlNs, BAD_CAST "offsetVector", BAD_CAST resy);
xmlNewProp(psOffsetX, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
xmlNewProp(psOffsetY, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
}
}
}
/************************************************************************/
/* msWCSCommon20_CreateRangeType() */
/* */
/* Inserts the RangeType section into an existing DOM structure. */
/************************************************************************/
static void msWCSCommon20_CreateRangeType(layerObj* layer, wcs20coverageMetadataObjPtr cm, char *bands,
xmlNsPtr psGmlNs, xmlNsPtr psGmlcovNs, xmlNsPtr psSweNs, xmlNsPtr psXLinkNs, xmlNodePtr psRoot)
{
xmlNodePtr psRangeType, psDataRecord, psField, psQuantity,
psUom, psConstraint, psAllowedValues = NULL, psNilValues = NULL;
char **arr = NULL;
int i, num = 0;
if(NULL != bands) {
arr = msStringSplit(bands, ',', &num);
}
psRangeType = xmlNewChild( psRoot, psGmlcovNs, BAD_CAST "rangeType", NULL);
psDataRecord = xmlNewChild(psRangeType, psSweNs, BAD_CAST "DataRecord", NULL);
/* iterate over every band */
for(i = 0; i < cm->numbands; ++i) {
/* only add bands that are in the range subset */
if (NULL != arr && num > 0) {
int found = MS_FALSE, j, repr;
for(j = 0; j < num; ++j) {
msStringParseInteger(arr[j], &repr);
if(repr == i + 1) {
found = MS_TRUE;
break;
}
}
if(found == MS_FALSE) {
/* ignore this band since it is not in the range subset */
continue;
}
}
/* add field tag */
psField = xmlNewChild(psDataRecord, psSweNs, BAD_CAST "field", NULL);
if(cm->bands[i].name != NULL) {
xmlNewProp(psField, BAD_CAST "name", BAD_CAST cm->bands[i].name);
} else {
xmlNewProp(psField, BAD_CAST "name", BAD_CAST "band");
}
/* add Quantity tag */
psQuantity = xmlNewChild(psField, psSweNs, BAD_CAST "Quantity", NULL);
if(cm->bands[i].definition != NULL) {
xmlNewProp(psQuantity, BAD_CAST "definition", BAD_CAST cm->bands[i].definition);
}
if(cm->bands[i].description != NULL) {
xmlNewChild(psQuantity, psSweNs, BAD_CAST "description", BAD_CAST cm->bands[i].description);
}
/* if there are given nilvalues -> add them to the first field */
/* all other fields get a reference to these */
if(cm->numnilvalues > 0) {
int j;
psNilValues = xmlNewChild(
xmlNewChild(psQuantity, psSweNs, BAD_CAST "nilValues", NULL),
psSweNs, BAD_CAST "NilValues", NULL);
for(j = 0; j < cm->numnilvalues; ++j) {
xmlNodePtr psTemp =
xmlNewChild(psNilValues, psSweNs, BAD_CAST "nilValue", BAD_CAST cm->nilvalues[j]);
if(j < cm->numnilvalues)
xmlNewProp(psTemp, BAD_CAST "reason", BAD_CAST cm->nilvalues_reasons[j]);
}
} else { /* create an empty nilValues tag */
xmlNewChild(psQuantity, psSweNs, BAD_CAST "nilValues", NULL);
}
psUom = xmlNewChild(psQuantity, psSweNs, BAD_CAST "uom", NULL);
if(cm->bands[i].uom != NULL) {
xmlNewProp(psUom, BAD_CAST "code", BAD_CAST cm->bands[i].uom);
} else {
xmlNewProp(psUom, BAD_CAST "code", BAD_CAST "W.m-2.Sr-1");
}
/* add constraint */
psConstraint = xmlNewChild(psQuantity, psSweNs, BAD_CAST "constraint", NULL);
{
char interval[100], significant_figures[100];
psAllowedValues = xmlNewChild(psConstraint, psSweNs, BAD_CAST "AllowedValues", NULL);
/* Interval */
snprintf(interval, sizeof(interval), "%.5g %.5g", cm->bands[i].interval_min, cm->bands[i].interval_max);
xmlNewChild(psAllowedValues, psSweNs, BAD_CAST "interval", BAD_CAST interval);
/* Significant figures */
snprintf(significant_figures, sizeof(significant_figures), "%d", cm->bands[i].significant_figures);
xmlNewChild(psAllowedValues, psSweNs, BAD_CAST "significantFigures", BAD_CAST significant_figures);
}
}
msFreeCharArray(arr,num);
}
/************************************************************************/
/* msWCSWriteDocument20() */
/* */
/* Writes out an xml structure to the stream. */
/************************************************************************/
static int msWCSWriteDocument20(mapObj* map, xmlDocPtr psDoc)
{
xmlChar *buffer = NULL;
int size = 0;
msIOContext *context = NULL;
const char *encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
if( msIO_needBinaryStdout() == MS_FAILURE ) {
return MS_FAILURE;
}
if (encoding)
msIO_setHeader("Content-type","application/gml+xml; charset=%s", encoding);
else
msIO_setHeader("Content-type","application/gml+xml");
msIO_sendHeaders();
context = msIO_getHandler(stdout);
xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
msIO_contextWrite(context, buffer, size);
xmlFree(buffer);
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSWriteFile20() */
/* */
/* Writes an image object to the stream. If multipart is set, */
/* then content sections are inserted. */
/************************************************************************/
static int msWCSWriteFile20(mapObj* map, imageObj* image, wcs20ParamsObjPtr params, int multipart)
{
int status;
char* filename = NULL;
char *base_dir = NULL;
const char *fo_filename;
int i;
fo_filename = msGetOutputFormatOption( image->format, "FILENAME", NULL );
/* -------------------------------------------------------------------- */
/* Fetch the driver we will be using and check if it supports */
/* VSIL IO. */
/* -------------------------------------------------------------------- */
if( EQUALN(image->format->driver,"GDAL/",5) ) {
GDALDriverH hDriver;
const char *pszExtension = image->format->extension;
msAcquireLock( TLOCK_GDAL );
hDriver = GDALGetDriverByName( image->format->driver+5 );
if( hDriver == NULL ) {
msReleaseLock( TLOCK_GDAL );
msSetError( MS_MISCERR,
"Failed to find %s driver.",
"msWCSWriteFile20()",
image->format->driver+5 );
return msWCSException(map, "mapserv", "NoApplicableCode",
params->version);
}
if( pszExtension == NULL )
pszExtension = "img.tmp";
if( GDALGetMetadataItem( hDriver, GDAL_DCAP_VIRTUALIO, NULL )
!= NULL ) {
base_dir = msTmpFile(map, map->mappath, "/vsimem/wcsout", NULL);
if( fo_filename )
filename = msStrdup(CPLFormFilename(base_dir,
fo_filename,NULL));
else
filename = msStrdup(CPLFormFilename(base_dir,
"out", pszExtension ));
/* CleanVSIDir( "/vsimem/wcsout" ); */
msReleaseLock( TLOCK_GDAL );
status = msSaveImage(map, image, filename);
if( status != MS_SUCCESS ) {
msSetError(MS_MISCERR, "msSaveImage() failed",
"msWCSWriteFile20()");
return msWCSException20(map, "mapserv", "NoApplicableCode",
params->version);
}
}
msReleaseLock( TLOCK_GDAL );
}
/* -------------------------------------------------------------------- */
/* If we weren't able to write data under /vsimem, then we just */
/* output a single "stock" filename. */
/* -------------------------------------------------------------------- */
if( filename == NULL ) {
if(multipart) {
msIO_fprintf( stdout, "--wcs\n" );
msIO_fprintf(
stdout,
"Content-Type: %s\n"
"Content-Description: coverage data\n"
"Content-Transfer-Encoding: binary\n",
MS_IMAGE_MIME_TYPE(map->outputformat));
if( fo_filename != NULL )
msIO_fprintf( stdout,
"Content-ID: coverage/%s\n"
"Content-Disposition: INLINE; filename=%s%c%c",
fo_filename,
fo_filename,
10, 10 );
else
msIO_fprintf( stdout,
"Content-ID: coverage/wcs.%s\n"
"Content-Disposition: INLINE%c%c",
MS_IMAGE_EXTENSION(map->outputformat),
10, 10 );
} else {
msIO_setHeader("Content-Type",MS_IMAGE_MIME_TYPE(map->outputformat));
msIO_setHeader("Content-Description","coverage data");
msIO_setHeader("Content-Transfer-Encoding","binary");
if( fo_filename != NULL ) {
msIO_setHeader("Content-ID","coverage/%s",fo_filename);
msIO_setHeader("Content-Disposition","INLINE; filename=%s",fo_filename);
} else {
msIO_setHeader("Content-ID","coverage/wcs.%s",MS_IMAGE_EXTENSION(map->outputformat));
msIO_setHeader("Content-Disposition","INLINE");
}
msIO_sendHeaders();
}
status = msSaveImage(map, image, NULL);
if( status != MS_SUCCESS ) {
msSetError( MS_MISCERR, "msSaveImage() failed", "msWCSWriteFile20()");
return msWCSException(map, "mapserv", "NoApplicableCode", params->version);
}
if(multipart)
msIO_fprintf( stdout, "\n--wcs--%c%c", 10, 10 );
return MS_SUCCESS;
}
/* -------------------------------------------------------------------- */
/* When potentially listing multiple files, we take great care */
/* to identify the "primary" file and list it first. In fact */
/* it is the only file listed in the coverages document. */
/* -------------------------------------------------------------------- */
{
char **all_files = CPLReadDir( base_dir );
int count = CSLCount(all_files);
if( msIO_needBinaryStdout() == MS_FAILURE )
return MS_FAILURE;
msAcquireLock( TLOCK_GDAL );
for( i = count-1; i >= 0; i-- ) {
const char *this_file = all_files[i];
if( EQUAL(this_file,".") || EQUAL(this_file,"..") ) {
all_files = CSLRemoveStrings( all_files, i, 1, NULL );
continue;
}
if( i > 0 && EQUAL(this_file,CPLGetFilename(filename)) ) {
all_files = CSLRemoveStrings( all_files, i, 1, NULL );
all_files = CSLInsertString(all_files,0,CPLGetFilename(filename));
i++;
}
}
/* -------------------------------------------------------------------- */
/* Dump all the files in the memory directory as mime sections. */
/* -------------------------------------------------------------------- */
count = CSLCount(all_files);
if(count > 1 && multipart == MS_FALSE) {
msDebug( "msWCSWriteFile20(): force multipart output without gml summary because we have multiple files in the result.\n" );
multipart = MS_TRUE;
msIO_setHeader("Content-Type","multipart/related; boundary=wcs");
msIO_sendHeaders();
}
for( i = 0; i < count; i++ ) {
const char *mimetype = NULL;
FILE *fp;
unsigned char block[4000];
int bytes_read;
if( i == 0
&& !EQUAL(MS_IMAGE_MIME_TYPE(map->outputformat), "unknown") )
mimetype = MS_IMAGE_MIME_TYPE(map->outputformat);
if( mimetype == NULL )
mimetype = "application/octet-stream";
if(multipart) {
msIO_fprintf( stdout, "--wcs\n" );
msIO_fprintf(
stdout,
"Content-Type: %s\n"
"Content-Description: coverage data\n"
"Content-Transfer-Encoding: binary\n"
"Content-ID: coverage/%s\n"
"Content-Disposition: INLINE; filename=%s%c%c",
mimetype,
all_files[i],
all_files[i],
10, 10 );
} else {
msIO_setHeader("Content-Type",mimetype);
msIO_setHeader("Content-Description","coverage data");
msIO_setHeader("Content-Transfer-Encoding","binary");
msIO_setHeader("Content-ID","coverage/%s",all_files[i]);
msIO_setHeader("Content-Disposition","INLINE; filename=%s",all_files[i]);
msIO_sendHeaders();
}
fp = VSIFOpenL(
CPLFormFilename(base_dir, all_files[i], NULL),
"rb" );
if( fp == NULL ) {
msReleaseLock( TLOCK_GDAL );
msSetError( MS_MISCERR,
"Failed to open %s for streaming to stdout.",
"msWCSWriteFile20()", all_files[i] );
return MS_FAILURE;
}
while( (bytes_read = VSIFReadL(block, 1, sizeof(block), fp)) > 0 )
msIO_fwrite( block, 1, bytes_read, stdout );
VSIFCloseL( fp );
VSIUnlink( CPLFormFilename(base_dir, all_files[i], NULL) );
}
msFree(base_dir);
msFree(filename);
CSLDestroy( all_files );
msReleaseLock( TLOCK_GDAL );
if(multipart)
msIO_fprintf( stdout, "\n--wcs--%c%c", 10, 10 );
return MS_SUCCESS;
}
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSGetRangesetAxisMetadata20() */
/* */
/* Looks up a layers metadata for a specific axis information. */
/************************************************************************/
static const char *msWCSLookupRangesetAxisMetadata20(hashTableObj *table,
const char *axis, const char *item)
{
char buf[500], *value;
if(table == NULL || axis == NULL || item == NULL) {
return NULL;
}
strlcpy(buf, axis, sizeof(buf));
strlcat(buf, "_", sizeof(buf));
strlcat(buf, item, sizeof(buf));
if((value = msLookupHashTable(table, buf)) != NULL) {
return value;
}
return msOWSLookupMetadata(table, "CO", buf);
}
/************************************************************************/
/* msWCSGetCoverageMetadata20() */
/* */
/* Inits a coverageMetadataObj. Uses msWCSGetCoverageMetadata() */
/* but exchanges the SRS URN by an URI for compliancy with 2.0. */
/************************************************************************/
static int msWCSGetCoverageMetadata20(layerObj *layer, wcs20coverageMetadataObj *cm)
{
char *srs_uri = NULL;
int i = 0;
if ( msCheckParentPointer(layer->map,"map") == MS_FAILURE )
return MS_FAILURE;
if((cm->srs = msOWSGetEPSGProj(&(layer->projection),
&(layer->metadata), "CO", MS_TRUE)) == NULL) {
if((cm->srs = msOWSGetEPSGProj(&(layer->map->projection),
&(layer->map->web.metadata), "CO", MS_TRUE)) == NULL) {
msSetError(MS_WCSERR, "Unable to determine the SRS for this layer, "
"no projection defined and no metadata available.",
"msWCSGetCoverageMetadata20()");
return MS_FAILURE;
}
}
/* -------------------------------------------------------------------- */
/* Get the SRS in uri format. */
/* -------------------------------------------------------------------- */
if((srs_uri = msOWSGetProjURI(&(layer->projection), &(layer->metadata),
"CO", MS_TRUE)) == NULL) {
srs_uri = msOWSGetProjURI(&(layer->map->projection),
&(layer->map->web.metadata), "CO", MS_TRUE);
}
if( srs_uri != NULL ) {
if( strlen(srs_uri) > sizeof(cm->srs_uri) - 1 ) {
msSetError(MS_WCSERR, "SRS URI too long!",
"msWCSGetCoverageMetadata()");
return MS_FAILURE;
}
strlcpy( cm->srs_uri, srs_uri, sizeof(cm->srs_uri) );
msFree( srs_uri );
} else {
cm->srs_uri[0] = '\0';
}
/* setup nilvalues */
cm->numnilvalues = 0;
cm->nilvalues = NULL;
cm->nilvalues_reasons = NULL;
cm->native_format = NULL;
/* -------------------------------------------------------------------- */
/* If we have "virtual dataset" metadata on the layer, then use */
/* that in preference to inspecting the file(s). */
/* We require extent and either size or resolution. */
/* -------------------------------------------------------------------- */
if( msOWSLookupMetadata(&(layer->metadata), "CO", "extent") != NULL
&& (msOWSLookupMetadata(&(layer->metadata), "CO", "resolution") != NULL
|| msOWSLookupMetadata(&(layer->metadata), "CO", "size") != NULL) ) {
const char *value;
/* get extent */
cm->extent.minx = 0.0;
cm->extent.maxx = 0.0;
cm->extent.miny = 0.0;
cm->extent.maxy = 0.0;
if( msOWSGetLayerExtent( layer->map, layer, "CO", &cm->extent ) == MS_FAILURE )
return MS_FAILURE;
/* get resolution */
cm->xresolution = 0.0;
cm->yresolution = 0.0;
if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "resolution")) != NULL ) {
char **tokens;
int n;
tokens = msStringSplit(value, ' ', &n);
if( tokens == NULL || n != 2 ) {
msSetError( MS_WCSERR, "Wrong number of arguments for wcs|ows_resolution metadata.", "msWCSGetCoverageMetadata20()");
msFreeCharArray( tokens, n );
return MS_FAILURE;
}
cm->xresolution = atof(tokens[0]);
cm->yresolution = atof(tokens[1]);
msFreeCharArray( tokens, n );
}
/* get Size (in pixels and lines) */
cm->xsize = 0;
cm->ysize = 0;
if( (value=msOWSLookupMetadata(&(layer->metadata), "CO", "size")) != NULL ) {
char **tokens;
int n;
tokens = msStringSplit(value, ' ', &n);
if( tokens == NULL || n != 2 ) {
msSetError( MS_WCSERR, "Wrong number of arguments for wcs|ows_size metadata.", "msWCSGetCoverageMetadata20()");
msFreeCharArray( tokens, n );
return MS_FAILURE;
}
cm->xsize = atoi(tokens[0]);
cm->ysize = atoi(tokens[1]);
msFreeCharArray( tokens, n );
}
/* try to compute raster size */
if( cm->xsize == 0 && cm->ysize == 0 && cm->xresolution != 0.0 && cm->yresolution != 0.0 && cm->extent.minx != cm->extent.maxx && cm->extent.miny != cm->extent.maxy ) {
cm->xsize = (int) ((cm->extent.maxx - cm->extent.minx) / cm->xresolution + 0.5);
cm->ysize = (int) fabs((cm->extent.maxy - cm->extent.miny) / cm->yresolution + 0.5);
}
/* try to compute raster resolution */
if( (cm->xresolution == 0.0 || cm->yresolution == 0.0) && cm->xsize != 0 && cm->ysize != 0 ) {
cm->xresolution = (cm->extent.maxx - cm->extent.minx) / cm->xsize;
cm->yresolution = (cm->extent.maxy - cm->extent.miny) / cm->ysize;
}
/* do we have information to do anything */
if( cm->xresolution == 0.0 || cm->yresolution == 0.0 || cm->xsize == 0 || cm->ysize == 0 ) {
msSetError( MS_WCSERR, "Failed to collect extent and resolution for WCS coverage from metadata for layer '%s'. Need value wcs|ows_resolution or wcs|ows_size values.", "msWCSGetCoverageMetadata20()", layer->name );
return MS_FAILURE;
}
/* compute geotransform */
cm->geotransform[0] = cm->extent.minx;
cm->geotransform[1] = cm->xresolution;
cm->geotransform[2] = 0.0;
cm->geotransform[3] = cm->extent.maxy;
cm->geotransform[4] = 0.0;
cm->geotransform[5] = -fabs(cm->yresolution);
/* get bands count, or assume 1 if not found */
cm->numbands = 1;
if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "bandcount")) != NULL) {
int numbands = 0;
msStringParseInteger(value, &numbands);
cm->numbands = (size_t)numbands;
}
cm->bands = msSmallCalloc(sizeof(wcs20rasterbandMetadataObj), cm->numbands);
/* get bands type, or assume float if not found */
cm->imagemode = MS_IMAGEMODE_FLOAT32;
if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "imagemode")) != NULL ) {
if( EQUAL(value,"INT16") )
cm->imagemode = MS_IMAGEMODE_INT16;
else if( EQUAL(value,"FLOAT32") )
cm->imagemode = MS_IMAGEMODE_FLOAT32;
else if( EQUAL(value,"BYTE") )
cm->imagemode = MS_IMAGEMODE_BYTE;
else {
msSetError( MS_WCSERR, "Content of wcs|ows_imagemode (%s) not recognised. Should be one of BYTE, INT16 or FLOAT32.", "msWCSGetCoverageMetadata20()", value );
return MS_FAILURE;
}
}
if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "native_format")) != NULL ) {
cm->native_format = msStrdup(value);
}
/* determine nilvalues and reasons */
{
int n_nilvalues = 0, n_nilvalues_reasons = 0;
char **t_nilvalues = NULL, **t_nilvalues_reasons = NULL;
if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "nilvalues")) != NULL ) {
t_nilvalues = msStringSplit(value, ' ', &n_nilvalues);
} else if((value = msOWSLookupMetadata(&(layer->metadata), "CO", "rangeset_nullvalue")) != NULL) {
t_nilvalues = msStringSplit(value, ' ', &n_nilvalues);
}
if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "nilvalues_reasons")) != NULL ) {
t_nilvalues_reasons = msStringSplit(value, ' ', &n_nilvalues_reasons);
}
if(n_nilvalues > 0) {
int i;
cm->numnilvalues = n_nilvalues;
cm->nilvalues = msSmallCalloc(sizeof(char*), n_nilvalues);
cm->nilvalues_reasons = msSmallCalloc(sizeof(char*), n_nilvalues);
for(i = 0; i < n_nilvalues; ++i) {
cm->nilvalues[i] = msStrdup(t_nilvalues[i]);
if(i < n_nilvalues_reasons) {
cm->nilvalues_reasons[i] = msStrdup(t_nilvalues_reasons[i]);
} else {
cm->nilvalues_reasons[i] = msStrdup("");
}
}
}
msFreeCharArray(t_nilvalues, n_nilvalues);
msFreeCharArray(t_nilvalues_reasons, n_nilvalues_reasons);
}
{
int num_band_names = 0, i, j;
char **band_names = NULL;
char *wcs11_band_names_key = "rangeset_axes";
char *wcs20_band_names_key = "band_names";
char *wcs11_interval_key = "interval";
char *wcs20_interval_key = "interval";
char *interval_key = NULL;
char *significant_figures_key = "significant_figures";
char *wcs11_keys[] =
{ "label", "semantic", "values_type", "values_semantic", "description" };
char *wcs20_keys[] =
{ "band_name", "band_interpretation", "band_uom", "band_definition", "band_description" };
char **keys = NULL;
char **interval_array;
int num_interval;
wcs20rasterbandMetadataObj default_values;
/* Decide whether WCS1.1 or WCS2.0 keys should be used */
if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", wcs20_band_names_key) ) != NULL ) {
keys = wcs20_keys;
interval_key = wcs20_interval_key;
band_names = msStringSplit(value, ' ', &num_band_names);
} else if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", wcs11_band_names_key)) != NULL ) {
keys = wcs11_keys;
interval_key = wcs11_interval_key;
band_names = msStringSplit(value, ' ', &num_band_names);
}
/* return with error when number of bands does not match */
/* the number of names */
if (num_band_names != cm->numbands && num_band_names != 0) {
msFreeCharArray(band_names, num_band_names);
msSetError( MS_WCSERR,
"Wrong number of band names given in layer '%s'. "
"Expected %d, got %d.", "msWCSGetCoverageMetadata20()",
layer->name, cm->numbands, num_band_names );
return MS_FAILURE;
}
/* look up default metadata values */
for(j = 1; j < 5; ++j) {
if(keys != NULL) {
default_values.values[j] = (char *)msOWSLookupMetadata(&(layer->metadata), "CO", keys[j]);
}
}
/* set default values for interval and significant figures */
switch(cm->imagemode) {
case MS_IMAGEMODE_BYTE:
case MS_IMAGEMODE_PC256:
default_values.interval_min = 0.;
default_values.interval_max = 255.;
default_values.significant_figures = 3;
break;
case MS_IMAGEMODE_INT16:
default_values.interval_min = 0.;
default_values.interval_max = (double)USHRT_MAX;
default_values.significant_figures = 5;
break;
case MS_IMAGEMODE_FLOAT32:
default_values.interval_min = -FLT_MAX;
default_values.interval_max = FLT_MAX;
default_values.significant_figures = 12;
break;
}
/* lookup default interval values */
if (interval_key != NULL
&& (value = msOWSLookupMetadata(&(layer->metadata), "CO", interval_key)) != NULL) {
interval_array = msStringSplit(value, ' ', &num_interval);
if (num_interval != 2
|| msStringParseDouble(interval_array[0], &(default_values.interval_min)) != MS_SUCCESS
|| msStringParseDouble(interval_array[1], &(default_values.interval_max)) != MS_SUCCESS) {
msFreeCharArray(band_names, num_band_names);
msFreeCharArray(interval_array, num_interval);
msSetError(MS_WCSERR, "Wrong interval format for default axis.",
"msWCSGetCoverageMetadata20()");
return MS_FAILURE;
}
msFreeCharArray(interval_array, num_interval);
}
/* lookup default value for significant figures */
if((value = msOWSLookupMetadata(&(layer->metadata), "CO", significant_figures_key)) != NULL) {
if(msStringParseInteger(value, &(default_values.significant_figures)) != MS_SUCCESS) {
msFreeCharArray(band_names, num_band_names);
msSetError(MS_WCSERR, "Wrong significant figures format "
"for default axis.",
"msWCSGetCoverageMetadata20()");
return MS_FAILURE;
}
}
/* iterate over every band */
for(i = 0; i < cm->numbands; ++i) {
cm->bands[i].name = NULL;
/* look up band metadata or copy defaults */
if(num_band_names != 0) {
cm->bands[i].name = msStrdup(band_names[i]);
for(j = 1; j < 5; ++j) {
value = (char *)msWCSLookupRangesetAxisMetadata20(&(layer->metadata),
cm->bands[i].name, keys[j]);
if(value != NULL) {
cm->bands[i].values[j] = msStrdup(value);
} else if(default_values.values[j] != NULL) {
cm->bands[i].values[j] = msStrdup(default_values.values[j]);
}
}
}
/* set up interval */
value = (char *)msWCSLookupRangesetAxisMetadata20(&(layer->metadata),
cm->bands[i].name, interval_key);
if(value != NULL) {
num_interval = 0;
interval_array = msStringSplit(value, ' ', &num_interval);
if (num_interval != 2
|| msStringParseDouble(interval_array[0], &(cm->bands[i].interval_min)) != MS_SUCCESS
|| msStringParseDouble(interval_array[1], &(cm->bands[i].interval_max)) != MS_SUCCESS) {
msFreeCharArray(band_names, num_band_names);
msFreeCharArray(interval_array, num_interval);
msSetError(MS_WCSERR, "Wrong interval format for axis %s.",
"msWCSGetCoverageMetadata20()", cm->bands[i].name);
return MS_FAILURE;
}
msFreeCharArray(interval_array, num_interval);
} else {
cm->bands[i].interval_min = default_values.interval_min;
cm->bands[i].interval_max = default_values.interval_max;
}
/* set up significant figures */
value = (char *)msWCSLookupRangesetAxisMetadata20(&(layer->metadata),
cm->bands[i].name, significant_figures_key);
if(value != NULL) {
if(msStringParseInteger(value, &(cm->bands[i].significant_figures)) != MS_SUCCESS) {
msFreeCharArray(band_names, num_band_names);
msSetError(MS_WCSERR, "Wrong significant figures format "
"for axis %s.",
"msWCSGetCoverageMetadata20()", cm->bands[i].name);
return MS_FAILURE;
}
} else {
cm->bands[i].significant_figures = default_values.significant_figures;
}
}
msFreeCharArray(band_names, num_band_names);
}
} else if( layer->data == NULL ) {
/* no virtual metadata, not ok unless we're talking 1 image, hopefully we can fix that */
msSetError( MS_WCSERR, "RASTER Layer with no DATA statement and no WCS virtual dataset metadata. Tileindexed raster layers not supported for WCS without virtual dataset metadata (cm->extent, wcs_res, wcs_size).", "msWCSGetCoverageMetadata20()" );
return MS_FAILURE;
} else {
/* work from the file (e.g. DATA) */
GDALDatasetH hDS;
GDALDriverH hDriver;
GDALRasterBandH hBand;
const char szPath[MS_MAXPATHLEN];
const char *driver_short_name, *driver_long_name;
msGDALInitialize();
msTryBuildPath3((char *)szPath, layer->map->mappath, layer->map->shapepath, layer->data);
msAcquireLock( TLOCK_GDAL );
hDS = GDALOpen( szPath, GA_ReadOnly );
if( hDS == NULL ) {
msReleaseLock( TLOCK_GDAL );
msSetError( MS_IOERR, "%s", "msWCSGetCoverageMetadata20()", CPLGetLastErrorMsg() );
return MS_FAILURE;
}
msGetGDALGeoTransform( hDS, layer->map, layer, cm->geotransform );
cm->xsize = GDALGetRasterXSize( hDS );
cm->ysize = GDALGetRasterYSize( hDS );
cm->extent.minx = cm->geotransform[0];
cm->extent.maxx = cm->geotransform[0] + cm->geotransform[1] * cm->xsize + cm->geotransform[2] * cm->ysize;
cm->extent.miny = cm->geotransform[3] + cm->geotransform[4] * cm->xsize + cm->geotransform[5] * cm->ysize;
cm->extent.maxy = cm->geotransform[3];
cm->xresolution = cm->geotransform[1];
cm->yresolution = cm->geotransform[5];
cm->numbands = GDALGetRasterCount( hDS );
/* TODO nilvalues? */
if( cm->numbands == 0 ) {
msReleaseLock( TLOCK_GDAL );
msSetError( MS_WCSERR, "Raster file %s has no raster bands. This cannot be used in a layer.", "msWCSGetCoverageMetadata20()", layer->data );
return MS_FAILURE;
}
hBand = GDALGetRasterBand( hDS, 1 );
switch( GDALGetRasterDataType( hBand ) ) {
case GDT_Byte:
cm->imagemode = MS_IMAGEMODE_BYTE;
break;
case GDT_Int16:
cm->imagemode = MS_IMAGEMODE_INT16;
break;
default:
cm->imagemode = MS_IMAGEMODE_FLOAT32;
break;
}
cm->bands = msSmallCalloc(sizeof(wcs20rasterbandMetadataObj), cm->numbands);
/* get as much band metadata as possible */
for(i = 0; i < cm->numbands; ++i) {
char bandname[32];
GDALColorInterp colorInterp;
hBand = GDALGetRasterBand(hDS, i + 1);
snprintf(bandname, sizeof(bandname), "band%d", i+1);
cm->bands[i].name = msStrdup(bandname);
colorInterp = GDALGetRasterColorInterpretation(hBand);
cm->bands[i].interpretation = msStrdup(GDALGetColorInterpretationName(colorInterp));
cm->bands[i].uom = msStrdup(GDALGetRasterUnitType(hBand));
if(strlen(cm->bands[i].uom) == 0) {
msFree(cm->bands[i].uom);
cm->bands[i].uom = NULL;
}
/* set up interval and significant figures */
switch(cm->imagemode) {
case MS_IMAGEMODE_BYTE:
case MS_IMAGEMODE_PC256:
cm->bands[i].interval_min = 0.;
cm->bands[i].interval_max = 255.;
cm->bands[i].significant_figures = 3;
break;
case MS_IMAGEMODE_INT16:
cm->bands[i].interval_min = 0.;
cm->bands[i].interval_max = (double)USHRT_MAX;
cm->bands[i].significant_figures = 5;
break;
case MS_IMAGEMODE_FLOAT32:
cm->bands[i].interval_min = -FLT_MAX;
cm->bands[i].interval_max = FLT_MAX;
cm->bands[i].significant_figures = 12;
break;
}
}
hDriver = GDALGetDatasetDriver(hDS);
driver_short_name = GDALGetDriverShortName(hDriver);
driver_long_name = GDALGetDriverLongName(hDriver);
/* TODO: improve this, exchange strstr() */
for(i = 0; i < layer->map->numoutputformats; ++i) {
if(strstr( layer->map->outputformatlist[i]->driver, driver_short_name) != NULL
|| strstr(layer->map->outputformatlist[i]->driver, driver_long_name) != NULL) {
cm->native_format = msStrdup(layer->map->outputformatlist[i]->mimetype);
break;
}
}
GDALClose( hDS );
msReleaseLock( TLOCK_GDAL );
}
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSClearCoverageMetadata20() */
/* */
/* Returns all dynamically allocated memory from a coverage meta- */
/* data object. */
/************************************************************************/
static int msWCSClearCoverageMetadata20(wcs20coverageMetadataObj *cm)
{
int i = 0, j = 0;
msFree(cm->native_format);
for(i = 0; i < cm->numnilvalues; ++i) {
msFree(cm->nilvalues[i]);
msFree(cm->nilvalues_reasons[i]);
}
msFree(cm->nilvalues);
msFree(cm->nilvalues_reasons);
for(i = 0; i < cm->numbands; ++i) {
for(j = 0; j < 5; ++j) {
msFree(cm->bands[i].values[j]);
}
}
msFree(cm->bands);
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSException20() */
/* */
/* Writes out an OWS compliant exception. */
/************************************************************************/
int msWCSException20(mapObj *map, const char *exceptionCode,
const char *locator, const char *version)
{
int size = 0;
char *errorString = NULL;
char *errorMessage = NULL;
char *schemasLocation = NULL;
const char * encoding;
char *xsi_schemaLocation = NULL;
char version_string[OWS_VERSION_MAXLEN];
xmlDocPtr psDoc = NULL;
xmlNodePtr psRootNode = NULL;
xmlNodePtr psMainNode = NULL;
xmlNsPtr psNsOws = NULL;
xmlNsPtr psNsXsi = NULL;
xmlChar *buffer = NULL;
encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
errorString = msGetErrorString("\n");
errorMessage = msEncodeHTMLEntities(errorString);
schemasLocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
psDoc = xmlNewDoc(BAD_CAST "1.0");
psRootNode = xmlNewNode(NULL, BAD_CAST "ExceptionReport");
psNsOws = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_20_NAMESPACE_URI,
BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
xmlSetNs(psRootNode, psNsOws);
psNsXsi = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
/* add attributes to root element */
xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST version);
xmlNewProp(psRootNode, BAD_CAST "xml:lang", BAD_CAST msOWSGetLanguage(map, "exception"));
/* get 2 digits version string: '2.0' */
msOWSGetVersionString(OWS_2_0_0, version_string);
version_string[3]= '\0';
xsi_schemaLocation = msStrdup((char *)psNsOws->href);
xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, (char *)schemasLocation);
xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/ows/");
xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, version_string);
xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/owsExceptionReport.xsd");
/* add namespace'd attributes to root element */
xmlNewNsProp(psRootNode, psNsXsi, BAD_CAST "schemaLocation", BAD_CAST xsi_schemaLocation);
/* add child element */
psMainNode = xmlNewChild(psRootNode, NULL, BAD_CAST "Exception", NULL);
/* add attributes to child */
xmlNewProp(psMainNode, BAD_CAST "exceptionCode", BAD_CAST exceptionCode);
if (locator != NULL) {
xmlNewProp(psMainNode, BAD_CAST "locator", BAD_CAST locator);
}
if (errorMessage != NULL) {
xmlNewChild(psMainNode, NULL, BAD_CAST "ExceptionText", BAD_CAST errorMessage);
}
/*psRootNode = msOWSCommonExceptionReport(psNsOws, OWS_2_0_0,
schemasLocation, version, msOWSGetLanguage(map, "exception"),
exceptionCode, locator, errorMessage);*/
xmlDocSetRootElement(psDoc, psRootNode);
if (encoding)
msIO_setHeader("Content-type","text/xml; charset=%s", encoding);
else
msIO_setHeader("Content-type","text/xml");
msIO_sendHeaders();
xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding
: "ISO-8859-1"), 1);
msIO_printf("%s", buffer);
/* free buffer and the document */
free(errorString);
free(errorMessage);
free(schemasLocation);
free(xsi_schemaLocation);
xmlFree(buffer);
xmlFreeDoc(psDoc);
/* clear error since we have already reported it */
msResetErrorList();
return MS_FAILURE;
}
#define MAX_MIMES 20
static int msWCSGetCapabilities20_CreateProfiles(
mapObj *map, xmlNodePtr psServiceIdentification, xmlNsPtr psOwsNs)
{
xmlNodePtr psProfile, psTmpNode;
char *available_mime_types[MAX_MIMES];
int i = 0;
/* even indices are urls, uneven are mime-types, or null*/
char *urls_and_mime_types[] = {
MS_WCS_20_PROFILE_CORE, NULL,
MS_WCS_20_PROFILE_KVP, NULL,
MS_WCS_20_PROFILE_POST, NULL,
MS_WCS_20_PROFILE_GML, NULL,
MS_WCS_20_PROFILE_GML_MULTIPART, NULL,
MS_WCS_20_PROFILE_GML_SPECIAL, NULL,
MS_WCS_20_PROFILE_GML_GEOTIFF, "image/tiff",
MS_WCS_20_PROFILE_GEOTIFF, "image/tiff",
MS_WCS_20_PROFILE_CRS, NULL,
MS_WCS_20_PROFILE_SCALING, NULL,
MS_WCS_20_PROFILE_RANGESUBSET, NULL,
NULL, NULL /* guardian */
};
/* navigate to node where profiles shall be inserted */
for(psTmpNode = psServiceIdentification->children; psTmpNode->next != NULL; psTmpNode = psTmpNode->next) {
if(EQUAL((char *)psTmpNode->name, "ServiceTypeVersion"))
break;
}
/* get list of all available mime types */
msGetOutputFormatMimeList(map, available_mime_types, MAX_MIMES);
while(urls_and_mime_types[i] != NULL) {
char *mime_type;
mime_type = urls_and_mime_types[i+1];
/* check if there is a mime type */
if(mime_type != NULL) {
/* check if the mime_type is in the list of outputformats */
if(CSLPartialFindString(available_mime_types, mime_type) == -1)
continue;
}
/* create a new node and attach it in the tree */
psProfile = xmlNewNode(psOwsNs, BAD_CAST "Profile");
xmlNodeSetContent(psProfile, BAD_CAST urls_and_mime_types[i]);
xmlAddNextSibling(psTmpNode, psProfile);
psTmpNode = psProfile;
i += 2;
}
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSGetCapabilities20_CoverageSummary() */
/* */
/* Helper function to create a short summary for a specific */
/* coverage. */
/************************************************************************/
static int msWCSGetCapabilities20_CoverageSummary(
mapObj *map, wcs20ParamsObjPtr params,
xmlDocPtr doc, xmlNodePtr psContents, layerObj *layer )
{
wcs20coverageMetadataObj cm;
int status;
xmlNodePtr psCSummary, psMetadata;
const char *metadatalink_href = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_href");
xmlNsPtr psWcsNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "wcs" );
xmlNsPtr psOwsNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "ows" );
xmlNsPtr psXlinkNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "xlink" );
status = msWCSGetCoverageMetadata20(layer, &cm);
if(status != MS_SUCCESS) return MS_FAILURE;
psCSummary = xmlNewChild( psContents, psWcsNs, BAD_CAST "CoverageSummary", NULL );
xmlNewChild(psCSummary, psWcsNs, BAD_CAST "CoverageId", BAD_CAST layer->name);
xmlNewChild(psCSummary, psWcsNs, BAD_CAST "CoverageSubtype", BAD_CAST "RectifiedGridCoverage");
/* Add references to additional coverage metadata */
if (metadatalink_href != NULL) {
const char *metadatalink_type = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_type");
const char *metadatalink_format = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_format");
psMetadata = xmlNewChild(psCSummary, psOwsNs, BAD_CAST "Metadata", NULL);
xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "type", BAD_CAST "simple");
xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "href", BAD_CAST metadatalink_href);
if (metadatalink_type != NULL) {
xmlNewProp(psMetadata, BAD_CAST "about", BAD_CAST metadatalink_type);
}
if (metadatalink_format != NULL) {
xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "role", BAD_CAST metadatalink_format);
}
}
msWCSClearCoverageMetadata20(&cm);
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSGetCapabilities20() */
/* */
/* Performs the GetCapabilities operation. Writes out a xml */
/* structure with server specific information and a summary */
/* of all available coverages. */
/************************************************************************/
int msWCSGetCapabilities20(mapObj *map, cgiRequestObj *req,
wcs20ParamsObjPtr params, owsRequestObj *ows_request)
{
xmlDocPtr psDoc = NULL; /* document pointer */
xmlNodePtr psRootNode,
psOperationsNode,
psNode;
const char *updatesequence = NULL;
xmlNsPtr psOwsNs = NULL,
psXLinkNs = NULL,
psWcsNs = NULL;
char *script_url=NULL, *script_url_encoded=NULL, *format_list=NULL;
int i;
/* -------------------------------------------------------------------- */
/* Create document. */
/* -------------------------------------------------------------------- */
psDoc = xmlNewDoc(BAD_CAST "1.0");
psRootNode = xmlNewNode(NULL, BAD_CAST "Capabilities");
xmlDocSetRootElement(psDoc, psRootNode);
/* -------------------------------------------------------------------- */
/* Name spaces */
/* -------------------------------------------------------------------- */
msWCSPrepareNamespaces20(psDoc, psRootNode, map);
/* lookup namespaces */
psOwsNs = xmlSearchNs( psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX );
psWcsNs = xmlSearchNs( psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX );
xmlSearchNs( psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX );
psXLinkNs = xmlSearchNs( psDoc, psRootNode, BAD_CAST "xlink" );
xmlSetNs(psRootNode, psWcsNs);
xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST params->version );
updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
if (params->updatesequence != NULL) {
i = msOWSNegotiateUpdateSequence(params->updatesequence, updatesequence);
if (i == 0) { /* current */
msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)",
"msWCSGetCapabilities20()", params->updatesequence, updatesequence);
xmlFreeDoc(psDoc);
return msWCSException(map, "updatesequence",
"CurrentUpdateSequence", params->version);
}
if (i > 0) { /* invalid */
msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)",
"msWCSGetCapabilities20()", params->updatesequence, updatesequence);
xmlFreeDoc(psDoc);
return msWCSException(map, "updatesequence",
"InvalidUpdateSequence", params->version);
}
}
if(updatesequence != NULL) {
xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST updatesequence);
}
/* -------------------------------------------------------------------- */
/* Service identification. */
/* -------------------------------------------------------------------- */
if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "ServiceIdentification") ) {
psNode = xmlAddChild(psRootNode, msOWSCommonServiceIdentification(
psOwsNs, map, "OGC WCS", params->version, "CO"));
msWCSGetCapabilities20_CreateProfiles(map, psNode, psOwsNs);
}
/* Service Provider */
if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "ServiceProvider") ) {
xmlAddChild(psRootNode,
msOWSCommonServiceProvider(psOwsNs, psXLinkNs, map, "CO"));
}
/* -------------------------------------------------------------------- */
/* Operations metadata. */
/* -------------------------------------------------------------------- */
if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "OperationsMetadata") ) {
if ((script_url = msOWSGetOnlineResource(map, "CO", "onlineresource", req)) == NULL
|| (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
xmlFreeDoc(psDoc);
msSetError(MS_WCSERR, "Server URL not found", "msWCSGetCapabilities20()");
return msWCSException(map, "mapserv", "NoApplicableCode", params->version);
}
free(script_url);
psOperationsNode = xmlAddChild(psRootNode,msOWSCommonOperationsMetadata(psOwsNs));
/* -------------------------------------------------------------------- */
/* GetCapabilities - add Sections and AcceptVersions? */
/* -------------------------------------------------------------------- */
psNode = msOWSCommonOperationsMetadataOperation(
psOwsNs, psXLinkNs,
"GetCapabilities", OWS_METHOD_GETPOST, script_url_encoded);
xmlAddChild(psNode->last->last->last,
msOWSCommonOperationsMetadataDomainType(OWS_2_0_0, psOwsNs, "Constraint",
"PostEncoding", "XML"));
xmlAddChild(psOperationsNode, psNode);
/* -------------------------------------------------------------------- */
/* DescribeCoverage */
/* -------------------------------------------------------------------- */
if (msOWSRequestIsEnabled(map, NULL, "C", "DescribeCoverage", MS_FALSE)) {
psNode = msOWSCommonOperationsMetadataOperation(
psOwsNs, psXLinkNs,
"DescribeCoverage", OWS_METHOD_GETPOST, script_url_encoded);
xmlAddChild(psNode->last->last->last,
msOWSCommonOperationsMetadataDomainType(OWS_2_0_0, psOwsNs, "Constraint",
"PostEncoding", "XML"));
xmlAddChild(psOperationsNode, psNode);
}
/* -------------------------------------------------------------------- */
/* GetCoverage */
/* -------------------------------------------------------------------- */
if (msOWSRequestIsEnabled(map, NULL, "C", "GetCoverage", MS_FALSE)) {
psNode = msOWSCommonOperationsMetadataOperation(
psOwsNs, psXLinkNs,
"GetCoverage", OWS_METHOD_GETPOST, script_url_encoded);
xmlAddChild(psNode->last->last->last,
msOWSCommonOperationsMetadataDomainType(OWS_2_0_0, psOwsNs, "Constraint",
"PostEncoding", "XML"));
xmlAddChild(psOperationsNode, psNode);
}
msFree(script_url_encoded);
}
/* -------------------------------------------------------------------- */
/* Service metadata. */
/* -------------------------------------------------------------------- */
if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "ServiceMetadata") ) {
psNode = xmlNewChild(psRootNode, psWcsNs, BAD_CAST "ServiceMetadata", NULL);
/* Add formats list */
format_list = msWCSGetFormatsList20(map, NULL);
msLibXml2GenerateList(psNode, psWcsNs, "formatSupported", format_list, ',');
msFree(format_list);
}
/* -------------------------------------------------------------------- */
/* Contents section. */
/* -------------------------------------------------------------------- */
if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "Contents") ) {
psNode = xmlNewChild( psRootNode, psWcsNs, BAD_CAST "Contents", NULL );
if(ows_request->numlayers == 0) {
xmlAddChild(psNode,
xmlNewComment(BAD_CAST("WARNING: No WCS layers are enabled. "
"Check wcs/ows_enable_request settings.")));
} else {
for(i = 0; i < map->numlayers; ++i) {
layerObj *layer = map->layers[i];
int status;
if(!msWCSIsLayerSupported(layer))
continue;
if (!msIntegerInArray(layer->index, ows_request->enabled_layers, ows_request->numlayers))
continue;
status = msWCSGetCapabilities20_CoverageSummary(
map, params, psDoc, psNode, layer );
if(status != MS_SUCCESS) {
xmlFreeDoc(psDoc);
xmlCleanupParser();
return msWCSException(map, "mapserv", "Internal", params->version);
}
}
}
}
/* -------------------------------------------------------------------- */
/* Write out the document and clean up. */
/* -------------------------------------------------------------------- */
msWCSWriteDocument20(map, psDoc);
xmlFreeDoc(psDoc);
xmlCleanupParser();
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSDescribeCoverage20_CoverageDescription() */
/* */
/* Creates a description of a specific coverage with the three */
/* major sections: BoundedBy, DomainSet and RangeType. */
/************************************************************************/
static int msWCSDescribeCoverage20_CoverageDescription(mapObj *map,
layerObj *layer, wcs20ParamsObjPtr params, xmlDocPtr psDoc, xmlNodePtr psRootNode )
{
int status, swapAxes;
wcs20coverageMetadataObj cm;
xmlNodePtr psCD;
xmlNsPtr psWcsNs, psGmlNs, psGmlcovNs, psSweNs, psXLinkNs;
psWcsNs = psGmlNs = psGmlcovNs = psSweNs = psXLinkNs = NULL;
psWcsNs = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
psGmlNs = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX);
psGmlcovNs = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_GMLCOV_NAMESPACE_PREFIX);
psSweNs = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_SWE_NAMESPACE_PREFIX);
psXLinkNs = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
/* -------------------------------------------------------------------- */
/* Verify layer is processable. */
/* -------------------------------------------------------------------- */
if( msCheckParentPointer(layer->map,"map") == MS_FAILURE )
return MS_FAILURE;
if(!msWCSIsLayerSupported(layer))
return MS_SUCCESS;
/* -------------------------------------------------------------------- */
/* Setup coverage metadata. */
/* -------------------------------------------------------------------- */
status = msWCSGetCoverageMetadata20(layer, &cm);
if(status != MS_SUCCESS)
return status;
swapAxes = msWCSSwapAxes20(cm.srs_uri);
/* fill in bands rangeset info, if required. */
/* msWCSSetDefaultBandsRangeSetInfo( NULL, &cm, layer ); */
/* -------------------------------------------------------------------- */
/* Create CoverageDescription node. */
/* -------------------------------------------------------------------- */
psCD = xmlNewChild( psRootNode, psWcsNs, BAD_CAST "CoverageDescription", NULL );
xmlNewNsProp(psCD, psGmlNs, BAD_CAST "id", BAD_CAST layer->name);
/* -------------------------------------------------------------------- */
/* gml:boundedBy */
/* -------------------------------------------------------------------- */
msWCSCommon20_CreateBoundedBy(layer, &cm, psGmlNs, psCD, &(layer->projection), swapAxes);
xmlNewChild(psCD, psWcsNs, BAD_CAST "CoverageId", BAD_CAST layer->name);
/* -------------------------------------------------------------------- */
/* gml:domainSet */
/* -------------------------------------------------------------------- */
msWCSCommon20_CreateDomainSet(layer, &cm, psGmlNs, psCD, &(layer->projection), swapAxes);
/* -------------------------------------------------------------------- */
/* gmlcov:rangeType */
/* -------------------------------------------------------------------- */
msWCSCommon20_CreateRangeType(layer, &cm, NULL, psGmlNs, psGmlcovNs, psSweNs, psXLinkNs, psCD);
/* -------------------------------------------------------------------- */
/* wcs:ServiceParameters */
/* -------------------------------------------------------------------- */
{
xmlNodePtr psSP;
psSP = xmlNewChild( psCD, psWcsNs, BAD_CAST "ServiceParameters", NULL);
xmlNewChild(psSP, psWcsNs, BAD_CAST "CoverageSubtype", BAD_CAST "RectifiedGridCoverage");
/* -------------------------------------------------------------------- */
/* SupportedCRS */
/* -------------------------------------------------------------------- */
/* for now, WCS 2.0 does not allow per coverage CRS definitions */
/*{
xmlNodePtr psSupportedCrss;
char *owned_value;
psSupportedCrss = xmlNewChild(psSP, psWcsNs,
BAD_CAST "SupportedCRSs", NULL);
if ((owned_value = msOWSGetProjURI(&(layer->projection),
&(layer->metadata), "CO", MS_FALSE)) != NULL)
{ }
else if ((owned_value = msOWSGetProjURI(&(layer->map->projection),
&(layer->map->web.metadata), "CO", MS_FALSE)) != NULL)
{ }
else {
msDebug("missing required information, no SRSs defined.\n");
}
if (owned_value != NULL && strlen(owned_value) > 0) {
msLibXml2GenerateList(psSupportedCrss, psWcsNs,
"SupportedCRS", owned_value, ' ');
}
xmlNewChild(psSupportedCrss, psWcsNs,
BAD_CAST "NativeCRS", BAD_CAST cm.srs_uri);
msFree(owned_value);
}*/
/* -------------------------------------------------------------------- */
/* SupportedFormats */
/* -------------------------------------------------------------------- */
/* for now, WCS 2.0 does not allow per coverage format definitions */
/*{
xmlNodePtr psSupportedFormats;
char *format_list;
psSupportedFormats =
xmlNewChild(psSP, psWcsNs, BAD_CAST "SupportedFormats", NULL);
format_list = msWCSGetFormatsList20(layer->map, layer);
if (strlen(format_list) > 0) {
msLibXml2GenerateList(psSupportedFormats, psWcsNs,
"SupportedFormat", format_list, ',');
msFree(format_list);
}*/
/* -------------------------------------------------------------------- */
/* nativeFormat */
/* -------------------------------------------------------------------- */
xmlNewChild(psSP, psWcsNs,
BAD_CAST "nativeFormat", BAD_CAST (cm.native_format ?
cm.native_format : ""));
if (!cm.native_format) {
msDebug("msWCSDescribeCoverage20_CoverageDescription(): "
"No native format specified.\n");
}
}
msWCSClearCoverageMetadata20(&cm);
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSDescribeCoverage20() */
/* */
/* Implementation of the DescibeCoverage Operation. The result */
/* of this operation is a xml document, containing specific */
/* information about a coverage identified by an ID. The result */
/* is written on the stream. */
/************************************************************************/
int msWCSDescribeCoverage20(mapObj *map, wcs20ParamsObjPtr params, owsRequestObj *ows_request)
{
xmlDocPtr psDoc = NULL; /* document pointer */
xmlNodePtr psRootNode;
xmlNsPtr psWcsNs = NULL;
int i, j;
/* create DOM document and root node */
psDoc = xmlNewDoc(BAD_CAST "1.0");
psRootNode = xmlNewNode(NULL, BAD_CAST "CoverageDescriptions");
xmlDocSetRootElement(psDoc, psRootNode);
/* prepare initial namespace definitions */
msWCSPrepareNamespaces20(psDoc, psRootNode, map);
psWcsNs = xmlSearchNs(psDoc, psRootNode,
BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
xmlSetNs(psRootNode, psWcsNs);
/* check if IDs are given */
if (params->ids) {
/* for each given ID in the ID-list */
for (j = 0; params->ids[j]; j++) {
i = msGetLayerIndex(map, params->ids[j]);
if (i == -1 || (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
msSetError(MS_WCSERR, "Unknown coverage: (%s)",
"msWCSDescribeCoverage20()", params->ids[j]);
return msWCSException(map, "NoSuchCoverage", "coverage",
params->version);
}
/* create coverage description for the specified layer */
if(msWCSDescribeCoverage20_CoverageDescription(map, (GET_LAYER(map, i)),
params, psDoc, psRootNode) == MS_FAILURE) {
msSetError(MS_WCSERR, "Error retrieving coverage description.", "msWCSDescribeCoverage20()");
return msWCSException(map, "MissingParameterValue", "coverage",
params->version);
}
}
} else {
/* Throw error, since IDs are mandatory */
msSetError(MS_WCSERR, "Missing COVERAGEID parameter.", "msWCSDescribeCoverage20()");
return msWCSException(map, "MissingParameterValue", "coverage",
params->version);
}
/* write out the DOM document to the stream */
msWCSWriteDocument20(map, psDoc);
/* cleanup */
xmlFreeDoc(psDoc);
xmlCleanupParser();
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSGetCoverage_FinalizeParamsObj20() */
/* */
/* Finalizes a wcs20ParamsObj for a GetCoverage operation. In the */
/* process, the params boundig box is adjusted to the subsets, */
/* width, height and resolution are determined and the subset crs */
/* is found out. */
/************************************************************************/
static int msWCSGetCoverage20_FinalizeParamsObj(wcs20ParamsObjPtr params)
{
int returnValue;
static const int numAxis = 2;
char *validXAxisNames[] = {"x", "xaxis", "x-axis", "x_axis", "long", "long_axis", "long-axis", "lon", "lon_axis", "lon-axis", NULL};
char *validYAxisNames[] = {"y", "yaxis", "y-axis", "y_axis", "lat", "lat_axis", "lat-axis", NULL};
char ***validAxisNames;
char *crs = NULL;
wcs20AxisObjPtr *axes;
axes = (wcs20AxisObjPtr*)msSmallMalloc(sizeof(wcs20AxisObjPtr) * numAxis);
validAxisNames = msSmallCalloc(sizeof(char**), numAxis);
validAxisNames[0] = validXAxisNames;
validAxisNames[1] = validYAxisNames;
returnValue = msWCSValidateAndFindAxes20(params, validAxisNames, numAxis, axes);
msFree(validAxisNames);
if(returnValue != MS_SUCCESS) {
msFree(axes);
return MS_FAILURE;
}
if (axes[0] != NULL) {
if(axes[0]->subset != NULL) {
msDebug("Subset for X-axis found: %s\n", axes[0]->subset->axis);
if (!axes[0]->subset->min.unbounded)
params->bbox.minx = axes[0]->subset->min.scalar;
if (!axes[0]->subset->max.unbounded)
params->bbox.maxx = axes[0]->subset->max.scalar;
crs = axes[0]->subset->crs;
}
params->width = axes[0]->size;
params->resolutionX = axes[0]->resolution;
if(axes[0]->resolutionUOM != NULL) {
params->resolutionUnits = msStrdup(axes[0]->resolutionUOM);
}
}
if (axes[1] != NULL) {
if(axes[1]->subset != NULL) {
msDebug("Subset for Y-axis found: %s\n", axes[1]->subset->axis);
if (!axes[1]->subset->min.unbounded)
params->bbox.miny = axes[1]->subset->min.scalar;
if (!axes[1]->subset->max.unbounded)
params->bbox.maxy = axes[1]->subset->max.scalar;
if(crs != NULL && axes[0] != NULL && axes[0]->subset!= NULL) {
if(!EQUAL(crs, axes[1]->subset->crs)) {
msSetError(MS_WCSERR, "CRS for axis %s and axis %s are not the same.",
"msWCSCreateBoundingBox20()", axes[0]->name, axes[1]->name);
msFree(axes);
return MS_FAILURE;
}
} else {
crs = axes[1]->subset->crs;
}
}
params->height = axes[1]->size;
params->resolutionY = axes[1]->resolution;
if(params->resolutionUnits == NULL && axes[1]->resolutionUOM != NULL) {
params->resolutionUnits = msStrdup(axes[1]->resolutionUOM);
} else if(params->resolutionUnits != NULL && axes[1]->resolutionUOM != NULL
&& !EQUAL(params->resolutionUnits, axes[1]->resolutionUOM)) {
msSetError(MS_WCSERR, "The units of measure of the resolution for"
"axis %s and axis %s are not the same.",
"msWCSCreateBoundingBox20()", axes[0]->name, axes[1]->name);
msFree(axes);
return MS_FAILURE;
}
}
msFree(axes);
/* check if projections are equal */
if(crs != NULL) {
params->subsetcrs = msStrdup(crs);
} else {
params->subsetcrs = msStrdup("imageCRS");
}
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSGetCoverage20_GetBands() */
/* */
/* Returns a string, containing a comma-separated list of band */
/* indices. */
/************************************************************************/
static int msWCSGetCoverage20_GetBands(mapObj *map, layerObj *layer,
wcs20ParamsObjPtr params, wcs20coverageMetadataObjPtr cm, char **bandlist)
{
int i = 0, count, maxlen, index;
char *tmp = NULL;
char **band_ids = NULL;
/* if rangesubset parameter is not given, default to all bands */
if(NULL == params->range_subset) {
*bandlist = msStrdup("1");
for(i = 1; i < cm->numbands; ++i) {
char strnumber[10];
snprintf(strnumber, sizeof(strnumber), ",%d", i + 1);
*bandlist = msStringConcatenate(*bandlist, strnumber);
}
return MS_SUCCESS;
}
count = CSLCount(params->range_subset);
maxlen = count * 4 * sizeof(char);
*bandlist = msSmallCalloc(sizeof(char), maxlen);
if (NULL == (tmp = msOWSGetEncodeMetadata(&layer->metadata,
"CO", "rangeset_axes", NULL))) {
tmp = msOWSGetEncodeMetadata(&layer->metadata,
"CO", "band_names", NULL);
}
if(NULL != tmp) {
band_ids = CSLTokenizeString2(tmp, " ", 0);
msFree(tmp);
}
for(i = 0; i < count; ++i) {
/* print ',' if not the first value */
if(i != 0) {
strlcat(*bandlist, ",", maxlen);
}
/* check if the string represents an integer */
if(msStringParseInteger(params->range_subset[i], &index) == MS_SUCCESS) {
tmp = msIntToString((int)index);
strlcat(*bandlist, tmp, maxlen);
msFree(tmp);
continue;
}
/* check if the string is equal to a band identifier */
/* if so, what is the index of the band */
index = CSLFindString(band_ids, params->range_subset[i]);
if(index != -1) {
tmp = msIntToString((int)index + 1);
strlcat(*bandlist, tmp, maxlen);
msFree(tmp);
continue;
}
msSetError(MS_WCSERR, "'%s' is not a valid band identifier.",
"msWCSGetCoverage20_GetBands()", params->range_subset[i]);
return MS_FAILURE;
}
CSLDestroy(band_ids);
return MS_SUCCESS;
}
/************************************************************************/
/* msWCSGetCoverage20() */
/* */
/* Implementation of the GetCoverage Operation. The coverage */
/* is either returned as an image or as a multipart xml/image. */
/* The result is written on the stream. */
/************************************************************************/
int msWCSGetCoverage20(mapObj *map, cgiRequestObj *request,
wcs20ParamsObjPtr params, owsRequestObj *ows_request)
{
layerObj *layer = NULL;
wcs20coverageMetadataObj cm;
imageObj *image = NULL;
outputFormatObj *format = NULL;
rectObj subsets, bbox;
projectionObj imageProj;
int status, i;
double x_1, x_2, y_1, y_2;
char *coverageName, *bandlist=NULL, numbands[8];
/* number of coverage ids should be 1 */
if (params->ids == NULL || params->ids[0] == NULL) {
msSetError(MS_WCSERR, "Required parameter CoverageID was not supplied.",
"msWCSGetCoverage20()");
return msWCSException(map, "MissingParameterValue", "coverage",
params->version);
}
if (params->ids[1] != NULL) {
msSetError(MS_WCSERR, "GetCoverage operation supports only one coverage.",
"msWCSGetCoverage20()");
return msWCSException(map, "TooManyParameterValues", "coverage",
params->version);
}
/* find the right layer */
layer = NULL;
for(i = 0; i < map->numlayers; i++) {
coverageName = msOWSGetEncodeMetadata(&(GET_LAYER(map, i)->metadata),
"CO", "name",
GET_LAYER(map, i)->name);
if (EQUAL(coverageName, params->ids[0]) &&
(msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers))) {
layer = GET_LAYER(map, i);
i = map->numlayers; /* to exit loop don't use break, we want to free resources first */
}
msFree(coverageName);
}
/* throw exception if no Layer was found */
if (layer == NULL) {
msSetError(MS_WCSERR,
"COVERAGE=%s not found, not in supported layer list. A layer might be disabled for \
this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage20()", params->ids[0]);
return msWCSException(map, "InvalidParameterValue", "coverage",
params->version);
}
/* retrieve coverage metadata */
status = msWCSGetCoverageMetadata20(layer, &cm);
if (status != MS_SUCCESS) {
msWCSClearCoverageMetadata20(&cm);
return MS_FAILURE;
}
/* fill in bands rangeset info, if required. */
/* msWCSSetDefaultBandsRangeSetInfo(NULL, &cm, layer ); */
/* set resolution, size and maximum extent */
layer->extent = map->extent = cm.extent;
map->cellsize = cm.xresolution;
map->width = cm.xsize;
map->height = cm.ysize;
/************************************************************************/
/* finalize the params object. determine subset crs and subset */
/* bbox. Also project the image to the subset crs. */
/************************************************************************/
msInitProjection(&imageProj);
if (msLoadProjectionString(&imageProj, cm.srs) == -1) {
msWCSClearCoverageMetadata20(&cm);
msSetError(MS_WCSERR,
"Error loading CRS %s.",
"msWCSGetCoverage20()", params->subsetcrs);
return msWCSException(map, "InvalidParameterValue",
"projection", params->version);
}
if(msWCSGetCoverage20_FinalizeParamsObj(params) == MS_FAILURE) {
msWCSClearCoverageMetadata20(&cm);
return msWCSException(map, "InvalidParameterValue", "extent", params->version);
}
subsets = params->bbox;
if(EQUAL(params->subsetcrs, "imageCRS")) {
/* subsets are in imageCRS; reproject them to real coordinates */
rectObj orig_bbox = subsets;
msFreeProjection(&(map->projection));
map->projection = imageProj;
if(subsets.minx != -DBL_MAX || subsets.maxx != DBL_MAX) {
x_1 = cm.geotransform[0]
+ orig_bbox.minx * cm.geotransform[1]
+ orig_bbox.miny * cm.geotransform[2];
x_2 = cm.geotransform[0]
+ (orig_bbox.maxx+1) * cm.geotransform[1]
+ (orig_bbox.maxy+1) * cm.geotransform[2];
subsets.minx = MIN(x_1, x_2);
subsets.maxx = MAX(x_1, x_2);
}
if(subsets.miny != -DBL_MAX || subsets.maxy != DBL_MAX) {
y_1 = cm.geotransform[3]
+ (orig_bbox.maxx+1) * cm.geotransform[4]
+ (orig_bbox.maxy+1) * cm.geotransform[5];
/*subsets.miny -= cm.geotransform[4]/2 + cm.geotransform[5]/2;*/
y_2 = cm.geotransform[3]
+ orig_bbox.minx * cm.geotransform[4]
+ orig_bbox.miny * cm.geotransform[5];
subsets.miny = MIN(y_1, y_2);
subsets.maxy = MAX(y_1, y_2);
}
} else { /* if crs is not the 'imageCRS' */
projectionObj subsetProj;
/* if the subsets have a crs given, project the image extent to it */
msInitProjection(&subsetProj);
if(msLoadProjectionString(&subsetProj, params->subsetcrs) != MS_SUCCESS) {
msWCSClearCoverageMetadata20(&cm);
msSetError(MS_WCSERR,
"Error loading CRS %s.",
"msWCSGetCoverage20()", params->subsetcrs);
return msWCSException(map, "InvalidParameterValue",
"projection", params->version);
}
if(msProjectionsDiffer(&imageProj, &subsetProj)) {
msProjectRect(&imageProj, &subsetProj, &(layer->extent));
map->extent = layer->extent;
msFreeProjection(&(map->projection));
map->projection = subsetProj;
msFreeProjection(&imageProj);
} else {
msFreeProjection(&(map->projection));
map->projection = imageProj;
msFreeProjection(&subsetProj);
}
}
/* create boundings of params subsets and image extent */
if(msRectOverlap(&subsets, &(layer->extent)) == MS_FALSE) {
/* extent and bbox do not overlap -> exit */
msWCSClearCoverageMetadata20(&cm);
msSetError(MS_WCSERR, "Image extent does not intersect with desired region.",
"msWCSGetCoverage20()");
return msWCSException(map, "ExtentError", "extent", params->version);
}
/* write combined bounding box */
bbox.minx = MAX(subsets.minx, map->extent.minx);
bbox.miny = MAX(subsets.miny, map->extent.miny);
bbox.maxx = MIN(subsets.maxx, map->extent.maxx);
bbox.maxy = MIN(subsets.maxy, map->extent.maxy);
/* check if we are overspecified */
if((params->width != 0 && params->resolutionX != MS_WCS20_UNBOUNDED)
|| (params->height != 0 && params->resolutionY != MS_WCS20_UNBOUNDED)) {
msWCSClearCoverageMetadata20(&cm);
msSetError(MS_WCSERR, "GetCoverage operation supports only one of SIZE or RESOLUTION per axis.",
"msWCSGetCoverage20()");
return msWCSException(map, "TooManyParameterValues", "coverage",
params->version);
}
/************************************************************************/
/* check both axes: see if either size or resolution are given (and */
/* calculate the other value). If both are not given, calculate them */
/* from the bounding box. */
/************************************************************************/
/* check x axis */
if(params->width != 0) {
/* TODO Unit Of Measure? */
params->resolutionX = (bbox.maxx - bbox.minx) / params->width;
} else if(params->resolutionX != MS_WCS20_UNBOUNDED) {
params->width = MS_NINT((bbox.maxx - bbox.minx) / params->resolutionX);
} else {
if(ABS(bbox.maxx - bbox.minx) != ABS(map->extent.maxx - map->extent.minx)) {
double total = ABS(map->extent.maxx - map->extent.minx),
part = ABS(bbox.maxx - bbox.minx);
params->width = MS_NINT((part * map->width) / total);
} else {
params->width = map->width;
}
params->resolutionX = (bbox.maxx - bbox.minx) / params->width;
}
/* check y axis */
if(params->height != 0) {
params->resolutionY = (bbox.maxy - bbox.miny) / params->height;
} else if(params->resolutionY != MS_WCS20_UNBOUNDED) {
params->height = MS_NINT((bbox.maxy - bbox.miny) / params->resolutionY);
} else {
if(ABS(bbox.maxy - bbox.miny) != ABS(map->extent.maxy - map->extent.miny)) {
double total = ABS(map->extent.maxy - map->extent.miny),
part = ABS(bbox.maxy - bbox.miny);
params->height = MS_NINT((part * map->height) / total);
} else {
params->height = map->height;
}
params->resolutionY = (bbox.maxy - bbox.miny) / params->height;
}
/* WCS 2.0 is center of pixel oriented */
bbox.minx += params->resolutionX * 0.5;
bbox.maxx -= params->resolutionX * 0.5;
bbox.miny += params->resolutionY * 0.5;
bbox.maxy -= params->resolutionY * 0.5;
/* if parameter 'outputcrs' is given, project the image to this crs */
if(params->outputcrs != NULL) {
projectionObj outputProj;
msInitProjection(&outputProj);
if(msLoadProjectionString(&outputProj, params->outputcrs) == -1) {
msFreeProjection(&outputProj);
msWCSClearCoverageMetadata20(&cm);
return msWCSException(map, "InvalidParameterValue", "coverage",
params->version);
}
if(msProjectionsDiffer(&(map->projection), &outputProj)) {
msDebug("msWCSGetCoverage20(): projecting to outputcrs %s\n", params->outputcrs);
msProjectRect(&(map->projection), &outputProj, &bbox);
msFreeProjection(&(map->projection));
map->projection = outputProj;
/* recalculate resolutions, needed if UOM changes (e.g: deg -> m) */
params->resolutionX = (bbox.maxx - bbox.minx) / params->width;
params->resolutionY = (bbox.maxy - bbox.miny) / params->height;
}
}
/* set the bounding box as new map extent */
map->extent = bbox;
map->width = params->width;
map->height = params->height;
/* Are we exceeding the MAXSIZE limit on result size? */
if(map->width > map->maxsize || map->height > map->maxsize ) {
msWCSClearCoverageMetadata20(&cm);
msSetError(MS_WCSERR, "Raster size out of range, width and height of "
"resulting coverage must be no more than MAXSIZE=%d.",
"msWCSGetCoverage20()", map->maxsize);
return msWCSException(map, "InvalidParameterValue",
"size", params->version);
}
/* Mapserver only supports square cells */
if (params->resolutionX <= params->resolutionY)
map->cellsize = params->resolutionX;
else
map->cellsize = params->resolutionY;
msDebug("msWCSGetCoverage20(): Set parameters from original"
"data. Width: %d, height: %d, cellsize: %f, extent: %f,%f,%f,%f\n",
map->width, map->height, map->cellsize, map->extent.minx,
map->extent.miny, map->extent.maxx, map->extent.maxy);
/**
* Which format to use?
*
* 1) format parameter
* 2) native format (from metadata) or GDAL format of the input dataset
* 3) exception
**/
if (!params->format) {
if (cm.native_format) {
params->format = msStrdup(cm.native_format);
}
}
if (!params->format) {
msSetError(MS_WCSERR, "Output format could not be automatically determined. "
"Use the FORMAT parameter to specify a format.",
"msWCSGetCoverage20()");
msWCSClearCoverageMetadata20(&cm);
return msWCSException(map, "MissingParameterValue", "format",
params->version);
}
/* make sure layer is on */
layer->status = MS_ON;
msMapComputeGeotransform(map);
/* fill in bands rangeset info, if required. */
/* msWCSSetDefaultBandsRangeSetInfo(params, &cm, layer); */
/* msDebug("Bandcount: %d\n", cm.bandcount); */
msApplyDefaultOutputFormats(map);
if (msGetOutputFormatIndex(map, params->format) == -1) {
msSetError(MS_WCSERR, "Unrecognized value '%s' for the FORMAT parameter.",
"msWCSGetCoverage20()", params->format);
msWCSClearCoverageMetadata20(&cm);
return msWCSException(map, "InvalidParameterValue", "format",
params->version);
}
/* create a temporary outputformat (we likely will need to tweak parts) */
format = msCloneOutputFormat(msSelectOutputFormat(map, params->format));
msApplyOutputFormat(&(map->outputformat), format, MS_NOOVERRIDE,
MS_NOOVERRIDE, MS_NOOVERRIDE);
if(msWCSGetCoverage20_GetBands(map, layer, params, &cm, &bandlist) != MS_SUCCESS) {
msFree(bandlist);
msWCSClearCoverageMetadata20(&cm);
return msWCSException(map, "InvalidParameterValue", "rangesubset",
params->version);
}
msLayerSetProcessingKey(layer, "BANDS", bandlist);
snprintf(numbands, sizeof(numbands), "%d", msCountChars(bandlist, ',')+1);
msSetOutputFormatOption(map->outputformat, "BAND_COUNT", numbands);
/* check for the interpolation */
/* Defaults to NEAREST */
if(params->interpolation != NULL) {
if(EQUALN(params->interpolation,"NEAREST",7)) {
msLayerSetProcessingKey(layer, "RESAMPLE", "NEAREST");
} else if(EQUAL(params->interpolation,"BILINEAR")) {
msLayerSetProcessingKey(layer, "RESAMPLE", "BILINEAR");
} else if(EQUAL(params->interpolation,"AVERAGE")) {
msLayerSetProcessingKey(layer, "RESAMPLE", "AVERAGE");
} else {
msFree(bandlist);
msSetError( MS_WCSERR, "'%s' specifies an unsupported interpolation method.",
"msWCSGetCoverage20()", params->interpolation );
msWCSClearCoverageMetadata20(&cm);
return msWCSException(map, "InvalidParameterValue", "interpolation", params->version);
}
} else {
msLayerSetProcessingKey(layer, "RESAMPLE", "NEAREST");
}
/* since the dataset is only used in one layer, set it to be */
/* closed after drawing the layer. This normally defaults to */
/* DEFER and will produce a memory leak, because the dataset */
/* will not be closed. */
if( msLayerGetProcessingKey(layer, "CLOSE_CONNECTION") == NULL ) {
msLayerSetProcessingKey(layer, "CLOSE_CONNECTION", "NORMAL");
}
/* create the image object */
if (!map->outputformat) {
msWCSClearCoverageMetadata20(&cm);
msFree(bandlist);
msSetError(MS_WCSERR, "The map outputformat is missing!",
"msWCSGetCoverage20()");
return msWCSException(map, NULL, NULL, params->version);
} else if (MS_RENDERER_PLUGIN(map->outputformat)) {
image = msImageCreate(map->width, map->height, map->outputformat,
map->web.imagepath, map->web.imageurl, map->resolution,
map->defresolution, &map->imagecolor);
} else if (MS_RENDERER_RAWDATA(map->outputformat)) {
image = msImageCreate(map->width, map->height, map->outputformat,
map->web.imagepath, map->web.imageurl, map->resolution,
map->defresolution, &map->imagecolor);
} else {
msFree(bandlist);
msWCSClearCoverageMetadata20(&cm);
msSetError(MS_WCSERR, "Map outputformat not supported for WCS!",
"msWCSGetCoverage20()");
return msWCSException(map, NULL, NULL, params->version);
}
if (image == NULL) {
msFree(bandlist);
msWCSClearCoverageMetadata20(&cm);
return msWCSException(map, NULL, NULL, params->version);
}
/* Actually produce the "grid". */
if( MS_RENDERER_RAWDATA(map->outputformat) ) {
status = msDrawRasterLayerLow( map, layer, image, NULL );
} else {
rasterBufferObj rb;
MS_IMAGE_RENDERER(image)->getRasterBufferHandle(image,&rb);
status = msDrawRasterLayerLow( map, layer, image, &rb );
}
if( status != MS_SUCCESS ) {
msFree(bandlist);
msFreeImage(image);
msWCSClearCoverageMetadata20(&cm);
return msWCSException(map, NULL, NULL, params->version );
}
/* GML+Image */
/* Embed the image into multipart message */
if(params->multipart == MS_TRUE) {
xmlDocPtr psDoc = NULL; /* document pointer */
xmlNodePtr psRootNode, psRangeSet, psFile, psRangeParameters;
xmlNsPtr psGmlNs = NULL,
psGmlcovNs = NULL,
psSweNs = NULL,
psXLinkNs = NULL;
wcs20coverageMetadataObj tmpCm;
char *srs_uri, *default_filename;
const char *filename;
char *file_ref, *role;
int length = 0, swapAxes;
/* Create Document */
psDoc = xmlNewDoc(BAD_CAST "1.0");
psRootNode = xmlNewNode(NULL, BAD_CAST MS_WCS_GML_COVERAGETYPE_RECTIFIED_GRID_COVERAGE);
xmlDocSetRootElement(psDoc, psRootNode);
msWCSPrepareNamespaces20(psDoc, psRootNode, map);
psGmlNs = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX);
psGmlcovNs = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_GMLCOV_NAMESPACE_PREFIX);
psSweNs = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_SWE_NAMESPACE_PREFIX);
xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
psXLinkNs = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
xmlNewNsProp(psRootNode, psGmlNs, BAD_CAST "id", BAD_CAST layer->name);
xmlSetNs(psRootNode, psGmlcovNs);
srs_uri = msOWSGetProjURI(&map->projection, NULL, "CO", 1);
tmpCm = cm;
tmpCm.extent = map->extent;
tmpCm.xsize = map->width;
tmpCm.ysize = map->height;
strlcpy(tmpCm.srs_uri, srs_uri, sizeof(tmpCm.srs_uri));
tmpCm.xresolution = map->gt.geotransform[1];
tmpCm.yresolution = map->gt.geotransform[5];
tmpCm.extent.minx = MIN(map->gt.geotransform[0], map->gt.geotransform[0] + map->width * tmpCm.xresolution);
tmpCm.extent.miny = MIN(map->gt.geotransform[3], map->gt.geotransform[3] + map->height * tmpCm.yresolution);
tmpCm.extent.maxx = MAX(map->gt.geotransform[0], map->gt.geotransform[0] + map->width * tmpCm.xresolution);
tmpCm.extent.maxy = MAX(map->gt.geotransform[3], map->gt.geotransform[3] + map->height * tmpCm.yresolution);
swapAxes = msWCSSwapAxes20(srs_uri);
msFree(srs_uri);
/* Setup layer information */
msWCSCommon20_CreateBoundedBy(layer, &tmpCm, psGmlNs, psRootNode, &(map->projection), swapAxes);
msWCSCommon20_CreateDomainSet(layer, &tmpCm, psGmlNs, psRootNode, &(map->projection), swapAxes);
psRangeSet = xmlNewChild(psRootNode, psGmlNs, BAD_CAST "rangeSet", NULL);
psFile = xmlNewChild(psRangeSet, psGmlNs, BAD_CAST "File", NULL);
/* TODO: wait for updated specifications */
psRangeParameters = xmlNewChild(psFile, psGmlNs, BAD_CAST "rangeParameters", NULL);
default_filename = msStrdup("out.");
default_filename = msStringConcatenate(default_filename, MS_IMAGE_EXTENSION(image->format));
filename = msGetOutputFormatOption(image->format, "FILENAME", default_filename);
length = strlen("cid:coverage/") + strlen(filename) + 1;
file_ref = msSmallMalloc(length);
strlcpy(file_ref, "cid:coverage/", length);
strlcat(file_ref, filename, length);
msFree(default_filename);
if(EQUAL(MS_IMAGE_MIME_TYPE(map->outputformat), "image/tiff")) {
length = strlen(MS_WCS_20_PROFILE_GML_GEOTIFF) + 1;
role = msSmallMalloc(length);
strlcpy(role, MS_WCS_20_PROFILE_GML_GEOTIFF, length);
} else {
length = strlen(MS_IMAGE_MIME_TYPE(map->outputformat)) + 1;
role = msSmallMalloc(length);
strlcpy(role, MS_IMAGE_MIME_TYPE(map->outputformat), length);
}
xmlNewNsProp(psRangeParameters, psXLinkNs, BAD_CAST "href", BAD_CAST file_ref);
xmlNewNsProp(psRangeParameters, psXLinkNs, BAD_CAST "role", BAD_CAST role);
xmlNewNsProp(psRangeParameters, psXLinkNs, BAD_CAST "arcrole", BAD_CAST "fileReference");
xmlNewChild(psFile, psGmlNs, BAD_CAST "fileReference", BAD_CAST file_ref);
xmlNewChild(psFile, psGmlNs, BAD_CAST "fileStructure", NULL);
xmlNewChild(psFile, psGmlNs, BAD_CAST "mimeType", BAD_CAST MS_IMAGE_MIME_TYPE(map->outputformat));
msWCSCommon20_CreateRangeType(layer, &cm, bandlist, psGmlNs, psGmlcovNs, psSweNs, psXLinkNs, psRootNode);
msIO_setHeader("Content-Type","multipart/related; boundary=wcs");
msIO_sendHeaders();
msIO_printf("--wcs\n");
msWCSWriteDocument20(map, psDoc);
msWCSWriteFile20(map, image, params, 1);
msFree(file_ref);
msFree(role);
xmlFreeDoc(psDoc);
xmlCleanupParser();
/* just print out the file without gml */
} else {
msWCSWriteFile20(map, image, params, 0);
}
msFree(bandlist);
msWCSClearCoverageMetadata20(&cm);
msFreeImage(image);
return MS_SUCCESS;
}
#endif /* defined(USE_LIBXML2) */
#endif /* defined(USE_WCS_SVR) */
|
the_stack_data/232955456.c | #include <stdio.h>
void convertShortToByte(short byte){
for(int i=15; i>=0; i--) {
int bit = (byte >> i) & 0x01;
printf("%d", bit);
}
}
void printCurrentOffset(short var2){
for(int i = 1; i< var2; i++){
printf(" ");
}
}
int main(int argc, char **argv)
{
system("clear");
short var = 0x8000;
short var2 = 0x01;
do{
//printCurrentOffset(var2); //offset with whatever is in var2 to animate
convertShortToByte(var | var2);
short tempBitmask = ~var;
var = var >> 1;
var &= tempBitmask;
var2 = var2 << 1;
if(var == 0x00){
var = 0x8000;
var2 = 0x01;
}
getchar();
system("clear");
}
while(1);
return 0;
}
|
the_stack_data/988997.c | /*
* Code stolen from Jan Newmarch's "Raspberry Pi GPU Audio Video
* Programming" book chapter 5 p.28.
*/
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <unistd.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
typedef struct
{
uint32_t scrnWidth;
uint32_t scrnHeight;
EGLDisplay display;
EGLSurface surface;
EGLContext context;
EGLConfig config;
} EGL_STATE_T;
EGL_STATE_T eglState;
EGL_STATE_T* pEglState = &eglState;
void printConfigInfo(int configNr, EGLDisplay display, EGLConfig* config)
{
int iTemp;
printf("Configuration %d is:\n", configNr);
eglGetConfigAttrib(display, *config, EGL_RED_SIZE, &iTemp);
printf("\tRed size is %d: \n", iTemp);
eglGetConfigAttrib(display, *config, EGL_BLUE_SIZE, &iTemp);
printf("\tBlue size is %d: \n", iTemp);
eglGetConfigAttrib(display, *config, EGL_GREEN_SIZE, &iTemp);
printf("\tGreen size is %d: \n", iTemp);
eglGetConfigAttrib(display, *config, EGL_BUFFER_SIZE, &iTemp);
printf("\tBuffer size is %d: \n", iTemp);
eglGetConfigAttrib(display, *config, EGL_BIND_TO_TEXTURE_RGB, &iTemp);
if (iTemp == EGL_TRUE)
printf("\tCan be bound to RGB texture.\n");
else
printf("\tCan't be bound to RGB texture.\n");
eglGetConfigAttrib(display, *config, EGL_BIND_TO_TEXTURE_RGBA, &iTemp);
if (iTemp == EGL_TRUE)
printf("\tCan be bound to RGBA texture.\n");
else
printf("\tCan't be bound to RGBA texture.\n");
}
void initEGL(EGL_STATE_T* state)
{
EGLBoolean bResult;
EGLint numConfigs;
EGLConfig* configs;
// Get an EGL display connection.
state->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (state->display == EGL_NO_DISPLAY)
{
fprintf(stderr, "No display connection matching native_display available.\n");
}
// Initialize the EGL display connection.
bResult = eglInitialize(state->display, NULL, NULL);
if (bResult == EGL_FALSE)
{
fprintf(stderr, "Can't initialize EGL!\n");
}
// Get the number of configurations.
eglGetConfigs(state->display, NULL, 0, &numConfigs);
printf("EGL has %d configurations.\n", numConfigs);
// Allocate memory for the configurations.
configs = calloc(numConfigs, sizeof *configs);
eglGetConfigs(state->display, configs, numConfigs, &numConfigs);
// Get all config info.
int iConfCnt;
for (iConfCnt = 0; iConfCnt < numConfigs; iConfCnt++)
{
printConfigInfo(iConfCnt, state->display, &configs[iConfCnt]);
}
}
int main(int argc, char* argv[])
{
initEGL(pEglState);
return 0;
}
|
the_stack_data/70450828.c | #include <stdio.h>
#include <time.h>
#define ARRAY_LEN 500000
int binsearch(int, int[], int);
int binsearchFast(int, int[], int);
main()
{
clock_t start, finish;
int i, v[ARRAY_LEN];
for (i = 0; i < ARRAY_LEN; i++)
v[i] = i;//init the test array
start = clock();
int p;
for (i = 0; i < ARRAY_LEN; i++) {
p = binsearch(i, v, ARRAY_LEN);
//printf("%d at %d\n", i, p);
}
finish = clock();
printf("the time of binsearch duration: %f\n", ((double)(finish - start)) / CLOCKS_PER_SEC);
//printf("binsearchFast:\n");
start = clock();
for (i = 0; i < ARRAY_LEN; i++) {
p = binsearchFast(i, v, ARRAY_LEN);
//printf("%d at %d\n", i, p);
}
finish = clock();
printf("the time of the binsearchFast duration: %f\n", ((double)(finish - start)) / CLOCKS_PER_SEC);
for (i = -10000; i < ARRAY_LEN; i++) {
p = binsearchFast(i, v, ARRAY_LEN);
if (i < 0 && p != -1)
break;
else if (i >= 0 && p != i)
break;
}
printf("i: %d\n", i);
}
/* binsearch: find x in v[0] <= v[1] <= ... v[n-1] */
int binsearch(int x, int v[], int n)
{
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if (x < v[mid])
high = mid - 1;
else if (x > v[mid])
low = mid + 1;
else
return mid;
}
return -1;
}
int binsearchFast(int x, int v[], int n)
{
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if (x <= v[mid])
high = mid - 1;
else
low = mid + 1;
}
if (x == v[mid])
return mid;//find the value
else if (x > v[mid])
mid += 1;
else
mid -= 1;
if (mid < 0 || mid > n - 1)
return -1;
else
return mid;
}
|
the_stack_data/193893883.c | #include <stdio.h>
int main(void) {
char c[9][10] = {
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
};
int n;
scanf("%d", &n);
if (n < 10) printf("%s\n", c[n-1]);
else printf("Greater than 9");
return 0;
}
|
the_stack_data/29825955.c | /*
* lrand48.c
*/
#include <stdlib.h>
#include <stdint.h>
extern unsigned short __rand48_seed[3]; /* Common with mrand48.c, srand48.c */
long lrand48(void)
{
return (uint32_t) jrand48(__rand48_seed) >> 1;
}
|
the_stack_data/15003.c | /*
This algorithm stores the linked list in a sorted manner and doesn't sort it when it needs
to be displayed. When the insertion happens, it checks and inserts it in the right place.
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *link;
} *head = NULL, *searchPtr = NULL, *ptr = NULL, *newNode = NULL, *ptrBefore = NULL;
void displayMenu()
{
printf("\n\n ---------------- MENU ----------------\n");
printf("1. Insert\n");
printf("2. DELETE\n");
printf("3. Display\n");
printf("0. Exit\n");
}
struct node *createNode() //Creates a node with NULL as the link
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->link = NULL;
//Creates a new node and assigns it to the variable newNode which is a global variable
//and the other functions directly access the global variable, hence the function
//doesn't return the new node created.
}
struct node *searchNode(int element) // Returns the pointer to the node which contains the
// data that was searched for. Else returns NULL
{
ptr = head;
while (ptr != NULL)
{
if (ptr->data == element)
return ptr;
ptr = ptr->link;
}
return ptr;
}
void insert(int element) // Takes the element to be inserted as argument
{
ptr = head;
ptrBefore = head;
if (head == NULL)
{
newNode = createNode();
newNode->data = element;
head = newNode;
return;
}
while (ptr != NULL) // Loop finds the node before which a new node has to be created
{
if (ptr->data > element)
break;
ptr = ptr->link;
}
if (ptr == head) // Case when the element is smaller than the first element
// This is similar to insertBegin()
{
newNode = createNode();
newNode->data = element;
newNode->link = head;
head = newNode;
return;
}
while (ptrBefore->link != ptr) // Loop to find the node before ptr so a newNode can be inserted between both of them
ptrBefore = ptrBefore->link;
newNode = createNode(); // Regular linking
newNode->data = element;
ptrBefore->link = newNode;
newNode->link = ptr;
}
void deleteNode() //To delete a node at any location
{
if (searchPtr == head) // Case when the head is to be deleted
{
ptr = head;
head = head->link;
free(ptr);
printf("Deleted successfully\n");
return;
}
ptr = head;
while (ptr->link != searchPtr) //To search for the previous node, that lies before the node to be deleted.
ptr = ptr->link;
ptr->link = searchPtr->link;
free(searchPtr);
printf("Deleted successfully\n");
}
void display()
{
if (head == NULL)
{
printf("List is empty\n");
return;
}
else
{
ptr = head;
while (ptr != NULL)
{
printf("%d ", ptr->data);
ptr = ptr->link;
}
}
}
int main()
{
char menu;
int element;
while (1)
{
displayMenu();
printf("Enter your choice: ");
scanf(" %c", &menu);
switch (menu)
{
case '1':
printf("Enter the data: ");
scanf("%d", &element);
insert(element);
break;
case '2':
printf("Enter the element you want to delete: ");
scanf("%d", &element);
searchPtr = searchNode(element);
if (searchPtr == NULL)
printf("The element doesn't exist in the list\n");
else
deleteNode();
break;
case '3':
display();
break;
case '0':
exit(0);
break;
default:
printf("Wrong choice\n\n\n");
break;
}
}
return 0;
} |
the_stack_data/32745.c | #include <stdio.h>
int main(){
int i = 0;
printf("Demo is running\n");
while(i<20){
i=i+1;
sleep(1);
printf("Demo has running %d seconds.\n", i);
fflush(stdout);
}
printf("Demo is ending.\n");
}
|
the_stack_data/89200248.c | /* { dg-do assemble } */
/* Invalid assembly generated due to port bug. */
struct tcp_opt {
unsigned int window_clamp;
unsigned int rcv_ssthresh;
unsigned short advmss;
};
extern int sysctl_tcp_app_win;
void tcp_init_buffer_space(struct tcp_opt *tp, int maxwin)
{
if (tp->window_clamp >= maxwin)
if (sysctl_tcp_app_win && maxwin>4*tp->advmss)
tp->window_clamp
= ({
int _x = maxwin;
typeof(4*tp->advmss) _y = (4*tp->advmss);
_x > _y ? _x : _y;
});
if (sysctl_tcp_app_win
&& tp->window_clamp > 2*tp->advmss
&& tp->window_clamp + tp->advmss > maxwin)
tp->window_clamp
= ({
unsigned short _x = maxwin;
unsigned short _y = (maxwin-tp->advmss);
_x > _y ? _x : _y;
});
tp->rcv_ssthresh
= ({
unsigned int _x = (tp->rcv_ssthresh);
unsigned int _y = (tp->window_clamp);
_x < _y ? _x : _y;
});
}
|
the_stack_data/75137744.c | /* Write the program expr, which evaluates a reverse Polish expression from the
command line, where each operator or operand is a separate argument. For example:
expr 2 3 4 + * evaluates 2*(3+4). */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char **op;
char c;
int pos = 0;
float result;
if (argc < 4)
printf ("not enought arguments: expr numbers operators\n");
else
{
while (isdigit((*++argv)[0]))
pos++;
op = argv-1;
result = atof(*--argv);
while (--pos > 0 && (++op != NULL) && (--argv != NULL))
switch((*op)[0])
{
case '+':
result += atof(*argv);
break;
case '-':
result = atof(*argv) - result;
break;
case '*':
result *= atof(*argv);
break;
case '/':
result = atof(*argv) / result;
break;
default:
printf("invalid operator!\n");
pos = 0;
break;
}
}
printf("The result is: %.2f\n", result);
return 0;
}
|
the_stack_data/54826684.c | /*Exercise 4 - Functions
Implement the three functions minimum(), maximum() and multiply() below the main() function.
Do not change the code given in the main() function when you are implementing your solution.*/
#include <stdio.h>
int minimum(int n1, int n2);
int maximum(int n3, int n4);
int multiply(int n5, int n6);
int main() {
int no1, no2;
printf("Enter a value for no 1 : ");
scanf("%d", &no1);
printf("Enter a value for no 2 : ");
scanf("%d", &no2);
printf("%d ", minimum(no1, no2));
printf("%d ", maximum(no1, no2));
printf("%d ", multiply(no1, no2));
return 0;
}
int minimum(int n1, int n2)
{
if(n1<n2)
{
return n1;
}
else
{
return n2;
}
}
int maximum(int n3, int n4)
{
if(n3>n4)
{
return n3;
}
else
{
return n4;
}
}
int multiply(int n5, int n6)
{
return n5*n6;
}
|
the_stack_data/845539.c | #include <stdio.h>
#include <stdlib.h>
#define IN 1 /* Inside a word */
#define OUT 0 /* outside a 'd */
char ** mytoc( char *string, char delim )
{
int a, numChars = 0;
for( a=0 ; string[a] ; a++ )
{
numChars++;
}
char *paragraph = (char *)malloc(numChars+1);
for( a=0 ; string[a] ; a++ )
{
paragraph[ a ] = string[ a ];
}
int n, i, currChar, numWords, state, pIndex;
// number, index, current character, number of words, and state (in or out), pointer index
state = OUT; // By default, we are not inside a word until the loop starts
numWords = 0;
for( n = 0; paragraph[n]; n++ ) {
currChar = paragraph[n];
// if current char is a deliminator, we are not in a word
if( currChar == delim )
state = OUT;
// otherwise we are in a word and count up
else if( state == OUT ) {
state = IN;
++numWords;
}
}
// knowing the number of workds, we can allocate enough space for the token vector
char **tokens = calloc( numWords+2, sizeof(char*));
// clever solution: rather than copying the string or individual words and counting the number
// of characters each has, we can modify the existing string such that instances of the deliminator
// are turned into the null character (indicating the end of that string), and point each element
// of the token vector to the address of the first element of each individual word!
char temp = delim;
pIndex = 0;
for( i = 0; paragraph[i]; i++ ) {
if( paragraph[i] == delim || paragraph[i] == '\n' || paragraph[i] == '\t' ) {
temp = paragraph[i];
paragraph[i] = '\0';
}
else if( paragraph[i] != '\0' && ( temp == delim || temp == '\n' || temp == '\t' ) ) {
tokens[ pIndex++ ] = ¶graph[i];
temp = paragraph[i];
}
}
return tokens;
}
void printTokens( char **tVector )
{
char **tvTemp;
int n;
tvTemp = tVector;
for( n = 0; *tvTemp != '\0'; n++ ) {
printf( "%d: \"%s\"\n", n, *tvTemp );
tvTemp++;
}
printf( "\n" );
}
void freeTokens( char **tVector )
{
printf( "%s\n", *tVector );
while( *tVector != NULL ) {
free( *tVector );
tVector++;
}
free( tVector );
}
|
the_stack_data/58054.c | int dynload_plain_testfunc() { return 5; } |
the_stack_data/125141204.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern float strtof(char const *str , char const *endptr ) ;
extern void signal(int sig , void *func ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void megaInit(void)
{
{
}
}
int main(int argc , char *argv[] )
{
unsigned int input[1] ;
unsigned int output[1] ;
int randomFuns_i5 ;
unsigned int randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 4242424242U) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
void RandomFunc(unsigned int input[1] , unsigned int output[1] )
{
unsigned int state[1] ;
unsigned int local1 ;
unsigned short copy11 ;
{
state[0UL] = (input[0UL] + 914778474UL) ^ 3462201355U;
local1 = 0UL;
while (local1 < 0U) {
if (state[0UL] > local1) {
if (state[0UL] == local1) {
state[0UL] = state[local1] - state[0UL];
} else {
copy11 = *((unsigned short *)(& state[local1]) + 1);
*((unsigned short *)(& state[local1]) + 1) = *((unsigned short *)(& state[local1]) + 0);
*((unsigned short *)(& state[local1]) + 0) = copy11;
}
} else
if (state[0UL] <= local1) {
state[0UL] |= ((state[0UL] + state[local1]) & 31U) << 3UL;
} else {
state[local1] |= (state[local1] & 31U) << 4UL;
}
local1 ++;
}
output[0UL] = state[0UL] - 674032645UL;
}
}
|
the_stack_data/18886493.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: [email protected], [email protected], [email protected],
[email protected], [email protected])
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
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 disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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.
*/
/*
Classic PI calculation using reduction
*/
#define num_steps 2000000000
#include <stdio.h>
int main(int argc, char** argv)
{
double pi = 0.0;
long int i;
double x, interval_width;
interval_width = 1.0/(double)num_steps;
#pragma omp parallel for reduction(+:pi) private(x)
for (i = 0; i < num_steps; i++) {
x = (i+ 0.5) * interval_width;
pi += 1.0 / (x*x + 1.0);
}
pi = pi * 4.0 * interval_width;
printf ("PI=%f\n", pi);
return 0;
}
|
the_stack_data/76700568.c | /*Exercise 2 - Selection
Write a program to calculate the amount to be paid for a rented vehicle.
• Input the distance the van has travelled
• The first 30 km is at a rate of 50/= per km.
• The remaining distance is calculated at the rate of 40/= per km.
e.g.
Distance -> 20
Amount = 20 x 50 = 1000
Distance -> 50
Amount = 30 x 50 + (50-30) x 40 = 2300*/
#include <stdio.h>
int main() {
int distance;
int amountLess = 0, amountHigh = 0 , amount = 0;
int remainingDis;
printf("Distance -> ");
scanf("%d", &distance);
if(distance<30)
{
amountLess = 50*distance;
}
if(distance >= 30)
{
amountLess = 50 * 30;
remainingDis = distance - 30;
amountHigh = 40 * remainingDis;
}
printf("Amount = %d", amount = amountHigh + amountLess);
return 0;
}
|
the_stack_data/336379.c | /**
******************************************************************************
* @file stm32f7xx_ll_usart.c
* @author MCD Application Team
* @brief USART LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 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.
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32f7xx_ll_usart.h"
#include "stm32f7xx_ll_rcc.h"
#include "stm32f7xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F7xx_LL_Driver
* @{
*/
#if defined (USART1) || defined (USART2) || defined (USART3) || defined (USART6) || defined (UART4) || defined (UART5) || defined (UART7) || defined (UART8)
/** @addtogroup USART_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup USART_LL_Private_Constants
* @{
*/
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup USART_LL_Private_Macros
* @{
*/
/* __BAUDRATE__ The maximum Baud Rate is derived from the maximum clock available
* divided by the smallest oversampling used on the USART (i.e. 8) */
#define IS_LL_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) <= 27000000U)
/* __VALUE__ In case of oversampling by 16 and 8, BRR content must be greater than or equal to 16d. */
#define IS_LL_USART_BRR(__VALUE__) (((__VALUE__) >= 16U) \
&& ((__VALUE__) <= 0x0000FFFFU))
#define IS_LL_USART_DIRECTION(__VALUE__) (((__VALUE__) == LL_USART_DIRECTION_NONE) \
|| ((__VALUE__) == LL_USART_DIRECTION_RX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX_RX))
#define IS_LL_USART_PARITY(__VALUE__) (((__VALUE__) == LL_USART_PARITY_NONE) \
|| ((__VALUE__) == LL_USART_PARITY_EVEN) \
|| ((__VALUE__) == LL_USART_PARITY_ODD))
#define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_7B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_8B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_9B))
#define IS_LL_USART_OVERSAMPLING(__VALUE__) (((__VALUE__) == LL_USART_OVERSAMPLING_16) \
|| ((__VALUE__) == LL_USART_OVERSAMPLING_8))
#define IS_LL_USART_LASTBITCLKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_LASTCLKPULSE_NO_OUTPUT) \
|| ((__VALUE__) == LL_USART_LASTCLKPULSE_OUTPUT))
#define IS_LL_USART_CLOCKPHASE(__VALUE__) (((__VALUE__) == LL_USART_PHASE_1EDGE) \
|| ((__VALUE__) == LL_USART_PHASE_2EDGE))
#define IS_LL_USART_CLOCKPOLARITY(__VALUE__) (((__VALUE__) == LL_USART_POLARITY_LOW) \
|| ((__VALUE__) == LL_USART_POLARITY_HIGH))
#define IS_LL_USART_CLOCKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_CLOCK_DISABLE) \
|| ((__VALUE__) == LL_USART_CLOCK_ENABLE))
#define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_0_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_1) \
|| ((__VALUE__) == LL_USART_STOPBITS_1_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_2))
#define IS_LL_USART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_USART_HWCONTROL_NONE) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_CTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS_CTS))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup USART_LL_Exported_Functions
* @{
*/
/** @addtogroup USART_LL_EF_Init
* @{
*/
/**
* @brief De-initialize USART registers (Registers restored to their default values).
* @param USARTx USART Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are de-initialized
* - ERROR: USART registers are not de-initialized
*/
ErrorStatus LL_USART_DeInit(USART_TypeDef *USARTx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
if (USARTx == USART1)
{
/* Force reset of USART clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_USART1);
/* Release reset of USART clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_USART1);
}
else if (USARTx == USART2)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART2);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART2);
}
else if (USARTx == USART3)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART3);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART3);
}
else if (USARTx == USART6)
{
/* Force reset of USART clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_USART6);
/* Release reset of USART clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_USART6);
}
else if (USARTx == UART4)
{
/* Force reset of UART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART4);
/* Release reset of UART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART4);
}
else if (USARTx == UART5)
{
/* Force reset of UART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART5);
/* Release reset of UART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART5);
}
else if (USARTx == UART7)
{
/* Force reset of UART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART7);
/* Release reset of UART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART7);
}
else if (USARTx == UART8)
{
/* Force reset of UART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART8);
/* Release reset of UART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART8);
}
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Initialize USART registers according to the specified
* parameters in USART_InitStruct.
* @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0),
* USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @note Baud rate value stored in USART_InitStruct BaudRate field, should be valid (different from 0).
* @param USARTx USART Instance
* @param USART_InitStruct: pointer to a LL_USART_InitTypeDef structure
* that contains the configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are initialized according to USART_InitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, LL_USART_InitTypeDef *USART_InitStruct)
{
ErrorStatus status = ERROR;
uint32_t periphclk = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_BAUDRATE(USART_InitStruct->BaudRate));
assert_param(IS_LL_USART_DATAWIDTH(USART_InitStruct->DataWidth));
assert_param(IS_LL_USART_STOPBITS(USART_InitStruct->StopBits));
assert_param(IS_LL_USART_PARITY(USART_InitStruct->Parity));
assert_param(IS_LL_USART_DIRECTION(USART_InitStruct->TransferDirection));
assert_param(IS_LL_USART_HWCONTROL(USART_InitStruct->HardwareFlowControl));
assert_param(IS_LL_USART_OVERSAMPLING(USART_InitStruct->OverSampling));
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/*---------------------------- USART CR1 Configuration ---------------------
* Configure USARTx CR1 (USART Word Length, Parity, Mode and Oversampling bits) with parameters:
* - DataWidth: USART_CR1_M bits according to USART_InitStruct->DataWidth value
* - Parity: USART_CR1_PCE, USART_CR1_PS bits according to USART_InitStruct->Parity value
* - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to USART_InitStruct->TransferDirection value
* - Oversampling: USART_CR1_OVER8 bit according to USART_InitStruct->OverSampling value.
*/
MODIFY_REG(USARTx->CR1,
(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS |
USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8),
(USART_InitStruct->DataWidth | USART_InitStruct->Parity |
USART_InitStruct->TransferDirection | USART_InitStruct->OverSampling));
/*---------------------------- USART CR2 Configuration ---------------------
* Configure USARTx CR2 (Stop bits) with parameters:
* - Stop Bits: USART_CR2_STOP bits according to USART_InitStruct->StopBits value.
* - CLKEN, CPOL, CPHA and LBCL bits are to be configured using LL_USART_ClockInit().
*/
LL_USART_SetStopBitsLength(USARTx, USART_InitStruct->StopBits);
/*---------------------------- USART CR3 Configuration ---------------------
* Configure USARTx CR3 (Hardware Flow Control) with parameters:
* - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according to USART_InitStruct->HardwareFlowControl value.
*/
LL_USART_SetHWFlowCtrl(USARTx, USART_InitStruct->HardwareFlowControl);
/*---------------------------- USART BRR Configuration ---------------------
* Retrieve Clock frequency used for USART Peripheral
*/
if (USARTx == USART1)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART1_CLKSOURCE);
}
else if (USARTx == USART2)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART2_CLKSOURCE);
}
else if (USARTx == USART3)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART3_CLKSOURCE);
}
else if (USARTx == USART6)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART6_CLKSOURCE);
}
else if (USARTx == UART4)
{
periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_UART4_CLKSOURCE);
}
else if (USARTx == UART5)
{
periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_UART5_CLKSOURCE);
}
else if (USARTx == UART7)
{
periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_UART7_CLKSOURCE);
}
else if (USARTx == UART8)
{
periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_UART8_CLKSOURCE);
}
else
{
/* Nothing to do, as error code is already assigned to ERROR value */
}
/* Configure the USART Baud Rate :
- valid baud rate value (different from 0) is required
- Peripheral clock as returned by RCC service, should be valid (different from 0).
*/
if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO)
&& (USART_InitStruct->BaudRate != 0U))
{
status = SUCCESS;
LL_USART_SetBaudRate(USARTx,
periphclk,
USART_InitStruct->OverSampling,
USART_InitStruct->BaudRate);
/* Check BRR is greater than or equal to 16d */
assert_param(IS_LL_USART_BRR(USARTx->BRR));
}
}
/* Endif (=> USART not in Disabled state => return ERROR) */
return (status);
}
/**
* @brief Set each @ref LL_USART_InitTypeDef field to default value.
* @param USART_InitStruct: pointer to a @ref LL_USART_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_StructInit(LL_USART_InitTypeDef *USART_InitStruct)
{
/* Set USART_InitStruct fields to default values */
USART_InitStruct->BaudRate = 9600U;
USART_InitStruct->DataWidth = LL_USART_DATAWIDTH_8B;
USART_InitStruct->StopBits = LL_USART_STOPBITS_1;
USART_InitStruct->Parity = LL_USART_PARITY_NONE ;
USART_InitStruct->TransferDirection = LL_USART_DIRECTION_TX_RX;
USART_InitStruct->HardwareFlowControl = LL_USART_HWCONTROL_NONE;
USART_InitStruct->OverSampling = LL_USART_OVERSAMPLING_16;
}
/**
* @brief Initialize USART Clock related settings according to the
* specified parameters in the USART_ClockInitStruct.
* @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0),
* USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @param USARTx USART Instance
* @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure
* that contains the Clock configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers related to Clock settings are initialized according to USART_ClockInitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_ClockInit(USART_TypeDef *USARTx, LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
ErrorStatus status = SUCCESS;
/* Check USART Instance and Clock signal output parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_CLOCKOUTPUT(USART_ClockInitStruct->ClockOutput));
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/*---------------------------- USART CR2 Configuration -----------------------*/
/* If Clock signal has to be output */
if (USART_ClockInitStruct->ClockOutput == LL_USART_CLOCK_DISABLE)
{
/* Deactivate Clock signal delivery :
* - Disable Clock Output: USART_CR2_CLKEN cleared
*/
LL_USART_DisableSCLKOutput(USARTx);
}
else
{
/* Ensure USART instance is USART capable */
assert_param(IS_USART_INSTANCE(USARTx));
/* Check clock related parameters */
assert_param(IS_LL_USART_CLOCKPOLARITY(USART_ClockInitStruct->ClockPolarity));
assert_param(IS_LL_USART_CLOCKPHASE(USART_ClockInitStruct->ClockPhase));
assert_param(IS_LL_USART_LASTBITCLKOUTPUT(USART_ClockInitStruct->LastBitClockPulse));
/*---------------------------- USART CR2 Configuration -----------------------
* Configure USARTx CR2 (Clock signal related bits) with parameters:
* - Enable Clock Output: USART_CR2_CLKEN set
* - Clock Polarity: USART_CR2_CPOL bit according to USART_ClockInitStruct->ClockPolarity value
* - Clock Phase: USART_CR2_CPHA bit according to USART_ClockInitStruct->ClockPhase value
* - Last Bit Clock Pulse Output: USART_CR2_LBCL bit according to USART_ClockInitStruct->LastBitClockPulse value.
*/
MODIFY_REG(USARTx->CR2,
USART_CR2_CLKEN | USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_LBCL,
USART_CR2_CLKEN | USART_ClockInitStruct->ClockPolarity |
USART_ClockInitStruct->ClockPhase | USART_ClockInitStruct->LastBitClockPulse);
}
}
/* Else (USART not in Disabled state => return ERROR */
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Set each field of a @ref LL_USART_ClockInitTypeDef type structure to default value.
* @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
/* Set LL_USART_ClockInitStruct fields with default values */
USART_ClockInitStruct->ClockOutput = LL_USART_CLOCK_DISABLE;
USART_ClockInitStruct->ClockPolarity = LL_USART_POLARITY_LOW; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->ClockPhase = LL_USART_PHASE_1EDGE; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->LastBitClockPulse = LL_USART_LASTCLKPULSE_NO_OUTPUT; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* USART1 || USART2 || USART3 || USART6 || UART4 || UART5 || UART7 || UART8 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/154830502.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
float comprimento;
float largura;
float area;
printf ("digite o comprimento do campo: \n");
scanf ("%f", &comprimento);
printf ("digite a largura do campo: \n");
scanf ("%f", &largura);
area= comprimento*largura;
printf ("a area do campo e: %f \n", area);
system("pause");
return (0);
}
|
the_stack_data/122015092.c | /*
* Operations on rectangle on a graphics screen.
*/
#include <stdbool.h>
#include <stdio.h>
struct point {
int x;
int y;
};
struct rectangle {
struct point upper_left;
struct point lower_right;
};
// Helper function to return positive length of the side.
static inline int length(int x1, int x2);
static inline int area(const struct rectangle *r);
static struct point center(const struct rectangle *r);
static void move(struct rectangle *r, int x, int y);
// Does the point lies within rectangle
static bool within(const struct rectangle *r, struct point p);
static void print_rectangle(const struct rectangle *r);
int main(void)
{
struct rectangle r = {
{-4, 2},
{2, -4},
};
print_rectangle(&r);
printf("Area: %d\n", area(&r));
printf("Center point: %d, %d\n", center(&r).x, center(&r).y);
printf("%d\n\n", within(&r, (struct point) {-3, 1,}));
move(&r, 4, 4);
print_rectangle(&r);
}
static inline int length(int x1, int x2)
{
int l = x2 - x1;
return l < 0 ? -l : l;
}
static inline int area(const struct rectangle *r)
{
return length(r->lower_right.x, r->upper_left.x)
* length(r->lower_right.y, r->upper_left.y);
}
static struct point center(const struct rectangle *r)
{
int half_length_x = length(r->lower_right.x, r->upper_left.x) / 2;
int half_length_y = length(r->lower_right.y, r->upper_left.y) / 2;
return (struct point) {
.x = r->upper_left.x + half_length_x,
.y = r->lower_right.y + half_length_y,
};
}
static void move(struct rectangle *r, int x, int y)
{
r->upper_left.x += x;
r->upper_left.y += y;
r->lower_right.x += x;
r->lower_right.y += y;
}
static bool within(const struct rectangle *r, struct point p)
{
return r->upper_left.x <= p.x && p.x <= r->lower_right.x
&& r->lower_right.y <= p.y && p.y <= r->upper_left.y;
}
static void print_rectangle(const struct rectangle *r)
{
int i;
// Little ugly formatting :)
printf("%3d, %-3d", r->upper_left.x, r->upper_left.y);
printf(" ___________ \n");
for (i = 0; i < 3; i++)
printf("%8c%-12c%c\n", ' ', '|', '|');
printf("%8c%c___________%c%3d, %-3d\n\n", ' ', '|', '|', r->lower_right.x, r->lower_right.y);
}
|
the_stack_data/93887656.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int
main(int argc, char * argv[])
{
int i, fd;
for(i = 0; i < argc; i++){
/* create an empty file */
if((fd = open(argv[i],O_CREAT,0666) > 0) > 0){
close(fd);
} else {
perror("open");
}
}
return 0;
}
|
the_stack_data/47118.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int expression) { if (!expression) { ERROR: /* assert not proved */
/* assert not proved */
__VERIFIER_error(); }; return; }
int __global_lock;
void __VERIFIER_atomic_begin() { /* reachable */
/* reachable */
/* reachable */
/* reachable */
/* reachable */
/* reachable */
__VERIFIER_assume(__global_lock==0); __global_lock=1; return; }
void __VERIFIER_atomic_end() { __VERIFIER_assume(__global_lock==1); __global_lock=0; return; }
#include "assert.h"
#include "pthread.h"
#ifndef TRUE
#define TRUE (_Bool)1
#endif
#ifndef FALSE
#define FALSE (_Bool)0
#endif
#ifndef NULL
#define NULL ((void*)0)
#endif
#ifndef FENCE
#define FENCE(x) ((void)0)
#endif
#ifndef IEEE_FLOAT_EQUAL
#define IEEE_FLOAT_EQUAL(x,y) (x==y)
#endif
#ifndef IEEE_FLOAT_NOTEQUAL
#define IEEE_FLOAT_NOTEQUAL(x,y) (x!=y)
#endif
void * P0(void *arg);
void * P1(void *arg);
void * P2(void *arg);
void fence();
void isync();
void lwfence();
int __unbuffered_cnt;
int __unbuffered_cnt = 0;
int __unbuffered_p0_EAX;
int __unbuffered_p0_EAX = 0;
int __unbuffered_p1_EAX;
int __unbuffered_p1_EAX = 0;
int __unbuffered_p2_EAX;
int __unbuffered_p2_EAX = 0;
_Bool __unbuffered_p2_EAX$flush_delayed;
int __unbuffered_p2_EAX$mem_tmp;
_Bool __unbuffered_p2_EAX$r_buff0_thd0;
_Bool __unbuffered_p2_EAX$r_buff0_thd1;
_Bool __unbuffered_p2_EAX$r_buff0_thd2;
_Bool __unbuffered_p2_EAX$r_buff0_thd3;
_Bool __unbuffered_p2_EAX$r_buff1_thd0;
_Bool __unbuffered_p2_EAX$r_buff1_thd1;
_Bool __unbuffered_p2_EAX$r_buff1_thd2;
_Bool __unbuffered_p2_EAX$r_buff1_thd3;
_Bool __unbuffered_p2_EAX$read_delayed;
int *__unbuffered_p2_EAX$read_delayed_var;
int __unbuffered_p2_EAX$w_buff0;
_Bool __unbuffered_p2_EAX$w_buff0_used;
int __unbuffered_p2_EAX$w_buff1;
_Bool __unbuffered_p2_EAX$w_buff1_used;
_Bool main$tmp_guard0;
_Bool main$tmp_guard1;
int x;
int x = 0;
int y;
int y = 0;
_Bool y$flush_delayed;
int y$mem_tmp;
_Bool y$r_buff0_thd0;
_Bool y$r_buff0_thd1;
_Bool y$r_buff0_thd2;
_Bool y$r_buff0_thd3;
_Bool y$r_buff1_thd0;
_Bool y$r_buff1_thd1;
_Bool y$r_buff1_thd2;
_Bool y$r_buff1_thd3;
_Bool y$read_delayed;
int *y$read_delayed_var;
int y$w_buff0;
_Bool y$w_buff0_used;
int y$w_buff1;
_Bool y$w_buff1_used;
int z;
int z = 0;
_Bool weak$$choice0;
_Bool weak$$choice1;
_Bool weak$$choice2;
void * P0(void *arg)
{
__VERIFIER_atomic_begin();
__unbuffered_p0_EAX = z;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void * P1(void *arg)
{
__VERIFIER_atomic_begin();
__unbuffered_p1_EAX = x;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
y$w_buff1 = y$w_buff0;
y$w_buff0 = 1;
y$w_buff1_used = y$w_buff0_used;
y$w_buff0_used = TRUE;
__VERIFIER_assert(!(y$w_buff1_used && y$w_buff0_used));
y$r_buff1_thd0 = y$r_buff0_thd0;
y$r_buff1_thd1 = y$r_buff0_thd1;
y$r_buff1_thd2 = y$r_buff0_thd2;
y$r_buff1_thd3 = y$r_buff0_thd3;
y$r_buff0_thd2 = TRUE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
y = y$w_buff0_used && y$r_buff0_thd2 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd2 ? y$w_buff1 : y);
y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd2 ? FALSE : y$w_buff0_used;
y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd2 || y$w_buff1_used && y$r_buff1_thd2 ? FALSE : y$w_buff1_used;
y$r_buff0_thd2 = y$w_buff0_used && y$r_buff0_thd2 ? FALSE : y$r_buff0_thd2;
y$r_buff1_thd2 = y$w_buff0_used && y$r_buff0_thd2 || y$w_buff1_used && y$r_buff1_thd2 ? FALSE : y$r_buff1_thd2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void * P2(void *arg)
{
__VERIFIER_atomic_begin();
weak$$choice0 = nondet_1();
weak$$choice2 = nondet_1();
y$flush_delayed = weak$$choice2;
y$mem_tmp = y;
weak$$choice1 = nondet_1();
y = !y$w_buff0_used ? y : (y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff0 : (y$w_buff0_used && !y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? (weak$$choice0 ? y : (weak$$choice1 ? y$w_buff0 : y$w_buff1)) : (y$w_buff0_used && y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? (weak$$choice0 ? y$w_buff1 : y$w_buff0) : (weak$$choice0 ? y$w_buff0 : y))));
y$w_buff0 = weak$$choice2 ? y$w_buff0 : (!y$w_buff0_used ? y$w_buff0 : (y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff0 : (y$w_buff0_used && !y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? y$w_buff0 : (y$w_buff0_used && y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? y$w_buff0 : y$w_buff0))));
y$w_buff1 = weak$$choice2 ? y$w_buff1 : (!y$w_buff0_used ? y$w_buff1 : (y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff1 : (y$w_buff0_used && !y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? y$w_buff1 : (y$w_buff0_used && y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? y$w_buff1 : y$w_buff1))));
y$w_buff0_used = weak$$choice2 ? y$w_buff0_used : (!y$w_buff0_used ? y$w_buff0_used : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : (y$w_buff0_used && !y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? weak$$choice0 || !weak$$choice1 : (y$w_buff0_used && y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? weak$$choice0 : weak$$choice0))));
y$w_buff1_used = weak$$choice2 ? y$w_buff1_used : (!y$w_buff0_used ? y$w_buff1_used : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : (y$w_buff0_used && !y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? weak$$choice0 : (y$w_buff0_used && y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? FALSE : FALSE))));
y$r_buff0_thd3 = weak$$choice2 ? y$r_buff0_thd3 : (!y$w_buff0_used ? y$r_buff0_thd3 : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : (y$w_buff0_used && !y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? y$r_buff0_thd3 : (y$w_buff0_used && y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? FALSE : FALSE))));
y$r_buff1_thd3 = weak$$choice2 ? y$r_buff1_thd3 : (!y$w_buff0_used ? y$r_buff1_thd3 : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : (y$w_buff0_used && !y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? (weak$$choice0 ? y$r_buff1_thd3 : FALSE) : (y$w_buff0_used && y$r_buff1_thd3 && y$w_buff1_used && !y$r_buff0_thd3 ? FALSE : FALSE))));
__unbuffered_p2_EAX$read_delayed = TRUE;
__unbuffered_p2_EAX$read_delayed_var = &y;
__unbuffered_p2_EAX = y;
y = y$flush_delayed ? y$mem_tmp : y;
y$flush_delayed = FALSE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
z = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
y = y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd3 ? y$w_buff1 : y);
y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd3 ? FALSE : y$w_buff0_used;
y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd3 || y$w_buff1_used && y$r_buff1_thd3 ? FALSE : y$w_buff1_used;
y$r_buff0_thd3 = y$w_buff0_used && y$r_buff0_thd3 ? FALSE : y$r_buff0_thd3;
y$r_buff1_thd3 = y$w_buff0_used && y$r_buff0_thd3 || y$w_buff1_used && y$r_buff1_thd3 ? FALSE : y$r_buff1_thd3;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void fence()
{
}
void isync()
{
}
void lwfence()
{
}
int main()
{
pthread_create(NULL, NULL, P0, NULL);
pthread_create(NULL, NULL, P1, NULL);
pthread_create(NULL, NULL, P2, NULL);
__VERIFIER_atomic_begin();
main$tmp_guard0 = __unbuffered_cnt == 3;
__VERIFIER_atomic_end();
__VERIFIER_assume(main$tmp_guard0);
__VERIFIER_atomic_begin();
y = y$w_buff0_used && y$r_buff0_thd0 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd0 ? y$w_buff1 : y);
y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd0 ? FALSE : y$w_buff0_used;
y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd0 || y$w_buff1_used && y$r_buff1_thd0 ? FALSE : y$w_buff1_used;
y$r_buff0_thd0 = y$w_buff0_used && y$r_buff0_thd0 ? FALSE : y$r_buff0_thd0;
y$r_buff1_thd0 = y$w_buff0_used && y$r_buff0_thd0 || y$w_buff1_used && y$r_buff1_thd0 ? FALSE : y$r_buff1_thd0;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
weak$$choice1 = nondet_1();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
__unbuffered_p2_EAX = __unbuffered_p2_EAX$read_delayed ? (weak$$choice1 ? *__unbuffered_p2_EAX$read_delayed_var : __unbuffered_p2_EAX) : __unbuffered_p2_EAX;
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
main$tmp_guard1 = !(__unbuffered_p0_EAX == 1 && __unbuffered_p1_EAX == 1 && __unbuffered_p2_EAX == 1);
__VERIFIER_atomic_end();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
__VERIFIER_assert(main$tmp_guard1);
/* reachable */
return 0;
}
|
the_stack_data/81090.c | //
#include <stdio.h>
int main(){
int a, b, c, d, x;
printf("Please enter 4 numbers separated by spaces > ");
scanf("%d %d %d %d", &a, &b, &c, &d);
if (a>b)
x = b;
else
x = a;
if (b>c)
x = c;
if (c>d)
x = d;
printf("%d is the smallest\n", x);
return 0;
}
|
the_stack_data/80318.c | // CORRECT
#include <stdio.h>
int main(int argc, char **argv) {
int a, b, c, d;
puts("Enter bar(a, b, c) = ?");
scanf("bar(%d, %d, %d) = ?", &a, &b, &c);
d = (c + 1) * b + a;
printf("Result %d\n", d);
} |
the_stack_data/46290.c | /* $Header: /cvsup/minix/src/lib/ack/libp/rnd.c,v 1.1 2005/10/10 15:27:47 beng Exp $ */
/*
* (c) copyright 1983 by the Vrije Universiteit, Amsterdam, The Netherlands.
*
* This product is part of the Amsterdam Compiler Kit.
*
* Permission to use, sell, duplicate or disclose this software must be
* obtained in writing. Requests for such permissions may be sent to
*
* Dr. Andrew S. Tanenbaum
* Wiskundig Seminarium
* Vrije Universiteit
* Postbox 7161
* 1007 MC Amsterdam
* The Netherlands
*
*/
double _rnd(r) double r; {
return(r + (r<0 ? -0.5 : 0.5));
}
|
the_stack_data/126703675.c | #include <stdio.h>
int main() {
int p,i;
for(i=1;i>0;i++)
{
scanf("%d",&p);
if(p==2002)
{
printf("Acesso Permitido\n");
break;
}
else
printf("Senha Invalida\n");
}
return 0;
}
|
the_stack_data/64199706.c | /* { dg-do compile } */
/* { dg-options "-O -fdump-tree-fre1-details" } */
/* { dg-additional-options "-fno-common" { target hppa*-*-hpux* } } */
typedef double d128 __attribute__((vector_size(16)));
typedef float f128 __attribute__((vector_size(16)));
typedef short s128 __attribute__((vector_size(16)));
typedef char c256 __attribute__((vector_size(32)));
d128 d;
f128 f;
s128 s;
c256 c;
void test1 (double x)
{
d = (d128){x + x, x + x};
d = (d128){x + x, x + x};
}
void test2 (float x)
{
f = (f128){x + x, x + x, x + x, x + x};
f = (f128){x + x, x + x, x + x, x + x};
}
void test3 (short x)
{
s = (s128){x + x, x + x, x + x, x + x, x + x, x + x, x + x, x + x};
s = (s128){x + x, x + x, x + x, x + x, x + x, x + x, x + x, x + x};
}
void test4 (unsigned char x)
{
c = (c256){x + x, x + x, x + x, x + x, x + x, x + x, x + x, x + x,
x + x, x + x, x + x, x + x, x + x, x + x, x + x, x + x,
x + x, x + x, x + x, x + x, x + x, x + x, x + x, x + x,
x + x, x + x, x + x, x + x, x + x, x + x, x + x, x + x};
c = (c256){x + x, x + x, x + x, x + x, x + x, x + x, x + x, x + x,
x + x, x + x, x + x, x + x, x + x, x + x, x + x, x + x,
x + x, x + x, x + x, x + x, x + x, x + x, x + x, x + x,
x + x, x + x, x + x, x + x, x + x, x + x, x + x, x + x};
}
/* { dg-final { scan-tree-dump-times "Replaced \{" 4 "fre1" } } */
/* { dg-final { scan-tree-dump-times "Deleted redundant store" 4 "fre1" } } */
|
the_stack_data/92326119.c | // Test instrumentation of general constructs in C.
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-general.c %s -o - -emit-llvm -fprofile-instr-generate | FileCheck -check-prefix=PGOGEN %s
// RUN: llvm-profdata merge %S/Inputs/c-general.proftext -o %t.profdata
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-general.c %s -o - -emit-llvm -fprofile-instr-use=%t.profdata | FileCheck -check-prefix=PGOUSE %s
// PGOGEN: @[[SLC:__llvm_profile_counters_simple_loops]] = hidden global [4 x i64] zeroinitializer
// PGOGEN: @[[IFC:__llvm_profile_counters_conditionals]] = hidden global [11 x i64] zeroinitializer
// PGOGEN: @[[EEC:__llvm_profile_counters_early_exits]] = hidden global [9 x i64] zeroinitializer
// PGOGEN: @[[JMC:__llvm_profile_counters_jumps]] = hidden global [22 x i64] zeroinitializer
// PGOGEN: @[[SWC:__llvm_profile_counters_switches]] = hidden global [19 x i64] zeroinitializer
// PGOGEN: @[[BSC:__llvm_profile_counters_big_switch]] = hidden global [17 x i64] zeroinitializer
// PGOGEN: @[[BOC:__llvm_profile_counters_boolean_operators]] = hidden global [8 x i64] zeroinitializer
// PGOGEN: @[[BLC:__llvm_profile_counters_boolop_loops]] = hidden global [9 x i64] zeroinitializer
// PGOGEN: @[[COC:__llvm_profile_counters_conditional_operator]] = hidden global [3 x i64] zeroinitializer
// PGOGEN: @[[MAC:__llvm_profile_counters_main]] = hidden global [1 x i64] zeroinitializer
// PGOGEN: @[[STC:__llvm_profile_counters_static_func]] = internal global [2 x i64] zeroinitializer
// PGOGEN-LABEL: @simple_loops()
// PGOUSE-LABEL: @simple_loops()
// PGOGEN: store {{.*}} @[[SLC]], i64 0, i64 0
void simple_loops() {
int i;
// PGOGEN: store {{.*}} @[[SLC]], i64 0, i64 1
// PGOUSE: br {{.*}} !prof ![[SL1:[0-9]+]]
for (i = 0; i < 100; ++i) {
}
// PGOGEN: store {{.*}} @[[SLC]], i64 0, i64 2
// PGOUSE: br {{.*}} !prof ![[SL2:[0-9]+]]
while (i > 0)
i--;
// PGOGEN: store {{.*}} @[[SLC]], i64 0, i64 3
// PGOUSE: br {{.*}} !prof ![[SL3:[0-9]+]]
do {} while (i++ < 75);
// PGOGEN-NOT: store {{.*}} @[[SLC]],
// PGOUSE-NOT: br {{.*}} !prof ![0-9]+
}
// PGOGEN-LABEL: @conditionals()
// PGOUSE-LABEL: @conditionals()
// PGOGEN: store {{.*}} @[[IFC]], i64 0, i64 0
void conditionals() {
// PGOGEN: store {{.*}} @[[IFC]], i64 0, i64 1
// PGOUSE: br {{.*}} !prof ![[IF1:[0-9]+]]
for (int i = 0; i < 100; ++i) {
// PGOGEN: store {{.*}} @[[IFC]], i64 0, i64 2
// PGOUSE: br {{.*}} !prof ![[IF2:[0-9]+]]
if (i % 2) {
// PGOGEN: store {{.*}} @[[IFC]], i64 0, i64 3
// PGOUSE: br {{.*}} !prof ![[IF3:[0-9]+]]
if (i) {}
// PGOGEN: store {{.*}} @[[IFC]], i64 0, i64 4
// PGOUSE: br {{.*}} !prof ![[IF4:[0-9]+]]
} else if (i % 3) {
// PGOGEN: store {{.*}} @[[IFC]], i64 0, i64 5
// PGOUSE: br {{.*}} !prof ![[IF5:[0-9]+]]
if (i) {}
} else {
// PGOGEN: store {{.*}} @[[IFC]], i64 0, i64 6
// PGOUSE: br {{.*}} !prof ![[IF6:[0-9]+]]
if (i) {}
}
// PGOGEN: store {{.*}} @[[IFC]], i64 0, i64 8
// PGOGEN: store {{.*}} @[[IFC]], i64 0, i64 7
// PGOUSE: br {{.*}} !prof ![[IF7:[0-9]+]]
if (1 && i) {}
// PGOGEN: store {{.*}} @[[IFC]], i64 0, i64 10
// PGOGEN: store {{.*}} @[[IFC]], i64 0, i64 9
// PGOUSE: br {{.*}} !prof ![[IF8:[0-9]+]]
if (0 || i) {}
}
// PGOGEN-NOT: store {{.*}} @[[IFC]],
// PGOUSE-NOT: br {{.*}} !prof ![0-9]+
}
// PGOGEN-LABEL: @early_exits()
// PGOUSE-LABEL: @early_exits()
// PGOGEN: store {{.*}} @[[EEC]], i64 0, i64 0
void early_exits() {
int i = 0;
// PGOGEN: store {{.*}} @[[EEC]], i64 0, i64 1
// PGOUSE: br {{.*}} !prof ![[EE1:[0-9]+]]
if (i) {}
// PGOGEN: store {{.*}} @[[EEC]], i64 0, i64 2
// PGOUSE: br {{.*}} !prof ![[EE2:[0-9]+]]
while (i < 100) {
i++;
// PGOGEN: store {{.*}} @[[EEC]], i64 0, i64 3
// PGOUSE: br {{.*}} !prof ![[EE3:[0-9]+]]
if (i > 50)
break;
// PGOGEN: store {{.*}} @[[EEC]], i64 0, i64 4
// PGOUSE: br {{.*}} !prof ![[EE4:[0-9]+]]
if (i % 2)
continue;
}
// PGOGEN: store {{.*}} @[[EEC]], i64 0, i64 5
// PGOUSE: br {{.*}} !prof ![[EE5:[0-9]+]]
if (i) {}
// PGOGEN: store {{.*}} @[[EEC]], i64 0, i64 6
do {
// PGOGEN: store {{.*}} @[[EEC]], i64 0, i64 7
// PGOUSE: br {{.*}} !prof ![[EE6:[0-9]+]]
if (i > 75)
return;
else
i++;
// PGOUSE: br {{.*}} !prof ![[EE7:[0-9]+]]
} while (i < 100);
// PGOGEN: store {{.*}} @[[EEC]], i64 0, i64 8
// Never reached -> no weights
if (i) {}
// PGOGEN-NOT: store {{.*}} @[[EEC]],
// PGOUSE-NOT: br {{.*}} !prof ![0-9]+
}
// PGOGEN-LABEL: @jumps()
// PGOUSE-LABEL: @jumps()
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 0
void jumps() {
int i;
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 1
// PGOUSE: br {{.*}} !prof ![[JM1:[0-9]+]]
for (i = 0; i < 2; ++i) {
goto outofloop;
// Never reached -> no weights
if (i) {}
}
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 3
outofloop:
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 4
// PGOUSE: br {{.*}} !prof ![[JM2:[0-9]+]]
if (i) {}
goto loop1;
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 5
// PGOUSE: br {{.*}} !prof ![[JM3:[0-9]+]]
while (i) {
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 6
loop1:
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 7
// PGOUSE: br {{.*}} !prof ![[JM4:[0-9]+]]
if (i) {}
}
goto loop2;
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 8
first:
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 9
second:
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 10
third:
i++;
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 11
// PGOUSE: br {{.*}} !prof ![[JM5:[0-9]+]]
if (i < 3)
goto loop2;
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 12
// PGOUSE: br {{.*}} !prof ![[JM6:[0-9]+]]
while (i < 3) {
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 13
loop2:
// PGOUSE: switch {{.*}} [
// PGOUSE: ], !prof ![[JM7:[0-9]+]]
switch (i) {
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 15
case 0:
goto first;
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 16
case 1:
goto second;
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 17
case 2:
goto third;
}
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 14
}
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 18
// PGOUSE: br {{.*}} !prof ![[JM8:[0-9]+]]
for (i = 0; i < 10; ++i) {
goto withinloop;
// never reached -> no weights
if (i) {}
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 20
withinloop:
// PGOGEN: store {{.*}} @[[JMC]], i64 0, i64 21
// PGOUSE: br {{.*}} !prof ![[JM9:[0-9]+]]
if (i) {}
}
// PGOGEN-NOT: store {{.*}} @[[JMC]],
// PGOUSE-NOT: br {{.*}} !prof ![0-9]+
}
// PGOGEN-LABEL: @switches()
// PGOUSE-LABEL: @switches()
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 0
void switches() {
static int weights[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5};
// No cases -> no weights
switch (weights[0]) {
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 2
default:
break;
}
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 1
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 3
// PGOUSE: br {{.*}} !prof ![[SW1:[0-9]+]]
for (int i = 0, len = sizeof(weights) / sizeof(weights[0]); i < len; ++i) {
// PGOUSE: switch {{.*}} [
// PGOUSE: ], !prof ![[SW2:[0-9]+]]
switch (i[weights]) {
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 5
case 1:
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 6
// PGOUSE: br {{.*}} !prof ![[SW3:[0-9]+]]
if (i) {}
// fallthrough
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 7
case 2:
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 8
// PGOUSE: br {{.*}} !prof ![[SW4:[0-9]+]]
if (i) {}
break;
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 9
case 3:
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 10
// PGOUSE: br {{.*}} !prof ![[SW5:[0-9]+]]
if (i) {}
continue;
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 11
case 4:
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 12
// PGOUSE: br {{.*}} !prof ![[SW6:[0-9]+]]
if (i) {}
// PGOUSE: switch {{.*}} [
// PGOUSE: ], !prof ![[SW7:[0-9]+]]
switch (i) {
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 14
case 6 ... 9:
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 15
// PGOUSE: br {{.*}} !prof ![[SW8:[0-9]+]]
if (i) {}
continue;
}
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 13
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 16
default:
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 17
// PGOUSE: br {{.*}} !prof ![[SW9:[0-9]+]]
if (i == len - 1)
return;
}
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 4
}
// PGOGEN: store {{.*}} @[[SWC]], i64 0, i64 18
// Never reached -> no weights
if (weights[0]) {}
// PGOGEN-NOT: store {{.*}} @[[SWC]],
// PGOUSE-NOT: br {{.*}} !prof ![0-9]+
}
// PGOGEN-LABEL: @big_switch()
// PGOUSE-LABEL: @big_switch()
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 0
void big_switch() {
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 1
// PGOUSE: br {{.*}} !prof ![[BS1:[0-9]+]]
for (int i = 0; i < 32; ++i) {
// PGOUSE: switch {{.*}} [
// PGOUSE: ], !prof ![[BS2:[0-9]+]]
switch (1 << i) {
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 3
case (1 << 0):
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 4
// PGOUSE: br {{.*}} !prof ![[BS3:[0-9]+]]
if (i) {}
// fallthrough
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 5
case (1 << 1):
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 6
// PGOUSE: br {{.*}} !prof ![[BS4:[0-9]+]]
if (i) {}
break;
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 7
case (1 << 2) ... (1 << 12):
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 8
// PGOUSE: br {{.*}} !prof ![[BS5:[0-9]+]]
if (i) {}
break;
// The branch for the large case range above appears after the case body
// PGOUSE: br {{.*}} !prof ![[BS6:[0-9]+]]
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 9
case (1 << 13):
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 10
// PGOUSE: br {{.*}} !prof ![[BS7:[0-9]+]]
if (i) {}
break;
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 11
case (1 << 14) ... (1 << 28):
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 12
// PGOUSE: br {{.*}} !prof ![[BS8:[0-9]+]]
if (i) {}
break;
// The branch for the large case range above appears after the case body
// PGOUSE: br {{.*}} !prof ![[BS9:[0-9]+]]
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 13
case (1 << 29) ... ((1 << 29) + 1):
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 14
// PGOUSE: br {{.*}} !prof ![[BS10:[0-9]+]]
if (i) {}
break;
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 15
default:
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 16
// PGOUSE: br {{.*}} !prof ![[BS11:[0-9]+]]
if (i) {}
break;
}
// PGOGEN: store {{.*}} @[[BSC]], i64 0, i64 2
}
// PGOGEN-NOT: store {{.*}} @[[BSC]],
// PGOUSE-NOT: br {{.*}} !prof ![0-9]+
// PGOUSE: ret void
}
// PGOGEN-LABEL: @boolean_operators()
// PGOUSE-LABEL: @boolean_operators()
// PGOGEN: store {{.*}} @[[BOC]], i64 0, i64 0
void boolean_operators() {
int v;
// PGOGEN: store {{.*}} @[[BOC]], i64 0, i64 1
// PGOUSE: br {{.*}} !prof ![[BO1:[0-9]+]]
for (int i = 0; i < 100; ++i) {
// PGOGEN: store {{.*}} @[[BOC]], i64 0, i64 2
// PGOUSE: br {{.*}} !prof ![[BO2:[0-9]+]]
v = i % 3 || i;
// PGOGEN: store {{.*}} @[[BOC]], i64 0, i64 3
// PGOUSE: br {{.*}} !prof ![[BO3:[0-9]+]]
v = i % 3 && i;
// PGOGEN: store {{.*}} @[[BOC]], i64 0, i64 5
// PGOGEN: store {{.*}} @[[BOC]], i64 0, i64 4
// PGOUSE: br {{.*}} !prof ![[BO4:[0-9]+]]
// PGOUSE: br {{.*}} !prof ![[BO5:[0-9]+]]
v = i % 3 || i % 2 || i;
// PGOGEN: store {{.*}} @[[BOC]], i64 0, i64 7
// PGOGEN: store {{.*}} @[[BOC]], i64 0, i64 6
// PGOUSE: br {{.*}} !prof ![[BO6:[0-9]+]]
// PGOUSE: br {{.*}} !prof ![[BO7:[0-9]+]]
v = i % 2 && i % 3 && i;
}
// PGOGEN-NOT: store {{.*}} @[[BOC]],
// PGOUSE-NOT: br {{.*}} !prof ![0-9]+
}
// PGOGEN-LABEL: @boolop_loops()
// PGOUSE-LABEL: @boolop_loops()
// PGOGEN: store {{.*}} @[[BLC]], i64 0, i64 0
void boolop_loops() {
int i = 100;
// PGOGEN: store {{.*}} @[[BLC]], i64 0, i64 2
// PGOGEN: store {{.*}} @[[BLC]], i64 0, i64 1
// PGOUSE: br {{.*}} !prof ![[BL1:[0-9]+]]
// PGOUSE: br {{.*}} !prof ![[BL2:[0-9]+]]
while (i && i > 50)
i--;
// PGOGEN: store {{.*}} @[[BLC]], i64 0, i64 4
// PGOGEN: store {{.*}} @[[BLC]], i64 0, i64 3
// PGOUSE: br {{.*}} !prof ![[BL3:[0-9]+]]
// PGOUSE: br {{.*}} !prof ![[BL4:[0-9]+]]
while ((i % 2) || (i > 0))
i--;
// PGOGEN: store {{.*}} @[[BLC]], i64 0, i64 6
// PGOGEN: store {{.*}} @[[BLC]], i64 0, i64 5
// PGOUSE: br {{.*}} !prof ![[BL5:[0-9]+]]
// PGOUSE: br {{.*}} !prof ![[BL6:[0-9]+]]
for (i = 100; i && i > 50; --i);
// PGOGEN: store {{.*}} @[[BLC]], i64 0, i64 8
// PGOGEN: store {{.*}} @[[BLC]], i64 0, i64 7
// PGOUSE: br {{.*}} !prof ![[BL7:[0-9]+]]
// PGOUSE: br {{.*}} !prof ![[BL8:[0-9]+]]
for (; (i % 2) || (i > 0); --i);
// PGOGEN-NOT: store {{.*}} @[[BLC]],
// PGOUSE-NOT: br {{.*}} !prof ![0-9]+
}
// PGOGEN-LABEL: @conditional_operator()
// PGOUSE-LABEL: @conditional_operator()
// PGOGEN: store {{.*}} @[[COC]], i64 0, i64 0
void conditional_operator() {
int i = 100;
// PGOGEN: store {{.*}} @[[COC]], i64 0, i64 1
// PGOUSE: br {{.*}} !prof ![[CO1:[0-9]+]]
int j = i < 50 ? i : 1;
// PGOGEN: store {{.*}} @[[COC]], i64 0, i64 2
// PGOUSE: br {{.*}} !prof ![[CO2:[0-9]+]]
int k = i ?: 0;
// PGOGEN-NOT: store {{.*}} @[[COC]],
// PGOUSE-NOT: br {{.*}} !prof ![0-9]+
}
void do_fallthrough() {
for (int i = 0; i < 10; ++i) {
int j = 0;
do {
// The number of exits out of this do-loop via the break statement
// exceeds the counter value for the loop (which does not include the
// fallthrough count). Make sure that does not violate any assertions.
if (i < 8) break;
j++;
} while (j < 2);
}
}
// PGOGEN-LABEL: @static_func()
// PGOUSE-LABEL: @static_func()
// PGOGEN: store {{.*}} @[[STC]], i64 0, i64 0
static void static_func() {
// PGOGEN: store {{.*}} @[[STC]], i64 0, i64 1
// PGOUSE: br {{.*}} !prof ![[ST1:[0-9]+]]
for (int i = 0; i < 10; ++i) {
}
}
// PGOUSE-DAG: ![[SL1]] = metadata !{metadata !"branch_weights", i32 101, i32 2}
// PGOUSE-DAG: ![[SL2]] = metadata !{metadata !"branch_weights", i32 101, i32 2}
// PGOUSE-DAG: ![[SL3]] = metadata !{metadata !"branch_weights", i32 76, i32 2}
// PGOUSE-DAG: ![[EE1]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
// PGOUSE-DAG: ![[EE2]] = metadata !{metadata !"branch_weights", i32 52, i32 1}
// PGOUSE-DAG: ![[EE3]] = metadata !{metadata !"branch_weights", i32 2, i32 51}
// PGOUSE-DAG: ![[EE4]] = metadata !{metadata !"branch_weights", i32 26, i32 26}
// PGOUSE-DAG: ![[EE5]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
// PGOUSE-DAG: ![[EE6]] = metadata !{metadata !"branch_weights", i32 2, i32 26}
// PGOUSE-DAG: ![[EE7]] = metadata !{metadata !"branch_weights", i32 26, i32 1}
// PGOUSE-DAG: ![[IF1]] = metadata !{metadata !"branch_weights", i32 101, i32 2}
// PGOUSE-DAG: ![[IF2]] = metadata !{metadata !"branch_weights", i32 51, i32 51}
// PGOUSE-DAG: ![[IF3]] = metadata !{metadata !"branch_weights", i32 51, i32 1}
// PGOUSE-DAG: ![[IF4]] = metadata !{metadata !"branch_weights", i32 34, i32 18}
// PGOUSE-DAG: ![[IF5]] = metadata !{metadata !"branch_weights", i32 34, i32 1}
// PGOUSE-DAG: ![[IF6]] = metadata !{metadata !"branch_weights", i32 17, i32 2}
// PGOUSE-DAG: ![[IF7]] = metadata !{metadata !"branch_weights", i32 100, i32 2}
// PGOUSE-DAG: ![[IF8]] = metadata !{metadata !"branch_weights", i32 100, i32 2}
// PGOUSE-DAG: ![[JM1]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
// PGOUSE-DAG: ![[JM2]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
// PGOUSE-DAG: ![[JM3]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
// PGOUSE-DAG: ![[JM4]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
// PGOUSE-DAG: ![[JM5]] = metadata !{metadata !"branch_weights", i32 3, i32 2}
// PGOUSE-DAG: ![[JM6]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
// PGOUSE-DAG: ![[JM7]] = metadata !{metadata !"branch_weights", i32 1, i32 2, i32 2, i32 2}
// PGOUSE-DAG: ![[JM8]] = metadata !{metadata !"branch_weights", i32 11, i32 2}
// PGOUSE-DAG: ![[JM9]] = metadata !{metadata !"branch_weights", i32 10, i32 2}
// PGOUSE-DAG: ![[SW1]] = metadata !{metadata !"branch_weights", i32 16, i32 1}
// PGOUSE-DAG: ![[SW2]] = metadata !{metadata !"branch_weights", i32 6, i32 2, i32 3, i32 4, i32 5}
// PGOUSE-DAG: ![[SW3]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
// PGOUSE-DAG: ![[SW4]] = metadata !{metadata !"branch_weights", i32 3, i32 2}
// PGOUSE-DAG: ![[SW5]] = metadata !{metadata !"branch_weights", i32 4, i32 1}
// PGOUSE-DAG: ![[SW6]] = metadata !{metadata !"branch_weights", i32 5, i32 1}
// PGOUSE-DAG: ![[SW7]] = metadata !{metadata !"branch_weights", i32 1, i32 2, i32 2, i32 2, i32 2}
// PGOUSE-DAG: ![[SW8]] = metadata !{metadata !"branch_weights", i32 5, i32 1}
// PGOUSE-DAG: ![[SW9]] = metadata !{metadata !"branch_weights", i32 2, i32 5}
// PGOUSE-DAG: ![[BS1]] = metadata !{metadata !"branch_weights", i32 33, i32 2}
// PGOUSE-DAG: ![[BS2]] = metadata !{metadata !"branch_weights", i32 29, i32 2, i32 2, i32 2, i32 2, i32 1}
// PGOUSE-DAG: ![[BS3]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
// PGOUSE-DAG: ![[BS4]] = metadata !{metadata !"branch_weights", i32 2, i32 2}
// PGOUSE-DAG: ![[BS5]] = metadata !{metadata !"branch_weights", i32 12, i32 1}
// PGOUSE-DAG: ![[BS6]] = metadata !{metadata !"branch_weights", i32 12, i32 3}
// PGOUSE-DAG: ![[BS7]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
// PGOUSE-DAG: ![[BS8]] = metadata !{metadata !"branch_weights", i32 16, i32 1}
// PGOUSE-DAG: ![[BS9]] = metadata !{metadata !"branch_weights", i32 16, i32 14}
// PGOUSE-DAG: ![[BS10]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
// PGOUSE-DAG: ![[BS11]] = metadata !{metadata !"branch_weights", i32 3, i32 1}
// PGOUSE-DAG: ![[BO1]] = metadata !{metadata !"branch_weights", i32 101, i32 2}
// PGOUSE-DAG: ![[BO2]] = metadata !{metadata !"branch_weights", i32 67, i32 35}
// PGOUSE-DAG: ![[BO3]] = metadata !{metadata !"branch_weights", i32 67, i32 35}
// PGOUSE-DAG: ![[BO4]] = metadata !{metadata !"branch_weights", i32 67, i32 35}
// PGOUSE-DAG: ![[BO5]] = metadata !{metadata !"branch_weights", i32 18, i32 18}
// PGOUSE-DAG: ![[BO6]] = metadata !{metadata !"branch_weights", i32 51, i32 51}
// PGOUSE-DAG: ![[BO7]] = metadata !{metadata !"branch_weights", i32 34, i32 18}
// PGOUSE-DAG: ![[BL1]] = metadata !{metadata !"branch_weights", i32 52, i32 1}
// PGOUSE-DAG: ![[BL2]] = metadata !{metadata !"branch_weights", i32 51, i32 2}
// PGOUSE-DAG: ![[BL3]] = metadata !{metadata !"branch_weights", i32 26, i32 27}
// PGOUSE-DAG: ![[BL4]] = metadata !{metadata !"branch_weights", i32 51, i32 2}
// PGOUSE-DAG: ![[BL5]] = metadata !{metadata !"branch_weights", i32 52, i32 1}
// PGOUSE-DAG: ![[BL6]] = metadata !{metadata !"branch_weights", i32 51, i32 2}
// PGOUSE-DAG: ![[BL7]] = metadata !{metadata !"branch_weights", i32 26, i32 27}
// PGOUSE-DAG: ![[BL8]] = metadata !{metadata !"branch_weights", i32 51, i32 2}
// PGOUSE-DAG: ![[CO1]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
// PGOUSE-DAG: ![[CO2]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
// PGOUSE-DAG: ![[ST1]] = metadata !{metadata !"branch_weights", i32 11, i32 2}
int main(int argc, const char *argv[]) {
simple_loops();
conditionals();
early_exits();
jumps();
switches();
big_switch();
boolean_operators();
boolop_loops();
conditional_operator();
do_fallthrough();
static_func();
return 0;
}
|
the_stack_data/51700647.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* The size of a BLOCK in characters. Suggested 16384. Should try 2^16=65536 */
#define ONE_BLOCK_SIZE 65536
/* The main stack is a double-chain of DoubleChainedBlock objects.
* Each DoubleChainedBlock holds an array[ONE_BLOCK_SIZE] of char. */
typedef struct _DoubleChainedBlock{
unsigned int rank ;
struct _DoubleChainedBlock *prev ;
char *contents ;
struct _DoubleChainedBlock *next ;
} DoubleChainedBlock ;
char initContents[ONE_BLOCK_SIZE] = {'\0'} ;
DoubleChainedBlock initBlock = {0,NULL,initContents,NULL} ;
static DoubleChainedBlock *curStack = &initBlock ;
static char *curStackTop = initContents ;
static unsigned long int maintraffic = 0 ;
void setCurLocation(unsigned long int location) {
unsigned int targetRank = (unsigned int)location/ONE_BLOCK_SIZE ;
unsigned int targetOffset = (unsigned int)location%ONE_BLOCK_SIZE ;
if (targetRank>curStack->rank)
while (targetRank>curStack->rank) curStack = curStack->next ;
else if (targetRank<curStack->rank)
while (targetRank<curStack->rank) curStack = curStack->prev ;
curStackTop = curStack->contents + targetOffset ;
}
unsigned long int getCurLocation() {
return (curStackTop-curStack->contents)+curStack->rank*ONE_BLOCK_SIZE ;
}
void showLocation(unsigned long int location) {
printf("%1i.%05i", (unsigned int)location/ONE_BLOCK_SIZE, (unsigned int)location%ONE_BLOCK_SIZE) ;
}
/*************** REPEATED ACCESS MECHANISM *********************/
typedef struct _StackRepeatCell {
int hasBackPop ;
unsigned long int backPop ;
unsigned long int resume ;
unsigned long int freePush ;
struct _StackRepeatCell *previous ;
} StackRepeatCell ;
StackRepeatCell *stackRepeatTop = NULL ;
void showStackRepeatsRec(StackRepeatCell *inRepeatStack) {
if (inRepeatStack->previous) {showStackRepeatsRec(inRepeatStack->previous) ; printf(" ; ") ;}
printf("<") ;
if (inRepeatStack->hasBackPop) showLocation(inRepeatStack->backPop) ;
printf("|") ;
showLocation(inRepeatStack->resume) ;
printf("|") ;
showLocation(inRepeatStack->freePush) ;
printf(">") ;
}
void showStackRepeats() {
showStackRepeatsRec(stackRepeatTop) ;
}
void showStack() {
DoubleChainedBlock *inStack = &initBlock ;
int i ;
while (inStack) {
printf("[%1i] ",inStack->rank) ;
for (i=0 ; i<ONE_BLOCK_SIZE ; ++i) {
if (i!=0 && i%4==0) printf(".") ;
if (inStack==curStack && &(inStack->contents[i])==curStackTop) printf(" | ") ;
printf("%02x",(unsigned char)inStack->contents[i]) ;
}
inStack = inStack->next ;
if (inStack) printf("\n ") ;
}
printf("\n REPEATS:") ;
if (stackRepeatTop)
showStackRepeats() ;
else
printf(" none!") ;
printf("\n") ;
}
void showStackSize(int i4i, int i8i, int r4i, int r8i, int c8i, int c16i, int s1i, int biti, int ptri) {
printf(" --> <") ;
showLocation(getCurLocation()) ;
printf(">%1i.%1i.%1i.%1i.%1i.%1i.%1i.%1i.%1i\n",i4i, i8i, r4i, r8i, c8i, c16i, s1i, biti, ptri) ;
}
void adStack_showPeakSize() {
DoubleChainedBlock *inStack = &initBlock ;
int i = 0 ;
while (inStack) {
inStack = inStack->next ;
++i ;
}
printf("Peak stack size (%1i blocks): %1llu bytes\n",
i, ((long long int)i)*((long long int)ONE_BLOCK_SIZE)) ;
}
void showTotalTraffic(unsigned long long int localtraffic) {
printf("Total pushed traffic %1llu bytes\n", maintraffic+localtraffic) ;
}
/** If we are in a protected, read-only section, memorize location as "backPop"
* and go to the "freePush" location */
void checkPushInReadOnly() {
if (stackRepeatTop) {
unsigned long int current = getCurLocation() ;
if (current<stackRepeatTop->freePush) {
stackRepeatTop->hasBackPop = 1 ;
stackRepeatTop->backPop = current ;
setCurLocation(stackRepeatTop->freePush) ;
/* printf(" FREEPUSH(") ; //Trace */
/* showLocation(stackRepeatTop->backPop) ; //Trace */
/* printf("=>") ; //Trace */
/* showLocation(stackRepeatTop->freePush) ; //Trace */
/* printf(")") ; //Trace */
}
}
}
/** If current location is the "freePush" location,
* go back to its "backPop" location, which is in a protected, read-only section */
void checkPopToReadOnly() {
if (stackRepeatTop && stackRepeatTop->hasBackPop) {
unsigned long int current = getCurLocation() ;
if (current==stackRepeatTop->freePush) {
setCurLocation(stackRepeatTop->backPop) ;
stackRepeatTop->hasBackPop = 0 ;
/* printf(" BACKPOP(") ; //Trace */
/* showLocation(stackRepeatTop->freePush) ; //Trace */
/* printf("=>") ; //Trace */
/* showLocation(stackRepeatTop->backPop) ; //Trace */
/* printf(")") ; //Trace */
}
}
}
// A global for communication from startStackRepeat1() to startStackRepeat2():
StackRepeatCell *newRepeatCell = NULL ;
void startStackRepeat1() {
// Create (push) a new "stack" repeat level:
newRepeatCell = (StackRepeatCell *)malloc(sizeof(StackRepeatCell)) ;
newRepeatCell->previous = stackRepeatTop ;
newRepeatCell->hasBackPop = 0 ;
// Store current location as the "resume" location:
unsigned long int current = getCurLocation() ;
newRepeatCell->resume = current ;
// Move to the "freePush" location if there is one:
if (stackRepeatTop && current<stackRepeatTop->freePush)
setCurLocation(stackRepeatTop->freePush) ;
}
void startStackRepeat2() {
// Store current stack location as the "freePush" location:
newRepeatCell->freePush = getCurLocation() ;
// Reset current location to stored "resume" location:
setCurLocation(newRepeatCell->resume) ;
// Make this new repeat level the current repeat level:
stackRepeatTop = newRepeatCell ;
/* printf("\n+Rep ") ; showStackRepeats() ; printf("\n") ; //Trace */
}
void resetStackRepeat1() {
/* printf("\n>Rep ") ; showStackRepeats() ; printf("\n") ; //Trace */
// If we are in a nested checkpoint, force exit from it:
if (stackRepeatTop->hasBackPop) {
//setCurLocation(stackRepeatTop->backPop) ; //correct but useless code
stackRepeatTop->hasBackPop = 0 ;
}
// Go to repeat location of current repeat level
setCurLocation(stackRepeatTop->freePush) ;
}
void resetStackRepeat2() {
// Reset current location to "ResumeLocation":
setCurLocation(stackRepeatTop->resume) ;
}
void endStackRepeat() {
/* printf("\n-Rep ") ; showStackRepeats() ; printf("\n") ; //Trace */
// If we are in a nested checkpoint, go back to its "backPop" (read-only) location:
if (stackRepeatTop->hasBackPop) {
setCurLocation(stackRepeatTop->backPop) ;
//stackRepeatTop->hasBackPop = 0 ; //correct but useless code
}
// Remove (pop) top "stack" repeat level:
StackRepeatCell *oldRepeatCell = stackRepeatTop ;
stackRepeatTop = stackRepeatTop->previous ;
free(oldRepeatCell) ;
// current location may have moved back ; check if we must move further back:
checkPopToReadOnly() ;
}
/******************* PUSH/POP MECHANISM *******************/
/* PUSHes "nbChars" consecutive chars from a location starting at address "x".
* Checks that there is enough space left to hold "nbChars" chars.
* Otherwise, allocates the necessary space. */
void pushNArray(char *x, unsigned int nbChars, int checkReadOnly) {
if (checkReadOnly) checkPushInReadOnly() ;
if (checkReadOnly) maintraffic += nbChars ;
/* unsigned long int lfrom = getCurLocation() ; //Trace */
unsigned int nbmax = ONE_BLOCK_SIZE-(curStackTop-(curStack->contents)) ;
if (nbChars <= nbmax) {
memcpy(curStackTop,x,nbChars) ;
curStackTop+=nbChars ;
} else {
char *inx = x+(nbChars-nbmax) ;
if (nbmax>0) memcpy(curStackTop,inx,nbmax) ;
while (inx>x) {
if (curStack->next)
curStack = curStack->next ;
else {
/* Create new block: */
DoubleChainedBlock *newStack ;
char *contents = (char *)malloc(ONE_BLOCK_SIZE*sizeof(char)) ;
newStack = (DoubleChainedBlock*)malloc(sizeof(DoubleChainedBlock)) ;
if ((contents == NULL) || (newStack == NULL)) {
DoubleChainedBlock *stack = curStack ;
int nbBlocks = (stack?-1:0) ;
while(stack) {
stack = stack->prev ;
nbBlocks++ ;
}
printf("Out of memory (allocated %i blocks of %i bytes)\n",
nbBlocks, ONE_BLOCK_SIZE) ;
exit(0);
}
curStack->next = newStack ;
newStack->prev = curStack ;
newStack->rank = curStack->rank + 1 ;
newStack->next = NULL ;
newStack->contents = contents ;
curStack = newStack ;
/* new block created! */
}
inx -= ONE_BLOCK_SIZE ;
if(inx>x)
memcpy(curStack->contents,inx,ONE_BLOCK_SIZE) ;
else {
unsigned int nbhead = (inx-x)+ONE_BLOCK_SIZE ;
curStackTop = curStack->contents ;
memcpy(curStackTop,x,nbhead) ;
curStackTop += nbhead ;
}
}
}
/* unsigned long int lto = getCurLocation() ; //Trace */
/* printf("pushNArray(") ; //Trace */
/* showLocation(lfrom) ; //Trace */
/* printf("=>") ; //Trace */
/* showLocation(lto) ; //Trace */
/* printf(")") ; //Trace */
}
/* POPs "nbChars" consecutive chars to a location starting at address "x".
* Checks that there is enough data to fill "nbChars" chars.
* Otherwise, pops as many blocks as necessary. */
void popNArray(char *x, unsigned int nbChars, int checkReadOnly) {
/* unsigned long int lfrom = getCurLocation() ; //Trace */
unsigned int nbmax = curStackTop-(curStack->contents) ;
if (nbChars <= nbmax) {
curStackTop-=nbChars ;
memcpy(x,curStackTop,nbChars);
} else {
char *tlx = x+nbChars ;
if (nbmax>0) memcpy(x,curStack->contents,nbmax) ;
x+=nbmax ;
while (x<tlx) {
curStack = curStack->prev ;
if (curStack==NULL) printf("Popping from an empty stack!!!\n") ;
if (x+ONE_BLOCK_SIZE<tlx) {
memcpy(x,curStack->contents,ONE_BLOCK_SIZE) ;
x += ONE_BLOCK_SIZE ;
} else {
unsigned int nbtail = tlx-x ;
curStackTop = (curStack->contents)+ONE_BLOCK_SIZE-nbtail ;
memcpy(x,curStackTop,nbtail) ;
x = tlx ;
}
}
}
/* unsigned long int lto = getCurLocation() ; //Trace */
/* printf("popNArray(") ; //Trace */
/* showLocation(lfrom) ; //Trace */
/* printf("=>") ; //Trace */
/* showLocation(lto) ; //Trace */
/* printf(")") ; //Trace */
if (checkReadOnly) checkPopToReadOnly() ;
}
typedef struct {float r,i;} ccmplx ;
typedef struct {double dr, di;} cdcmplx ;
void pushInteger4Array(int *x, int n) {
pushNArray((char *)x,(unsigned int)(n*4), 1) ;
}
void popInteger4Array(int *x, int n) {
popNArray((char *)x,(unsigned int)(n*4), 1) ;
}
void pushInteger8Array(long *x, int n) {
pushNArray((char *)x,(unsigned int)(n*8), 1) ;
}
void popInteger8Array(long *x, int n) {
popNArray((char *)x,(unsigned int)(n*8), 1) ;
}
void pushReal4Array(float *x, int n) {
pushNArray((char *)x,(unsigned int)(n*4), 1) ;
}
void popReal4Array(float *x, int n) {
popNArray((char *)x,(unsigned int)(n*4), 1) ;
}
void pushReal8Array(double *x, int n) {
pushNArray((char *)x,(unsigned int)(n*8), 1) ;
}
void popReal8Array(double *x, int n) {
popNArray((char *)x,(unsigned int)(n*8), 1) ;
}
void pushComplex8Array(ccmplx *x, int n) {
pushNArray((char *)x,(unsigned int)(n*8), 1) ;
}
void popComplex8Array(ccmplx *x, int n) {
popNArray((char *)x,(unsigned int)(n*8), 1) ;
}
void pushComplex16Array(cdcmplx *x, int n) {
pushNArray((char *)x,(unsigned int)(n*16), 1) ;
}
void popComplex16Array(cdcmplx *x, int n) {
popNArray((char *)x,(unsigned int)(n*16), 1) ;
}
void pushCharacterArray(char *x, int n) {
pushNArray(x,(unsigned int)n, 1) ;
}
void popCharacterArray(char *x, int n) {
popNArray(x,(unsigned int)n, 1) ;
}
/* ********* Useful only for testpushpop.f90. Should go away! ********* */
void showpushpopsequence_(int *op, int *index, int* nbobjects, int* sorts, int* sizes) {
char *prefix = "" ;
if (*op==1) prefix = "+" ;
else if (*op==-1) prefix = "-" ;
else if (*op==2) prefix = "+s" ;
else if (*op==-2) prefix = "-s" ;
else if (*op==-3) prefix = "Ls" ;
printf("%s%02i", prefix, *index) ;
// Comment the rest for compact display:
printf(":") ;
int i ;
for (i=0 ; i<*nbobjects ; ++i) {
switch (sorts[i]) {
case 1:
printf(" I4") ;
break ;
case 2:
printf(" I8") ;
break ;
case 3:
printf(" R4") ;
break ;
case 4:
printf(" R8") ;
break ;
case 5:
printf(" C8") ;
break ;
case 6:
printf(" C16") ;
break ;
case 7:
printf(" char") ;
break ;
case 8:
printf(" bit") ;
break ;
case 9:
printf(" PTR") ;
break ;
}
if (sizes[i]!=0) printf("[%1i]",sizes[i]) ;
}
}
/****************** INTERFACE CALLED FROM FORTRAN *******************/
void showstack_() {
showStack() ;
}
void showstacksize_(int *i4i, int *i8i, int *r4i, int *r8i, int *c8i, int *c16i, int *s1i, int *biti, int *ptri) {
showStackSize(*i4i,*i8i,*r4i,*r8i,*c8i,*c16i,*s1i,*biti,*ptri) ;
}
void adstack_showpeaksize_() {
adStack_showPeakSize() ;
}
void adstack_showpeaksize__() {
adStack_showPeakSize() ;
}
void showtotaltraffic_(unsigned long long int *traffic) {
showTotalTraffic(*traffic) ;
}
void startstackrepeat1_() {
startStackRepeat1() ;
}
void startstackrepeat2_() {
startStackRepeat2() ;
}
void resetstackrepeat1_() {
resetStackRepeat1() ;
}
void resetstackrepeat2_() {
resetStackRepeat2() ;
}
void endstackrepeat_() {
endStackRepeat() ;
}
void pushnarray_(char *x, unsigned int *nbChars, int *checkReadOnly) {
pushNArray(x, *nbChars, *checkReadOnly) ;
}
void popnarray_(char *x, unsigned int *nbChars, int *checkReadOnly) {
popNArray(x, *nbChars, *checkReadOnly) ;
}
void pushinteger4array_(int *ii, int *ll) {
pushInteger4Array(ii, *ll) ;
}
void popinteger4array_(int *ii, int *ll) {
popInteger4Array(ii, *ll) ;
}
void pushinteger8array_(long *ii, int *ll) {
pushInteger8Array(ii, *ll) ;
}
void popinteger8array_(long *ii, int *ll) {
popInteger8Array(ii, *ll) ;
}
void pushreal4array_(float *ii, int *ll) {
pushReal4Array(ii, *ll) ;
}
void popreal4array_(float *ii, int *ll) {
popReal4Array(ii, *ll) ;
}
void pushreal8array_(double *ii, int *ll) {
pushReal8Array(ii, *ll) ;
}
void popreal8array_(double *ii, int *ll) {
popReal8Array(ii, *ll) ;
}
void pushcomplex8array_(ccmplx *ii, int *ll) {
pushComplex8Array(ii, *ll) ;
}
void popcomplex8array_(ccmplx *ii, int *ll) {
popComplex8Array(ii, *ll) ;
}
void pushcomplex16array_(cdcmplx *ii, int *ll) {
pushComplex16Array(ii, *ll) ;
}
void popcomplex16array_(cdcmplx *ii, int *ll) {
popComplex16Array(ii, *ll) ;
}
void pushcharacterarray_(char *ii, int *ll) {
pushCharacterArray(ii, *ll) ;
}
void popcharacterarray_(char *ii, int *ll) {
popCharacterArray(ii, *ll) ;
}
void pushbooleanarray_(char *x, unsigned int *n) {
pushNArray(x,(*n*4), 1) ;
}
void popbooleanarray_(char *x, unsigned int *n) {
popNArray(x,(*n*4), 1) ;
}
|
the_stack_data/37638793.c | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
int main (int argc, char** argv) {
int k, i, j;
float result;
float *v, *v1, *v2;
float **mat;
/* Check arguments */
if (argc != 2) {
fprintf(stderr, "Wrong number of arguments. Syntax: %s k", argv[0]);
return -1;
}
k = atoi(argv[1]);
/* Memory allocation */
v = (float*) malloc(k*sizeof(float));
v1 = (float*) malloc(k*sizeof(float));
v2 = (float*) malloc(k*sizeof(float));
mat = (float**) malloc(k*sizeof(float*));
for (i=0; i<k; i++) {
mat[i] = (float*) malloc(k*sizeof(float));
}
/* Arrays and matrix filling */
srand(time(NULL)); // seeding rand()
fprintf(stdout, "v1:\n");
for (i=0; i<k; i++) {
v1[i] = ((float) (rand() % 100) / 100) - 0.5;
fprintf(stdout, "%f ", v1[i]);
}
fprintf(stdout, "\n");
fprintf(stdout, "v2:\n");
for (i=0; i<k; i++) {
v2[i] = ((float) (rand() % 100) / 100) - 0.5;
fprintf(stdout, "%f ", v2[i]);
}
fprintf(stdout, "\n");
fprintf(stdout, "matr:\n");
for (i=0; i<k; i++) {
for (j=0; j<k; j++) {
mat[i][j] = ((float) (rand() % 100) / 100) - 0.5;
fprintf(stdout, "%f ", mat[i][j]);
}
fprintf(stdout, "\n");
}
fprintf(stdout, "\n");
/* (v1T*mat*v2) is divided into two easier operations */
/* a) v = (mat*v2) */
for (i=0; i<k; i++) {
v[i] = 0;
for (j=0; j<k; j++) {
v[i] += mat[i][j]*v2[i];
}
}
/* b) result = (v1T*v) */
result = 0;
for (i=0; i<k; i++) {
result += v1[i]*v[i];
}
/* Print the result */
fprintf(stdout, "Result = %2f\n", result);
return 0;
}
|
the_stack_data/1052157.c | /* C program for Dijkstra's shortest path algorithm for adjacency
list representation of graph*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// A structure to represent a node in adjacency list
struct AdjListNode
{
int dest;
int weight;
struct AdjListNode* next;
};
// A structure to represent an adjacency list
struct AdjList
{
struct AdjListNode *head; // pointer to head node of list
};
// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
int V;
struct AdjList* array;
};
// A utility function to create a new adjacency list node
struct AdjListNode* newAdjListNode(int dest, int weight)
{
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->weight = weight;
newNode->next = NULL;
return newNode;
}
// A utility function that creates a graph of V vertices
struct Graph* createGraph(int V)
{
struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
graph->V = V;
// Create an array of adjacency lists. Size of array will be V
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
// Initialize each adjacency list as empty by making head as NULL
for (int i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}
// Adds an edge to an undirected graph
void addEdge(struct Graph* graph, int src, int dest, int weight)
{
// Add an edge from source(src) to destination(dest). A new node is added to the adjacency
// list of src. The node is added at the beginning
struct AdjListNode* newNode = newAdjListNode(dest, weight);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
// Since graph is undirected, add an edge from dest to src also
newNode = newAdjListNode(src, weight);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
// Structure to represent a min heap node
struct MinHeapNode
{
int v;
int dist;
};
// Structure to represent a min heap
struct MinHeap
{
int size; // Number of heap nodes present currently
int capacity; // Capacity of min heap
int *pos; // This is needed for decreaseKey()
struct MinHeapNode **array;
};
// A utility function to create a new Min Heap Node
struct MinHeapNode* newMinHeapNode(int v, int dist)
{
struct MinHeapNode* minHeapNode =
(struct MinHeapNode*) malloc(sizeof(struct MinHeapNode));
minHeapNode->v = v;
minHeapNode->dist = dist;
return minHeapNode;
}
// A utility function to create a Min Heap
struct MinHeap* createMinHeap(int capacity)
{
struct MinHeap* minHeap =
(struct MinHeap*) malloc(sizeof(struct MinHeap));
minHeap->pos = (int *)malloc(capacity * sizeof(int));
minHeap->size = 0;
minHeap->capacity = capacity;
minHeap->array =
(struct MinHeapNode**) malloc(capacity * sizeof(struct MinHeapNode*));
return minHeap;
}
// A utility function to swap two nodes of min heap. Needed for min heapify
void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b)
{
struct MinHeapNode* t = *a;
*a = *b;
*b = t;
}
// A standard function to heapify at given idx
// This function also updates position of nodes when they are swapped.
// Position is needed for decreaseKey()
void minHeapify(struct MinHeap* minHeap, int idx)
{
int smallest, left, right;
smallest = idx;
left = 2 * idx + 1;
right = 2 * idx + 2;
if (left < minHeap->size &&
minHeap->array[left]->dist < minHeap->array[smallest]->dist )
smallest = left;
if (right < minHeap->size &&
minHeap->array[right]->dist < minHeap->array[smallest]->dist )
smallest = right;
if (smallest != idx)
{
// The nodes to be swapped in min heap
struct MinHeapNode *smallestNode = minHeap->array[smallest];
struct MinHeapNode *idxNode = minHeap->array[idx];
// Swap positions
minHeap->pos[smallestNode->v] = idx;
minHeap->pos[idxNode->v] = smallest;
// Swap nodes
swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
// A utility function to check if the given minHeap is ampty or not
int isEmpty(struct MinHeap* minHeap)
{
return minHeap->size == 0;
}
// Standard function to extract minimum node from heap
struct MinHeapNode* extractMin(struct MinHeap* minHeap)
{
if (isEmpty(minHeap))
return NULL;
// Store the root node
struct MinHeapNode* root = minHeap->array[0];
// Replace root node with last node
struct MinHeapNode* lastNode = minHeap->array[minHeap->size - 1];
minHeap->array[0] = lastNode;
// Update position of last node
minHeap->pos[root->v] = minHeap->size-1;
minHeap->pos[lastNode->v] = 0;
// Reduce heap size and heapify root
--minHeap->size;
minHeapify(minHeap, 0);
return root;
}
// Function to decreasy dist value of a given vertex v. This function
// uses pos[] of min heap to get the current index of node in min heap
void decreaseKey(struct MinHeap* minHeap, int v, int dist)
{
// Get the index of v in heap array
int i = minHeap->pos[v];
// Get the node and update its dist value
minHeap->array[i]->dist = dist;
// Travel up while the complete tree is not hepified.
// This is a O(Logn) loop
while (i && minHeap->array[i]->dist < minHeap->array[(i - 1) / 2]->dist)
{
// Swap this node with its parent
minHeap->pos[minHeap->array[i]->v] = (i-1)/2;
minHeap->pos[minHeap->array[(i-1)/2]->v] = i;
swapMinHeapNode(&minHeap->array[i], &minHeap->array[(i - 1) / 2]);
// move to parent index
i = (i - 1) / 2;
}
}
// A utility function to check if a given vertex
// 'v' is in min heap or not
int isInMinHeap(struct MinHeap *minHeap, int v)
{
if (minHeap->pos[v] < minHeap->size)
return 1;
return 0;
}
// A utility function used to print the solution
void printArr(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < n; ++i)
printf("%d \t\t %d\n", i, dist[i]);
}
// The main function that calulates distances of shortest paths from src to all
// vertices. It is a O(ELogV) function
void dijkstra(struct Graph* graph, int src)
{
int V = graph->V;// Get the number of vertices in graph
int dist[V]; // dist values used to pick minimum weight edge in cut
// minHeap represents set E
struct MinHeap* minHeap = createMinHeap(V);
// Initialize min heap with all vertices. dist value of all vertices
for (int v = 0; v < V; ++v)
{
dist[v] = INT_MAX;
minHeap->array[v] = newMinHeapNode(v, dist[v]);
minHeap->pos[v] = v;
}
// Make dist value of src vertex as 0 so that it is extracted first
minHeap->array[src] = newMinHeapNode(src, dist[src]);
minHeap->pos[src] = src;
dist[src] = 0;
decreaseKey(minHeap, src, dist[src]);
// Initially size of min heap is equal to V
minHeap->size = V;
// In the followin loop, min heap contains all nodes
// whose shortest distance is not yet finalized.
while (!isEmpty(minHeap))
{
// Extract the vertex with minimum distance value
struct MinHeapNode* minHeapNode = extractMin(minHeap);
int u = minHeapNode->v; // Store the extracted vertex number
// Traverse through all adjacent vertices of u (the extracted
// vertex) and update their distance values
struct AdjListNode* pCrawl = graph->array[u].head;
while (pCrawl != NULL)
{
int v = pCrawl->dest;
// If shortest distance to v is not finalized yet, and distance to v
// through u is less than its previously calculated distance
if (isInMinHeap(minHeap, v) && dist[u] != INT_MAX &&
pCrawl->weight + dist[u] < dist[v])
{
dist[v] = dist[u] + pCrawl->weight;
// update distance value in min heap also
decreaseKey(minHeap, v, dist[v]);
}
pCrawl = pCrawl->next;
}
}
// print the calculated shortest distances
printArr(dist, V);
}
// Driver program to test above functions
int main()
{
// create the graph given in above fugure
printf("Enter number of vertices\n");
int V;
scanf("%d",&V);
int s,d,wt,c;
int e=0;
struct Graph* graph = createGraph(V);
do
{
e++;
printf("Enter src\n");
scanf("%d",&s);
printf("Enter dest\n");
scanf("%d",&d);
printf("Enter weight\n");
scanf("%d",&wt);
addEdge(graph,s,d,wt);
printf("Enter -1 to exit,any other number to continue\n");
scanf("%d",&c);
}while(c!=-1 && e<=(V)*(V-1)/2);
dijkstra(graph, 0);
return 0;
}
|
the_stack_data/50136968.c | #include <stdio.h>
#include <stdlib.h>
#define SIZE 64
#define T 64
typedef float float_t;
float_t tab[SIZE][SIZE];
void compute() {
int i, j;
for(i = 1;i < SIZE - 1; i++)
for(j = 1;j < SIZE - 1; j++) {
tab[i][j] = i*j;
}
}
int main(int argc, char *argv[]) {
int t;
for(t = 0; t < T; t++)
compute();
return 0;
}
|
the_stack_data/92327291.c | #include <stdio.h>
#include <string.h>
int main()
{
int jogos, mig = 0, rit = 0; char miguel[20], rita[20];
for (jogos = 0; jogos < 5; jogos ++)
{
scanf("%[^\n]", rita);
getchar();
scanf("%[^\n]", miguel);
if (strcmp(rita,"pedra") == 0)
{
if (strcmp(miguel,"pedra") == 0)
{
jogos --;
}
else if (strcmp(miguel,"tesoura") == 0)
{
rit ++;
}
else
{
mig ++;
}
}
else if (strcmp(rita,"tesoura") == 0)
{
if (strcmp(miguel,"tesoura") == 0)
{
jogos --;
}
else if (strcmp(miguel,"pedra") == 0)
{
mig ++;
}
else
{
rit ++;
}
}
else
{
if (strcmp(miguel,"papel") == 0)
{
jogos --;
}
else if (strcmp(miguel,"pedra") == 0)
{
rit ++;
}
else
{
mig ++;
}
}
getchar();
}
if (mig > rit)
{
printf("MIGUEL\n");
}
else
{
printf("MARIA\n");
}
return(0);
}
|
the_stack_data/997990.c | #include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
//para imprimir o endereço
#include <stdint.h>
#define MAXLINE 4096
//Cria e retorna um socket descriptor
int Socket(int family, int type, int flags)
{
int sockfd;
if ((sockfd = socket(family, type, flags)) < 0) {
perror("socket");
exit(1);
} else
return sockfd;
}
//Preenche dados referentes ao endereco do servidor
void Servaddr(struct sockaddr_in* servaddr, char* ip, char* port)
{
bzero(servaddr, sizeof(*servaddr)); //zera os bits da estrutura com o endereço do servidor
servaddr->sin_family = AF_INET; //escolhe o protocolo
servaddr->sin_port = htons(atoi(port)); //determina a porta e converte para o padrão big-endian
if (inet_pton(AF_INET, ip, &servaddr->sin_addr) <= 0) {
perror("inet_pton error");
exit(1);
}
}
//Conecta o socket ao servidor
void Connect(int sockfd, struct sockaddr_in * servaddr)
{
if (connect(sockfd, (struct sockaddr *) servaddr, sizeof(*servaddr)) < 0) { //caso não consiga se conectar com o servidor
perror("connect error");
exit(1);
}
}
int main(int argc, char **argv) {
int sockfd, n;
char recvline[MAXLINE + 1];
char sendline[MAXLINE + 1];
char error[MAXLINE + 1];
struct sockaddr_in servaddr;
//Para obter o endereço do socket
socklen_t addrlen = sizeof(servaddr);
if (argc != 3) { //Caso o usuário não tenha fornecido um IP e a porta para conexão
strcpy(error,"uso: ");
strcat(error,argv[0]);
strcat(error," <IPaddress> <Port>");
perror(error);
exit(1);
}
//Inicializa o socket
sockfd = Socket(AF_INET, SOCK_STREAM, 0);
//Preenche informacoes relativas ao socket do servidor
Servaddr(&servaddr, argv[1], argv[2]);
//Conecta o socket ao servidor
Connect(sockfd, &servaddr);
//Imprime o endereço do socket local
getsockname(sockfd,(struct sockaddr *)&servaddr, &addrlen);
printf("Endereço local: %s:%u \n", inet_ntoa(servaddr.sin_addr),ntohs(servaddr.sin_port));
//Imprime o endereço do socket remoto
getpeername(sockfd,(struct sockaddr *)&servaddr, &addrlen);
printf("Endereço do host: %s:%u \n",inet_ntoa(servaddr.sin_addr), ntohs(servaddr.sin_port));
//Le entrada padrao e envia para servidor continuamente
for ( ; ; ) {
fgets (sendline, MAXLINE - 1, stdin);
write (sockfd, sendline, strlen(sendline));
if (strcmp(sendline, "bye\n") == 0){
printf("Conexao encerrada.\n");
break;
}
n = read(sockfd, recvline, MAXLINE);
recvline[n] = 0;
printf("%s", recvline);
if (n < 0) { //caso o número de bits lido seja negativo, lança erro
perror("read error");
exit(1);
}
}
exit(0);
}
|
the_stack_data/90763465.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_convert_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cado-car <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/16 21:10:39 by cado-car #+# #+# */
/* Updated: 2021/06/28 15:50:55 by cado-car ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
int ft_is_whitespace(char c);
int ft_strlen(char *str);
int ft_is_base_valid(char *base);
int ft_convert_from_base(char *str, char *base);
char *ft_convert_to_base(char *base, int nbr, int signal);
char *ft_convert_base(char *nbr, char *base_from, char *base_to)
{
int i;
int signal;
int rad;
int result;
if (!ft_is_base_valid(base_from) || !ft_is_base_valid(base_to))
return (NULL);
signal = 1;
rad = ft_strlen(base_from);
result = 0;
i = 0;
while (ft_is_whitespace(nbr[i]) == 1)
i++;
while (nbr[i] == '+' || nbr[i] == '-')
{
if (nbr[i] == '-')
signal *= -1;
i++;
}
result = ft_convert_from_base(&nbr[i], base_from);
if (result == 0)
signal = 1;
return (ft_convert_to_base(base_to, result, signal));
}
int ft_is_base_valid(char *base)
{
int i;
int c;
int len;
i = 0;
len = ft_strlen(base);
if (base[i] == '\0' || len == 1)
return (0);
while (base[i] != '\0')
{
if (base[i] == '+' || base[i] == '-' || ft_is_whitespace(base[i]) == 1)
return (0);
c = 1;
while (base[i + c] != '\0')
{
if (base[i + c] == base[i])
return (0);
c++;
}
i++;
}
return (1);
}
int ft_strlen(char *str)
{
int n;
n = 0;
while (str[n] != '\0')
n++;
return (n);
}
int ft_is_whitespace(char c)
{
if ((c >= 9 && c <= 13) || c == 32)
return (1);
else
return (0);
}
|
the_stack_data/232954695.c | #include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define max(a, b) (((a) > (b)) ? (a) : (b))
char *text = "stupid_spring_string_bla";
char *pattern = "string";
/* the first skip table is used to skip to the next nearest match */
static int * build_first_skip_table(char *pattern)
{
unsigned int *skip_table;
unsigned int i;
skip_table = malloc(256 * sizeof(unsigned int));
if (!skip_table) {
printf("Error: no memory for build_first_skip_table\n");
exit(-1);
}
/* fill table with max jump */
for (i = 0; i < 256; i++) {
skip_table[i] = strlen(pattern);
}
/* then compute jump for characters in pattern */
for (i = 0; i < strlen(pattern) - 1; i++) {
skip_table[pattern[i]] = strlen(pattern) - i - 1;
}
return skip_table;
}
/**
* Build second skip table
*
* Note: this could be hugely optimized but this way it was simple
* to write and hopefully to read. Anyways, this is constant time at init so
* it hardly matters */
static int * build_second_skip_table(char *string)
{
unsigned int *skip_table;
unsigned int i, j, decal, k;
unsigned int ssize, psize;
char *pattern, *invstring;
char offender;
int match;
ssize = strlen(string);
skip_table = malloc(ssize * sizeof(unsigned int));
invstring = calloc(ssize * 2, sizeof(char));
pattern = calloc(ssize * 2, sizeof(char));
if (!skip_table || !invstring || !pattern) {
printf("Error: no memory for build_second_skip_table\n");
exit(-1);
}
/* fill table with max size because it's hard to detect it */
for (i = 0; i < ssize; i++) {
skip_table[i] = ssize;
}
/* invert string for less brainfuck algorithm */
for (i = 0; i < ssize; i++) {
invstring[i] = string[ssize - 1 - i];
}
/* first occurence is rather special */
i = 0;
while (invstring[i] == invstring[i + 1]) {
i++;
}
skip_table[0] = i + 1;
/* for each subpattern of the string */
for (i = 0; i < ssize - 1; i++) {
strncpy(pattern, invstring, i + 1);
psize = strlen(pattern);
offender = invstring[i + 1];
/* for each shift of the subpattern */
for (decal = 0; decal < ssize - 1; decal++) {
match = 1;
/* compare shifted subpattern with string */
for (k = 0; k < psize; k++) {
if (pattern[k] != invstring[decal + k]) {
/* abuse the calloc trick */
if (invstring[decal + k] == 0) {
break;
}
match = 0;
break;
}
}
/* pattern matches, but check offender */
if (match) {
if (invstring[decal + k] != offender) {
skip_table[i + 1] = decal;
break;
}
}
}
}
free(invstring);
free(pattern);
return skip_table;
}
#if 0
/* second skip table */
static int * build_second_skip_table(char *pattern)
{
unsigned int *skip_table;
unsigned int i;
unsigned int psize;
char *position;
char offender;
psize = strlen(pattern);
skip_table = malloc(psize * sizeof(int));
if (!skip_table) {
printf("Error: no memory for build_second_skip_table\n");
exit(-1);
}
/* first occurence is rather special */
i = psize - 1;
while (pattern[i] == pattern[i - 1]) {
i--;
}
skip_table[0] = psize - i - 1;
/* now find lowest shift */
for (i = psize - 1; i > 0; i--) {
position = pattern;
offender = pattern[i - 1];
printf("pattern = %s, offender = %c\n", pattern + i, offender);
while (position = strstr(position, pattern + i)) {
printf("3 %d\n", position - pattern);
if (position - pattern >= 2) {
if (*(position - 1) != offender) {
skip_table[psize - i] = position - pattern;
printf("Value = %d\n", position - pattern);
} else {
printf("Offender\n");
}
}
position += 1; // += i ?
}
}
printf("Done");
}
#endif
int bm(char *text, char *pattern)
{
unsigned int *first_skipt, *second_skipt;
unsigned int tsize, psize;
int i, j;
char curchar; //FIXME: remove, for tests
unsigned int fskip, sskip;
first_skipt = build_first_skip_table(pattern);
second_skipt = build_second_skip_table(pattern);
tsize = strlen(text);
psize = strlen(pattern);
i = psize - 1;
while (i < tsize) {
j = psize - 1;
while (j >= 0 && text[i] == pattern[j]) {
--i;
--j;
}
if (j < 0) {
free(first_skipt);
free(second_skipt);
return i + 1;
}
fskip = first_skipt[text[i]]; //0->255
sskip = second_skipt[psize - 1 - j]; //0->psize-1
i += max(fskip, sskip);
//i += max(first_skipt[text[i]], second_skipt[j]);
}
free(first_skipt);
free(second_skipt);
return -1;
}
int main(int argc, char *argv[])
{
bm(text, pattern);
return 0;
}
|
the_stack_data/104827981.c | char *mx_strcpy(char *dst, const char *src) {
int count = 0;
while (src[count]) {
dst[count] = src[count];
count++;
}
dst[count] = '\0';
return dst;
}
|
the_stack_data/54825914.c | /*
Enormous Input Test
The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime.
Input
The input begins with two positive integers n k (n, k<=10^7). The next n lines of input contain one positive integer ti, not greater than 10^9, each.
Output
Write a single integer to output, denoting how many integers ti are divisible by k.
Example
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
*/
main()
{
int n,count=0;
long int d,no;
printf("Enter No. of Inputs");
scanf("%d",&n);
printf("Enter the Divisor");
scanf("%ld",&d);
while(n)
{
scanf("%ld",&no);
if(no%d==0)
count++;
n--;
}
printf("%d",count);
getch();
}
|
the_stack_data/89200303.c | /*************************************************************************/
/* */
/* SNU-RT Benchmark Suite for Worst Case Timing Analysis */
/* ===================================================== */
/* Collected and Modified by S.-S. Lim */
/* [email protected] */
/* Real-Time Research Group */
/* Seoul National University */
/* */
/* */
/* < Features > - restrictions for our experimental environment */
/* */
/* 1. Completely structured. */
/* - There are no unconditional jumps. */
/* - There are no exit from loop bodies. */
/* (There are no 'break' or 'return' in loop bodies) */
/* 2. No 'switch' statements. */
/* 3. No 'do..while' statements. */
/* 4. Expressions are restricted. */
/* - There are no multiple expressions joined by 'or', */
/* 'and' operations. */
/* 5. No library calls. */
/* - All the functions needed are implemented in the */
/* source file. */
/* */
/* */
/*************************************************************************/
/* */
/* FILE: bs.c */
/* SOURCE : Public Domain Code */
/* */
/* DESCRIPTION : */
/* */
/* Binary search for the array of 15 integer elements. */
/* */
/* REMARK : */
/* */
/* EXECUTION TIME : */
/* */
/* */
/*************************************************************************/
struct DATA {
int key;
int value;
} ;
#ifdef DEBUG
int cnt1;
#endif
struct DATA data[15] = { {1, 100},
{5,200},
{6, 300},
{7, 700},
{8, 900},
{9, 250},
{10, 400},
{11, 600},
{12, 800},
{13, 1500},
{14, 1200},
{15, 110},
{16, 140},
{17, 133},
{18, 10} };
binary_search(int x)
{
int fvalue, mid, up, low ;
low = 0;
up = 14;
fvalue = -1 /* all data are positive */ ;
while (low <= up) {
mid = (low + up) >> 1;
if ( data[mid].key == x ) { /* found */
up = low - 1;
fvalue = data[mid].value;
#ifdef DEBUG
printf("FOUND!!\n");
#endif
}
else /* not found */
if ( data[mid].key > x ) {
up = mid - 1;
#ifdef DEBUG
printf("MID-1\n");
#endif
}
else {
low = mid + 1;
#ifdef DEBUG
printf("MID+1\n");
#endif
}
#ifdef DEBUG
cnt1++;
#endif
}
#ifdef DEBUG
printf("Loop Count : %d\n", cnt1);
#endif
return fvalue;
}
int main()
{
binary_search(8);
}
|
the_stack_data/34513275.c | // RUN: %clang_cc1 -triple x86_64-linux-android -emit-llvm -O -o - %s \
// RUN: | FileCheck %s --check-prefix=ANDROID --check-prefix=CHECK
// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -O -o - %s \
// RUN: | FileCheck %s --check-prefix=GNU --check-prefix=CHECK
// RUN: %clang_cc1 -triple x86_64 -emit-llvm -O -o - %s \
// RUN: | FileCheck %s --check-prefix=GNU --check-prefix=CHECK
// NaCl is an example of a target for which long double is the same as double.
// RUN: %clang_cc1 -triple x86_64-nacl -emit-llvm -O -o - %s \
// RUN: | FileCheck %s --check-prefix=NACL --check-prefix=CHECK
// Android uses fp128 for long double but other x86_64 targets use x86_fp80.
long double dataLD = 1.0L;
// ANDROID: @dataLD ={{.*}} local_unnamed_addr global fp128 0xL00000000000000003FFF000000000000, align 16
// GNU: @dataLD ={{.*}} local_unnamed_addr global x86_fp80 0xK3FFF8000000000000000, align 16
long double _Complex dataLDC = {1.0L, 1.0L};
// ANDROID: @dataLDC ={{.*}} local_unnamed_addr global { fp128, fp128 } { fp128 0xL00000000000000003FFF000000000000, fp128 0xL00000000000000003FFF000000000000 }, align 16
// GNU: @dataLDC ={{.*}} local_unnamed_addr global { x86_fp80, x86_fp80 } { x86_fp80 0xK3FFF8000000000000000, x86_fp80 0xK3FFF8000000000000000 }, align 16
long double TestLD(long double x) {
return x * x;
// ANDROID: define{{.*}} fp128 @TestLD(fp128 %x)
// GNU: define{{.*}} x86_fp80 @TestLD(x86_fp80 %x)
// NACL: define{{.*}} double @TestLD(double %x)
}
long double _Complex TestLDC(long double _Complex x) {
return x * x;
// ANDROID: define{{.*}} void @TestLDC({ fp128, fp128 }* {{.*}}, { fp128, fp128 }* {{.*}} %x)
// GNU: define{{.*}} { x86_fp80, x86_fp80 } @TestLDC({ x86_fp80, x86_fp80 }* {{.*}} %x)
// NACL: define{{.*}} { double, double } @TestLDC(double %x{{.*}}, double %x{{.*}})
}
typedef __builtin_va_list va_list;
int TestGetVarInt(va_list ap) {
return __builtin_va_arg(ap, int);
// Since int can be passed in memory or register there are two branches.
// CHECK: define{{.*}} i32 @TestGetVarInt(
// CHECK: br label
// CHECK: br label
// CHECK: = phi
// CHECK: ret i32
}
double TestGetVarDouble(va_list ap) {
return __builtin_va_arg(ap, double);
// Since double can be passed in memory or register there are two branches.
// CHECK: define{{.*}} double @TestGetVarDouble(
// CHECK: br label
// CHECK: br label
// CHECK: = phi
// CHECK: ret double
}
long double TestGetVarLD(va_list ap) {
return __builtin_va_arg(ap, long double);
// fp128 and double can be passed in memory or in register, but x86_fp80 is in
// memory.
// ANDROID: define{{.*}} fp128 @TestGetVarLD(
// GNU: define{{.*}} x86_fp80 @TestGetVarLD(
// NACL: define{{.*}} double @TestGetVarLD(
// ANDROID: br label
// ANDROID: br label
// NACL: br
// ANDROID: = phi
// GNU-NOT: br
// GNU-NOT: = phi
// NACL: = phi
// ANDROID: ret fp128
// GNU: ret x86_fp80
}
long double _Complex TestGetVarLDC(va_list ap) {
return __builtin_va_arg(ap, long double _Complex);
// Pair of fp128 or x86_fp80 are passed as struct in memory.
// ANDROID: define{{.*}} void @TestGetVarLDC({ fp128, fp128 }* {{.*}}, %struct.__va_list_tag*
// GNU: define{{.*}} { x86_fp80, x86_fp80 } @TestGetVarLDC(
// Pair of double can go in SSE registers or memory
// NACL: define{{.*}} { double, double } @TestGetVarLDC(
// ANDROID-NOT: br
// GNU-NOT: br
// NACL: br
// ANDROID-NOT: phi
// GNU-NOT: phi
// NACL: phi
// ANDROID: ret void
// GNU: ret { x86_fp80, x86_fp80 }
// NACL: ret { double, double }
}
void TestVarArg(const char *s, ...);
void TestPassVarInt(int x) {
TestVarArg("A", x);
// CHECK: define{{.*}} void @TestPassVarInt(i32 %x)
// CHECK: call {{.*}} @TestVarArg(i8* {{.*}}, i32 %x)
}
void TestPassVarFloat(float x) {
TestVarArg("A", x);
// CHECK: define{{.*}} void @TestPassVarFloat(float %x)
// CHECK: call {{.*}} @TestVarArg(i8* {{.*}}, double %
}
void TestPassVarDouble(double x) {
TestVarArg("A", x);
// CHECK: define{{.*}} void @TestPassVarDouble(double %x)
// CHECK: call {{.*}} @TestVarArg(i8* {{.*}}, double %x
}
void TestPassVarLD(long double x) {
TestVarArg("A", x);
// ANDROID: define{{.*}} void @TestPassVarLD(fp128 %x)
// ANDROID: call {{.*}} @TestVarArg(i8* {{.*}}, fp128 %x
// GNU: define{{.*}} void @TestPassVarLD(x86_fp80 %x)
// GNU: call {{.*}} @TestVarArg(i8* {{.*}}, x86_fp80 %x
// NACL: define{{.*}} void @TestPassVarLD(double %x)
// NACL: call {{.*}} @TestVarArg(i8* {{.*}}, double %x
}
void TestPassVarLDC(long double _Complex x) {
TestVarArg("A", x);
// ANDROID: define{{.*}} void @TestPassVarLDC({ fp128, fp128 }* {{.*}} %x)
// ANDROID: store fp128 %{{.*}}, fp128* %
// ANDROID-NEXT: store fp128 %{{.*}}, fp128* %
// ANDROID-NEXT: call {{.*}} @TestVarArg(i8* {{.*}}, { fp128, fp128 }* {{.*}} %
// GNU: define{{.*}} void @TestPassVarLDC({ x86_fp80, x86_fp80 }* {{.*}} %x)
// GNU: store x86_fp80 %{{.*}}, x86_fp80* %
// GNU-NEXT: store x86_fp80 %{{.*}}, x86_fp80* %
// GNU-NEXT: call {{.*}} @TestVarArg(i8* {{.*}}, { x86_fp80, x86_fp80 }* {{.*}} %
// NACL: define{{.*}} void @TestPassVarLDC(double %x{{.*}}, double %x{{.*}})
// NACL: call {{.*}} @TestVarArg(i8* {{.*}}, double %x{{.*}}, double %x{{.*}})
}
|
the_stack_data/15148.c | #include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid;
/* 새로운 자식을 fork 한다. */
pid = fork();
if (pid < 0) { /* 에러가 발생한 경우 */
fprintf(stderr, "Fork failed");
return 1;
}else if(pid == 0) { /* 자식 프로세스 */
printf("================================\n");
printf("CHILD: ls command\n");
execlp("/bin/ls","ls",NULL);
printf("/'execlp/' call was unsuccessful\n"); /* 해당 줄의 코드는 출력되지 않는다. 왜? */
}else { /* 부모 프로세스 */
/* parent will wait for the child to complete */
wait(NULL);
/* 해당 pid에 대해서 wait하도록 다음 명령어로 대체하여 수행해본다.
*
* waitpid(pid, NULL, 0);
*
* 같은 결과를 가져오지만 항상 같은 것은 아니다.
*/
printf("--------------------------------\n");
printf("PARENT: Child Complete\n");
printf("--------------------------------\n");
}
return 0;
}
|
the_stack_data/75136587.c | #ifdef COMPILE_FOR_TEST
#include <assert.h>
#define assume(cond) assert(cond)
#endif
void main(int argc, char* argv[]) {
int x_0_0;//sh_buf.outcnt
int x_0_1;//sh_buf.outcnt
int x_0_2;//sh_buf.outcnt
int x_0_3;//sh_buf.outcnt
int x_0_4;//sh_buf.outcnt
int x_0_5;//sh_buf.outcnt
int x_0_6;//sh_buf.outcnt
int x_0_7;//sh_buf.outcnt
int x_1_0;//sh_buf.outbuf[0]
int x_1_1;//sh_buf.outbuf[0]
int x_2_0;//sh_buf.outbuf[1]
int x_2_1;//sh_buf.outbuf[1]
int x_3_0;//sh_buf.outbuf[2]
int x_3_1;//sh_buf.outbuf[2]
int x_4_0;//sh_buf.outbuf[3]
int x_4_1;//sh_buf.outbuf[3]
int x_5_0;//sh_buf.outbuf[4]
int x_5_1;//sh_buf.outbuf[4]
int x_6_0;//sh_buf.outbuf[5]
int x_7_0;//sh_buf.outbuf[6]
int x_8_0;//sh_buf.outbuf[7]
int x_9_0;//sh_buf.outbuf[8]
int x_10_0;//sh_buf.outbuf[9]
int x_11_0;//LOG_BUFSIZE
int x_11_1;//LOG_BUFSIZE
int x_12_0;//CREST_scheduler::lock_0
int x_13_0;//t3 T0
int x_14_0;//t2 T0
int x_15_0;//arg T0
int x_16_0;//functioncall::param T0
int x_16_1;//functioncall::param T0
int x_17_0;//buffered T0
int x_18_0;//functioncall::param T0
int x_18_1;//functioncall::param T0
int x_19_0;//functioncall::param T0
int x_19_1;//functioncall::param T0
int x_20_0;//functioncall::param T0
int x_20_1;//functioncall::param T0
int x_21_0;//functioncall::param T0
int x_21_1;//functioncall::param T0
int x_22_0;//direction T0
int x_23_0;//functioncall::param T0
int x_23_1;//functioncall::param T0
int x_24_0;//functioncall::param T0
int x_24_1;//functioncall::param T0
int x_25_0;//functioncall::param T0
int x_25_1;//functioncall::param T0
int x_26_0;//functioncall::param T0
int x_26_1;//functioncall::param T0
int x_27_0;//functioncall::param T0
int x_27_1;//functioncall::param T0
int x_28_0;//functioncall::param T0
int x_28_1;//functioncall::param T0
int x_29_0;//functioncall::param T0
int x_29_1;//functioncall::param T0
int x_30_0;//functioncall::param T0
int x_30_1;//functioncall::param T0
int x_31_0;//functioncall::param T0
int x_31_1;//functioncall::param T0
int x_32_0;//functioncall::param T0
int x_32_1;//functioncall::param T0
int x_33_0;//functioncall::param T0
int x_33_1;//functioncall::param T0
int x_34_0;//functioncall::param T0
int x_34_1;//functioncall::param T0
int x_35_0;//functioncall::param T1
int x_35_1;//functioncall::param T1
int x_36_0;//functioncall::param T1
int x_36_1;//functioncall::param T1
int x_37_0;//i T1
int x_37_1;//i T1
int x_37_2;//i T1
int x_38_0;//rv T1
int x_39_0;//rv T1
int x_39_1;//rv T1
int x_40_0;//functioncall::param T1
int x_40_1;//functioncall::param T1
int x_41_0;//functioncall::param T1
int x_41_1;//functioncall::param T1
int x_42_0;//functioncall::param T1
int x_42_1;//functioncall::param T1
int x_43_0;//functioncall::param T1
int x_43_1;//functioncall::param T1
int x_44_0;//functioncall::param T1
int x_44_1;//functioncall::param T1
int x_45_0;//functioncall::param T1
int x_45_1;//functioncall::param T1
int x_46_0;//functioncall::param T1
int x_46_1;//functioncall::param T1
int x_47_0;//functioncall::param T1
int x_47_1;//functioncall::param T1
int x_48_0;//functioncall::param T1
int x_48_1;//functioncall::param T1
int x_49_0;//functioncall::param T2
int x_49_1;//functioncall::param T2
int x_50_0;//functioncall::param T2
int x_50_1;//functioncall::param T2
int x_51_0;//i T2
int x_51_1;//i T2
int x_51_2;//i T2
int x_51_3;//i T2
int x_52_0;//rv T2
int x_53_0;//rv T2
int x_53_1;//rv T2
int x_54_0;//functioncall::param T2
int x_54_1;//functioncall::param T2
int x_55_0;//functioncall::param T2
int x_55_1;//functioncall::param T2
int x_56_0;//functioncall::param T2
int x_56_1;//functioncall::param T2
int x_57_0;//functioncall::param T2
int x_57_1;//functioncall::param T2
int x_58_0;//functioncall::param T2
int x_58_1;//functioncall::param T2
int x_59_0;//functioncall::param T2
int x_59_1;//functioncall::param T2
int x_59_2;//functioncall::param T2
int x_60_0;//functioncall::param T2
int x_60_1;//functioncall::param T2
T_0_0_0: x_0_0 = 0;
T_0_1_0: x_1_0 = 0;
T_0_2_0: x_2_0 = 0;
T_0_3_0: x_3_0 = 0;
T_0_4_0: x_4_0 = 0;
T_0_5_0: x_5_0 = 0;
T_0_6_0: x_6_0 = 0;
T_0_7_0: x_7_0 = 0;
T_0_8_0: x_8_0 = 0;
T_0_9_0: x_9_0 = 0;
T_0_10_0: x_10_0 = 0;
T_0_11_0: x_11_0 = 0;
T_0_12_0: x_13_0 = 1697663424;
T_0_13_0: x_14_0 = 901907040;
T_0_14_0: x_15_0 = 0;
T_0_15_0: x_16_0 = 212179953;
T_0_16_0: x_16_1 = -1;
T_0_17_0: x_17_0 = 0;
T_0_18_0: x_18_0 = 1380393363;
T_0_19_0: x_18_1 = x_17_0;
T_0_20_0: x_19_0 = 2069386296;
T_0_21_0: x_19_1 = 97;
T_0_22_0: x_20_0 = 1338815156;
T_0_23_0: x_20_1 = 0;
T_0_24_0: x_21_0 = 1474106319;
T_0_25_0: x_21_1 = 0;
T_0_26_0: x_22_0 = 901902400;
T_0_27_0: x_23_0 = 1320036158;
T_0_28_0: x_23_1 = x_22_0;
T_0_29_0: x_24_0 = 737524459;
T_0_30_0: x_24_1 = 0;
T_0_31_0: x_12_0 = -1;
T_0_32_0: x_0_1 = 5;
T_0_33_0: x_1_1 = 72;
T_0_34_0: x_2_1 = 69;
T_0_35_0: x_3_1 = 76;
T_0_36_0: x_4_1 = 76;
T_0_37_0: x_5_1 = 79;
T_0_38_0: x_25_0 = 109999608;
T_0_39_0: x_25_1 = 83;
T_0_40_0: x_26_0 = 130415466;
T_0_41_0: x_26_1 = 1;
T_0_42_0: x_27_0 = 377193742;
T_0_43_0: x_27_1 = 1;
T_0_44_0: x_28_0 = 9768864;
T_0_45_0: x_28_1 = 1;
T_0_46_0: x_29_0 = 261775239;
T_0_47_0: x_29_1 = 82;
T_0_48_0: x_30_0 = 1142416626;
T_0_49_0: x_30_1 = 90;
T_0_50_0: x_31_0 = 1825571830;
T_0_51_0: x_31_1 = 1;
T_0_52_0: x_32_0 = 699990639;
T_0_53_0: x_32_1 = 1;
T_0_54_0: x_33_0 = 523640966;
T_0_55_0: x_33_1 = 2;
T_0_56_0: x_34_0 = 711277958;
T_0_57_0: x_34_1 = 2;
T_0_58_0: x_11_1 = 5;
T_1_59_1: x_35_0 = 1375239949;
T_1_60_1: x_35_1 = x_27_1;
T_1_61_1: x_36_0 = 1945409727;
T_1_62_1: x_36_1 = x_28_1;
T_1_63_1: x_37_0 = 0;
T_1_64_1: x_38_0 = -950463999;
T_2_65_2: x_49_0 = 332699735;
T_2_66_2: x_49_1 = x_33_1;
T_2_67_2: x_50_0 = 252167031;
T_2_68_2: x_50_1 = x_34_1;
T_2_69_2: x_51_0 = 0;
T_2_70_2: x_52_0 = -952565247;
T_2_71_2: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_53_0 = 908969904;
T_1_72_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_39_0 = 908969904;
T_1_73_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_40_0 = 403544067;
T_1_74_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_40_1 = -1;
T_1_75_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_39_1 = x_40_1;
T_1_76_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_39_1 + 1 == 0) x_0_2 = 0;
T_1_77_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_41_0 = 23321305;
T_1_78_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_41_1 = 9;
T_1_79_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_42_0 = 1603863562;
T_1_80_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_42_1 = x_41_1;
T_1_81_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_0_3 = 0;
T_1_82_1: if (x_36_1 < x_11_1) x_43_0 = 1537988727;
T_1_83_1: if (x_36_1 < x_11_1) x_43_1 = 47456044119808;
T_1_84_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_54_0 = 460393066;
T_1_85_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_54_1 = -1;
T_1_86_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_53_1 = x_54_1;
T_2_87_2: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_53_1 + 1 == 0) x_0_4 = 0;
T_2_88_2: if (x_36_1 < x_11_1) x_44_0 = 408900919;
T_2_89_2: if (x_36_1 < x_11_1) x_44_1 = x_0_3 + x_36_1;
T_2_90_2: if (x_36_1 < x_11_1) x_37_1 = 0;
T_1_91_1: if (x_36_1 < x_11_1 && x_37_1 < x_35_1) x_45_0 = 1735312804;
T_1_92_1: if (x_36_1 < x_11_1 && x_37_1 < x_35_1) x_45_1 = 47456044119808;
T_1_93_1: if (x_36_1 < x_11_1) x_37_2 = 1 + x_37_1;
T_1_94_1: if (x_36_1 < x_11_1) x_46_0 = 383833922;
T_1_95_1: if (x_36_1 < x_11_1) x_46_1 = 47456044119808;
T_1_96_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_55_0 = 581727840;
T_1_97_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_55_1 = 9;
T_1_98_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_56_0 = 415965933;
T_1_99_1: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_56_1 = x_55_1;
T_2_100_2: if (x_0_1 + x_50_1 > x_11_1 && x_0_1 != 0) x_0_5 = 0;
T_2_101_2: if (x_50_1 < x_11_1) x_57_0 = 596013875;
T_2_102_2: if (x_50_1 < x_11_1) x_57_1 = 47456046221056;
T_2_103_2: if (x_36_1 < x_11_1) x_0_6 = x_0_4 + x_36_1;
T_2_104_2: if (x_50_1 < x_11_1) x_58_0 = 1962121203;
T_2_105_2: if (x_50_1 < x_11_1) x_58_1 = x_0_5 + x_50_1;
T_2_106_2: if (x_50_1 < x_11_1) x_51_1 = 0;
T_2_107_2: if (x_50_1 < x_11_1 && x_51_1 < x_49_1) x_59_0 = 337868581;
T_2_108_2: if (x_50_1 < x_11_1 && x_51_1 < x_49_1) x_59_1 = 47456046221056;
T_2_109_2: if (x_50_1 < x_11_1) x_51_2 = 1 + x_51_1;
T_2_110_2: if (x_50_1 < x_11_1 && x_51_2 < x_49_1) x_59_2 = 47456046221056;
T_2_111_2: if (x_50_1 < x_11_1) x_51_3 = 1 + x_51_2;
T_2_112_2: if (x_50_1 < x_11_1) x_60_0 = 1934829032;
T_2_113_2: if (x_50_1 < x_11_1) x_60_1 = 47456046221056;
T_2_114_2: if (x_36_1 < x_11_1) x_47_0 = 1288743874;
T_2_115_2: if (x_36_1 < x_11_1) x_47_1 = 47456044119808;
T_2_116_2: if (x_50_1 < x_11_1) x_0_7 = x_0_6 + x_50_1;
T_2_117_2: if (x_36_1 < x_11_1) x_48_0 = 1657904739;
T_1_118_1: if (x_36_1 < x_11_1) x_48_1 = 47456044119808;
T_1_119_1: if (x_36_1 < x_11_1) assert(x_0_7 == x_44_1);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.