Merge change 6004
* changes:
Add aggregator test tag to list
diff --git a/include/cutils/ashmem.h b/include/cutils/ashmem.h
index 0683bf2..fd56dbe 100644
--- a/include/cutils/ashmem.h
+++ b/include/cutils/ashmem.h
@@ -10,6 +10,8 @@
#ifndef _CUTILS_ASHMEM_H
#define _CUTILS_ASHMEM_H
+#include <stdint.h>
+
#ifdef __cplusplus
extern "C" {
#endif
diff --git a/include/cutils/compiler.h b/include/cutils/compiler.h
new file mode 100644
index 0000000..09112d5
--- /dev/null
+++ b/include/cutils/compiler.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_CUTILS_COMPILER_H
+#define ANDROID_CUTILS_COMPILER_H
+
+/*
+ * helps the compiler's optimizer predicting branches
+ */
+
+#ifdef __cplusplus
+# define CC_LIKELY( exp ) (__builtin_expect( !!(exp), true ))
+# define CC_UNLIKELY( exp ) (__builtin_expect( !!(exp), false ))
+#else
+# define CC_LIKELY( exp ) (__builtin_expect( !!(exp), 1 ))
+# define CC_UNLIKELY( exp ) (__builtin_expect( !!(exp), 0 ))
+#endif
+
+#endif // ANDROID_CUTILS_COMPILER_H
diff --git a/libacc/acc.cpp b/libacc/acc.cpp
index 83fc2fe..60546f1 100644
--- a/libacc/acc.cpp
+++ b/libacc/acc.cpp
@@ -68,6 +68,8 @@
};
class Compiler : public ErrorSink {
+ struct Type;
+
class CodeBuf {
char* ind; // Output code pointer
char* pProgramBase;
@@ -157,8 +159,7 @@
* architecture.
*
* The code generator implements the following abstract machine:
- * R0 - the main accumulator.
- * R1 - the secondary accumulator.
+ * R0 - the accumulator.
* FP - a frame pointer for accessing function arguments and local
* variables.
* SP - a stack pointer for storing intermediate results while evaluating
@@ -168,7 +169,7 @@
* stack such that the first argument has the lowest address.
* After the call, the result is in R0. The caller is responsible for
* removing the arguments from the stack.
- * The R0 and R1 registers are not saved across function calls. The
+ * The R0 register is not saved across function calls. The
* FP and SP registers are saved.
*/
@@ -218,7 +219,13 @@
int localVariableSize) = 0;
/* load immediate value to R0 */
- virtual void li(int t) = 0;
+ virtual void li(int i) = 0;
+
+ /* load floating point immediate value to R0 */
+ virtual void lif(float f) = 0;
+
+ /* load double-precision floating point immediate value to R0 */
+ virtual void lid(double d) = 0;
/* Jump to a target, and return the address of the word that
* holds the target data, in case it needs to be fixed up later.
@@ -232,41 +239,42 @@
*/
virtual int gtst(bool l, int t) = 0;
- /* Compare R1 against R0, and store the boolean result in R0.
+ /* Compare TOS against R0, and store the boolean result in R0.
+ * Pops TOS.
* op specifies the comparison.
*/
virtual void gcmp(int op) = 0;
- /* Perform the arithmetic op specified by op. R1 is the
+ /* Perform the arithmetic op specified by op. TOS is the
* left argument, R0 is the right argument.
+ * Pops TOS.
*/
virtual void genOp(int op) = 0;
- /* Set R1 to 0.
+ /* Compare 0 against R0, and store the boolean result in R0.
+ * op specifies the comparison.
*/
- virtual void clearR1() = 0;
+ virtual void gUnaryCmp(int op) = 0;
+
+ /* Perform the arithmetic op specified by op. 0 is the
+ * left argument, R0 is the right argument.
+ */
+ virtual void genUnaryOp(int op) = 0;
/* Push R0 onto the stack.
*/
virtual void pushR0() = 0;
- /* Pop R1 off of the stack.
+ /* Store R0 to the address stored in TOS.
+ * The TOS is popped.
+ * pPointerType is the type of the pointer (of the input R0).
*/
- virtual void popR1() = 0;
-
- /* Store R0 to the address stored in R1.
- * isInt is true if a whole 4-byte integer value
- * should be stored, otherwise a 1-byte character
- * value should be stored.
- */
- virtual void storeR0ToR1(bool isInt) = 0;
+ virtual void storeR0ToTOS(Type* pPointerType) = 0;
/* Load R0 from the address stored in R0.
- * isInt is true if a whole 4-byte integer value
- * should be loaded, otherwise a 1-byte character
- * value should be loaded.
+ * pPointerType is the type of the pointer (of the input R0).
*/
- virtual void loadR0FromR0(bool isInt) = 0;
+ virtual void loadR0FromR0(Type* pPointerType) = 0;
/* Load the absolute address of a variable to R0.
* If ea <= LOCAL, then this is a local variable, or an
@@ -362,6 +370,16 @@
*/
virtual int jumpOffset() = 0;
+ /**
+ * Stack alignment (in bytes) for this type of data
+ */
+ virtual size_t stackAlignment(Type* type) = 0;
+
+ /**
+ * Array element alignment (in bytes) for this type of data.
+ */
+ virtual size_t sizeOf(Type* type) = 0;
+
protected:
/*
* Output a byte. Handles all values, 0..ff.
@@ -392,6 +410,12 @@
mErrorSink->verror(fmt, ap);
va_end(ap);
}
+
+ void assert(bool test) {
+ if (!test) {
+ error("code generator assertion failed.");
+ }
+ }
private:
CodeBuf* pCodeBuf;
ErrorSink* mErrorSink;
@@ -474,6 +498,18 @@
}
}
+ virtual void lif(float f) {
+ union { float f; int i; } converter;
+ converter.f = f;
+ li(converter.i);
+ }
+
+ virtual void lid(double d) {
+ union { double d; int i[2]; } converter;
+ converter.d = d;
+ assert(false);
+ }
+
virtual int gjmp(int t) {
LOG_API("gjmp(%d);\n", t);
return o4(0xEA000000 | encodeAddress(t)); // b .L33
@@ -489,6 +525,8 @@
virtual void gcmp(int op) {
LOG_API("gcmp(%d);\n", op);
+ o4(0xE8BD0002); // ldmfd sp!,{r1}
+ mStackUse -= 4;
o4(0xE1510000); // cmp r1, r1
switch(op) {
case OP_EQUALS:
@@ -523,6 +561,8 @@
virtual void genOp(int op) {
LOG_API("genOp(%d);\n", op);
+ o4(0xE8BD0002); // ldmfd sp!,{r1}
+ mStackUse -= 4;
switch(op) {
case OP_MUL:
o4(0x0E0000091); // mul r0,r1,r0
@@ -563,9 +603,38 @@
}
}
- virtual void clearR1() {
- LOG_API("clearR1();\n");
+ virtual void gUnaryCmp(int op) {
+ LOG_API("gcmp(%d);\n", op);
o4(0xE3A01000); // mov r1, #0
+ o4(0xE1510000); // cmp r1, r1
+ switch(op) {
+ case OP_NOT_EQUALS:
+ o4(0x03A00000); // moveq r0,#0
+ o4(0x13A00001); // movne r0,#1
+ break;
+ default:
+ error("Unknown unary comparison op %d", op);
+ break;
+ }
+ }
+
+ virtual void genUnaryOp(int op) {
+ LOG_API("genOp(%d);\n", op);
+ switch(op) {
+ case OP_PLUS:
+ // Do nothing
+ break;
+ case OP_MINUS:
+ o4(0xE3A01000); // mov r1, #0
+ o4(0xE0410000); // sub r0,r1,r0
+ break;
+ case OP_BIT_NOT:
+ o4(0xE1E00000); // mvn r0, r0
+ break;
+ default:
+ error("Unknown unary op %d\n", op);
+ break;
+ }
}
virtual void pushR0() {
@@ -575,28 +644,38 @@
LOG_STACK("pushR0: %d\n", mStackUse);
}
- virtual void popR1() {
- LOG_API("popR1();\n");
+ virtual void storeR0ToTOS(Type* pPointerType) {
+ LOG_API("storeR0ToTOS(%d);\n", isInt);
+ assert(pPointerType->tag == TY_POINTER);
o4(0xE8BD0002); // ldmfd sp!,{r1}
mStackUse -= 4;
- LOG_STACK("popR1: %d\n", mStackUse);
- }
-
- virtual void storeR0ToR1(bool isInt) {
- LOG_API("storeR0ToR1(%d);\n", isInt);
- if (isInt) {
- o4(0xE5810000); // str r0, [r1]
- } else {
- o4(0xE5C10000); // strb r0, [r1]
+ switch (pPointerType->pHead->tag) {
+ case TY_INT:
+ o4(0xE5810000); // str r0, [r1]
+ break;
+ case TY_CHAR:
+ o4(0xE5C10000); // strb r0, [r1]
+ break;
+ default:
+ assert(false);
+ break;
}
}
- virtual void loadR0FromR0(bool isInt) {
- LOG_API("loadR0FromR0(%d);\n", isInt);
- if (isInt)
- o4(0xE5900000); // ldr r0, [r0]
- else
- o4(0xE5D00000); // ldrb r0, [r0]
+ virtual void loadR0FromR0(Type* pPointerType) {
+ LOG_API("loadR0FromR0(%d);\n", pPointerType);
+ assert(pPointerType->tag == TY_POINTER);
+ switch (pPointerType->pHead->tag) {
+ case TY_INT:
+ o4(0xE5900000); // ldr r0, [r0]
+ break;
+ case TY_CHAR:
+ o4(0xE5D00000); // ldrb r0, [r0]
+ break;
+ default:
+ assert(false);
+ break;
+ }
}
virtual void leaR0(int ea) {
@@ -834,6 +913,37 @@
return 0;
}
+ /**
+ * Stack alignment (in bytes) for this type of data
+ */
+ virtual size_t stackAlignment(Type* pType){
+ switch(pType->tag) {
+ case TY_DOUBLE:
+ return 8;
+ default:
+ return 4;
+ }
+ }
+
+ /**
+ * Array element alignment (in bytes) for this type of data.
+ */
+ virtual size_t sizeOf(Type* pType){
+ switch(pType->tag) {
+ case TY_INT:
+ return 4;
+ case TY_CHAR:
+ return 1;
+ default:
+ return 0;
+ case TY_FLOAT:
+ return 4;
+ case TY_DOUBLE:
+ return 8;
+ case TY_POINTER:
+ return 4;
+ }
+ }
private:
static FILE* disasmOut;
@@ -921,8 +1031,20 @@
}
/* load immediate value */
- virtual void li(int t) {
- oad(0xb8, t); /* mov $xx, %eax */
+ virtual void li(int i) {
+ oad(0xb8, i); /* mov $xx, %eax */
+ }
+
+ virtual void lif(float f) {
+ union { float f; int i; } converter;
+ converter.f = f;
+ assert(false);
+ }
+
+ virtual void lid(double d) {
+ union { double d; int i[2]; } converter;
+ converter.d = d;
+ assert(false);
}
virtual int gjmp(int t) {
@@ -937,6 +1059,7 @@
virtual void gcmp(int op) {
int t = decodeOp(op);
+ o(0x59); /* pop %ecx */
o(0xc139); /* cmp %eax,%ecx */
li(0);
o(0x0f); /* setxx %al */
@@ -945,32 +1068,60 @@
}
virtual void genOp(int op) {
+ o(0x59); /* pop %ecx */
o(decodeOp(op));
if (op == OP_MOD)
o(0x92); /* xchg %edx, %eax */
}
- virtual void clearR1() {
+ virtual void gUnaryCmp(int op) {
oad(0xb9, 0); /* movl $0, %ecx */
+ int t = decodeOp(op);
+ o(0xc139); /* cmp %eax,%ecx */
+ li(0);
+ o(0x0f); /* setxx %al */
+ o(t + 0x90);
+ o(0xc0);
+ }
+
+ virtual void genUnaryOp(int op) {
+ oad(0xb9, 0); /* movl $0, %ecx */
+ o(decodeOp(op));
}
virtual void pushR0() {
o(0x50); /* push %eax */
}
- virtual void popR1() {
+ virtual void storeR0ToTOS(Type* pPointerType) {
+ assert(pPointerType->tag == TY_POINTER);
o(0x59); /* pop %ecx */
+ switch (pPointerType->pHead->tag) {
+ case TY_INT:
+ o(0x0189); /* movl %eax/%al, (%ecx) */
+ break;
+ case TY_CHAR:
+ o(0x0188); /* movl %eax/%al, (%ecx) */
+ break;
+ default:
+ assert(false);
+ break;
+ }
}
- virtual void storeR0ToR1(bool isInt) {
- o(0x0188 + isInt); /* movl %eax/%al, (%ecx) */
- }
-
- virtual void loadR0FromR0(bool isInt) {
- if (isInt)
- o(0x8b); /* mov (%eax), %eax */
- else
- o(0xbe0f); /* movsbl (%eax), %eax */
+ virtual void loadR0FromR0(Type* pPointerType) {
+ assert(pPointerType->tag == TY_POINTER);
+ switch (pPointerType->pHead->tag) {
+ case TY_INT:
+ o(0x8b); /* mov (%eax), %eax */
+ break;
+ case TY_CHAR:
+ o(0xbe0f); /* movsbl (%eax), %eax */
+ break;
+ default:
+ assert(false);
+ break;
+ }
ob(0); /* add zero in code */
}
@@ -1055,6 +1206,38 @@
return err;
}
+ /**
+ * Stack alignment (in bytes) for this type of data
+ */
+ virtual size_t stackAlignment(Type* pType){
+ switch(pType->tag) {
+ case TY_DOUBLE:
+ return 8;
+ default:
+ return 4;
+ }
+ }
+
+ /**
+ * Array element alignment (in bytes) for this type of data.
+ */
+ virtual size_t sizeOf(Type* pType){
+ switch(pType->tag) {
+ case TY_INT:
+ return 4;
+ case TY_CHAR:
+ return 1;
+ default:
+ return 0;
+ case TY_FLOAT:
+ return 4;
+ case TY_DOUBLE:
+ return 8;
+ case TY_POINTER:
+ return 4;
+ }
+ }
+
private:
/** Output 1 to 4 bytes.
@@ -1143,6 +1326,16 @@
mpBase->li(t);
}
+ virtual void lif(float f) {
+ fprintf(stderr, "lif(%g)\n", f);
+ mpBase->lif(f);
+ }
+
+ virtual void lid(double d) {
+ fprintf(stderr, "lid(%g)\n", d);
+ mpBase->lid(d);
+ }
+
virtual int gjmp(int t) {
int result = mpBase->gjmp(t);
fprintf(stderr, "gjmp(%d) = %d\n", t, result);
@@ -1166,9 +1359,15 @@
mpBase->genOp(op);
}
- virtual void clearR1() {
- fprintf(stderr, "clearR1()\n");
- mpBase->clearR1();
+
+ virtual void gUnaryCmp(int op) {
+ fprintf(stderr, "gUnaryCmp(%d)\n", op);
+ mpBase->gUnaryCmp(op);
+ }
+
+ virtual void genUnaryOp(int op) {
+ fprintf(stderr, "genUnaryOp(%d)\n", op);
+ mpBase->genUnaryOp(op);
}
virtual void pushR0() {
@@ -1176,19 +1375,14 @@
mpBase->pushR0();
}
- virtual void popR1() {
- fprintf(stderr, "popR1()\n");
- mpBase->popR1();
+ virtual void storeR0ToTOS(Type* pPointerType) {
+ fprintf(stderr, "storeR0ToTOS(%d)\n", pPointerType->pHead->tag);
+ mpBase->storeR0ToTOS(pPointerType);
}
- virtual void storeR0ToR1(bool isInt) {
- fprintf(stderr, "storeR0ToR1(%d)\n", isInt);
- mpBase->storeR0ToR1(isInt);
- }
-
- virtual void loadR0FromR0(bool isInt) {
- fprintf(stderr, "loadR0FromR0(%d)\n", isInt);
- mpBase->loadR0FromR0(isInt);
+ virtual void loadR0FromR0(Type* pPointerType) {
+ fprintf(stderr, "loadR0FromR0(%d)\n", pPointerType->pHead->tag);
+ mpBase->loadR0FromR0(pPointerType);
}
virtual void leaR0(int ea) {
@@ -1262,6 +1456,20 @@
fprintf(stderr, "finishCompile() = %d\n", result);
return result;
}
+
+ /**
+ * Stack alignment (in bytes) for this type of data
+ */
+ virtual size_t stackAlignment(Type* pType){
+ return mpBase->stackAlignment(pType);
+ }
+
+ /**
+ * Array element alignment (in bytes) for this type of data.
+ */
+ virtual size_t sizeOf(Type* pType){
+ return mpBase->sizeOf(pType);
+ }
};
#endif // PROVIDE_TRACE_CODEGEN
@@ -1492,8 +1700,6 @@
probe.pText = (char*) pText;
Token* pValue = (Token*) hashmapGet(mpMap, &probe);
if (pValue) {
- // printf("intern - found existing %s for %d\n",
- // pValue->pText, pValue->id);
return pValue->id;
}
}
@@ -1508,7 +1714,6 @@
pToken->id = mTokens.size() + TOKEN_BASE;
mTokens.push_back(pToken);
hashmapPut(mpMap, pToken, pToken);
- // printf("intern - new token %s %d\n", pToken->pText, pToken->id);
return pToken->id;
}
@@ -1657,6 +1862,10 @@
* ensure(1) = c;
}
+ void append(String& other) {
+ appendBytes(other.getUnwrapped(), other.len());
+ }
+
char* orphan() {
char* result = mpBase;
mpBase = 0;
@@ -1765,6 +1974,7 @@
tokenid_t tok;
size_t level;
VariableInfo* pOldDefinition;
+ Type* pType;
};
class SymbolStack {
@@ -1820,6 +2030,12 @@
return pNewV;
}
+ VariableInfo* add(Type* pType) {
+ VariableInfo* pVI = add(pType->id);
+ pVI->pType = pType;
+ return pVI;
+ }
+
void forEach(bool (*fn)(VariableInfo*, void*), void* context) {
for (size_t i = 0; i < mStack.size(); i++) {
if (! fn(mStack[i], context)) {
@@ -1847,6 +2063,7 @@
int ch; // Current input character, or EOF
tokenid_t tok; // token
intptr_t tokc; // token extra info
+ double tokd; // floating point constant value
int tokl; // token operator level
intptr_t rsym; // return symbol
intptr_t loc; // local variable index
@@ -1865,6 +2082,16 @@
SymbolStack mGlobals;
SymbolStack mLocals;
+ // Prebuilt types, makes things slightly faster.
+ Type* mkpInt; // int
+ Type* mkpChar; // char
+ Type* mkpVoid; // void
+ Type* mkpFloat;
+ Type* mkpDouble;
+ Type* mkpIntPtr;
+ Type* mkpCharPtr;
+ Type* mkpPtrIntFn;
+
InputStream* file;
CodeBuf codeBuf;
@@ -1879,6 +2106,8 @@
static const int TOK_DUMMY = 1;
static const int TOK_NUM = 2;
+ static const int TOK_NUM_FLOAT = 3;
+ static const int TOK_NUM_DOUBLE = 4;
// 3..255 are character and/or operators
@@ -1975,11 +2204,24 @@
* (char*) 0 = 0;
}
- VariableInfo* VI(tokenid_t t) {
- if ( t < TOK_SYMBOL || t-TOK_SYMBOL >= mTokenTable.size()) {
+ void assert(bool isTrue) {
+ if (!isTrue) {
internalError();
}
- // printf("Looking up %s %d\n", nameof(t), t);
+ }
+
+ bool isSymbol(tokenid_t t) {
+ return t >= TOK_SYMBOL &&
+ ((size_t) (t-TOK_SYMBOL)) < mTokenTable.size();
+ }
+
+ bool isSymbolOrKeyword(tokenid_t t) {
+ return t >= TOK_KEYWORD &&
+ ((size_t) (t-TOK_KEYWORD)) < mTokenTable.size();
+ }
+
+ VariableInfo* VI(tokenid_t t) {
+ assert(isSymbol(t));
VariableInfo* pV = mTokenTable[t].mpVariableInfo;
if (pV && pV->tok != t) {
internalError();
@@ -1991,7 +2233,8 @@
return t >= TOK_SYMBOL && VI(t) != 0;
}
- inline const char* nameof(tokenid_t t) {
+ const char* nameof(tokenid_t t) {
+ assert(isSymbolOrKeyword(t));
return mTokenTable[t].pText;
}
@@ -2105,6 +2348,56 @@
return ch >= '0' && ch <= '7';
}
+ bool acceptCh(int c) {
+ bool result = c == ch;
+ if (result) {
+ pdef(ch);
+ inp();
+ }
+ return result;
+ }
+
+ bool acceptDigitsCh() {
+ bool result = false;
+ while (isdigit(ch)) {
+ result = true;
+ pdef(ch);
+ inp();
+ }
+ return result;
+ }
+
+ void parseFloat() {
+ tok = TOK_NUM_DOUBLE;
+ // mTokenString already has the integral part of the number.
+ acceptCh('.');
+ acceptDigitsCh();
+ bool doExp = true;
+ if (acceptCh('e') || acceptCh('E')) {
+ // Don't need to do any extra work
+ } else if (ch == 'f' || ch == 'F') {
+ pdef('e'); // So it can be parsed by strtof.
+ inp();
+ tok = TOK_NUM_FLOAT;
+ } else {
+ doExp = false;
+ }
+ if (doExp) {
+ bool digitsRequired = acceptCh('-');
+ bool digitsFound = acceptDigitsCh();
+ if (digitsRequired && ! digitsFound) {
+ error("malformed exponent");
+ }
+ }
+ char* pText = mTokenString.getUnwrapped();
+ if (tok == TOK_NUM_FLOAT) {
+ tokd = strtof(pText, 0);
+ } else {
+ tokd = strtod(pText, 0);
+ }
+ //fprintf(stderr, "float constant: %s (%d) %g\n", pText, tok, tokd);
+ }
+
void next() {
int l, a;
@@ -2133,8 +2426,16 @@
inp();
}
if (isdigit(tok)) {
- tokc = strtol(mTokenString.getUnwrapped(), 0, 0);
- tok = TOK_NUM;
+ // Start of a numeric constant. Could be integer, float, or
+ // double, won't know until we look further.
+ if (ch == '.' || ch == 'e' || ch == 'e'
+ || ch == 'f' || ch == 'F') {
+ parseFloat();
+ } else {
+ // It's an integer constant
+ tokc = strtol(mTokenString.getUnwrapped(), 0, 0);
+ tok = TOK_NUM;
+ }
} else {
tok = mTokenTable.intern(mTokenString.getUnwrapped(),
mTokenString.len());
@@ -2209,7 +2510,8 @@
{
String buf;
decodeToken(buf, tok);
- printf("%s\n", buf.getUnwrapped()); }
+ fprintf(stderr, "%s\n", buf.getUnwrapped());
+ }
#endif
}
@@ -2296,76 +2598,106 @@
next();
}
- /* l is one if '=' parsing wanted (quick hack) */
- void unary(intptr_t l) {
- intptr_t n, t, a;
- int c;
- String tString;
- t = 0;
- n = 1; /* type of expression 0 = forward, 1 = value, other = lvalue */
- if (tok == '\"') {
+ bool accept(intptr_t c) {
+ if (tok == c) {
+ next();
+ return true;
+ }
+ return false;
+ }
+
+ bool acceptStringLiteral() {
+ if (tok == '"') {
pGen->li((int) glo);
- while (ch != '\"' && ch != EOF) {
- *allocGlobalSpace(1) = getq();
+ // This while loop merges multiple adjacent string constants.
+ while (tok == '"') {
+ while (ch != '"' && ch != EOF) {
+ *allocGlobalSpace(1) = getq();
+ }
+ if (ch != '"') {
+ error("Unterminated string constant.");
+ }
+ inp();
+ next();
}
- if (ch != '\"') {
- error("Unterminated string constant.");
- }
+ /* Null terminate */
*glo = 0;
/* align heap */
allocGlobalSpace((char*) (((intptr_t) glo + 4) & -4) - glo);
- inp();
- next();
+
+ return true;
+ }
+ return false;
+ }
+ /* Parse and evaluate a unary expression.
+ * allowAssignment is true if '=' parsing wanted (quick hack)
+ */
+ void unary(bool allowAssignment) {
+ intptr_t n, t, a;
+ t = 0;
+ n = 1; /* type of expression 0 = forward, 1 = value, other = lvalue */
+ if (acceptStringLiteral()) {
+ // Nothing else to do.
} else {
- c = tokl;
+ int c = tokl;
a = tokc;
+ double ad = tokd;
t = tok;
- tString = mTokenString;
next();
if (t == TOK_NUM) {
pGen->li(a);
+ } else if (t == TOK_NUM_FLOAT) {
+ pGen->lif(ad);
+ } else if (t == TOK_NUM_DOUBLE) {
+ pGen->lid(ad);
} else if (c == 2) {
/* -, +, !, ~ */
- unary(0);
- pGen->clearR1();
+ unary(false);
if (t == '!')
- pGen->gcmp(a);
+ pGen->gUnaryCmp(a);
else
- pGen->genOp(a);
+ pGen->genUnaryOp(a);
} else if (t == '(') {
expr();
skip(')');
} else if (t == '*') {
- /* parse cast */
+ /* This is a pointer dereference, but we currently only
+ * support a pointer dereference if it's immediately
+ * in front of a cast. So parse the cast right here.
+ */
skip('(');
- t = tok; /* get type */
- next(); /* skip int/char/void */
- next(); /* skip '*' or '(' */
- if (tok == '*') {
- /* function type */
- skip('*');
- skip(')');
- skip('(');
- skip(')');
+ Type* pCast = expectCastTypeDeclaration(mLocalArena);
+ // We currently only handle 3 types of cast:
+ // (int*), (char*) , (int (*)())
+ if(typeEqual(pCast, mkpIntPtr)) {
+ t = TOK_INT;
+ } else if (typeEqual(pCast, mkpCharPtr)) {
+ t = TOK_CHAR;
+ } else if (typeEqual(pCast, mkpPtrIntFn)){
t = 0;
+ } else {
+ String buffer;
+ decodeType(buffer, pCast);
+ error("Unsupported cast type %s", buffer.getUnwrapped());
+ decodeType(buffer, mkpPtrIntFn);
}
skip(')');
- unary(0);
- if (tok == '=') {
- next();
+ unary(false);
+ if (accept('=')) {
pGen->pushR0();
expr();
- pGen->popR1();
- pGen->storeR0ToR1(t == TOK_INT);
+ pGen->storeR0ToTOS(pCast);
} else if (t) {
- pGen->loadR0FromR0(t == TOK_INT);
+ pGen->loadR0FromR0(pCast);
}
+ // Else we fall through to the function call below, with
+ // t == 0 to trigger an indirect function call. Hack!
} else if (t == '&') {
pGen->leaR0((int) VI(tok)->pAddress);
next();
} else if (t == EOF ) {
error("Unexpected EOF.");
- } else if (!checkSymbol(t, &tString)) {
+ } else if (!checkSymbol(t)) {
// Don't have to do anything special here, the error
// message was printed by checkSymbol() above.
} else {
@@ -2377,11 +2709,10 @@
n = (intptr_t) VI(t)->pAddress;
/* forward reference: try dlsym */
if (!n) {
- n = (intptr_t) dlsym(RTLD_DEFAULT,
- tString.getUnwrapped());
+ n = (intptr_t) dlsym(RTLD_DEFAULT, nameof(t));
VI(t)->pAddress = (void*) n;
}
- if ((tok == '=') & l) {
+ if ((tok == '=') & allowAssignment) {
/* assignment */
next();
expr();
@@ -2389,7 +2720,7 @@
} else if (tok != '(') {
/* variable */
if (!n) {
- error("Undefined variable %s", tString.getUnwrapped());
+ error("Undefined variable %s", nameof(t));
}
pGen->loadR0(n, tokl == 11, tokc);
if (tokl == 11) {
@@ -2407,13 +2738,16 @@
/* push args and invert order */
a = pGen->beginFunctionCallArguments();
next();
- l = 0;
+ int l = 0;
while (tok != ')' && tok != EOF) {
expr();
pGen->storeR0ToArg(l);
- if (tok == ',')
- next();
l = l + 4;
+ if (accept(',')) {
+ // fine
+ } else if ( tok != ')') {
+ error("Expected ',' or ')'");
+ }
}
pGen->endFunctionCallArguments(a, l);
skip(')');
@@ -2430,28 +2764,29 @@
}
}
- void sum(int l) {
+ /* Recursive descent parser for binary operations.
+ */
+ void binaryOp(int level) {
intptr_t t, n, a;
t = 0;
- if (l-- == 1)
- unary(1);
+ if (level-- == 1)
+ unary(true);
else {
- sum(l);
+ binaryOp(level);
a = 0;
- while (l == tokl) {
+ while (level == tokl) {
n = tok;
t = tokc;
next();
- if (l > 8) {
+ if (level > 8) {
a = pGen->gtst(t == OP_LOGICAL_OR, a); /* && and || output code generation */
- sum(l);
+ binaryOp(level);
} else {
pGen->pushR0();
- sum(l);
- pGen->popR1();
+ binaryOp(level);
- if ((l == 4) | (l == 5)) {
+ if ((level == 4) | (level == 5)) {
pGen->gcmp(t);
} else {
pGen->genOp(t);
@@ -2459,7 +2794,7 @@
}
}
/* && and || output code generation */
- if (a && l > 8) {
+ if (a && level > 8) {
a = pGen->gtst(t == OP_LOGICAL_OR, a);
pGen->li(t != OP_LOGICAL_OR);
pGen->gjmp(5); /* jmp $ + 5 (sizeof li, FIXME for ARM) */
@@ -2470,7 +2805,7 @@
}
void expr() {
- sum(11);
+ binaryOp(11);
}
int test_expr() {
@@ -2481,9 +2816,10 @@
void block(intptr_t l, bool outermostFunctionBlock) {
intptr_t a, n, t;
- if (tok == TOK_INT || tok == TOK_CHAR) {
+ Type* pBaseType;
+ if ((pBaseType = acceptPrimitiveType(mLocalArena))) {
/* declarations */
- localDeclarations();
+ localDeclarations(pBaseType);
} else if (tok == TOK_IF) {
next();
skip('(');
@@ -2539,13 +2875,11 @@
mLocals.popLevel();
}
} else {
- if (tok == TOK_RETURN) {
- next();
+ if (accept(TOK_RETURN)) {
if (tok != ';')
expr();
rsym = pGen->gjmp(rsym); /* jmp */
- } else if (tok == TOK_BREAK) {
- next();
+ } else if (accept(TOK_BREAK)) {
*(int *) l = pGen->gjmp(*(int *) l);
} else if (tok != ';')
expr();
@@ -2553,105 +2887,352 @@
}
}
- typedef int Type;
- static const Type TY_UNKNOWN = 0;
- static const Type TY_INT = 1;
- static const Type TY_CHAR = 2;
- static const Type TY_VOID = 3;
- static const int TY_BASE_TYPE_MASK = 0xf;
- static const int TY_INDIRECTION_MASK = 0xf0;
- static const int TY_INDIRECTION_SHIFT = 4;
- static const int MAX_INDIRECTION_COUNT = 15;
+ enum TypeTag {
+ TY_INT, TY_CHAR, TY_VOID, TY_FLOAT, TY_DOUBLE,
+ TY_POINTER, TY_FUNC, TY_PARAM
+ };
- Type getBaseType(Type t) {
- return t & TY_BASE_TYPE_MASK;
- }
+ struct Type {
+ TypeTag tag;
+ tokenid_t id; // For function arguments
+ Type* pHead;
+ Type* pTail;
+ };
- int getIndirectionCount(Type t) {
- return (TY_INDIRECTION_MASK & t) >> TY_INDIRECTION_SHIFT;
- }
-
- void setIndirectionCount(Type& t, int count) {
- t = ((TY_INDIRECTION_MASK & (count << TY_INDIRECTION_SHIFT))
- | (t & ~TY_INDIRECTION_MASK));
- }
-
- bool acceptType(Type& t) {
- t = TY_UNKNOWN;
- if (tok == TOK_INT) {
- t = TY_INT;
- } else if (tok == TOK_CHAR) {
- t = TY_CHAR;
- } else if (tok == TOK_VOID) {
- t = TY_VOID;
- } else {
+ bool typeEqual(Type* a, Type* b) {
+ if (a == b) {
+ return true;
+ }
+ if (a == NULL || b == NULL) {
return false;
}
- next();
+ TypeTag at = a->tag;
+ if (at != b->tag) {
+ return false;
+ }
+ if (at == TY_POINTER) {
+ return typeEqual(a->pHead, b->pHead);
+ } else if (at == TY_FUNC || at == TY_PARAM) {
+ return typeEqual(a->pHead, b->pHead)
+ && typeEqual(a->pTail, b->pTail);
+ }
return true;
}
- Type acceptPointerDeclaration(Type& base) {
- Type t = base;
- int indirectionCount = 0;
- while (tok == '*' && indirectionCount <= MAX_INDIRECTION_COUNT) {
- next();
- indirectionCount++;
- }
- if (indirectionCount > MAX_INDIRECTION_COUNT) {
- error("Too many levels of pointer. Max %d", MAX_INDIRECTION_COUNT);
- }
- setIndirectionCount(t, indirectionCount);
- return t;
+ Type* createType(TypeTag tag, Type* pHead, Type* pTail, Arena& arena) {
+ assert(tag >= TY_INT && tag <= TY_PARAM);
+ Type* pType = (Type*) arena.alloc(sizeof(Type));
+ memset(pType, 0, sizeof(*pType));
+ pType->tag = tag;
+ pType->pHead = pHead;
+ pType->pTail = pTail;
+ return pType;
}
- void expectType(Type& t) {
- if (!acceptType(t)) {
+ Type* createPtrType(Type* pType, Arena& arena) {
+ return createType(TY_POINTER, pType, NULL, arena);
+ }
+
+ /**
+ * Try to print a type in declaration order
+ */
+ void decodeType(String& buffer, Type* pType) {
+ buffer.clear();
+ if (pType == NULL) {
+ buffer.appendCStr("null");
+ return;
+ }
+ decodeTypeImp(buffer, pType);
+ }
+
+ void decodeTypeImp(String& buffer, Type* pType) {
+ decodeTypeImpPrefix(buffer, pType);
+
+ String temp;
+ if (pType->id != 0) {
+ decodeToken(temp, pType->id);
+ buffer.append(temp);
+ }
+
+ decodeTypeImpPostfix(buffer, pType);
+ }
+
+ void decodeTypeImpPrefix(String& buffer, Type* pType) {
+ TypeTag tag = pType->tag;
+
+ if (tag >= TY_INT && tag <= TY_VOID) {
+ switch (tag) {
+ case TY_INT:
+ buffer.appendCStr("int");
+ break;
+ case TY_CHAR:
+ buffer.appendCStr("char");
+ break;
+ case TY_VOID:
+ buffer.appendCStr("void");
+ break;
+ case TY_FLOAT:
+ buffer.appendCStr("float");
+ break;
+ case TY_DOUBLE:
+ buffer.appendCStr("double");
+ break;
+ default:
+ break;
+ }
+ buffer.append(' ');
+ }
+
+ switch (tag) {
+ case TY_INT:
+ break;
+ case TY_CHAR:
+ break;
+ case TY_VOID:
+ break;
+ case TY_FLOAT:
+ break;
+ case TY_DOUBLE:
+ break;
+ case TY_POINTER:
+ decodeTypeImpPrefix(buffer, pType->pHead);
+ if(pType->pHead && pType->pHead->tag == TY_FUNC) {
+ buffer.append('(');
+ }
+ buffer.append('*');
+ break;
+ case TY_FUNC:
+ decodeTypeImp(buffer, pType->pHead);
+ break;
+ case TY_PARAM:
+ decodeTypeImp(buffer, pType->pHead);
+ break;
+ default:
+ String temp;
+ temp.printf("Unknown tag %d", pType->tag);
+ buffer.append(temp);
+ break;
+ }
+ }
+
+ void decodeTypeImpPostfix(String& buffer, Type* pType) {
+ TypeTag tag = pType->tag;
+
+ switch(tag) {
+ case TY_POINTER:
+ if(pType->pHead && pType->pHead->tag == TY_FUNC) {
+ buffer.append(')');
+ }
+ decodeTypeImpPostfix(buffer, pType->pHead);
+ break;
+ case TY_FUNC:
+ buffer.append('(');
+ for(Type* pArg = pType->pTail; pArg; pArg = pArg->pTail) {
+ decodeTypeImp(buffer, pArg);
+ if (pArg->pTail) {
+ buffer.appendCStr(", ");
+ }
+ }
+ buffer.append(')');
+ break;
+ default:
+ break;
+ }
+ }
+
+ void printType(Type* pType) {
+ String buffer;
+ decodeType(buffer, pType);
+ fprintf(stderr, "%s\n", buffer.getUnwrapped());
+ }
+
+ Type* acceptPrimitiveType(Arena& arena) {
+ Type* pType;
+ if (tok == TOK_INT) {
+ pType = mkpInt;
+ } else if (tok == TOK_CHAR) {
+ pType = mkpChar;
+ } else if (tok == TOK_VOID) {
+ pType = mkpVoid;
+ } else if (tok == TOK_FLOAT) {
+ pType = mkpFloat;
+ } else if (tok == TOK_DOUBLE) {
+ pType = mkpDouble;
+ } else {
+ return NULL;
+ }
+ next();
+ return pType;
+ }
+
+ Type* acceptDeclaration(Type* pType, bool nameAllowed, bool nameRequired,
+ Arena& arena) {
+ tokenid_t declName = 0;
+ pType = acceptDecl2(pType, declName, nameAllowed,
+ nameRequired, arena);
+ if (declName) {
+ // Clone the parent type so we can set a unique ID
+ pType = createType(pType->tag, pType->pHead,
+ pType->pTail, arena);
+
+ pType->id = declName;
+ }
+ // fprintf(stderr, "Parsed a declaration: ");
+ // printType(pType);
+ return pType;
+ }
+
+ Type* expectDeclaration(Type* pBaseType, Arena& arena) {
+ Type* pType = acceptDeclaration(pBaseType, true, true, arena);
+ if (! pType) {
+ error("Expected a declaration");
+ }
+ return pType;
+ }
+
+ /* Used for accepting types that appear in casts */
+ Type* acceptCastTypeDeclaration(Arena& arena) {
+ Type* pType = acceptPrimitiveType(arena);
+ if (pType) {
+ pType = acceptDeclaration(pType, false, false, arena);
+ }
+ return pType;
+ }
+
+ Type* expectCastTypeDeclaration(Arena& arena) {
+ Type* pType = acceptCastTypeDeclaration(arena);
+ if (! pType) {
+ error("Expected a declaration");
+ }
+ return pType;
+ }
+
+ Type* acceptDecl2(Type* pType, tokenid_t& declName,
+ bool nameAllowed, bool nameRequired, Arena& arena) {
+ int ptrCounter = 0;
+ while (accept('*')) {
+ ptrCounter++;
+ }
+ pType = acceptDecl3(pType, declName, nameAllowed, nameRequired, arena);
+ while (ptrCounter-- > 0) {
+ pType = createType(TY_POINTER, pType, NULL, arena);
+ }
+ return pType;
+ }
+
+ Type* acceptDecl3(Type* pType, tokenid_t& declName,
+ bool nameAllowed, bool nameRequired, Arena& arena) {
+ // direct-dcl :
+ // name
+ // (dcl)
+ // direct-dcl()
+ // direct-dcl[]
+ Type* pNewHead = NULL;
+ if (accept('(')) {
+ pNewHead = acceptDecl2(pNewHead, declName, nameAllowed,
+ nameRequired, arena);
+ skip(')');
+ } else if ((declName = acceptSymbol()) != 0) {
+ if (nameAllowed == false && declName) {
+ error("Symbol %s not allowed here", nameof(declName));
+ } else if (nameRequired && ! declName) {
+ String temp;
+ decodeToken(temp, tok);
+ error("Expected symbol. Got %s", temp.getUnwrapped());
+ }
+ }
+ while (accept('(')) {
+ // Function declaration
+ Type* pTail = acceptArgs(nameAllowed, arena);
+ pType = createType(TY_FUNC, pType, pTail, arena);
+ skip(')');
+ }
+
+ if (pNewHead) {
+ Type* pA = pNewHead;
+ while (pA->pHead) {
+ pA = pA->pHead;
+ }
+ pA->pHead = pType;
+ pType = pNewHead;
+ }
+ return pType;
+ }
+
+ Type* acceptArgs(bool nameAllowed, Arena& arena) {
+ Type* pHead = NULL;
+ Type* pTail = NULL;
+ for(;;) {
+ Type* pBaseArg = acceptPrimitiveType(arena);
+ if (pBaseArg) {
+ Type* pArg = acceptDeclaration(pBaseArg, nameAllowed, false,
+ arena);
+ if (pArg) {
+ Type* pParam = createType(TY_PARAM, pArg, NULL, arena);
+ if (!pHead) {
+ pHead = pParam;
+ pTail = pParam;
+ } else {
+ pTail->pTail = pParam;
+ pTail = pParam;
+ }
+ }
+ }
+ if (! accept(',')) {
+ break;
+ }
+ }
+ return pHead;
+ }
+
+ Type* expectPrimitiveType(Arena& arena) {
+ Type* pType = acceptPrimitiveType(arena);
+ if (!pType) {
String buf;
decodeToken(buf, tok);
error("Expected a type, got %s", buf.getUnwrapped());
}
+ return pType;
}
- void addGlobalSymbol() {
- VariableInfo* pVI = VI(tok);
+ void addGlobalSymbol(Type* pDecl) {
+ tokenid_t t = pDecl->id;
+ VariableInfo* pVI = VI(t);
if(pVI && pVI->pAddress) {
- reportDuplicate();
+ reportDuplicate(t);
}
- mGlobals.add(tok);
+ mGlobals.add(pDecl);
}
- void reportDuplicate() {
- error("Duplicate definition of %s", nameof(tok));
+ void reportDuplicate(tokenid_t t) {
+ error("Duplicate definition of %s", nameof(t));
}
- void addLocalSymbol() {
- if (mLocals.isDefinedAtCurrentLevel(tok)) {
- reportDuplicate();
+ void addLocalSymbol(Type* pDecl) {
+ tokenid_t t = pDecl->id;
+ if (mLocals.isDefinedAtCurrentLevel(t)) {
+ reportDuplicate(t);
}
- mLocals.add(tok);
+ mLocals.add(pDecl);
}
- void localDeclarations() {
+ void localDeclarations(Type* pBaseType) {
intptr_t a;
- Type base;
- while (acceptType(base)) {
+ while (pBaseType) {
while (tok != ';' && tok != EOF) {
- Type t = acceptPointerDeclaration(t);
- int variableAddress = 0;
- if (checkSymbol()) {
- addLocalSymbol();
- if (tok) {
- loc = loc + 4;
- variableAddress = -loc;
- VI(tok)->pAddress = (void*) variableAddress;
- }
+ Type* pDecl = expectDeclaration(pBaseType, mLocalArena);
+ if (!pDecl) {
+ break;
}
- next();
- if (tok == '=') {
+ int variableAddress = 0;
+ addLocalSymbol(pDecl);
+ loc = loc + pGen->sizeOf(pDecl);
+ loc = loc + 4;
+ variableAddress = -loc;
+ VI(pDecl->id)->pAddress = (void*) variableAddress;
+ if (accept('=')) {
/* assignment */
- next();
expr();
pGen->storeR0(variableAddress);
}
@@ -2659,11 +3240,12 @@
next();
}
skip(';');
+ pBaseType = acceptPrimitiveType(mLocalArena);
}
}
bool checkSymbol() {
- return checkSymbol(tok, &mTokenString);
+ return checkSymbol(tok);
}
void decodeToken(String& buffer, tokenid_t token) {
@@ -2672,7 +3254,11 @@
} else if (token == TOK_NUM) {
buffer.printf("numeric constant");
} else if (token >= 0 && token < 256) {
- buffer.printf("char \'%c\'", token);
+ if (token < 32) {
+ buffer.printf("'\\x%02x'", token);
+ } else {
+ buffer.printf("'%c'", token);
+ }
} else if (token >= TOK_KEYWORD && token < TOK_SYMBOL) {
buffer.printf("keyword \"%s\"", nameof(token));
} else {
@@ -2680,7 +3266,7 @@
}
}
- bool checkSymbol(tokenid_t token, String* pText) {
+ bool checkSymbol(tokenid_t token) {
bool result = token >= TOK_SYMBOL;
if (!result) {
String temp;
@@ -2690,32 +3276,39 @@
return result;
}
+ tokenid_t acceptSymbol() {
+ tokenid_t result = 0;
+ if (tok >= TOK_SYMBOL) {
+ result = tok;
+ next();
+ }
+ return result;
+ }
+
void globalDeclarations() {
while (tok != EOF) {
- Type base;
- expectType(base);
- Type t = acceptPointerDeclaration(t);
- if (tok < TOK_SYMBOL) {
- error("Unexpected token %d", tok);
+ Type* pBaseType = expectPrimitiveType(mGlobalArena);
+ if (!pBaseType) {
break;
}
- if (! isDefined(tok)) {
- addGlobalSymbol();
+ Type* pDecl = expectDeclaration(pBaseType, mGlobalArena);
+ if (!pDecl) {
+ break;
}
- VariableInfo* name = VI(tok);
+ if (! isDefined(pDecl->id)) {
+ addGlobalSymbol(pDecl);
+ }
+ VariableInfo* name = VI(pDecl->id);
if (name && name->pAddress) {
- error("Already defined global %s",
- mTokenString.getUnwrapped());
+ error("Already defined global %s", nameof(pDecl->id));
}
- next();
- if (tok == ',' || tok == ';' || tok == '=') {
+ if (pDecl->tag < TY_FUNC) {
// it's a variable declaration
for(;;) {
- if (name) {
+ if (name && !name->pAddress) {
name->pAddress = (int*) allocGlobalSpace(4);
}
- if (tok == '=') {
- next();
+ if (accept('=')) {
if (tok == TOK_NUM) {
if (name) {
* (int*) name->pAddress = tokc;
@@ -2725,52 +3318,50 @@
error("Expected an integer constant");
}
}
- if (tok != ',') {
+ if (!accept(',')) {
break;
}
- skip(',');
- t = acceptPointerDeclaration(t);
- addGlobalSymbol();
- name = VI(tok);
- next();
+ pDecl = expectDeclaration(pBaseType, mGlobalArena);
+ if (!pDecl) {
+ break;
+ }
+ if (! isDefined(pDecl->id)) {
+ addGlobalSymbol(pDecl);
+ }
+ name = VI(pDecl->id);
}
skip(';');
} else {
- if (name) {
- /* patch forward references (XXX: does not work for function
- pointers) */
- pGen->gsym((int) name->pForward);
- /* put function address */
- name->pAddress = (void*) codeBuf.getPC();
- }
- skip('(');
- mLocals.pushLevel();
- intptr_t a = 8;
- int argCount = 0;
- while (tok != ')' && tok != EOF) {
- Type aType;
- expectType(aType);
- aType = acceptPointerDeclaration(aType);
- if (checkSymbol()) {
- addLocalSymbol();
- if (tok) {
- /* read param name and compute offset */
- VI(tok)->pAddress = (void*) a;
- a = a + 4;
- }
+ // Function declaration
+ if (accept(';')) {
+ // forward declaration.
+ } else {
+ if (name) {
+ /* patch forward references (XXX: does not work for function
+ pointers) */
+ pGen->gsym((int) name->pForward);
+ /* put function address */
+ name->pAddress = (void*) codeBuf.getPC();
}
- next();
- if (tok == ',')
- next();
- argCount++;
+ // Calculate stack offsets for parameters
+ mLocals.pushLevel();
+ intptr_t a = 8;
+ int argCount = 0;
+ for (Type* pP = pDecl->pTail; pP; pP = pP->pTail) {
+ Type* pArg = pP->pHead;
+ addLocalSymbol(pArg);
+ /* read param name and compute offset */
+ VI(pArg->id)->pAddress = (void*) a;
+ a = a + 4;
+ argCount++;
+ }
+ rsym = loc = 0;
+ a = pGen->functionEntry(argCount);
+ block(0, true);
+ pGen->gsym(rsym);
+ pGen->functionExit(argCount, a, loc);
+ mLocals.popLevel();
}
- skip(')');
- rsym = loc = 0;
- a = pGen->functionEntry(argCount);
- block(0, true);
- pGen->gsym(rsym);
- pGen->functionExit(argCount, a, loc);
- mLocals.popLevel();
}
}
}
@@ -2878,6 +3469,7 @@
mLocals.setTokenTable(&mTokenTable);
internKeywords();
+ createPrimitiveTypes();
codeBuf.init(ALLOC_SIZE);
setArchitecture(NULL);
if (!pGen) {
@@ -2904,6 +3496,19 @@
return result;
}
+ void createPrimitiveTypes() {
+ mkpInt = createType(TY_INT, NULL, NULL, mGlobalArena);
+ mkpChar = createType(TY_CHAR, NULL, NULL, mGlobalArena);
+ mkpVoid = createType(TY_VOID, NULL, NULL, mGlobalArena);
+ mkpFloat = createType(TY_FLOAT, NULL, NULL, mGlobalArena);
+ mkpDouble = createType(TY_DOUBLE, NULL, NULL, mGlobalArena);
+ mkpIntPtr = createPtrType(mkpInt, mGlobalArena);
+ mkpCharPtr = createPtrType(mkpChar, mGlobalArena);
+ mkpPtrIntFn = createPtrType(
+ createType(TY_FUNC, mkpInt, NULL, mGlobalArena),
+ mGlobalArena);
+ }
+
void checkForUndefinedForwardReferences() {
mGlobals.forEach(static_ufrcFn, this);
}
diff --git a/libacc/tests/data/double.c b/libacc/tests/data/double.c
new file mode 100644
index 0000000..5bc20a3
--- /dev/null
+++ b/libacc/tests/data/double.c
@@ -0,0 +1,7 @@
+double atof(char *nptr);
+
+int main() {
+ printf("Value = %g\n", atof("10.42"));
+ return 0;
+}
+
diff --git a/libacc/tests/data/testStringConcat.c b/libacc/tests/data/testStringConcat.c
new file mode 100644
index 0000000..bf06ae1
--- /dev/null
+++ b/libacc/tests/data/testStringConcat.c
@@ -0,0 +1,4 @@
+int main() {
+ return printf("Hello" "," " world\n");
+}
+
diff --git a/libacc/tests/test.py b/libacc/tests/test.py
index ef5963b..016c587 100644
--- a/libacc/tests/test.py
+++ b/libacc/tests/test.py
@@ -58,8 +58,15 @@
def compare(a, b):
if a != b:
- firstDiff = firstDifference(a,b)
- print "Strings differ at character", firstDiff, a[firstDiff], b[firstDiff]
+ firstDiff = firstDifference(a, b)
+ print "Strings differ at character %d '%s' != '%s'" % (
+ firstDiff, safeAccess(a, firstDiff), safeAccess(b, firstDiff))
+
+def safeAccess(s, i):
+ if 0 <= i < len(s):
+ return s[i]
+ else:
+ return '?'
def firstDifference(a, b):
commonLen = min(len(a), len(b))
@@ -89,6 +96,11 @@
def testRunReturnVal(self):
self.compileCheck(["-R", "data/returnval-ansi.c"],
"Executing compiled code:\nresult: 42\n")
+
+ def testStingLiteralConcatenation(self):
+ self.compileCheck(["-R", "data/testStringConcat.c"],
+ "Executing compiled code:\nresult: 13\n", "Hello, world\n")
+
def testRunOTCCANSI(self):
self.compileCheck(["-R", "data/otcc-ansi.c", "data/returnval.c"],
"Executing compiled code:\notcc-ansi.c: About to execute compiled code:\natcc-ansi.c: result: 42\nresult: 42\n")
diff --git a/libcutils/Android.mk b/libcutils/Android.mk
index 6754a74..087d652 100644
--- a/libcutils/Android.mk
+++ b/libcutils/Android.mk
@@ -20,7 +20,7 @@
array.c \
hashmap.c \
atomic.c \
- native_handle.c \
+ native_handle.c \
buffer.c \
socket_inaddr_any_server.c \
socket_local_client.c \
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 47acd15..062957a 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -34,6 +34,7 @@
write /proc/cpu/alignment 4
write /proc/sys/kernel/sched_latency_ns 10000000
write /proc/sys/kernel/sched_wakeup_granularity_ns 2000000
+ write /proc/sys/kernel/sched_compat_yield 1
# Create cgroup mount points for process groups
mkdir /dev/cpuctl
@@ -78,6 +79,11 @@
mkdir /data/misc/keystore 0770 keystore keystore
mkdir /data/misc/vpn 0770 system system
mkdir /data/misc/vpn/profiles 0770 system system
+ mkdir /data/misc/wifi 0770 wifi system
+ chown wifi system /data/misc/wifi
+ touch /data/misc/wifi/wpa_supplicant.conf
+ chmod 0660 /data/misc/wifi/wpa_supplicant.conf
+ chown wifi system /data/misc/wifi/wpa_supplicant.conf
mkdir /data/local 0771 shell shell
mkdir /data/local/tmp 0771 shell shell
mkdir /data/data 0771 system system
@@ -288,13 +294,17 @@
service flash_recovery /system/bin/flash_image recovery /system/recovery.img
oneshot
-service racoon /system/bin/racoon -F -f /etc/racoon/racoon.conf
+service racoon /system/bin/racoon
socket racoon stream 600 system system
+ # racoon will setuid to vpn after getting necessary resources.
+ group net_admin keystore
disabled
oneshot
service mtpd /system/bin/mtpd
socket mtpd stream 600 system system
+ user vpn
+ group vpn net_admin net_raw
disabled
oneshot
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index 5a8dc0b..70b13dc 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -42,7 +42,7 @@
smd \
chmod \
chown \
- mkdosfs \
+ newfs_msdos \
netstat \
ioctl \
mv \
diff --git a/toolbox/mkdosfs.c b/toolbox/mkdosfs.c
deleted file mode 100644
index 66e720b..0000000
--- a/toolbox/mkdosfs.c
+++ /dev/null
@@ -1,848 +0,0 @@
-/* $NetBSD: newfs_msdos.c,v 1.18.2.1 2005/05/01 18:44:02 tron Exp $ */
-
-/*
- * Copyright (c) 1998 Robert Nordier
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS
- * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) 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.
- */
-
-#define __USE_FILE_OFFSET64
-
-#include <sys/cdefs.h>
-
-#include <sys/types.h>
-#include <sys/param.h>
-#ifdef __FreeBSD__
-#include <sys/diskslice.h>
-#endif
-#include <sys/mount.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/ioctl.h>
-
-#include <ctype.h>
-#include <err.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <paths.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <unistd.h>
-#ifdef __NetBSD__
-#include <disktab.h>
-#include <util.h>
-#endif
-
-#define MAXU16 0xffff /* maximum unsigned 16-bit quantity */
-#define BPN 4 /* bits per nibble */
-#define NPB 2 /* nibbles per byte */
-
-#define DOSMAGIC 0xaa55 /* DOS magic number */
-#define MINBPS 128 /* minimum bytes per sector */
-#define MAXSPC 128 /* maximum sectors per cluster */
-#define MAXNFT 16 /* maximum number of FATs */
-#define DEFBLK 4096 /* default block size */
-#define DEFBLK16 2048 /* default block size FAT16 */
-#define DEFRDE 512 /* default root directory entries */
-#define RESFTE 2 /* reserved FAT entries */
-#define MINCLS12 1 /* minimum FAT12 clusters */
-#define MINCLS16 0x1000 /* minimum FAT16 clusters */
-#define MINCLS32 2 /* minimum FAT32 clusters */
-#define MAXCLS12 0xfed /* maximum FAT12 clusters */
-#define MAXCLS16 0xfff5 /* maximum FAT16 clusters */
-#define MAXCLS32 0xffffff5 /* maximum FAT32 clusters */
-
-#define mincls(fat) ((fat) == 12 ? MINCLS12 : \
- (fat) == 16 ? MINCLS16 : \
- MINCLS32)
-
-#define maxcls(fat) ((fat) == 12 ? MAXCLS12 : \
- (fat) == 16 ? MAXCLS16 : \
- MAXCLS32)
-
-#define mk1(p, x) \
- (p) = (u_int8_t)(x)
-
-#define mk2(p, x) \
- (p)[0] = (u_int8_t)(x), \
- (p)[1] = (u_int8_t)((x) >> 010)
-
-#define mk4(p, x) \
- (p)[0] = (u_int8_t)(x), \
- (p)[1] = (u_int8_t)((x) >> 010), \
- (p)[2] = (u_int8_t)((x) >> 020), \
- (p)[3] = (u_int8_t)((x) >> 030)
-
-#define argto1(arg, lo, msg) argtou(arg, lo, 0xff, msg)
-#define argto2(arg, lo, msg) argtou(arg, lo, 0xffff, msg)
-#define argto4(arg, lo, msg) argtou(arg, lo, 0xffffffff, msg)
-#define argtox(arg, lo, msg) argtou(arg, lo, UINT_MAX, msg)
-
-#ifndef MAX
-#define MAX(x, y) ((x) > (y) ? (x) : (y))
-#endif
-#ifndef MIN
-#define MIN(x, y) ((x) < (y) ? (x) : (y))
-#endif
-
-static int powerof2(int x) {
- int i;
- for (i = 0; i < 32; i++) {
- if (x & 1) {
- x >>= 1;
- // if x is zero, then original x was a power of two
- return (x == 0);
- }
- x >>= 1;
- }
-
- return 0;
-}
-
-#ifndef howmany
-#define howmany(x, y) (((x)+((y)-1))/(y))
-#endif
-
-#pragma pack(push, 1)
-struct bs {
- u_int8_t jmp[3]; /* bootstrap entry point */
- u_int8_t oem[8]; /* OEM name and version */
-};
-#define BS_SIZE 11
-
-struct bsbpb {
- u_int8_t bps[2]; /* bytes per sector */
- u_int8_t spc; /* sectors per cluster */
- u_int8_t res[2]; /* reserved sectors */
- u_int8_t nft; /* number of FATs */
- u_int8_t rde[2]; /* root directory entries */
- u_int8_t sec[2]; /* total sectors */
- u_int8_t mid; /* media descriptor */
- u_int8_t spf[2]; /* sectors per FAT */
- u_int8_t spt[2]; /* sectors per track */
- u_int8_t hds[2]; /* drive heads */
- u_int8_t hid[4]; /* hidden sectors */
- u_int8_t bsec[4]; /* big total sectors */
-};
-#define BSBPB_SIZE 25
-
-struct bsxbpb {
- u_int8_t bspf[4]; /* big sectors per FAT */
- u_int8_t xflg[2]; /* FAT control flags */
- u_int8_t vers[2]; /* file system version */
- u_int8_t rdcl[4]; /* root directory start cluster */
- u_int8_t infs[2]; /* file system info sector */
- u_int8_t bkbs[2]; /* backup boot sector */
- u_int8_t rsvd[12]; /* reserved */
-};
-#define BSXBPB_SIZE 28
-
-struct bsx {
- u_int8_t drv; /* drive number */
- u_int8_t rsvd; /* reserved */
- u_int8_t sig; /* extended boot signature */
- u_int8_t volid[4]; /* volume ID number */
- u_int8_t label[11]; /* volume label */
- u_int8_t type[8]; /* file system type */
-};
-#define BSX_SIZE 26
-
-struct de {
- u_int8_t namext[11]; /* name and extension */
- u_int8_t attr; /* attributes */
- u_int8_t rsvd[10]; /* reserved */
- u_int8_t time[2]; /* creation time */
- u_int8_t date[2]; /* creation date */
- u_int8_t clus[2]; /* starting cluster */
- u_int8_t size[4]; /* size */
-#define DE_SIZE 32
-};
-#pragma pack(pop)
-
-struct bpb {
- u_int bps; /* bytes per sector */
- u_int spc; /* sectors per cluster */
- u_int res; /* reserved sectors */
- u_int nft; /* number of FATs */
- u_int rde; /* root directory entries */
- u_int sec; /* total sectors */
- u_int mid; /* media descriptor */
- u_int spf; /* sectors per FAT */
- u_int spt; /* sectors per track */
- u_int hds; /* drive heads */
- u_int hid; /* hidden sectors */
- u_int bsec; /* big total sectors */
- u_int bspf; /* big sectors per FAT */
- u_int rdcl; /* root directory start cluster */
- u_int infs; /* file system info sector */
- u_int bkbs; /* backup boot sector */
-};
-
-static u_int8_t bootcode[] = {
- 0xfa, /* cli */
- 0x31, 0xc0, /* xor ax,ax */
- 0x8e, 0xd0, /* mov ss,ax */
- 0xbc, 0x00, 0x7c, /* mov sp,7c00h */
- 0xfb, /* sti */
- 0x8e, 0xd8, /* mov ds,ax */
- 0xe8, 0x00, 0x00, /* call $ + 3 */
- 0x5e, /* pop si */
- 0x83, 0xc6, 0x19, /* add si,+19h */
- 0xbb, 0x07, 0x00, /* mov bx,0007h */
- 0xfc, /* cld */
- 0xac, /* lodsb */
- 0x84, 0xc0, /* test al,al */
- 0x74, 0x06, /* jz $ + 8 */
- 0xb4, 0x0e, /* mov ah,0eh */
- 0xcd, 0x10, /* int 10h */
- 0xeb, 0xf5, /* jmp $ - 9 */
- 0x30, 0xe4, /* xor ah,ah */
- 0xcd, 0x16, /* int 16h */
- 0xcd, 0x19, /* int 19h */
- 0x0d, 0x0a,
- 'N', 'o', 'n', '-', 's', 'y', 's', 't',
- 'e', 'm', ' ', 'd', 'i', 's', 'k',
- 0x0d, 0x0a,
- 'P', 'r', 'e', 's', 's', ' ', 'a', 'n',
- 'y', ' ', 'k', 'e', 'y', ' ', 't', 'o',
- ' ', 'r', 'e', 'b', 'o', 'o', 't',
- 0x0d, 0x0a,
- 0
-};
-
-static void print_bpb(struct bpb *);
-static u_int ckgeom(const char *, u_int, const char *);
-static u_int argtou(const char *, u_int, u_int, const char *);
-static int oklabel(const char *);
-static void mklabel(u_int8_t *, const char *);
-static void setstr(u_int8_t *, const char *, size_t);
-static void usage(char* progname);
-
-/*
- * Construct a FAT12, FAT16, or FAT32 file system.
- */
-int
-mkdosfs_main(int argc, char *argv[])
-{
- static char opts[] = "NB:F:I:L:O:S:a:b:c:e:f:h:i:k:m:n:o:r:s:u:";
- static const char *opt_B, *opt_L, *opt_O;
- static u_int opt_F, opt_I, opt_S, opt_a, opt_b, opt_c, opt_e;
- static u_int opt_h, opt_i, opt_k, opt_m, opt_n, opt_o, opt_r;
- static u_int opt_s, opt_u;
- static int opt_N;
- static int Iflag, mflag, oflag;
- char buf[MAXPATHLEN];
- struct stat sb;
- struct timeval tv;
- struct bpb bpb;
- struct tm *tm;
- struct bs *bs;
- struct bsbpb *bsbpb;
- struct bsxbpb *bsxbpb;
- struct bsx *bsx;
- struct de *de;
- u_int8_t *img;
- const char *fname, *dtype, *bname;
- ssize_t n;
- time_t now;
- u_int fat, bss, rds, cls, dir, lsn, x, x1, x2;
- int ch, fd, fd1;
- char* progname = argv[0];
-
- while ((ch = getopt(argc, argv, opts)) != -1)
- switch (ch) {
- case 'N':
- opt_N = 1;
- break;
- case 'B':
- opt_B = optarg;
- break;
- case 'F':
- if (strcmp(optarg, "12") &&
- strcmp(optarg, "16") &&
- strcmp(optarg, "32"))
- fprintf(stderr, "%s: bad FAT type\n", optarg);
- opt_F = atoi(optarg);
- break;
- case 'I':
- opt_I = argto4(optarg, 0, "volume ID");
- Iflag = 1;
- break;
- case 'L':
- if (!oklabel(optarg))
- fprintf(stderr, "%s: bad volume label\n", optarg);
- opt_L = optarg;
- break;
- case 'O':
- if (strlen(optarg) > 8)
- fprintf(stderr, "%s: bad OEM string\n", optarg);
- opt_O = optarg;
- break;
- case 'S':
- opt_S = argto2(optarg, 1, "bytes/sector");
- break;
- case 'a':
- opt_a = argto4(optarg, 1, "sectors/FAT");
- break;
- case 'b':
- opt_b = argtox(optarg, 1, "block size");
- opt_c = 0;
- break;
- case 'c':
- opt_c = argto1(optarg, 1, "sectors/cluster");
- opt_b = 0;
- break;
- case 'e':
- opt_e = argto2(optarg, 1, "directory entries");
- break;
- case 'h':
- opt_h = argto2(optarg, 1, "drive heads");
- break;
- case 'i':
- opt_i = argto2(optarg, 1, "info sector");
- break;
- case 'k':
- opt_k = argto2(optarg, 1, "backup sector");
- break;
- case 'm':
- opt_m = argto1(optarg, 0, "media descriptor");
- mflag = 1;
- break;
- case 'n':
- opt_n = argto1(optarg, 1, "number of FATs");
- break;
- case 'o':
- opt_o = argto4(optarg, 0, "hidden sectors");
- oflag = 1;
- break;
- case 'r':
- opt_r = argto2(optarg, 1, "reserved sectors");
- break;
- case 's':
- opt_s = argto4(optarg, 1, "file system size");
- break;
- case 'u':
- opt_u = argto2(optarg, 1, "sectors/track");
- break;
- default:
- usage(progname);
- }
- argc -= optind;
- argv += optind;
- if (argc < 1 || argc > 2)
- usage(progname);
- fname = *argv++;
- if (!strchr(fname, '/')) {
- snprintf(buf, sizeof(buf), "%sr%s", _PATH_DEV, fname);
- if (!(fname = strdup(buf)))
- fprintf(stderr, NULL);
- }
- dtype = *argv;
- if ((fd = open(fname, opt_N ? O_RDONLY : O_RDWR)) == -1 ||
- fstat(fd, &sb))
- fprintf(stderr, "%s\n", fname);
- memset(&bpb, 0, sizeof(bpb));
-
- if (opt_h)
- bpb.hds = opt_h;
- if (opt_u)
- bpb.spt = opt_u;
- if (opt_S)
- bpb.bps = opt_S;
- if (opt_s)
- bpb.bsec = opt_s;
- if (oflag)
- bpb.hid = opt_o;
-
- bpb.bps = 512; // 512 bytes/sector
- bpb.spc = 8; // 4K clusters
-
-
- fprintf(stderr, "opening %s\n", fname);
- if ((fd1 = open(fname, O_RDONLY)) == -1) {
- fprintf(stderr, "failed to open %s\n", fname);
- exit(1);
- }
-
- lseek64(fd1, 0, SEEK_SET);
- loff_t length = lseek64(fd1, 0, SEEK_END);
- if (length > 0) {
- bpb.bsec = length / bpb.bps;
- bpb.spt = bpb.bsec;
- // use FAT32 for 2 gig or greater
- if (length >= 2LL *1024 *1024 *1024) {
- fat = 32;
- } else {
- fat = 16;
- }
- }
- close(fd1);
- fd1 = -1;
-
- if (!powerof2(bpb.bps))
- fprintf(stderr, "bytes/sector (%u) is not a power of 2\n", bpb.bps);
- if (bpb.bps < MINBPS)
- fprintf(stderr, "bytes/sector (%u) is too small; minimum is %u\n",
- bpb.bps, MINBPS);
-
- if (!(fat = opt_F)) {
- if (!opt_e && (opt_i || opt_k))
- fat = 32;
- }
-
- if ((fat == 32 && opt_e) || (fat != 32 && (opt_i || opt_k)))
- fprintf(stderr, "-%c is not a legal FAT%s option\n",
- fat == 32 ? 'e' : opt_i ? 'i' : 'k',
- fat == 32 ? "32" : "12/16");
- if (fat == 32)
- bpb.rde = 0;
- if (opt_b) {
- if (!powerof2(opt_b))
- fprintf(stderr, "block size (%u) is not a power of 2\n", opt_b);
- if (opt_b < bpb.bps)
- fprintf(stderr, "block size (%u) is too small; minimum is %u\n",
- opt_b, bpb.bps);
- if (opt_b > bpb.bps * MAXSPC)
- fprintf(stderr, "block size (%u) is too large; maximum is %u\n",
- opt_b, bpb.bps * MAXSPC);
- bpb.spc = opt_b / bpb.bps;
- }
- if (opt_c) {
- if (!powerof2(opt_c))
- fprintf(stderr, "sectors/cluster (%u) is not a power of 2\n", opt_c);
- bpb.spc = opt_c;
- }
- if (opt_r)
- bpb.res = opt_r;
- if (opt_n) {
- if (opt_n > MAXNFT)
- fprintf(stderr, "number of FATs (%u) is too large; maximum is %u\n",
- opt_n, MAXNFT);
- bpb.nft = opt_n;
- }
- if (opt_e)
- bpb.rde = opt_e;
- if (mflag) {
- if (opt_m < 0xf0)
- fprintf(stderr, "illegal media descriptor (%#x)\n", opt_m);
- bpb.mid = opt_m;
- }
- if (opt_a)
- bpb.bspf = opt_a;
- if (opt_i)
- bpb.infs = opt_i;
- if (opt_k)
- bpb.bkbs = opt_k;
- bss = 1;
- bname = NULL;
- fd1 = -1;
- if (opt_B) {
- bname = opt_B;
- if (!strchr(bname, '/')) {
- snprintf(buf, sizeof(buf), "/boot/%s", bname);
- if (!(bname = strdup(buf)))
- fprintf(stderr, NULL);
- }
- if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb))
- fprintf(stderr, "%s", bname);
- if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bps ||
- sb.st_size < bpb.bps || sb.st_size > bpb.bps * MAXU16)
- fprintf(stderr, "%s: inappropriate file type or format\n", bname);
- bss = sb.st_size / bpb.bps;
- }
- if (!bpb.nft)
- bpb.nft = 2;
- if (!fat) {
- if (bpb.bsec < (bpb.res ? bpb.res : bss) +
- howmany((RESFTE + (bpb.spc ? MINCLS16 : MAXCLS12 + 1)) *
- ((bpb.spc ? 16 : 12) / BPN), bpb.bps * NPB) *
- bpb.nft +
- howmany(bpb.rde ? bpb.rde : DEFRDE,
- bpb.bps / DE_SIZE) +
- (bpb.spc ? MINCLS16 : MAXCLS12 + 1) *
- (bpb.spc ? bpb.spc : howmany(DEFBLK, bpb.bps)))
- fat = 12;
- else if (bpb.rde || bpb.bsec <
- (bpb.res ? bpb.res : bss) +
- howmany((RESFTE + MAXCLS16) * 2, bpb.bps) * bpb.nft +
- howmany(DEFRDE, bpb.bps / DE_SIZE) +
- (MAXCLS16 + 1) *
- (bpb.spc ? bpb.spc : howmany(8192, bpb.bps)))
- fat = 16;
- else
- fat = 32;
- }
- x = bss;
- if (fat == 32) {
- if (!bpb.infs) {
- if (x == MAXU16 || x == bpb.bkbs)
- fprintf(stderr, "no room for info sector\n");
- bpb.infs = x;
- }
- if (bpb.infs != MAXU16 && x <= bpb.infs)
- x = bpb.infs + 1;
- if (!bpb.bkbs) {
- if (x == MAXU16)
- fprintf(stderr, "no room for backup sector\n");
- bpb.bkbs = x;
- } else if (bpb.bkbs != MAXU16 && bpb.bkbs == bpb.infs)
- fprintf(stderr, "backup sector would overwrite info sector\n");
- if (bpb.bkbs != MAXU16 && x <= bpb.bkbs)
- x = bpb.bkbs + 1;
- }
- if (!bpb.res)
- bpb.res = fat == 32 ? MAX(x, MAX(16384 / bpb.bps, 4)) : x;
- else if (bpb.res < x)
- fprintf(stderr, "too few reserved sectors (need %d have %d)\n", x, bpb.res);
- if (fat != 32 && !bpb.rde)
- bpb.rde = DEFRDE;
- rds = howmany(bpb.rde, bpb.bps / DE_SIZE);
- if (!bpb.spc)
- for (bpb.spc = howmany(fat == 16 ? DEFBLK16 : DEFBLK, bpb.bps);
- bpb.spc < MAXSPC &&
- bpb.res +
- howmany((RESFTE + maxcls(fat)) * (fat / BPN),
- bpb.bps * NPB) * bpb.nft +
- rds +
- (u_int64_t)(maxcls(fat) + 1) * bpb.spc <= bpb.bsec;
- bpb.spc <<= 1);
- if (fat != 32 && bpb.bspf > MAXU16)
- fprintf(stderr, "too many sectors/FAT for FAT12/16\n");
- x1 = bpb.res + rds;
- x = bpb.bspf ? bpb.bspf : 1;
- if (x1 + (u_int64_t)x * bpb.nft > bpb.bsec)
- fprintf(stderr, "meta data exceeds file system size\n");
- x1 += x * bpb.nft;
- x = (u_int64_t)(bpb.bsec - x1) * bpb.bps * NPB /
- (bpb.spc * bpb.bps * NPB + fat / BPN * bpb.nft);
- x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN),
- bpb.bps * NPB);
- if (!bpb.bspf) {
- bpb.bspf = x2;
- x1 += (bpb.bspf - 1) * bpb.nft;
- }
- cls = (bpb.bsec - x1) / bpb.spc;
- x = (u_int64_t)bpb.bspf * bpb.bps * NPB / (fat / BPN) - RESFTE;
- if (cls > x)
- cls = x;
- if (bpb.bspf < x2)
- fprintf(stderr, "warning: sectors/FAT limits file system to %u clusters\n",
- cls);
- if (cls < mincls(fat))
- fprintf(stderr, "%u clusters too few clusters for FAT%u, need %u\n", cls, fat,
- mincls(fat));
- if (cls > maxcls(fat)) {
- cls = maxcls(fat);
- bpb.bsec = x1 + (cls + 1) * bpb.spc - 1;
- fprintf(stderr, "warning: FAT type limits file system to %u sectors\n",
- bpb.bsec);
- }
- printf("%s: %u sector%s in %u FAT%u cluster%s "
- "(%u bytes/cluster)\n", fname, cls * bpb.spc,
- cls * bpb.spc == 1 ? "" : "s", cls, fat,
- cls == 1 ? "" : "s", bpb.bps * bpb.spc);
- if (!bpb.mid)
- bpb.mid = !bpb.hid ? 0xf0 : 0xf8;
- if (fat == 32)
- bpb.rdcl = RESFTE;
- if (bpb.hid + bpb.bsec <= MAXU16) {
- bpb.sec = bpb.bsec;
- bpb.bsec = 0;
- }
- if (fat != 32) {
- bpb.spf = bpb.bspf;
- bpb.bspf = 0;
- }
- ch = 0;
- if (fat == 12)
- ch = 1; /* 001 Primary DOS with 12 bit FAT */
- else if (fat == 16) {
- if (bpb.bsec == 0)
- ch = 4; /* 004 Primary DOS with 16 bit FAT <32M */
- else
- ch = 6; /* 006 Primary 'big' DOS, 16-bit FAT (> 32MB) */
- /*
- * XXX: what about:
- * 014 DOS (16-bit FAT) - LBA
- * ?
- */
- } else if (fat == 32) {
- ch = 11; /* 011 Primary DOS with 32 bit FAT */
- /*
- * XXX: what about:
- * 012 Primary DOS with 32 bit FAT - LBA
- * ?
- */
- }
- if (ch != 0)
- printf("MBR type: %d\n", ch);
- print_bpb(&bpb);
- if (!opt_N) {
- gettimeofday(&tv, NULL);
- now = tv.tv_sec;
- tm = localtime(&now);
- if (!(img = malloc(bpb.bps)))
- fprintf(stderr, NULL);
- dir = bpb.res + (bpb.spf ? bpb.spf : bpb.bspf) * bpb.nft;
-
- for (lsn = 0; lsn < dir + (fat == 32 ? bpb.spc : rds); lsn++) {
- x = lsn;
- if (opt_B &&
- fat == 32 && bpb.bkbs != MAXU16 &&
- bss <= bpb.bkbs && x >= bpb.bkbs) {
- x -= bpb.bkbs;
- if (!x && lseek64(fd1, 0, SEEK_SET))
- fprintf(stderr, "lseek64 failed for %s\n", bname);
- }
- if (opt_B && x < bss) {
- if ((n = read(fd1, img, bpb.bps)) == -1)
- fprintf(stderr, "%s\n", bname);
- if (n != bpb.bps)
- fprintf(stderr, "%s: can't read sector %u\n", bname, x);
- } else
- memset(img, 0, bpb.bps);
- if (!lsn ||
- (fat == 32 && bpb.bkbs != MAXU16 && lsn == bpb.bkbs)) {
- x1 = BS_SIZE;
- bsbpb = (struct bsbpb *)(img + x1);
- mk2(bsbpb->bps, bpb.bps);
- mk1(bsbpb->spc, bpb.spc);
- mk2(bsbpb->res, bpb.res);
- mk1(bsbpb->nft, bpb.nft);
- mk2(bsbpb->rde, bpb.rde);
- mk2(bsbpb->sec, bpb.sec);
- mk1(bsbpb->mid, bpb.mid);
- mk2(bsbpb->spf, bpb.spf);
- mk2(bsbpb->spt, bpb.spt);
- mk2(bsbpb->hds, bpb.hds);
- mk4(bsbpb->hid, bpb.hid);
- mk4(bsbpb->bsec, bpb.bsec);
- x1 += BSBPB_SIZE;
- if (fat == 32) {
- bsxbpb = (struct bsxbpb *)(img + x1);
- mk4(bsxbpb->bspf, bpb.bspf);
- mk2(bsxbpb->xflg, 0);
- mk2(bsxbpb->vers, 0);
- mk4(bsxbpb->rdcl, bpb.rdcl);
- mk2(bsxbpb->infs, bpb.infs);
- mk2(bsxbpb->bkbs, bpb.bkbs);
- x1 += BSXBPB_SIZE;
- }
- bsx = (struct bsx *)(img + x1);
- mk1(bsx->sig, 0x29);
- if (Iflag)
- x = opt_I;
- else
- x = (((u_int)(1 + tm->tm_mon) << 8 |
- (u_int)tm->tm_mday) +
- ((u_int)tm->tm_sec << 8 |
- (u_int)(tv.tv_usec / 10))) << 16 |
- ((u_int)(1900 + tm->tm_year) +
- ((u_int)tm->tm_hour << 8 |
- (u_int)tm->tm_min));
- mk4(bsx->volid, x);
- mklabel(bsx->label, opt_L ? opt_L : "NO_NAME");
- snprintf(buf, sizeof(buf), "FAT%u", fat);
- setstr(bsx->type, buf, sizeof(bsx->type));
- if (!opt_B) {
- x1 += BSX_SIZE;
- bs = (struct bs *)img;
- mk1(bs->jmp[0], 0xeb);
- mk1(bs->jmp[1], x1 - 2);
- mk1(bs->jmp[2], 0x90);
- setstr(bs->oem, opt_O ? opt_O : "NetBSD",
- sizeof(bs->oem));
- memcpy(img + x1, bootcode, sizeof(bootcode));
- mk2(img + bpb.bps - 2, DOSMAGIC);
- }
- } else if (fat == 32 && bpb.infs != MAXU16 &&
- (lsn == bpb.infs ||
- (bpb.bkbs != MAXU16 &&
- lsn == bpb.bkbs + bpb.infs))) {
- mk4(img, 0x41615252);
- mk4(img + bpb.bps - 28, 0x61417272);
- mk4(img + bpb.bps - 24, 0xffffffff);
- mk4(img + bpb.bps - 20, bpb.rdcl);
- mk2(img + bpb.bps - 2, DOSMAGIC);
- } else if (lsn >= bpb.res && lsn < dir &&
- !((lsn - bpb.res) %
- (bpb.spf ? bpb.spf : bpb.bspf))) {
- mk1(img[0], bpb.mid);
- for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
- mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
- } else if (lsn == dir && opt_L) {
- de = (struct de *)img;
- mklabel(de->namext, opt_L);
- mk1(de->attr, 050);
- x = (u_int)tm->tm_hour << 11 |
- (u_int)tm->tm_min << 5 |
- (u_int)tm->tm_sec >> 1;
- mk2(de->time, x);
- x = (u_int)(tm->tm_year - 80) << 9 |
- (u_int)(tm->tm_mon + 1) << 5 |
- (u_int)tm->tm_mday;
- mk2(de->date, x);
- }
- if ((n = write(fd, img, bpb.bps)) == -1)
- fprintf(stderr, "%s\n", fname);
- if (n != bpb.bps)
- fprintf(stderr, "%s: can't write sector %u\n", fname, lsn);
- }
- }
- return 0;
-}
-
-/*
- * Print out BPB values.
- */
-static void
-print_bpb(struct bpb *bpb)
-{
- printf("bps=%u spc=%u res=%u nft=%u", bpb->bps, bpb->spc, bpb->res,
- bpb->nft);
- if (bpb->rde)
- printf(" rde=%u", bpb->rde);
- if (bpb->sec)
- printf(" sec=%u", bpb->sec);
- printf(" mid=%#x", bpb->mid);
- if (bpb->spf)
- printf(" spf=%u", bpb->spf);
- printf(" spt=%u hds=%u hid=%u", bpb->spt, bpb->hds, bpb->hid);
- if (bpb->bsec)
- printf(" bsec=%u", bpb->bsec);
- if (!bpb->spf) {
- printf(" bspf=%u rdcl=%u", bpb->bspf, bpb->rdcl);
- printf(" infs=");
- printf(bpb->infs == MAXU16 ? "%#x" : "%u", bpb->infs);
- printf(" bkbs=");
- printf(bpb->bkbs == MAXU16 ? "%#x" : "%u", bpb->bkbs);
- }
- printf("\n");
-}
-
-/*
- * Check a disk geometry value.
- */
-static u_int
-ckgeom(const char *fname, u_int val, const char *msg)
-{
- if (!val)
- fprintf(stderr, "%s: no default %s\n", fname, msg);
- if (val > MAXU16)
- fprintf(stderr, "%s: illegal %s\n", fname, msg);
- return val;
-}
-
-/*
- * Convert and check a numeric option argument.
- */
-static u_int
-argtou(const char *arg, u_int lo, u_int hi, const char *msg)
-{
- char *s;
- u_long x;
-
- errno = 0;
- x = strtoul(arg, &s, 0);
- if (errno || !*arg || *s || x < lo || x > hi)
- fprintf(stderr, "%s: bad %s\n", arg, msg);
- return x;
-}
-
-/*
- * Check a volume label.
- */
-static int
-oklabel(const char *src)
-{
- int c, i;
-
- for (i = 0; i <= 11; i++) {
- c = (u_char)*src++;
- if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
- break;
- }
- return i && !c;
-}
-
-/*
- * Make a volume label.
- */
-static void
-mklabel(u_int8_t *dest, const char *src)
-{
- int c, i;
-
- for (i = 0; i < 11; i++) {
- c = *src ? toupper((unsigned char)*src++) : ' ';
- *dest++ = !i && c == '\xe5' ? 5 : c;
- }
-}
-
-/*
- * Copy string, padding with spaces.
- */
-static void
-setstr(u_int8_t *dest, const char *src, size_t len)
-{
- while (len--)
- *dest++ = *src ? *src++ : ' ';
-}
-
-/*
- * Print usage message.
- */
-static void
-usage(char* progname)
-{
- fprintf(stderr,
- "usage: %s [ -options ] special [disktype]\n", progname);
- fprintf(stderr, "where the options are:\n");
- fprintf(stderr, "\t-N don't create file system: "
- "just print out parameters\n");
- fprintf(stderr, "\t-B get bootstrap from file\n");
- fprintf(stderr, "\t-F FAT type (12, 16, or 32)\n");
- fprintf(stderr, "\t-I volume ID\n");
- fprintf(stderr, "\t-L volume label\n");
- fprintf(stderr, "\t-O OEM string\n");
- fprintf(stderr, "\t-S bytes/sector\n");
- fprintf(stderr, "\t-a sectors/FAT\n");
- fprintf(stderr, "\t-b block size\n");
- fprintf(stderr, "\t-c sectors/cluster\n");
- fprintf(stderr, "\t-e root directory entries\n");
- fprintf(stderr, "\t-h drive heads\n");
- fprintf(stderr, "\t-i file system info sector\n");
- fprintf(stderr, "\t-k backup boot sector\n");
- fprintf(stderr, "\t-m media descriptor\n");
- fprintf(stderr, "\t-n number of FATs\n");
- fprintf(stderr, "\t-o hidden sectors\n");
- fprintf(stderr, "\t-r reserved sectors\n");
- fprintf(stderr, "\t-s file system size (sectors)\n");
- fprintf(stderr, "\t-u sectors/track\n");
- exit(1);
-}
-
-
diff --git a/toolbox/mount.c b/toolbox/mount.c
index 395c943..472c952 100644
--- a/toolbox/mount.c
+++ b/toolbox/mount.c
@@ -226,7 +226,7 @@
{
char *type = NULL;
int c;
- int loop;
+ int loop = 0;
progname = argv[0];
rwflag = MS_VERBOSE;
diff --git a/toolbox/newfs_msdos.c b/toolbox/newfs_msdos.c
new file mode 100644
index 0000000..4483cc0
--- /dev/null
+++ b/toolbox/newfs_msdos.c
@@ -0,0 +1,1098 @@
+/*
+ * Copyright (c) 1998 Robert Nordier
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) 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.
+ */
+
+#ifndef lint
+static const char rcsid[] =
+ "$FreeBSD: src/sbin/newfs_msdos/newfs_msdos.c,v 1.33 2009/04/11 14:56:29 ed Exp $";
+#endif /* not lint */
+
+#include <sys/param.h>
+
+#ifndef ANDROID
+ #include <sys/fdcio.h>
+ #include <sys/disk.h>
+ #include <sys/disklabel.h>
+ #include <sys/mount.h>
+#else
+ #include <stdarg.h>
+ #include <linux/fs.h>
+ #include <linux/hdreg.h>
+#endif
+
+#include <sys/stat.h>
+#include <sys/time.h>
+
+#include <ctype.h>
+#include <err.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <paths.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#define MAXU16 0xffff /* maximum unsigned 16-bit quantity */
+#define BPN 4 /* bits per nibble */
+#define NPB 2 /* nibbles per byte */
+
+#define DOSMAGIC 0xaa55 /* DOS magic number */
+#define MINBPS 512 /* minimum bytes per sector */
+#define MAXSPC 128 /* maximum sectors per cluster */
+#define MAXNFT 16 /* maximum number of FATs */
+#define DEFBLK 4096 /* default block size */
+#define DEFBLK16 2048 /* default block size FAT16 */
+#define DEFRDE 512 /* default root directory entries */
+#define RESFTE 2 /* reserved FAT entries */
+#define MINCLS12 1 /* minimum FAT12 clusters */
+#define MINCLS16 0x1000 /* minimum FAT16 clusters */
+#define MINCLS32 2 /* minimum FAT32 clusters */
+#define MAXCLS12 0xfed /* maximum FAT12 clusters */
+#define MAXCLS16 0xfff5 /* maximum FAT16 clusters */
+#define MAXCLS32 0xffffff5 /* maximum FAT32 clusters */
+
+#define mincls(fat) ((fat) == 12 ? MINCLS12 : \
+ (fat) == 16 ? MINCLS16 : \
+ MINCLS32)
+
+#define maxcls(fat) ((fat) == 12 ? MAXCLS12 : \
+ (fat) == 16 ? MAXCLS16 : \
+ MAXCLS32)
+
+#define mk1(p, x) \
+ (p) = (u_int8_t)(x)
+
+#define mk2(p, x) \
+ (p)[0] = (u_int8_t)(x), \
+ (p)[1] = (u_int8_t)((x) >> 010)
+
+#define mk4(p, x) \
+ (p)[0] = (u_int8_t)(x), \
+ (p)[1] = (u_int8_t)((x) >> 010), \
+ (p)[2] = (u_int8_t)((x) >> 020), \
+ (p)[3] = (u_int8_t)((x) >> 030)
+
+#define argto1(arg, lo, msg) argtou(arg, lo, 0xff, msg)
+#define argto2(arg, lo, msg) argtou(arg, lo, 0xffff, msg)
+#define argto4(arg, lo, msg) argtou(arg, lo, 0xffffffff, msg)
+#define argtox(arg, lo, msg) argtou(arg, lo, UINT_MAX, msg)
+
+struct bs {
+ u_int8_t jmp[3]; /* bootstrap entry point */
+ u_int8_t oem[8]; /* OEM name and version */
+};
+
+struct bsbpb {
+ u_int8_t bps[2]; /* bytes per sector */
+ u_int8_t spc; /* sectors per cluster */
+ u_int8_t res[2]; /* reserved sectors */
+ u_int8_t nft; /* number of FATs */
+ u_int8_t rde[2]; /* root directory entries */
+ u_int8_t sec[2]; /* total sectors */
+ u_int8_t mid; /* media descriptor */
+ u_int8_t spf[2]; /* sectors per FAT */
+ u_int8_t spt[2]; /* sectors per track */
+ u_int8_t hds[2]; /* drive heads */
+ u_int8_t hid[4]; /* hidden sectors */
+ u_int8_t bsec[4]; /* big total sectors */
+};
+
+struct bsxbpb {
+ u_int8_t bspf[4]; /* big sectors per FAT */
+ u_int8_t xflg[2]; /* FAT control flags */
+ u_int8_t vers[2]; /* file system version */
+ u_int8_t rdcl[4]; /* root directory start cluster */
+ u_int8_t infs[2]; /* file system info sector */
+ u_int8_t bkbs[2]; /* backup boot sector */
+ u_int8_t rsvd[12]; /* reserved */
+};
+
+struct bsx {
+ u_int8_t drv; /* drive number */
+ u_int8_t rsvd; /* reserved */
+ u_int8_t sig; /* extended boot signature */
+ u_int8_t volid[4]; /* volume ID number */
+ u_int8_t label[11]; /* volume label */
+ u_int8_t type[8]; /* file system type */
+};
+
+struct de {
+ u_int8_t namext[11]; /* name and extension */
+ u_int8_t attr; /* attributes */
+ u_int8_t rsvd[10]; /* reserved */
+ u_int8_t time[2]; /* creation time */
+ u_int8_t date[2]; /* creation date */
+ u_int8_t clus[2]; /* starting cluster */
+ u_int8_t size[4]; /* size */
+};
+
+struct bpb {
+ u_int bps; /* bytes per sector */
+ u_int spc; /* sectors per cluster */
+ u_int res; /* reserved sectors */
+ u_int nft; /* number of FATs */
+ u_int rde; /* root directory entries */
+ u_int sec; /* total sectors */
+ u_int mid; /* media descriptor */
+ u_int spf; /* sectors per FAT */
+ u_int spt; /* sectors per track */
+ u_int hds; /* drive heads */
+ u_int hid; /* hidden sectors */
+ u_int bsec; /* big total sectors */
+ u_int bspf; /* big sectors per FAT */
+ u_int rdcl; /* root directory start cluster */
+ u_int infs; /* file system info sector */
+ u_int bkbs; /* backup boot sector */
+};
+
+#define BPBGAP 0, 0, 0, 0, 0, 0
+
+static struct {
+ const char *name;
+ struct bpb bpb;
+} const stdfmt[] = {
+ {"160", {512, 1, 1, 2, 64, 320, 0xfe, 1, 8, 1, BPBGAP}},
+ {"180", {512, 1, 1, 2, 64, 360, 0xfc, 2, 9, 1, BPBGAP}},
+ {"320", {512, 2, 1, 2, 112, 640, 0xff, 1, 8, 2, BPBGAP}},
+ {"360", {512, 2, 1, 2, 112, 720, 0xfd, 2, 9, 2, BPBGAP}},
+ {"640", {512, 2, 1, 2, 112, 1280, 0xfb, 2, 8, 2, BPBGAP}},
+ {"720", {512, 2, 1, 2, 112, 1440, 0xf9, 3, 9, 2, BPBGAP}},
+ {"1200", {512, 1, 1, 2, 224, 2400, 0xf9, 7, 15, 2, BPBGAP}},
+ {"1232", {1024,1, 1, 2, 192, 1232, 0xfe, 2, 8, 2, BPBGAP}},
+ {"1440", {512, 1, 1, 2, 224, 2880, 0xf0, 9, 18, 2, BPBGAP}},
+ {"2880", {512, 2, 1, 2, 240, 5760, 0xf0, 9, 36, 2, BPBGAP}}
+};
+
+static const u_int8_t bootcode[] = {
+ 0xfa, /* cli */
+ 0x31, 0xc0, /* xor ax,ax */
+ 0x8e, 0xd0, /* mov ss,ax */
+ 0xbc, 0x00, 0x7c, /* mov sp,7c00h */
+ 0xfb, /* sti */
+ 0x8e, 0xd8, /* mov ds,ax */
+ 0xe8, 0x00, 0x00, /* call $ + 3 */
+ 0x5e, /* pop si */
+ 0x83, 0xc6, 0x19, /* add si,+19h */
+ 0xbb, 0x07, 0x00, /* mov bx,0007h */
+ 0xfc, /* cld */
+ 0xac, /* lodsb */
+ 0x84, 0xc0, /* test al,al */
+ 0x74, 0x06, /* jz $ + 8 */
+ 0xb4, 0x0e, /* mov ah,0eh */
+ 0xcd, 0x10, /* int 10h */
+ 0xeb, 0xf5, /* jmp $ - 9 */
+ 0x30, 0xe4, /* xor ah,ah */
+ 0xcd, 0x16, /* int 16h */
+ 0xcd, 0x19, /* int 19h */
+ 0x0d, 0x0a,
+ 'N', 'o', 'n', '-', 's', 'y', 's', 't',
+ 'e', 'm', ' ', 'd', 'i', 's', 'k',
+ 0x0d, 0x0a,
+ 'P', 'r', 'e', 's', 's', ' ', 'a', 'n',
+ 'y', ' ', 'k', 'e', 'y', ' ', 't', 'o',
+ ' ', 'r', 'e', 'b', 'o', 'o', 't',
+ 0x0d, 0x0a,
+ 0
+};
+
+static void check_mounted(const char *, mode_t);
+static void getstdfmt(const char *, struct bpb *);
+static void getdiskinfo(int, const char *, const char *, int,
+ struct bpb *);
+static void print_bpb(struct bpb *);
+static u_int ckgeom(const char *, u_int, const char *);
+static u_int argtou(const char *, u_int, u_int, const char *);
+static off_t argtooff(const char *, const char *);
+static int oklabel(const char *);
+static void mklabel(u_int8_t *, const char *);
+static void setstr(u_int8_t *, const char *, size_t);
+static void usage(void);
+
+#ifdef ANDROID
+static void err(int val, const char *fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ char *fmt2;
+ asprintf(&fmt2, "%s\n", fmt);
+ vfprintf(stderr, fmt2, ap);
+ free(fmt2);
+ va_end(ap);
+}
+
+static void errx(int val, const char *fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ char *fmt2;
+ asprintf(&fmt2, "%s\n", fmt);
+ vfprintf(stderr, fmt2, ap);
+ free(fmt2);
+ va_end(ap);
+}
+
+static void warnx(const char *fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ char *fmt2;
+ asprintf(&fmt2, "%s\n", fmt);
+ vfprintf(stderr, fmt2, ap);
+ free(fmt2);
+ va_end(ap);
+}
+#define powerof2(x) ((((x) - 1) & (x)) == 0)
+#define howmany(x, y) (((x) + ((y) - 1)) / (y))
+#define MAX(x,y) ((x) > (y) ? (x) : (y))
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+
+#endif
+/*
+ * Construct a FAT12, FAT16, or FAT32 file system.
+ */
+int
+newfs_msdos_main(int argc, char *argv[])
+{
+ static const char opts[] = "@:NB:C:F:I:L:O:S:a:b:c:e:f:h:i:k:m:n:o:r:s:u:";
+ const char *opt_B = NULL, *opt_L = NULL, *opt_O = NULL, *opt_f = NULL;
+ u_int opt_F = 0, opt_I = 0, opt_S = 0, opt_a = 0, opt_b = 0, opt_c = 0;
+ u_int opt_e = 0, opt_h = 0, opt_i = 0, opt_k = 0, opt_m = 0, opt_n = 0;
+ u_int opt_o = 0, opt_r = 0, opt_s = 0, opt_u = 0;
+ int opt_N = 0;
+ int Iflag = 0, mflag = 0, oflag = 0;
+ char buf[MAXPATHLEN];
+ struct stat sb;
+ struct timeval tv;
+ struct bpb bpb;
+ struct tm *tm;
+ struct bs *bs;
+ struct bsbpb *bsbpb;
+ struct bsxbpb *bsxbpb;
+ struct bsx *bsx;
+ struct de *de;
+ u_int8_t *img;
+ const char *fname, *dtype, *bname;
+ ssize_t n;
+ time_t now;
+ u_int fat, bss, rds, cls, dir, lsn, x, x1, x2;
+ int ch, fd, fd1;
+ off_t opt_create = 0, opt_ofs = 0;
+
+ while ((ch = getopt(argc, argv, opts)) != -1)
+ switch (ch) {
+ case '@':
+ opt_ofs = argtooff(optarg, "offset");
+ break;
+ case 'N':
+ opt_N = 1;
+ break;
+ case 'B':
+ opt_B = optarg;
+ break;
+ case 'C':
+ opt_create = argtooff(optarg, "create size");
+ break;
+ case 'F':
+ if (strcmp(optarg, "12") &&
+ strcmp(optarg, "16") &&
+ strcmp(optarg, "32"))
+ errx(1, "%s: bad FAT type", optarg);
+ opt_F = atoi(optarg);
+ break;
+ case 'I':
+ opt_I = argto4(optarg, 0, "volume ID");
+ Iflag = 1;
+ break;
+ case 'L':
+ if (!oklabel(optarg))
+ errx(1, "%s: bad volume label", optarg);
+ opt_L = optarg;
+ break;
+ case 'O':
+ if (strlen(optarg) > 8)
+ errx(1, "%s: bad OEM string", optarg);
+ opt_O = optarg;
+ break;
+ case 'S':
+ opt_S = argto2(optarg, 1, "bytes/sector");
+ break;
+ case 'a':
+ opt_a = argto4(optarg, 1, "sectors/FAT");
+ break;
+ case 'b':
+ opt_b = argtox(optarg, 1, "block size");
+ opt_c = 0;
+ break;
+ case 'c':
+ opt_c = argto1(optarg, 1, "sectors/cluster");
+ opt_b = 0;
+ break;
+ case 'e':
+ opt_e = argto2(optarg, 1, "directory entries");
+ break;
+ case 'f':
+ opt_f = optarg;
+ break;
+ case 'h':
+ opt_h = argto2(optarg, 1, "drive heads");
+ break;
+ case 'i':
+ opt_i = argto2(optarg, 1, "info sector");
+ break;
+ case 'k':
+ opt_k = argto2(optarg, 1, "backup sector");
+ break;
+ case 'm':
+ opt_m = argto1(optarg, 0, "media descriptor");
+ mflag = 1;
+ break;
+ case 'n':
+ opt_n = argto1(optarg, 1, "number of FATs");
+ break;
+ case 'o':
+ opt_o = argto4(optarg, 0, "hidden sectors");
+ oflag = 1;
+ break;
+ case 'r':
+ opt_r = argto2(optarg, 1, "reserved sectors");
+ break;
+ case 's':
+ opt_s = argto4(optarg, 1, "file system size");
+ break;
+ case 'u':
+ opt_u = argto2(optarg, 1, "sectors/track");
+ break;
+ default:
+ usage();
+ }
+ argc -= optind;
+ argv += optind;
+ if (argc < 1 || argc > 2)
+ usage();
+ fname = *argv++;
+ if (!opt_create && !strchr(fname, '/')) {
+ snprintf(buf, sizeof(buf), "%s%s", _PATH_DEV, fname);
+ if (!(fname = strdup(buf)))
+ err(1, NULL);
+ }
+ dtype = *argv;
+ if (opt_create) {
+ if (opt_N)
+ errx(1, "create (-C) is incompatible with -N");
+ fd = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0644);
+ if (fd == -1)
+ errx(1, "failed to create %s", fname);
+ if (ftruncate(fd, opt_create))
+ errx(1, "failed to initialize %jd bytes", (intmax_t)opt_create);
+ } else if ((fd = open(fname, opt_N ? O_RDONLY : O_RDWR)) == -1)
+ err(1, "%s", fname);
+ if (fstat(fd, &sb))
+ err(1, "%s", fname);
+ if (opt_create) {
+ if (!S_ISREG(sb.st_mode))
+ warnx("warning, %s is not a regular file", fname);
+ } else {
+ if (!S_ISCHR(sb.st_mode))
+ warnx("warning, %s is not a character device", fname);
+ }
+ if (!opt_N)
+ check_mounted(fname, sb.st_mode);
+ if (opt_ofs && opt_ofs != lseek(fd, opt_ofs, SEEK_SET))
+ errx(1, "cannot seek to %jd", (intmax_t)opt_ofs);
+ memset(&bpb, 0, sizeof(bpb));
+ if (opt_f) {
+ getstdfmt(opt_f, &bpb);
+ bpb.bsec = bpb.sec;
+ bpb.sec = 0;
+ bpb.bspf = bpb.spf;
+ bpb.spf = 0;
+ }
+ if (opt_h)
+ bpb.hds = opt_h;
+ if (opt_u)
+ bpb.spt = opt_u;
+ if (opt_S)
+ bpb.bps = opt_S;
+ if (opt_s)
+ bpb.bsec = opt_s;
+ if (oflag)
+ bpb.hid = opt_o;
+ if (!(opt_f || (opt_h && opt_u && opt_S && opt_s && oflag))) {
+ off_t delta;
+ getdiskinfo(fd, fname, dtype, oflag, &bpb);
+ bpb.bsec -= (opt_ofs / bpb.bps);
+ delta = bpb.bsec % bpb.spt;
+ if (delta != 0) {
+ warnx("trim %d sectors to adjust to a multiple of %d",
+ (int)delta, bpb.spt);
+ bpb.bsec -= delta;
+ }
+ if (bpb.spc == 0) { /* set defaults */
+ if (bpb.bsec <= 6000) /* about 3MB -> 512 bytes */
+ bpb.spc = 1;
+ else if (bpb.bsec <= (1<<17)) /* 64M -> 4k */
+ bpb.spc = 8;
+ else if (bpb.bsec <= (1<<19)) /* 256M -> 8k */
+ bpb.spc = 16;
+ else if (bpb.bsec <= (1<<21)) /* 1G -> 16k */
+ bpb.spc = 32;
+ else
+ bpb.spc = 64; /* otherwise 32k */
+ }
+ }
+ if (!powerof2(bpb.bps))
+ errx(1, "bytes/sector (%u) is not a power of 2", bpb.bps);
+ if (bpb.bps < MINBPS)
+ errx(1, "bytes/sector (%u) is too small; minimum is %u",
+ bpb.bps, MINBPS);
+ if (!(fat = opt_F)) {
+ if (opt_f)
+ fat = 12;
+ else if (!opt_e && (opt_i || opt_k))
+ fat = 32;
+ }
+ if ((fat == 32 && opt_e) || (fat != 32 && (opt_i || opt_k)))
+ errx(1, "-%c is not a legal FAT%s option",
+ fat == 32 ? 'e' : opt_i ? 'i' : 'k',
+ fat == 32 ? "32" : "12/16");
+ if (opt_f && fat == 32)
+ bpb.rde = 0;
+ if (opt_b) {
+ if (!powerof2(opt_b))
+ errx(1, "block size (%u) is not a power of 2", opt_b);
+ if (opt_b < bpb.bps)
+ errx(1, "block size (%u) is too small; minimum is %u",
+ opt_b, bpb.bps);
+ if (opt_b > bpb.bps * MAXSPC)
+ errx(1, "block size (%u) is too large; maximum is %u",
+ opt_b, bpb.bps * MAXSPC);
+ bpb.spc = opt_b / bpb.bps;
+ }
+ if (opt_c) {
+ if (!powerof2(opt_c))
+ errx(1, "sectors/cluster (%u) is not a power of 2", opt_c);
+ bpb.spc = opt_c;
+ }
+ if (opt_r)
+ bpb.res = opt_r;
+ if (opt_n) {
+ if (opt_n > MAXNFT)
+ errx(1, "number of FATs (%u) is too large; maximum is %u",
+ opt_n, MAXNFT);
+ bpb.nft = opt_n;
+ }
+ if (opt_e)
+ bpb.rde = opt_e;
+ if (mflag) {
+ if (opt_m < 0xf0)
+ errx(1, "illegal media descriptor (%#x)", opt_m);
+ bpb.mid = opt_m;
+ }
+ if (opt_a)
+ bpb.bspf = opt_a;
+ if (opt_i)
+ bpb.infs = opt_i;
+ if (opt_k)
+ bpb.bkbs = opt_k;
+ bss = 1;
+ bname = NULL;
+ fd1 = -1;
+ if (opt_B) {
+ bname = opt_B;
+ if (!strchr(bname, '/')) {
+ snprintf(buf, sizeof(buf), "/boot/%s", bname);
+ if (!(bname = strdup(buf)))
+ err(1, NULL);
+ }
+ if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb))
+ err(1, "%s", bname);
+ if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bps ||
+ sb.st_size < bpb.bps || sb.st_size > bpb.bps * MAXU16)
+ errx(1, "%s: inappropriate file type or format", bname);
+ bss = sb.st_size / bpb.bps;
+ }
+ if (!bpb.nft)
+ bpb.nft = 2;
+ if (!fat) {
+ if (bpb.bsec < (bpb.res ? bpb.res : bss) +
+ howmany((RESFTE + (bpb.spc ? MINCLS16 : MAXCLS12 + 1)) *
+ ((bpb.spc ? 16 : 12) / BPN), bpb.bps * NPB) *
+ bpb.nft +
+ howmany(bpb.rde ? bpb.rde : DEFRDE,
+ bpb.bps / sizeof(struct de)) +
+ (bpb.spc ? MINCLS16 : MAXCLS12 + 1) *
+ (bpb.spc ? bpb.spc : howmany(DEFBLK, bpb.bps)))
+ fat = 12;
+ else if (bpb.rde || bpb.bsec <
+ (bpb.res ? bpb.res : bss) +
+ howmany((RESFTE + MAXCLS16) * 2, bpb.bps) * bpb.nft +
+ howmany(DEFRDE, bpb.bps / sizeof(struct de)) +
+ (MAXCLS16 + 1) *
+ (bpb.spc ? bpb.spc : howmany(8192, bpb.bps)))
+ fat = 16;
+ else
+ fat = 32;
+ }
+ x = bss;
+ if (fat == 32) {
+ if (!bpb.infs) {
+ if (x == MAXU16 || x == bpb.bkbs)
+ errx(1, "no room for info sector");
+ bpb.infs = x;
+ }
+ if (bpb.infs != MAXU16 && x <= bpb.infs)
+ x = bpb.infs + 1;
+ if (!bpb.bkbs) {
+ if (x == MAXU16)
+ errx(1, "no room for backup sector");
+ bpb.bkbs = x;
+ } else if (bpb.bkbs != MAXU16 && bpb.bkbs == bpb.infs)
+ errx(1, "backup sector would overwrite info sector");
+ if (bpb.bkbs != MAXU16 && x <= bpb.bkbs)
+ x = bpb.bkbs + 1;
+ }
+ if (!bpb.res)
+ bpb.res = fat == 32 ? MAX(x, MAX(16384 / bpb.bps, 4)) : x;
+ else if (bpb.res < x)
+ errx(1, "too few reserved sectors");
+ if (fat != 32 && !bpb.rde)
+ bpb.rde = DEFRDE;
+ rds = howmany(bpb.rde, bpb.bps / sizeof(struct de));
+ if (!bpb.spc)
+ for (bpb.spc = howmany(fat == 16 ? DEFBLK16 : DEFBLK, bpb.bps);
+ bpb.spc < MAXSPC &&
+ bpb.res +
+ howmany((RESFTE + maxcls(fat)) * (fat / BPN),
+ bpb.bps * NPB) * bpb.nft +
+ rds +
+ (u_int64_t)(maxcls(fat) + 1) * bpb.spc <= bpb.bsec;
+ bpb.spc <<= 1);
+ if (fat != 32 && bpb.bspf > MAXU16)
+ errx(1, "too many sectors/FAT for FAT12/16");
+ x1 = bpb.res + rds;
+ x = bpb.bspf ? bpb.bspf : 1;
+ if (x1 + (u_int64_t)x * bpb.nft > bpb.bsec)
+ errx(1, "meta data exceeds file system size");
+ x1 += x * bpb.nft;
+ x = (u_int64_t)(bpb.bsec - x1) * bpb.bps * NPB /
+ (bpb.spc * bpb.bps * NPB + fat / BPN * bpb.nft);
+ x2 = howmany((RESFTE + MIN(x, maxcls(fat))) * (fat / BPN),
+ bpb.bps * NPB);
+ if (!bpb.bspf) {
+ bpb.bspf = x2;
+ x1 += (bpb.bspf - 1) * bpb.nft;
+ }
+ cls = (bpb.bsec - x1) / bpb.spc;
+ x = (u_int64_t)bpb.bspf * bpb.bps * NPB / (fat / BPN) - RESFTE;
+ if (cls > x)
+ cls = x;
+ if (bpb.bspf < x2)
+ warnx("warning: sectors/FAT limits file system to %u clusters",
+ cls);
+ if (cls < mincls(fat))
+ errx(1, "%u clusters too few clusters for FAT%u, need %u", cls, fat,
+ mincls(fat));
+ if (cls > maxcls(fat)) {
+ cls = maxcls(fat);
+ bpb.bsec = x1 + (cls + 1) * bpb.spc - 1;
+ warnx("warning: FAT type limits file system to %u sectors",
+ bpb.bsec);
+ }
+ printf("%s: %u sector%s in %u FAT%u cluster%s "
+ "(%u bytes/cluster)\n", fname, cls * bpb.spc,
+ cls * bpb.spc == 1 ? "" : "s", cls, fat,
+ cls == 1 ? "" : "s", bpb.bps * bpb.spc);
+ if (!bpb.mid)
+ bpb.mid = !bpb.hid ? 0xf0 : 0xf8;
+ if (fat == 32)
+ bpb.rdcl = RESFTE;
+ if (bpb.hid + bpb.bsec <= MAXU16) {
+ bpb.sec = bpb.bsec;
+ bpb.bsec = 0;
+ }
+ if (fat != 32) {
+ bpb.spf = bpb.bspf;
+ bpb.bspf = 0;
+ }
+ print_bpb(&bpb);
+ if (!opt_N) {
+ gettimeofday(&tv, NULL);
+ now = tv.tv_sec;
+ tm = localtime(&now);
+ if (!(img = malloc(bpb.bps)))
+ err(1, NULL);
+ dir = bpb.res + (bpb.spf ? bpb.spf : bpb.bspf) * bpb.nft;
+ for (lsn = 0; lsn < dir + (fat == 32 ? bpb.spc : rds); lsn++) {
+ x = lsn;
+ if (opt_B &&
+ fat == 32 && bpb.bkbs != MAXU16 &&
+ bss <= bpb.bkbs && x >= bpb.bkbs) {
+ x -= bpb.bkbs;
+ if (!x && lseek(fd1, opt_ofs, SEEK_SET))
+ err(1, "%s", bname);
+ }
+ if (opt_B && x < bss) {
+ if ((n = read(fd1, img, bpb.bps)) == -1)
+ err(1, "%s", bname);
+ if ((unsigned)n != bpb.bps)
+ errx(1, "%s: can't read sector %u", bname, x);
+ } else
+ memset(img, 0, bpb.bps);
+ if (!lsn ||
+ (fat == 32 && bpb.bkbs != MAXU16 && lsn == bpb.bkbs)) {
+ x1 = sizeof(struct bs);
+ bsbpb = (struct bsbpb *)(img + x1);
+ mk2(bsbpb->bps, bpb.bps);
+ mk1(bsbpb->spc, bpb.spc);
+ mk2(bsbpb->res, bpb.res);
+ mk1(bsbpb->nft, bpb.nft);
+ mk2(bsbpb->rde, bpb.rde);
+ mk2(bsbpb->sec, bpb.sec);
+ mk1(bsbpb->mid, bpb.mid);
+ mk2(bsbpb->spf, bpb.spf);
+ mk2(bsbpb->spt, bpb.spt);
+ mk2(bsbpb->hds, bpb.hds);
+ mk4(bsbpb->hid, bpb.hid);
+ mk4(bsbpb->bsec, bpb.bsec);
+ x1 += sizeof(struct bsbpb);
+ if (fat == 32) {
+ bsxbpb = (struct bsxbpb *)(img + x1);
+ mk4(bsxbpb->bspf, bpb.bspf);
+ mk2(bsxbpb->xflg, 0);
+ mk2(bsxbpb->vers, 0);
+ mk4(bsxbpb->rdcl, bpb.rdcl);
+ mk2(bsxbpb->infs, bpb.infs);
+ mk2(bsxbpb->bkbs, bpb.bkbs);
+ x1 += sizeof(struct bsxbpb);
+ }
+ bsx = (struct bsx *)(img + x1);
+ mk1(bsx->sig, 0x29);
+ if (Iflag)
+ x = opt_I;
+ else
+ x = (((u_int)(1 + tm->tm_mon) << 8 |
+ (u_int)tm->tm_mday) +
+ ((u_int)tm->tm_sec << 8 |
+ (u_int)(tv.tv_usec / 10))) << 16 |
+ ((u_int)(1900 + tm->tm_year) +
+ ((u_int)tm->tm_hour << 8 |
+ (u_int)tm->tm_min));
+ mk4(bsx->volid, x);
+ mklabel(bsx->label, opt_L ? opt_L : "NO NAME");
+ sprintf(buf, "FAT%u", fat);
+ setstr(bsx->type, buf, sizeof(bsx->type));
+ if (!opt_B) {
+ x1 += sizeof(struct bsx);
+ bs = (struct bs *)img;
+ mk1(bs->jmp[0], 0xeb);
+ mk1(bs->jmp[1], x1 - 2);
+ mk1(bs->jmp[2], 0x90);
+ setstr(bs->oem, opt_O ? opt_O : "BSD 4.4",
+ sizeof(bs->oem));
+ memcpy(img + x1, bootcode, sizeof(bootcode));
+ mk2(img + MINBPS - 2, DOSMAGIC);
+ }
+ } else if (fat == 32 && bpb.infs != MAXU16 &&
+ (lsn == bpb.infs ||
+ (bpb.bkbs != MAXU16 &&
+ lsn == bpb.bkbs + bpb.infs))) {
+ mk4(img, 0x41615252);
+ mk4(img + MINBPS - 28, 0x61417272);
+ mk4(img + MINBPS - 24, 0xffffffff);
+ mk4(img + MINBPS - 20, bpb.rdcl);
+ mk2(img + MINBPS - 2, DOSMAGIC);
+ } else if (lsn >= bpb.res && lsn < dir &&
+ !((lsn - bpb.res) %
+ (bpb.spf ? bpb.spf : bpb.bspf))) {
+ mk1(img[0], bpb.mid);
+ for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++)
+ mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff);
+ } else if (lsn == dir && opt_L) {
+ de = (struct de *)img;
+ mklabel(de->namext, opt_L);
+ mk1(de->attr, 050);
+ x = (u_int)tm->tm_hour << 11 |
+ (u_int)tm->tm_min << 5 |
+ (u_int)tm->tm_sec >> 1;
+ mk2(de->time, x);
+ x = (u_int)(tm->tm_year - 80) << 9 |
+ (u_int)(tm->tm_mon + 1) << 5 |
+ (u_int)tm->tm_mday;
+ mk2(de->date, x);
+ }
+ if ((n = write(fd, img, bpb.bps)) == -1)
+ err(1, "%s", fname);
+ if ((unsigned)n != bpb.bps)
+ errx(1, "%s: can't write sector %u", fname, lsn);
+ }
+ }
+ return 0;
+}
+
+/*
+ * Exit with error if file system is mounted.
+ */
+static void
+check_mounted(const char *fname, mode_t mode)
+{
+ struct statfs *mp;
+ const char *s1, *s2;
+ size_t len;
+ int n, r;
+
+#ifdef ANDROID
+ warnx("Skipping mount checks");
+#else
+ if (!(n = getmntinfo(&mp, MNT_NOWAIT)))
+ err(1, "getmntinfo");
+ len = strlen(_PATH_DEV);
+ s1 = fname;
+ if (!strncmp(s1, _PATH_DEV, len))
+ s1 += len;
+ r = S_ISCHR(mode) && s1 != fname && *s1 == 'r';
+ for (; n--; mp++) {
+ s2 = mp->f_mntfromname;
+ if (!strncmp(s2, _PATH_DEV, len))
+ s2 += len;
+ if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) ||
+ !strcmp(s1, s2))
+ errx(1, "%s is mounted on %s", fname, mp->f_mntonname);
+ }
+#endif
+}
+
+/*
+ * Get a standard format.
+ */
+static void
+getstdfmt(const char *fmt, struct bpb *bpb)
+{
+ u_int x, i;
+
+ x = sizeof(stdfmt) / sizeof(stdfmt[0]);
+ for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++);
+ if (i == x)
+ errx(1, "%s: unknown standard format", fmt);
+ *bpb = stdfmt[i].bpb;
+}
+
+/*
+ * Get disk slice, partition, and geometry information.
+ */
+
+#ifdef ANDROID
+static void
+getdiskinfo(int fd, const char *fname, const char *dtype, __unused int oflag,
+ struct bpb *bpb)
+{
+ struct hd_geometry geom;
+
+ if (ioctl(fd, BLKSSZGET, &bpb->bps)) {
+ fprintf(stderr, "Error getting bytes / sector (%s)", strerror(errno));
+ exit(1);
+ }
+
+ ckgeom(fname, bpb->bps, "bytes/sector");
+
+ if (ioctl(fd, BLKGETSIZE, &bpb->bsec)) {
+ fprintf(stderr, "Error getting blocksize (%s)", strerror(errno));
+ exit(1);
+ }
+
+ if (ioctl(fd, HDIO_GETGEO, &geom)) {
+ fprintf(stderr, "Error getting gemoetry (%s)", strerror(errno));
+ exit(1);
+ }
+
+ bpb->spt = geom.sectors;
+ ckgeom(fname, bpb->spt, "sectors/track");
+
+ bpb->hds = geom.heads;
+ ckgeom(fname, bpb->hds, "drive heads");
+}
+
+#else
+
+static void
+getdiskinfo(int fd, const char *fname, const char *dtype, __unused int oflag,
+ struct bpb *bpb)
+{
+ struct disklabel *lp, dlp;
+ struct fd_type type;
+ off_t ms, hs = 0;
+
+ lp = NULL;
+
+ /* If the user specified a disk type, try to use that */
+ if (dtype != NULL) {
+ lp = getdiskbyname(dtype);
+ }
+
+ /* Maybe it's a floppy drive */
+ if (lp == NULL) {
+ if (ioctl(fd, DIOCGMEDIASIZE, &ms) == -1) {
+ struct stat st;
+
+ if (fstat(fd, &st))
+ err(1, "Cannot get disk size");
+ /* create a fake geometry for a file image */
+ ms = st.st_size;
+ dlp.d_secsize = 512;
+ dlp.d_nsectors = 63;
+ dlp.d_ntracks = 255;
+ dlp.d_secperunit = ms / dlp.d_secsize;
+ lp = &dlp;
+ } else if (ioctl(fd, FD_GTYPE, &type) != -1) {
+ dlp.d_secsize = 128 << type.secsize;
+ dlp.d_nsectors = type.sectrac;
+ dlp.d_ntracks = type.heads;
+ dlp.d_secperunit = ms / dlp.d_secsize;
+ lp = &dlp;
+ }
+ }
+
+ /* Maybe it's a fixed drive */
+ if (lp == NULL) {
+ if (ioctl(fd, DIOCGDINFO, &dlp) == -1) {
+ if (bpb->bps == 0 && ioctl(fd, DIOCGSECTORSIZE, &dlp.d_secsize) == -1)
+ errx(1, "Cannot get sector size, %s", strerror(errno));
+
+ /* XXX Should we use bpb->bps if it's set? */
+ dlp.d_secperunit = ms / dlp.d_secsize;
+
+ if (bpb->spt == 0 && ioctl(fd, DIOCGFWSECTORS, &dlp.d_nsectors) == -1) {
+ warnx("Cannot get number of sectors per track, %s", strerror(errno));
+ dlp.d_nsectors = 63;
+ }
+ if (bpb->hds == 0 && ioctl(fd, DIOCGFWHEADS, &dlp.d_ntracks) == -1) {
+ warnx("Cannot get number of heads, %s", strerror(errno));
+ if (dlp.d_secperunit <= 63*1*1024)
+ dlp.d_ntracks = 1;
+ else if (dlp.d_secperunit <= 63*16*1024)
+ dlp.d_ntracks = 16;
+ else
+ dlp.d_ntracks = 255;
+ }
+ }
+
+ hs = (ms / dlp.d_secsize) - dlp.d_secperunit;
+ lp = &dlp;
+ }
+
+ if (bpb->bps == 0)
+ bpb->bps = ckgeom(fname, lp->d_secsize, "bytes/sector");
+ if (bpb->spt == 0)
+ bpb->spt = ckgeom(fname, lp->d_nsectors, "sectors/track");
+ if (bpb->hds == 0)
+ bpb->hds = ckgeom(fname, lp->d_ntracks, "drive heads");
+ if (bpb->bsec == 0)
+ bpb->bsec = lp->d_secperunit;
+ if (bpb->hid == 0)
+ bpb->hid = hs;
+}
+#endif
+
+/*
+ * Print out BPB values.
+ */
+static void
+print_bpb(struct bpb *bpb)
+{
+ printf("bps=%u spc=%u res=%u nft=%u", bpb->bps, bpb->spc, bpb->res,
+ bpb->nft);
+ if (bpb->rde)
+ printf(" rde=%u", bpb->rde);
+ if (bpb->sec)
+ printf(" sec=%u", bpb->sec);
+ printf(" mid=%#x", bpb->mid);
+ if (bpb->spf)
+ printf(" spf=%u", bpb->spf);
+ printf(" spt=%u hds=%u hid=%u", bpb->spt, bpb->hds, bpb->hid);
+ if (bpb->bsec)
+ printf(" bsec=%u", bpb->bsec);
+ if (!bpb->spf) {
+ printf(" bspf=%u rdcl=%u", bpb->bspf, bpb->rdcl);
+ printf(" infs=");
+ printf(bpb->infs == MAXU16 ? "%#x" : "%u", bpb->infs);
+ printf(" bkbs=");
+ printf(bpb->bkbs == MAXU16 ? "%#x" : "%u", bpb->bkbs);
+ }
+ printf("\n");
+}
+
+/*
+ * Check a disk geometry value.
+ */
+static u_int
+ckgeom(const char *fname, u_int val, const char *msg)
+{
+ if (!val)
+ errx(1, "%s: no default %s", fname, msg);
+ if (val > MAXU16)
+ errx(1, "%s: illegal %s %d", fname, msg, val);
+ return val;
+}
+
+/*
+ * Convert and check a numeric option argument.
+ */
+static u_int
+argtou(const char *arg, u_int lo, u_int hi, const char *msg)
+{
+ char *s;
+ u_long x;
+
+ errno = 0;
+ x = strtoul(arg, &s, 0);
+ if (errno || !*arg || *s || x < lo || x > hi)
+ errx(1, "%s: bad %s", arg, msg);
+ return x;
+}
+
+/*
+ * Same for off_t, with optional skmgpP suffix
+ */
+static off_t
+argtooff(const char *arg, const char *msg)
+{
+ char *s;
+ off_t x;
+
+ x = strtoll(arg, &s, 0);
+ /* allow at most one extra char */
+ if (errno || x < 0 || (s[0] && s[1]) )
+ errx(1, "%s: bad %s", arg, msg);
+ if (*s) { /* the extra char is the multiplier */
+ switch (*s) {
+ default:
+ errx(1, "%s: bad %s", arg, msg);
+ /* notreached */
+
+ case 's': /* sector */
+ case 'S':
+ x <<= 9; /* times 512 */
+ break;
+
+ case 'k': /* kilobyte */
+ case 'K':
+ x <<= 10; /* times 1024 */
+ break;
+
+ case 'm': /* megabyte */
+ case 'M':
+ x <<= 20; /* times 1024*1024 */
+ break;
+
+ case 'g': /* gigabyte */
+ case 'G':
+ x <<= 30; /* times 1024*1024*1024 */
+ break;
+
+ case 'p': /* partition start */
+ case 'P': /* partition start */
+ case 'l': /* partition length */
+ case 'L': /* partition length */
+ errx(1, "%s: not supported yet %s", arg, msg);
+ /* notreached */
+ }
+ }
+ return x;
+}
+
+/*
+ * Check a volume label.
+ */
+static int
+oklabel(const char *src)
+{
+ int c, i;
+
+ for (i = 0; i <= 11; i++) {
+ c = (u_char)*src++;
+ if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c))
+ break;
+ }
+ return i && !c;
+}
+
+/*
+ * Make a volume label.
+ */
+static void
+mklabel(u_int8_t *dest, const char *src)
+{
+ int c, i;
+
+ for (i = 0; i < 11; i++) {
+ c = *src ? toupper(*src++) : ' ';
+ *dest++ = !i && c == '\xe5' ? 5 : c;
+ }
+}
+
+/*
+ * Copy string, padding with spaces.
+ */
+static void
+setstr(u_int8_t *dest, const char *src, size_t len)
+{
+ while (len--)
+ *dest++ = *src ? *src++ : ' ';
+}
+
+/*
+ * Print usage message.
+ */
+static void
+usage(void)
+{
+ fprintf(stderr,
+ "usage: newfs_msdos [ -options ] special [disktype]\n"
+ "where the options are:\n"
+ "\t-@ create file system at specified offset\n"
+ "\t-B get bootstrap from file\n"
+ "\t-C create image file with specified size\n"
+ "\t-F FAT type (12, 16, or 32)\n"
+ "\t-I volume ID\n"
+ "\t-L volume label\n"
+ "\t-N don't create file system: just print out parameters\n"
+ "\t-O OEM string\n"
+ "\t-S bytes/sector\n"
+ "\t-a sectors/FAT\n"
+ "\t-b block size\n"
+ "\t-c sectors/cluster\n"
+ "\t-e root directory entries\n"
+ "\t-f standard format\n"
+ "\t-h drive heads\n"
+ "\t-i file system info sector\n"
+ "\t-k backup boot sector\n"
+ "\t-m media descriptor\n"
+ "\t-n number of FATs\n"
+ "\t-o hidden sectors\n"
+ "\t-r reserved sectors\n"
+ "\t-s file system size (sectors)\n"
+ "\t-u sectors/track\n");
+ exit(1);
+}
diff --git a/toolbox/route.c b/toolbox/route.c
index 2fd7108..4f66201 100644
--- a/toolbox/route.c
+++ b/toolbox/route.c
@@ -1,130 +1,103 @@
+/*
+ * Copyright (c) 2009, The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdarg.h>
-
-#include <errno.h>
#include <string.h>
-#include <ctype.h>
-
+#include <errno.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
-#include <linux/if.h>
-#include <linux/sockios.h>
#include <arpa/inet.h>
#include <linux/route.h>
-static void die(const char *fmt, ...)
-{
- va_list p;
-
- va_start(p, fmt);
- fprintf(stderr,"error(%s): ", strerror(errno));
- fprintf(stderr, fmt, p);
- va_end(p);
- exit(-1);
+static inline int set_address(const char *address, struct sockaddr *sa) {
+ return inet_aton(address, &((struct sockaddr_in *)sa)->sin_addr);
}
-static inline void init_sockaddr_in(struct sockaddr_in *sin, const char *addr)
-{
- sin->sin_family = AF_INET;
- sin->sin_port = 0;
- sin->sin_addr.s_addr = inet_addr(addr);
-}
-
-#define ADVANCE(argc, argv) do { argc--, argv++; } while(0)
-#define EXPECT_NEXT(argc, argv) do { \
- ADVANCE(argc, argv); \
- if (0 == argc) { \
- errno = EINVAL; \
- die("expecting one more argument"); \
- } \
-} while(0)
-
/* current support the following routing entries */
/* route add default dev wlan0 */
-/* route add default gw 192.168.20.1 dev wlan0 */
-/* route add net 192.168.1.1 netmask 255.255.255.0 gw 172.24.192.10 */
+/* route add default gw 192.168.1.1 dev wlan0 */
+/* route add -net 192.168.1.2 netmask 255.255.255.0 gw 192.168.1.1 */
int route_main(int argc, char *argv[])
{
- struct ifreq ifr;
- int s,i;
- struct rtentry rt;
- struct sockaddr_in ina;
-
- if (!argc)
- return 0;
+ struct rtentry rt = {
+ .rt_dst = {.sa_family = AF_INET},
+ .rt_genmask = {.sa_family = AF_INET},
+ .rt_gateway = {.sa_family = AF_INET},
+ };
- strncpy(ifr.ifr_name, argv[0], IFNAMSIZ);
- ifr.ifr_name[IFNAMSIZ-1] = 0;
- ADVANCE(argc, argv);
+ errno = EINVAL;
+ if (argc > 2 && !strcmp(argv[1], "add")) {
+ if (!strcmp(argv[2], "default")) {
+ /* route add default dev wlan0 */
+ if (argc > 4 && !strcmp(argv[3], "dev")) {
+ rt.rt_flags = RTF_UP | RTF_HOST;
+ rt.rt_dev = argv[4];
+ errno = 0;
+ goto apply;
+ }
- if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
- die("cannot open control socket\n");
- }
-
- while(argc > 0){
- if (!strcmp(argv[0], "add")) {
- EXPECT_NEXT(argc, argv);
- if (!strcmp(argv[0], "default")) {
- EXPECT_NEXT(argc, argv);
- memset((char *) &rt, 0, sizeof(struct rtentry));
- rt.rt_dst.sa_family = AF_INET;
- if(!strcmp(argv[0], "dev")) {
- EXPECT_NEXT(argc, argv);
- rt.rt_flags = RTF_UP | RTF_HOST;
- rt.rt_dev = argv[0];
- if (ioctl(s, SIOCADDRT, &rt) < 0)
- die("SIOCADDRT\n");
- } else if (!strcmp(argv[0], "gw")) {
- EXPECT_NEXT(argc, argv);
- rt.rt_flags = RTF_UP | RTF_GATEWAY;
- init_sockaddr_in((struct sockaddr_in *)&(rt.rt_genmask), "0.0.0.0");
- if(isdigit(argv[0][0])) {
- init_sockaddr_in((struct sockaddr_in *)&(rt.rt_gateway), argv[0]);
- } else {
- die("expecting an IP address for parameter \"gw\"\n");
- }
- EXPECT_NEXT(argc, argv);
- if (!strcmp(argv[0], "dev")) {
- EXPECT_NEXT(argc, argv);
- rt.rt_dev = argv[0];
- if (ioctl(s, SIOCADDRT, &rt) < 0) {
- die("SIOCADDRT\n");
- }
- }
- }
- } else {
- char keywords[3][10] = { "-net", "netmask", "gw" };
- struct sockaddr_in *paddr[3] = { &rt.rt_dst, &rt.rt_genmask, &rt.rt_gateway };
- int k = 0;
-
- memset((char *) &rt, 0, sizeof(struct rtentry));
+ /* route add default gw 192.168.1.1 dev wlan0 */
+ if (argc > 6 && !strcmp(argv[3], "gw") && !strcmp(argv[5], "dev")) {
rt.rt_flags = RTF_UP | RTF_GATEWAY;
- do {
- if (!strcmp(argv[0], keywords[k])) {
- EXPECT_NEXT(argc, argv);
- if (isdigit(argv[0][0])) {
- init_sockaddr_in(paddr[k], argv[0]);
- } else {
- die("expecting an IP/MASK address for parameter %s\n", keywords[k]);
- }
- if (k < 2)
- EXPECT_NEXT(argc, argv);
- } else {
- die("expecting keyword(s)\n");
- }
- } while (++k < 3);
-
- if (ioctl(s, SIOCADDRT, &rt) < 0) {
- die("SIOCADDRT\n");
+ rt.rt_dev = argv[6];
+ if (set_address(argv[4], &rt.rt_gateway)) {
+ errno = 0;
}
+ goto apply;
}
}
- ADVANCE(argc, argv);
+
+ /* route add -net 192.168.1.2 netmask 255.255.255.0 gw 192.168.1.1 */
+ if (argc > 7 && !strcmp(argv[2], "-net") &&
+ !strcmp(argv[4], "netmask") && !strcmp(argv[6], "gw")) {
+ rt.rt_flags = RTF_UP | RTF_GATEWAY;
+ if (set_address(argv[3], &rt.rt_dst) &&
+ set_address(argv[5], &rt.rt_genmask) &&
+ set_address(argv[7], &rt.rt_gateway)) {
+ errno = 0;
+ }
+ goto apply;
+ }
}
- return 0;
+apply:
+ if (!errno) {
+ int s = socket(AF_INET, SOCK_DGRAM, 0);
+ if (s != -1 && (ioctl(s, SIOCADDRT, &rt) != -1 || errno == EEXIST)) {
+ return 0;
+ }
+ }
+ puts(strerror(errno));
+ return errno;
}
diff --git a/vold/format.c b/vold/format.c
index d4e2327..cd40197 100755
--- a/vold/format.c
+++ b/vold/format.c
@@ -26,7 +26,7 @@
#include "diskmbr.h"
#include "logwrapper.h"
-static char MKDOSFS_PATH[] = "/system/bin/mkdosfs";
+static char MKDOSFS_PATH[] = "/system/bin/newfs_msdos";
static char MKE2FS_PATH[] = "/system/bin/mke2fs";
int format_partition(blkdev_t *part, char *type)
@@ -37,15 +37,17 @@
devpath = blkdev_get_devpath(part);
if (!strcmp(type, FORMAT_TYPE_FAT32)) {
- char *args[6];
+ char *args[9];
args[0] = MKDOSFS_PATH;
- args[1] = "-F 32";
- args[2] = "-c 32";
- args[3] = "-n 2";
- args[4] = "-O android";
- args[5] = devpath;
- args[6] = NULL;
- rc = logwrap(6, args, 1);
+ args[1] = "-F";
+ args[2] = "32";
+ args[3] = "-c";
+ args[4] = "16";
+ args[5] = "-O";
+ args[6] = "android";
+ args[7] = devpath;
+ args[8] = NULL;
+ rc = logwrap(8, args, 1);
} else {
char *args[7];
args[0] = MKE2FS_PATH;
diff --git a/vold/uevent.c b/vold/uevent.c
index cfb5786..66e70c5 100644
--- a/vold/uevent.c
+++ b/vold/uevent.c
@@ -272,8 +272,7 @@
else
door_open = false;
volmgr_safe_mode(low_batt || door_open);
- } else
- LOG_VOL("handle_switch_event(): Ignoring switch '%s'", name);
+ }
return 0;
}