/uspace/trunk/libc/generic/futex.c |
---|
0,0 → 1,168 |
/* |
* Copyright (C) 2006 Jakub Jermar |
* 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. |
* - The name of the author may not be used to endorse or promote products |
* derived from this software without specific prior written permission. |
* |
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 <futex.h> |
#include <atomic.h> |
#include <libc.h> |
#include <stdio.h> |
#include <types.h> |
#include <kernel/synch/synch.h> |
/* |
* Note about race conditions. |
* Because of non-atomic nature of operations performed sequentially on the futex |
* counter and the futex wait queue, there is a race condition: |
* |
* (wq->missed_wakeups == 1) && (futex->count = 1) |
* |
* Scenario 1 (wait queue timeout vs. futex_up()): |
* 1. assume wq->missed_wakeups == 0 && futex->count == -1 |
* (ie. thread A sleeping, thread B in the critical section) |
* 2. A receives timeout and gets removed from the wait queue |
* 3. B wants to leave the critical section and calls futex_up() |
* 4. B thus changes futex->count from -1 to 0 |
* 5. B has to call SYS_FUTEX_WAKEUP syscall to wake up the sleeping thread |
* 6. B finds the wait queue empty and changes wq->missed_wakeups from 0 to 1 |
* 7. A fixes futex->count (i.e. the number of waiting threads) by changing it from 0 to 1 |
* |
* Scenario 2 (conditional down operation vs. futex_up) |
* 1. assume wq->missed_wakeups == 0 && futex->count == 0 |
* (i.e. thread A is in the critical section) |
* 2. thread B performs futex_trydown() operation and changes futex->count from 0 to -1 |
* B is now obliged to call SYS_FUTEX_SLEEP syscall |
* 3. A wants to leave the critical section and does futex_up() |
* 4. A thus changes futex->count from -1 to 0 and must call SYS_FUTEX_WAKEUP syscall |
* 5. B finds the wait queue empty and immediatelly aborts the conditional sleep |
* 6. No thread is queueing in the wait queue so wq->missed_wakeups changes from 0 to 1 |
* 6. B fixes futex->count (i.e. the number of waiting threads) by changing it from 0 to 1 |
* |
* Both scenarios allow two threads to be in the critical section simultaneously. |
* One without kernel intervention and the other through wq->missed_wakeups being 1. |
* |
* To mitigate this problem, futex_down_timeout() detects that the syscall didn't sleep |
* in the wait queue, fixes the futex counter and RETRIES the whole operation again. |
* |
*/ |
/** Initialize futex counter. |
* |
* @param futex Futex. |
* @param val Initialization value. |
*/ |
void futex_initialize(atomic_t *futex, int val) |
{ |
atomic_set(futex, val); |
} |
int futex_down(atomic_t *futex) |
{ |
return futex_down_timeout(futex, SYNCH_NO_TIMEOUT, SYNCH_BLOCKING); |
} |
int futex_trydown(atomic_t *futex) |
{ |
return futex_down_timeout(futex, SYNCH_NO_TIMEOUT, SYNCH_NON_BLOCKING); |
} |
/** Try to down the futex. |
* |
* @param futex Futex. |
* @param usec Microseconds to wait. Zero value means sleep without timeout. |
* @param trydown If usec is zero and trydown is non-zero, only conditional |
* |
* @return ENOENT if there is no such virtual address. One of ESYNCH_OK_ATOMIC |
* and ESYNCH_OK_BLOCKED on success or ESYNCH_TIMEOUT if the lock was |
* not acquired because of a timeout or ESYNCH_WOULD_BLOCK if the |
* operation could not be carried out atomically (if requested so). |
*/ |
int futex_down_timeout(atomic_t *futex, uint32_t usec, int trydown) |
{ |
int rc; |
while (atomic_predec(futex) < 0) { |
rc = __SYSCALL3(SYS_FUTEX_SLEEP, (sysarg_t) &futex->count, (sysarg_t) usec, (sysarg_t) trydown); |
switch (rc) { |
case ESYNCH_OK_ATOMIC: |
/* |
* Because of a race condition between timeout and futex_up() |
* and between conditional futex_down_timeout() and futex_up(), |
* we have to give up and try again in this special case. |
*/ |
atomic_inc(futex); |
break; |
case ESYNCH_TIMEOUT: |
atomic_inc(futex); |
return ESYNCH_TIMEOUT; |
break; |
case ESYNCH_WOULD_BLOCK: |
/* |
* The conditional down operation should be implemented this way. |
* The userspace-only variant tends to accumulate missed wakeups |
* in the kernel futex wait queue. |
*/ |
atomic_inc(futex); |
return ESYNCH_WOULD_BLOCK; |
break; |
case ESYNCH_OK_BLOCKED: |
/* |
* Enter the critical section. |
* The futex counter has already been incremented for us. |
*/ |
return ESYNCH_OK_BLOCKED; |
break; |
default: |
return rc; |
} |
} |
/* |
* Enter the critical section. |
*/ |
return ESYNCH_OK_ATOMIC; |
} |
/** Up the futex. |
* |
* @param futex Futex. |
* |
* @return ENOENT if there is no such virtual address. Otherwise zero. |
*/ |
int futex_up(atomic_t *futex) |
{ |
long val; |
val = atomic_postinc(futex); |
if (val < 0) |
return __SYSCALL1(SYS_FUTEX_WAKEUP, (sysarg_t) &futex->count); |
return 0; |
} |
/uspace/trunk/libc/generic/thread.c |
---|
0,0 → 1,138 |
/* |
* Copyright (C) 2006 Jakub Jermar |
* 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. |
* - The name of the author may not be used to endorse or promote products |
* derived from this software without specific prior written permission. |
* |
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 <thread.h> |
#include <libc.h> |
#include <stdlib.h> |
#include <arch/faddr.h> |
#include <kernel/proc/uarg.h> |
#include <psthread.h> |
#include <string.h> |
#include <stdio.h> |
extern char _tdata_start; |
extern char _tdata_end; |
extern char _tbss_start; |
extern char _tbss_end; |
/** Create Thread Local storage area, return pointer to TCB(ThreadControlBlock) |
* |
* !! The code requires, that sections .tdata and .tbss are adjacent. |
* It may be changed in the future. |
*/ |
tcb_t * __make_tls(void) |
{ |
void *data; |
tcb_t *tcb; |
size_t tls_size = &_tbss_end - &_tdata_start; |
tcb = __alloc_tls(&data, tls_size); |
memcpy(data, &_tdata_start, &_tdata_end - &_tdata_start); |
memset(data + (&_tbss_start-&_tdata_start), &_tbss_end-&_tbss_start, 0); |
return tcb; |
} |
void __free_tls(tcb_t *tcb) |
{ |
size_t tls_size = &_tbss_end - &_tdata_start; |
__free_tls_arch(tcb, tls_size); |
} |
/** Main thread function. |
* |
* This function is called from __thread_entry() and is used |
* to call the thread's implementing function and perform cleanup |
* and exit when thread returns back. Do not call this function |
* directly. |
* |
* @param uarg Pointer to userspace argument structure. |
*/ |
void __thread_main(uspace_arg_t *uarg) |
{ |
tcb_t *tcb; |
/* This should initialize the area according to TLS specicification */ |
tcb = __make_tls(); |
__tcb_set(tcb); |
psthread_setup(tcb); |
uarg->uspace_thread_function(uarg->uspace_thread_arg); |
free(uarg->uspace_stack); |
free(uarg); |
psthread_teardown(tcb->pst_data); |
__free_tls(tcb); |
thread_exit(0); |
} |
/** Create userspace thread. |
* |
* This function creates new userspace thread and allocates userspace |
* stack and userspace argument structure for it. |
* |
* @param function Function implementing the thread. |
* @param arg Argument to be passed to thread. |
* @param name Symbolic name of the thread. |
* |
* @param TID of the new thread on success or -1 on failure. |
*/ |
int thread_create(void (* function)(void *), void *arg, char *name) |
{ |
char *stack; |
uspace_arg_t *uarg; |
stack = (char *) malloc(getpagesize()); |
if (!stack) |
return -1; |
uarg = (uspace_arg_t *) malloc(sizeof(uspace_arg_t)); |
if (!uarg) { |
free(stack); |
return -1; |
} |
uarg->uspace_entry = (void *) FADDR(__thread_entry); |
uarg->uspace_stack = (void *) stack; |
uarg->uspace_thread_function = function; |
uarg->uspace_thread_arg = arg; |
uarg->uspace_uarg = uarg; |
return __SYSCALL2(SYS_THREAD_CREATE, (sysarg_t) uarg, (sysarg_t) name); |
} |
/** Terminate current thread. |
* |
* @param stat Exit status. Currently not used. |
*/ |
void thread_exit(int status) |
{ |
__SYSCALL1(SYS_THREAD_EXIT, (sysarg_t) status); |
} |
/uspace/trunk/libc/generic/libc.c |
---|
0,0 → 1,55 |
/* |
* Copyright (C) 2005 Martin Decky |
* 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. |
* - The name of the author may not be used to endorse or promote products |
* derived from this software without specific prior written permission. |
* |
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 <libc.h> |
#include <unistd.h> |
#include <thread.h> |
#include <malloc.h> |
#include <psthread.h> |
void _exit(int status) { |
thread_exit(status); |
} |
#include <stdio.h> |
void __main(void) { |
tcb_t *tcb; |
tcb = __make_tls(); |
__tcb_set(tcb); |
psthread_setup(tcb); |
} |
void __exit(void) { |
tcb_t *tcb; |
tcb = __tcb_get(); |
psthread_teardown(tcb->pst_data); |
__free_tls(tcb); |
_exit(0); |
} |
/uspace/trunk/libc/generic/psthread.c |
---|
0,0 → 1,188 |
/* |
* Copyright (C) 2006 Ondrej Palkovsky |
* 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. |
* - The name of the author may not be used to endorse or promote products |
* derived from this software without specific prior written permission. |
* |
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 <libadt/list.h> |
#include <psthread.h> |
#include <malloc.h> |
#include <unistd.h> |
#include <thread.h> |
#include <stdio.h> |
#include <kernel/arch/faddr.h> |
static LIST_INITIALIZE(ready_list); |
static void psthread_exit(void) __attribute__ ((noinline)); |
static void psthread_main(void); |
/** Setup PSthread information into TCB structure */ |
psthread_data_t * psthread_setup(tcb_t *tcb) |
{ |
psthread_data_t *pt; |
pt = malloc(sizeof(*pt)); |
if (!pt) { |
return NULL; |
} |
tcb->pst_data = pt; |
pt->tcb = tcb; |
return pt; |
} |
void psthread_teardown(psthread_data_t *pt) |
{ |
free(pt); |
} |
/** Function to preempt to other pseudo thread without adding |
* currently running pseudo thread to ready_list. |
*/ |
void psthread_exit(void) |
{ |
psthread_data_t *pt; |
if (list_empty(&ready_list)) { |
/* Wait on IPC queue etc... */ |
printf("Cannot exit!!!\n"); |
_exit(0); |
} |
pt = list_get_instance(ready_list.next, psthread_data_t, link); |
list_remove(&pt->link); |
context_restore(&pt->ctx); |
} |
/** Function that is called on entry to new uspace thread */ |
void psthread_main(void) |
{ |
psthread_data_t *pt = __tcb_get()->pst_data; |
pt->retval = pt->func(pt->arg); |
pt->finished = 1; |
if (pt->waiter) |
list_append(&pt->waiter->link, &ready_list); |
psthread_exit(); |
} |
/** Schedule next userspace pseudo thread. |
* |
* @return 0 if there is no ready pseudo thread, 1 otherwise. |
*/ |
int psthread_schedule_next(void) |
{ |
psthread_data_t *pt; |
if (list_empty(&ready_list)) |
return 0; |
pt = __tcb_get()->pst_data; |
if (!context_save(&pt->ctx)) |
return 1; |
list_append(&pt->link, &ready_list); |
pt = list_get_instance(ready_list.next, psthread_data_t, link); |
list_remove(&pt->link); |
context_restore(&pt->ctx); |
} |
/** Wait for uspace pseudo thread to finish. |
* |
* @param psthrid Pseudo thread to wait for. |
* |
* @return Value returned by the finished thread. |
*/ |
int psthread_join(pstid_t psthrid) |
{ |
volatile psthread_data_t *pt, *mypt; |
volatile int retval; |
/* Handle psthrid = Kernel address -> it is wait for call */ |
pt = (psthread_data_t *) psthrid; |
if (!pt->finished) { |
mypt = __tcb_get()->pst_data; |
if (context_save(&((psthread_data_t *) mypt)->ctx)) { |
pt->waiter = (psthread_data_t *) mypt; |
psthread_exit(); |
} |
} |
retval = pt->retval; |
free(pt->stack); |
__free_tls(pt->tcb); |
psthread_teardown((void *)pt); |
return retval; |
} |
/** |
* Create a userspace thread and append it to ready list. |
* |
* @param func Pseudo thread function. |
* @param arg Argument to pass to func. |
* |
* @return 0 on failure, TLS of the new pseudo thread. |
*/ |
pstid_t psthread_create(int (*func)(void *), void *arg) |
{ |
psthread_data_t *pt; |
tcb_t *tcb; |
tcb = __make_tls(); |
if (!tcb) |
return 0; |
pt = psthread_setup(tcb); |
if (!pt) { |
__free_tls(tcb); |
return 0; |
} |
pt->stack = (char *) malloc(getpagesize()); |
if (!pt->stack) { |
__free_tls(tcb); |
psthread_teardown(pt); |
return 0; |
} |
pt->arg= arg; |
pt->func = func; |
pt->finished = 0; |
pt->waiter = NULL; |
context_save(&pt->ctx); |
context_set(&pt->ctx, FADDR(psthread_main), pt->stack, getpagesize(), |
tcb); |
list_append(&pt->link, &ready_list); |
return (pstid_t )pt; |
} |
/uspace/trunk/libc/generic/io/print.c |
---|
0,0 → 1,409 |
/* |
* Copyright (C) 2001-2004 Jakub Jermar |
* Copyright (C) 2006 Josef Cejka |
* 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. |
* - The name of the author may not be used to endorse or promote products |
* derived from this software without specific prior written permission. |
* |
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 <unistd.h> |
#include <io/io.h> |
#include <stdarg.h> |
#define __PRINTF_FLAG_PREFIX 0x00000001 /* show prefixes 0x or 0*/ |
#define __PRINTF_FLAG_SIGNED 0x00000002 /* signed / unsigned number */ |
#define __PRINTF_FLAG_ZEROPADDED 0x00000004 /* print leading zeroes */ |
#define __PRINTF_FLAG_LEFTALIGNED 0x00000010 /* align to left */ |
#define __PRINTF_FLAG_SHOWPLUS 0x00000020 /* always show + sign */ |
#define __PRINTF_FLAG_SPACESIGN 0x00000040 /* print space instead of plus */ |
#define __PRINTF_FLAG_BIGCHARS 0x00000080 /* show big characters */ |
#define __PRINTF_FLAG_NEGATIVE 0x00000100 /* number has - sign */ |
#define PRINT_NUMBER_BUFFER_SIZE (64+5) /* Buffer big enought for 64 bit number |
* printed in base 2, sign, prefix and |
* 0 to terminate string.. (last one is only for better testing |
* end of buffer by zero-filling subroutine) |
*/ |
typedef enum { |
PrintfQualifierByte = 0, |
PrintfQualifierShort, |
PrintfQualifierInt, |
PrintfQualifierLong, |
PrintfQualifierLongLong, |
PrintfQualifierSizeT, |
PrintfQualifierPointer |
} qualifier_t; |
static char digits_small[] = "0123456789abcdef"; /* Small hexadecimal characters */ |
static char digits_big[] = "0123456789ABCDEF"; /* Big hexadecimal characters */ |
/** Print number in given base |
* |
* Print significant digits of a number in given |
* base. |
* |
* @param num Number to print. |
* @param size not used, in future releases will be replaced with precision and width params |
* @param base Base to print the number in (should |
* be in range 2 .. 16). |
* @param flags output modifiers |
* @return number of written characters or EOF |
* |
*/ |
static int print_number(uint64_t num, size_t size, int base , uint64_t flags) |
{ |
/* FIXME: This is only first version. |
* Printf does not have support for specification of size |
* and precision, so this function writes with parameters defined by |
* their type size. |
*/ |
char *digits = digits_small; |
char d[PRINT_NUMBER_BUFFER_SIZE]; /* this is good enough even for base == 2, prefix and sign */ |
char *ptr = &d[PRINT_NUMBER_BUFFER_SIZE - 1]; |
if (flags & __PRINTF_FLAG_BIGCHARS) |
digits = digits_big; |
*ptr-- = 0; /* Put zero at end of string */ |
if (num == 0) { |
*ptr-- = '0'; |
} else { |
do { |
*ptr-- = digits[num % base]; |
} while (num /= base); |
} |
if (flags & __PRINTF_FLAG_PREFIX) { /*FIXME*/ |
switch(base) { |
case 2: /* Binary formating is not standard, but usefull */ |
*ptr = 'b'; |
if (flags & __PRINTF_FLAG_BIGCHARS) *ptr = 'B'; |
ptr--; |
*ptr-- = '0'; |
break; |
case 8: |
*ptr-- = 'o'; |
break; |
case 16: |
*ptr = 'x'; |
if (flags & __PRINTF_FLAG_BIGCHARS) *ptr = 'X'; |
ptr--; |
*ptr-- = '0'; |
break; |
} |
} |
if (flags & __PRINTF_FLAG_SIGNED) { |
if (flags & __PRINTF_FLAG_NEGATIVE) { |
*ptr-- = '-'; |
} else if (flags & __PRINTF_FLAG_SHOWPLUS) { |
*ptr-- = '+'; |
} else if (flags & __PRINTF_FLAG_SPACESIGN) { |
*ptr-- = ' '; |
} |
} |
/* Print leading zeroes */ |
if (flags & __PRINTF_FLAG_LEFTALIGNED) { |
flags &= ~__PRINTF_FLAG_ZEROPADDED; |
} |
if (flags & __PRINTF_FLAG_ZEROPADDED) { |
while (ptr != d ) { |
*ptr-- = '0'; |
} |
} |
return putstr(++ptr); |
} |
/** General formatted text print |
* |
* Print text formatted according the fmt parameter |
* and variant arguments. Each formatting directive |
* begins with \% (percentage) character and one of the |
* following character: |
* |
* \% Prints the percentage character. |
* |
* s The next variant argument is treated as char* |
* and printed as a NULL terminated string. |
* |
* c The next variant argument is treated as a single char. |
* |
* p The next variant argument is treated as a maximum |
* bit-width integer with respect to architecture |
* and printed in full hexadecimal width. |
* |
* P As with 'p', but '0x' is prefixed. |
* |
* q The next variant argument is treated as a 64b integer |
* and printed in full hexadecimal width. |
* |
* Q As with 'q', but '0x' is prefixed. |
* |
* l The next variant argument is treated as a 32b integer |
* and printed in full hexadecimal width. |
* |
* L As with 'l', but '0x' is prefixed. |
* |
* w The next variant argument is treated as a 16b integer |
* and printed in full hexadecimal width. |
* |
* W As with 'w', but '0x' is prefixed. |
* |
* b The next variant argument is treated as a 8b integer |
* and printed in full hexadecimal width. |
* |
* B As with 'b', but '0x' is prefixed. |
* |
* d The next variant argument is treated as integer |
* and printed in standard decimal format (only significant |
* digits). |
* |
* x The next variant argument is treated as integer |
* and printed in standard hexadecimal format (only significant |
* digits). |
* |
* X As with 'x', but '0x' is prefixed. |
* |
* All other characters from fmt except the formatting directives |
* are printed in verbatim. |
* |
* @param fmt Formatting NULL terminated string. |
*/ |
int printf(const char *fmt, ...) |
{ |
int i = 0, j = 0; /* i is index of currently processed char from fmt, j is index to the first not printed nonformating character */ |
int end; |
int counter; /* counter of printed characters */ |
int retval; /* used to store return values from called functions */ |
va_list ap; |
char c; |
qualifier_t qualifier; /* type of argument */ |
int base; /* base in which will be parameter (numbers only) printed */ |
uint64_t number; /* argument value */ |
size_t size; /* byte size of integer parameter */ |
uint64_t flags; |
counter = 0; |
va_start(ap, fmt); |
while ((c = fmt[i])) { |
/* control character */ |
if (c == '%' ) { |
/* print common characters if any processed */ |
if (i > j) { |
if ((retval = putnchars(&fmt[j], (size_t)(i - j))) == EOF) { /* error */ |
return -counter; |
} |
counter += retval; |
} |
j = i; |
/* parse modifiers */ |
flags = 0; |
end = 0; |
do { |
++i; |
switch (c = fmt[i]) { |
case '#': flags |= __PRINTF_FLAG_PREFIX; break; |
case '-': flags |= __PRINTF_FLAG_LEFTALIGNED; break; |
case '+': flags |= __PRINTF_FLAG_SHOWPLUS; break; |
case ' ': flags |= __PRINTF_FLAG_SPACESIGN; break; |
case '0': flags |= __PRINTF_FLAG_ZEROPADDED; break; |
default: end = 1; |
}; |
} while (end == 0); |
/* TODO: width & '*' operator */ |
/* TODO: precision and '*' operator */ |
switch (fmt[i++]) { |
case 'h': /* char or short */ |
qualifier = PrintfQualifierShort; |
if (fmt[i] == 'h') { |
i++; |
qualifier = PrintfQualifierByte; |
} |
break; |
case 'l': /* long or long long*/ |
qualifier = PrintfQualifierLong; |
if (fmt[i] == 'l') { |
i++; |
qualifier = PrintfQualifierLongLong; |
} |
break; |
case 'z': /* size_t */ |
qualifier = PrintfQualifierSizeT; |
break; |
default: |
qualifier = PrintfQualifierInt; /* default type */ |
--i; |
} |
base = 10; |
switch (c = fmt[i]) { |
/* |
* String and character conversions. |
*/ |
case 's': |
if ((retval = putstr(va_arg(ap, char*))) == EOF) { |
return -counter; |
}; |
counter += retval; |
j = i + 1; |
goto next_char; |
case 'c': |
c = va_arg(ap, unsigned long); |
if ((retval = putnchars(&c, sizeof(char))) == EOF) { |
return -counter; |
}; |
counter += retval; |
j = i + 1; |
goto next_char; |
/* |
* Integer values |
*/ |
case 'P': /* pointer */ |
flags |= __PRINTF_FLAG_BIGCHARS; |
case 'p': |
flags |= __PRINTF_FLAG_PREFIX; |
base = 16; |
qualifier = PrintfQualifierPointer; |
break; |
case 'b': |
base = 2; |
break; |
case 'o': |
base = 8; |
break; |
case 'd': |
case 'i': |
flags |= __PRINTF_FLAG_SIGNED; |
case 'u': |
break; |
case 'X': |
flags |= __PRINTF_FLAG_BIGCHARS; |
case 'x': |
base = 16; |
break; |
/* percentile itself */ |
case '%': |
j = i; |
goto next_char; |
/* |
* Bad formatting. |
*/ |
default: |
/* Unknown format |
* now, the j is index of '%' so we will |
* print whole bad format sequence |
*/ |
goto next_char; |
} |
/* Print integers */ |
/* print number */ |
switch (qualifier) { |
case PrintfQualifierByte: |
size = sizeof(unsigned char); |
number = (uint64_t)va_arg(ap, unsigned int); |
break; |
case PrintfQualifierShort: |
size = sizeof(unsigned short); |
number = (uint64_t)va_arg(ap, unsigned int); |
break; |
case PrintfQualifierInt: |
size = sizeof(unsigned int); |
number = (uint64_t)va_arg(ap, unsigned int); |
break; |
case PrintfQualifierLong: |
size = sizeof(unsigned long); |
number = (uint64_t)va_arg(ap, unsigned long); |
break; |
case PrintfQualifierLongLong: |
size = sizeof(unsigned long long); |
number = (uint64_t)va_arg(ap, unsigned long long); |
break; |
case PrintfQualifierPointer: |
size = sizeof(void *); |
number = (uint64_t)(unsigned long)va_arg(ap, void *); |
break; |
case PrintfQualifierSizeT: |
size = sizeof(size_t); |
number = (uint64_t)va_arg(ap, size_t); |
break; |
default: /* Unknown qualifier */ |
return -counter; |
} |
if (flags & __PRINTF_FLAG_SIGNED) { |
if (number & (0x1 << (size*8 - 1))) { |
flags |= __PRINTF_FLAG_NEGATIVE; |
if (size == sizeof(uint64_t)) { |
number = -((int64_t)number); |
} else { |
number = ~number; |
number &= (~((0xFFFFFFFFFFFFFFFFll) << (size * 8))); |
number++; |
} |
} |
} |
if ((retval = print_number(number, size, base, flags)) == EOF ) { |
return -counter; |
}; |
counter += retval; |
j = i + 1; |
} |
next_char: |
++i; |
} |
if (i > j) { |
if ((retval = putnchars(&fmt[j], (size_t)(i - j))) == EOF) { /* error */ |
return -counter; |
} |
counter += retval; |
} |
va_end(ap); |
return counter; |
} |
/uspace/trunk/libc/generic/io/io.c |
---|
0,0 → 1,87 |
/* |
* Copyright (C) 2005 Martin Decky |
* 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. |
* - The name of the author may not be used to endorse or promote products |
* derived from this software without specific prior written permission. |
* |
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 <libc.h> |
#include <unistd.h> |
#include <stdio.h> |
#include <io/io.h> |
static char nl = '\n'; |
int puts(const char * str) |
{ |
size_t count; |
for (count = 0; str[count] != 0; count++); |
if (write(1, (void * ) str, count) == count) { |
if (write(1, &nl, 1) == 1) |
return 0; |
} |
return EOF; |
} |
/** Put count chars from buffer to stdout without adding newline |
* @param buf Buffer with size at least count bytes |
* @param count |
* @return 0 on succes, EOF on fail |
*/ |
int putnchars(const char * buf, size_t count) |
{ |
if (write(1, (void * ) buf, count) == count) { |
return 0; |
} |
return EOF; |
} |
/** Same as puts, but does not print newline at end |
* |
*/ |
int putstr(const char * str) |
{ |
size_t count; |
if (str == NULL) { |
return putnchars("(NULL)",6 ); |
} |
for (count = 0; str[count] != 0; count++); |
if (write(1, (void * ) str, count) == count) { |
return 0; |
} |
return EOF; |
} |
ssize_t write(int fd, const void * buf, size_t count) |
{ |
return (ssize_t) __SYSCALL3(SYS_IO, (sysarg_t) fd, (sysarg_t) buf, (sysarg_t) count); |
} |
/uspace/trunk/libc/generic/mmap.c |
---|
0,0 → 1,91 |
/* |
* Copyright (C) 2006 Jakub Jermar |
* 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. |
* - The name of the author may not be used to endorse or promote products |
* derived from this software without specific prior written permission. |
* |
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 <libc.h> |
#include <unistd.h> |
/** mmap syscall |
* |
* @param address Virtual address where to place new address space area. |
* @param size Size of the area. |
* @param flags Flags describing type of the area. |
* |
* @return address on success, (void *) -1 otherwise. |
*/ |
void *mmap(void *address, size_t size, int flags) |
{ |
return (void *) __SYSCALL3(SYS_MMAP, (sysarg_t ) address, (sysarg_t) size, (sysarg_t) flags); |
} |
/** mremap syscall |
* |
* @param address Virtual address pointing into already existing address space area. |
* @param size New requested size of the area. |
* @param flags Currently unused. |
* |
* @return address on success, (void *) -1 otherwise. |
*/ |
void *mremap(void *address, size_t size, int flags) |
{ |
return (void *) __SYSCALL3(SYS_MREMAP, (sysarg_t ) address, (sysarg_t) size, (sysarg_t) flags); |
} |
static size_t heapsize = 0; |
/* Start of heap linker symbol */ |
extern char _heap; |
/** Sbrk emulation |
* |
* @param size New area that should be allocated or negative, |
if it should be shrinked |
* @return Pointer to newly allocated area |
*/ |
void *sbrk(ssize_t incr) |
{ |
void *res; |
/* Check for invalid values */ |
if (incr < 0 && -incr > heapsize) |
return NULL; |
/* Check for too large value */ |
if (incr > 0 && incr+heapsize < heapsize) |
return NULL; |
/* Check for too small values */ |
if (incr < 0 && incr+heapsize > heapsize) |
return NULL; |
res = mremap(&_heap, heapsize + incr,0); |
if (!res) |
return NULL; |
/* Compute start of new area */ |
res = (void *)&_heap + heapsize; |
heapsize += incr; |
return res; |
} |
/uspace/trunk/libc/generic/string.c |
---|
0,0 → 1,49 |
/* |
* Copyright (C) 2005 Martin Decky |
* 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. |
* - The name of the author may not be used to endorse or promote products |
* derived from this software without specific prior written permission. |
* |
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 <types.h> |
#include <string.h> |
/* Dummy implementation of mem/ functions */ |
void * memset(void *s, int c, size_t n) |
{ |
char *os = s; |
while (n--) |
*(os++) = c; |
return s; |
} |
void * memcpy(void *dest, void *src, size_t n) |
{ |
char *os = src; |
char *odst = dest; |
while (n--) |
*(odst++) = *(os++); |
return dest; |
} |